From 55fef13aaf67a61c6393b5a4339bef712b9aa2fe Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 23:21:49 +0000 Subject: [PATCH 01/13] Hosted egui apps on next: canvas claims, Ctrl+wheel pinch switch, host style in dock bodies - The key target's declared claims count for Alt-code entry and the key stage: with nothing focused the window's document canvas (`host_canvas`) stands for the focused component, so an app's Alt+digit shortcut it claims reaches it on Windows and Linux. A host stop's claimed press stays in egui's input, where the app reads it, focused or as the unfocused key target. - `RootEnv::ctrl_wheel_pinch` (default on) makes the fold of a fractional Ctrl+wheel into `Event::Zoom` a host choice: off, the wheel event stays as sent, for an app whose Ctrl+wheel does something else or zooms at its own rate. - `PanelSpec::host_body` marks a panel whose body is the app's own egui code: the dock hands its body, footer, header, rail footer and group view the style of the `Ui` the dock was shown in (`HostStyle`), while framework bodies keep the group's spacing. --- .../ui-contract/src/runtime/egui/alt_code.rs | 5 +- crates/ui-contract/src/runtime/egui/input.rs | 14 ++-- crates/ui-contract/src/runtime/egui/style.rs | 19 +++++ crates/ui-contract/src/runtime/env/root.rs | 13 ++++ crates/ui-contract/src/runtime/focus.rs | 19 +++-- crates/ui-contract/src/runtime/focus/nav.rs | 1 + .../ui-contract/src/runtime/focus/policy.rs | 4 +- crates/ui-contract/src/runtime/frame.rs | 21 +++++- crates/ui-contract/src/runtime/keys/input.rs | 74 ++++++++++++++----- crates/ui-contract/src/runtime/keys/route.rs | 4 +- .../ui-contract/tests/it/runtime/alt_code.rs | 67 ++++++++++++++++- crates/ui-contract/tests/it/runtime/wheel.rs | 7 ++ crates/ui-panels/src/docking/panels.rs | 4 +- crates/ui-panels/src/docking/spec.rs | 14 ++++ crates/ui-patterns/src/patterns/dock/area.rs | 58 ++++++++++++--- .../ui-patterns/tests/it/docking/host_body.rs | 57 ++++++++++++++ crates/ui-patterns/tests/it/docking/mod.rs | 1 + docs/craft-framework.md | 2 + docs/ui-docking.md | 4 +- 19 files changed, 334 insertions(+), 54 deletions(-) create mode 100644 crates/ui-patterns/tests/it/docking/host_body.rs diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs index 7320636a81..0639e31fa8 100644 --- a/crates/ui-contract/src/runtime/egui/alt_code.rs +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -40,8 +40,9 @@ struct Echo { /// after the Alt release. Returns whether an Alt release in `events` ended a hold in which digits were typed (a code, /// or one a focus loss dropped), so the key stage does not take it for a lone Alt. The caller does not call it on macOS, where Option+digit types its own characters. /// -/// `claimed` tells whether the key stage takes a press as a chord a component claims or a capture holds: such an -/// Alt+digit is its owner's, as an app's shortcut goes before Alt-code entry, and it ends the entry like any other key. +/// `claimed` tells whether the key stage takes a press as a chord the key target claims (the focused component, or with +/// nothing focused the window's document canvas) or a capture holds: such an Alt+digit is its owner's, as an app's +/// shortcut goes before Alt-code entry, and it ends the entry like any other key. pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: AltCodePages, os: Os, claimed: &dyn Fn(&Event) -> bool) -> bool { let composes = os == Os::Windows; let mut ended = false; diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index a960829606..db024b66fd 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -651,7 +651,7 @@ const PINCH_CONTINUES: f64 = 0.25; /// Windows and Linux: turns a fractional Ctrl+wheel (or a Wayland point-unit one) into `Event::Zoom` at egui's Ctrl-scroll /// speed; a whole notch stays a wheel event unless within 0.25 s of a pinch step. An input that carries `Event::Zoom` -/// already is left alone and ends the run of pinch steps. +/// already is left alone and ends the run of pinch steps. Runs while `RootEnv::ctrl_wheel_pinch` is on. pub(crate) fn fold_legacy_pinch(ctx: &Context, input: &mut RawInput) { let os = crate::runtime::windows::os_of(ctx); if os == Os::Mac { @@ -710,14 +710,16 @@ pub(crate) struct RawState { /// A frame's raw events reach only its first pass; a second pass's input holds none, so each wheel delta is scaled /// once and each digit folded once, with nothing to replay or remember between passes. pub(crate) fn prepare(ctx: &Context, input: &mut RawInput) { - fold_legacy_pinch(ctx, input); // This frame's `RootEnv`, which `set_input` stored before egui ran the input hook. - // PLAN: assumed `pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages)` in `runtime/frame.rs` (platform-w3). - let (wheel, pages) = crate::runtime::frame::root_input(ctx); - scale_wheel(&mut input.events, wheel); + let root = crate::runtime::frame::root_input(ctx); + if root.ctrl_wheel_pinch { + fold_legacy_pinch(ctx, input); + } + let pages = root.alt_codes; + scale_wheel(&mut input.events, root.wheel); let os = crate::runtime::windows::os_of(ctx); let macos = os == Os::Mac; - // A chord a component claims or a capture holds goes to its owner before Alt-code entry. + // A chord the key target claims or a capture holds goes to its owner before Alt-code entry. let claimed = crate::runtime::keys::claims_press(ctx, input); let events = &mut input.events; PerViewport::::with(ctx, input.viewport_id, |state| { diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index ff7b38fd33..b4d095956e 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -1,6 +1,7 @@ //! The theme styles' `right_to_left`. use egui::{Context, Ui}; +use std::sync::Arc; /// Turns off egui's own caret blink in `ui`, and hides the caret stroke unless `visible`: the runtime blinks it. pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) { @@ -63,3 +64,21 @@ pub(crate) fn set_theme_direction(ctx: &Context, root: &mut Ui, right_to_left: b pub(crate) fn set_item_spacing(ui: &mut Ui, gap: egui::Vec2) { ui.spacing_mut().item_spacing = gap; } + +/// The egui style of an app's own `Ui`, kept where a framework part takes the app's egui code into a `Ui` of its own: +/// the framework's regions set their layout spacing on the `Ui`s they hand out, and app code shown in one (a dock +/// panel's body that the app draws with egui) lays out as it would outside the part when the part applies this. +#[derive(Clone, Debug)] +pub struct HostStyle(Arc); + +impl HostStyle { + /// The style `ui` has now. + pub fn of(ui: &Ui) -> Self { + HostStyle(Arc::clone(ui.style())) + } + + /// Gives `ui` the kept style. + pub fn apply(&self, ui: &mut Ui) { + ui.set_style(Arc::clone(&self.0)); + } +} diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index 23fc27c0b9..68c90ca46e 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -55,6 +55,12 @@ pub struct RootEnv { pub wheel: WheelSpeed, /// The code pages that decode Alt+numpad codes. pub alt_codes: AltCodePages, + /// On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch + /// and arrives as `egui::Event::Zoom`: Windows hands a precision touchpad's pinch to apps only that way, and some + /// Wayland stacks do too. On by default. Off, it stays a wheel event with Ctrl held, for an app whose Ctrl+wheel + /// does something else or zooms at its own rate (Zoom with Trackpad Pinch off). Whole notches stay wheel events + /// either way; macOS sends a pinch as its own event. + pub ctrl_wheel_pinch: bool, } impl Default for RootEnv { @@ -78,6 +84,7 @@ impl Default for RootEnv { today: None, wheel: WheelSpeed::default(), alt_codes: AltCodePages::default(), + ctrl_wheel_pinch: true, } } } @@ -226,6 +233,12 @@ impl RootEnv { self.alt_codes = pages; self } + + /// Sets whether a fractional Ctrl+wheel arrives as a pinch (`ctrl_wheel_pinch`). + pub fn ctrl_wheel_pinch(mut self, pinch: bool) -> Self { + self.ctrl_wheel_pinch = pinch; + self + } } /// The mode, contrast and motion of a pass, with `System` resolved. diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 99f6d5c3c4..a707f2739c 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -76,6 +76,8 @@ pub(crate) struct FocusedRecord { pub(crate) claims: Vec, /// The component of the focused stop: only its state-dependent claims hold. pub(crate) focused: Option, + /// The focused stop is the app's own egui widget (`Stop::host`): it reads the presses it claims from egui. + pub(crate) host: bool, /// The arena root of the focused stop when the stop is a non-text member of an arena (a part of a canvas's frame /// overlay): the root's state-dependent claims hold too, so a canvas tool's keys work with a part focused. pub(crate) root: Option, @@ -234,18 +236,21 @@ pub(crate) fn register_stop(ctx: &Context, stop: Stop) { /// reaches the canvas by Tab, F6 or `request`; while it has focus, its keys route as `keys` says (the arrows as /// nudges, Escape as its `Intent::Cancel`). `keys` is `KeyUse::CANVAS`, or a variant such as /// `KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(..)` while the canvas edits text in place and Tab and the -/// clipboard are its own. With nothing focused the canvas is the key target: a bare Tab it keeps, and the clipboard -/// events and edit chords of its edit set, stay in egui's input for the app, and nothing toggles or fires with them; -/// Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus. With the canvas focused, Tab it keeps stays in egui too, and its edit set arrives as `Intent::Edit` +/// clipboard are its own. With nothing focused the canvas is the key target: a bare Tab it keeps, the chords it claims +/// (`KeyUse::with_claims`; Alt+numpad code entry leaves a claimed Alt+digit alone), and the clipboard events and edit +/// chords of its edit set, stay in egui's input for the app, and nothing toggles or fires with them; Page Up and Down, +/// Home and End arrive as its `Intent::Move`, as while it has the focus. With the canvas focused, Tab it keeps and the +/// chords it claims stay in egui too, and its edit set arrives as `Intent::Edit` /// (`keys::intents_of`), as for any focused stop. Call it each pass the canvas shows. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host()); } -/// The keys of the document canvas `viewport` registered in its last pass (`KeyUse::chrome_key`), framework or the -/// app's own. Read before the begin hook rotates the registrations, by the input hook and the begin hook's Tab moves. -pub(crate) fn canvas_keys(ctx: &Context, viewport: ViewportId) -> Option { - with_viewport(ctx, viewport, |state| state.stops.iter().find(|rec| rec.stop.keys.chrome_key).map(|rec| rec.stop.keys)) +/// The stop of the document canvas `viewport` registered in its last pass (`KeyUse::chrome_key`), framework or the +/// app's own (`Stop::host`). Read before the begin hook rotates the registrations, by the input hook and the begin +/// hook's Tab moves. +pub(crate) fn canvas_stop(ctx: &Context, viewport: ViewportId) -> Option { + with_viewport(ctx, viewport, |state| state.stops.iter().find(|rec| rec.stop.keys.chrome_key).map(|rec| rec.stop.clone())) } /// The document canvas the running viewport registered in its last pass (`KeyUse::chrome_key`): the window's key diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index f42f71537e..b59ad0a3c9 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -851,6 +851,7 @@ pub(super) fn end(state: &mut State, focused: Option, on_app_widget: bool, f state.record = super::FocusedRecord { claims: keys.map(|keys| keys.claims.to_vec()).unwrap_or_default(), focused: stop.as_ref().map(|stop| stop.id), + host: stop.as_ref().is_some_and(|stop| stop.host), root: stop.as_ref().filter(|stop| stop.root != stop.id && !stop.text).map(|stop| stop.root), menu: state.focused_menu_level(), pages: stop.as_ref().is_some_and(|stop| stop.role.pages), diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index 54a861ec41..a558622d9d 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -295,7 +295,9 @@ pub struct KeyUse { pub keep: KeepKeys, /// The keys that activate. pub activate: ActivateKeys, - /// Chords kept from the shortcut dispatcher while focused. + /// Chords kept from the shortcut dispatcher, and from Alt+numpad code entry, while focused, and for the window's + /// document canvas also while nothing has the focus. An app's own egui widget (`focus::host_canvas`) reads their + /// presses from egui's input; a framework component reads them as claimed chords. pub claims: &'static [Chord], /// Edit commands delivered as `Intent::Edit`. pub edits: EditSet, diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index bf59ec4053..2476846d4b 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -400,9 +400,24 @@ fn frame_hit(ctx: &Context) -> HitSizes { pass_state::with::(ctx, |state| state.hit.as_ref().map(|(_, hit)| *hit)).unwrap_or_else(|| resolved_hit(&AppSizes::default())) } -/// The wheel speed and Alt-code pages of the frame's root values; the defaults before the app sets any input. -pub(crate) fn root_input(ctx: &Context) -> (WheelSpeed, AltCodePages) { - pass_state::with::(ctx, |state| state.input.as_ref().map(|input| (input.root.wheel, input.root.alt_codes))).unwrap_or_default() +/// What the raw-input step reads of the frame's root values (`RootEnv`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct RootInput { + pub(crate) wheel: WheelSpeed, + pub(crate) alt_codes: AltCodePages, + pub(crate) ctrl_wheel_pinch: bool, +} + +impl RootInput { + fn of(root: &RootEnv) -> Self { + RootInput { wheel: root.wheel, alt_codes: root.alt_codes, ctrl_wheel_pinch: root.ctrl_wheel_pinch } + } +} + +/// The raw-input values of the frame's root values; the defaults before the app sets any input. +pub(crate) fn root_input(ctx: &Context) -> RootInput { + pass_state::with::(ctx, |state| state.input.as_ref().map(|input| RootInput::of(&input.root))) + .unwrap_or_else(|| RootInput::of(&RootEnv::default())) } /// How far a press may move and still be a click, in points: the app's hit tolerances (`HitSizes::slop`). egui's own diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 971384cadb..b64eaff53b 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -23,7 +23,7 @@ struct Strip<'a> { pages: bool, /// The focused component reads every press as a chord (`OwnerClass::Recorder`). records: bool, - claims: &'a [Chord], + claims: &'a Claims, edits: &'a dyn Fn(EditCommand) -> bool, /// The chords bound to the edit commands. edit_chords: &'a [(EditCommand, Chord)], @@ -235,7 +235,8 @@ impl Strip<'_> { /// What the key stage makes of a press of `key` with `input`. fn use_of(&self, key: Key, input: &KeyInput) -> PressUse { let mods = input.mods; - let claimed = self.claims.iter().find(|chord| self.layout.matches(chord, input, self.os)); + let matches = |claims: &[Chord]| claims.iter().find(|chord| self.layout.matches(chord, input, self.os)).copied(); + let claimed = matches(&self.claims.framework).map(|chord| (chord, false)).or_else(|| matches(&self.claims.host).map(|chord| (chord, true))); let ctrl_tab = key == Key::Tab && (if self.os == Os::Mac { mods.ctrl && !mods.cmd } else { mods.cmd }); let ctrl_tab = ctrl_tab && self.pages && !self.keeps_tab; let bare_tab = key == Key::Tab && !mods.cmd && !mods.ctrl && !mods.alt; @@ -255,8 +256,8 @@ impl Strip<'_> { .iter() .find(|(key, chord)| !matches!(key, WindowShortcut::Chrome(_)) && self.layout.matches(chord, input, self.os)) .map(|(key, _)| *key); - if let Some(chord) = claimed { - PressUse::Claimed(*chord) + if let Some((chord, egui)) = claimed { + PressUse::Claimed { chord, egui } } else if let Some((command, _)) = edit { PressUse::Edit(*command) } else if key == Key::Space && self.canvas_space { @@ -285,9 +286,9 @@ impl Strip<'_> { fn press(&self, batch: &mut Batch, key: Key, input: &KeyInput, repeat: bool, at: Option) -> bool { let mods = input.mods; match self.use_of(key, input) { - PressUse::Claimed(chord) => { + PressUse::Claimed { chord, egui } => { batch.claimed.push(chord); - false + egui } PressUse::Edit(command) => { batch.clips.push(command); @@ -364,8 +365,12 @@ impl Strip<'_> { /// What the key stage makes of one press (`Strip::use_of`). enum PressUse { - /// The focused component or a capture claims the chord. - Claimed(Chord), + /// The key target or a capture claims the chord. `egui`: the claim is an app's own egui widget's + /// (`Stop::host`), which reads the press from egui's input, so egui keeps it. + Claimed { + chord: Chord, + egui: bool, + }, /// The chord of an edit command the focused component lists. Edit(EditCommand), /// The Space of the canvas a dialog keeps open. @@ -393,6 +398,14 @@ enum PressUse { /// component, its arena root and its menu level, and a bare End where it declares `EndKey::EndMode`. pub(super) fn focused_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec { let mut claims = record.claims.clone(); + claims.extend(state_claims(record, stage)); + claims +} + +/// The chords of `focused_claims` that the focused stop does not declare: the state-dependent ones and the End of +/// `EndKey::EndMode`. +fn state_claims(record: &focus::FocusedRecord, stage: &Stage) -> Vec { + let mut claims = Vec::new(); let holds = |owner: Id| [record.focused, record.root, record.menu, record.menu_bar].contains(&Some(owner)); claims.extend(stage.claims.iter().filter(|(owner, _)| holds(*owner)).map(|(_, chord)| *chord)); // A bare End belongs to a stop that declares `EndKey::EndMode`: it reads the key as a claimed chord and toggles its @@ -432,7 +445,7 @@ pub(super) fn tab_toggles_now(ctx: &Context) -> bool { let viewport = crate::runtime::egui::pass::current_viewport(ctx); let enabled = Env::root_for(ctx, viewport).is_some_and(|env| env.tab_toggles_chrome); let focused = focus::focused_rec(ctx); - let canvas = focus::canvas_keys(ctx, viewport).is_some(); + let canvas = focus::canvas_stop(ctx, viewport).is_some(); let layer = overlay::key_layer(ctx, &focused.as_ref().map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(), None); let pressed = focused.as_ref().is_some_and(|rec| focus::origin(ctx, rec) == Some(focus::FocusOrigin::Press)); tab_toggles_chrome(enabled, canvas, layer, focused.as_ref().map(|rec| &rec.stop.keys), pressed) @@ -479,7 +492,8 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec Vec { - let mut claims = focused_claims(record, stage); - claims.extend(stage.captures.iter().map(|(_, chord)| *chord)); - claims +/// The chords the key stage takes as claimed (`PressUse::Claimed`). +struct Claims { + /// The captures', the menu level's and the menu bar's, and the key target's when it is a framework component. + framework: Vec, + /// The ones the key target declares (`KeyUse::claims`) when it is an app's own egui widget (`Stop::host`): egui + /// keeps their presses, where the app reads them. + host: Vec, +} + +/// The window's document canvas as the key target of `viewport`'s input: nothing has the focus, neither a framework +/// stop nor an app's own widget or popup (`Strip::canvas`). +fn target_canvas(ctx: &Context, viewport: ViewportId, record: &focus::FocusedRecord) -> Option { + focus::canvas_stop(ctx, viewport).filter(|_| record.keys.is_none() && !record.foreign) +} + +/// The claims of the key stage: the focused component's (`focused_claims`) and every capture's. With nothing focused +/// the window's document canvas `canvas` (`target_canvas`) stands for the focused component with the chords it +/// declares, as it does for a fired command (`claims::fire_claimed`). +fn stage_claims(record: &focus::FocusedRecord, canvas: Option<&focus::Stop>, stage: &Stage) -> Claims { + let (mut framework, mut host) = + if record.host { (state_claims(record, stage), record.claims.clone()) } else { (focused_claims(record, stage), Vec::new()) }; + framework.extend(stage.captures.iter().map(|(_, chord)| *chord)); + if let Some(canvas) = canvas { + let to = if canvas.host { &mut host } else { &mut framework }; + to.extend_from_slice(canvas.keys.claims); + } + Claims { framework, host } } /// Whether the key stage of `input`'s viewport will take a press as a claimed chord (`PressUse::Claimed`), read before @@ -590,11 +625,12 @@ pub(crate) fn claims_press(ctx: &Context, input: &RawInput) -> impl Fn(&egui::Ev let viewport = input.viewport_id; let os = crate::runtime::windows::os_of(ctx); let record = focus::record(ctx, viewport); - let (claims, mut layout) = with(ctx, viewport, |stage| (stage_claims(&record, stage), stage.layout.clone())); + let canvas = target_canvas(ctx, viewport, &record); + let (claims, mut layout) = with(ctx, viewport, |stage| (stage_claims(&record, canvas.as_ref(), stage), stage.layout.clone())); layout.set_latin(input.keyboard_layout_is_latin); let latin = input.latin_layout_chars.clone(); move |event: &egui::Event| match raw_input::key_event(event, os, &latin) { - KeyEvent::Press { input: pressed, .. } => claims.iter().any(|chord| layout.matches(chord, &pressed, os)), + KeyEvent::Press { input: pressed, .. } => claims.framework.iter().chain(&claims.host).any(|chord| layout.matches(chord, &pressed, os)), _ => false, } } diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 9abd1a09bf..5fcf46d9c7 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -187,7 +187,8 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { Some(intent) => push(&mut routed, driven.map(|driven| driven.list), intent, false), None => { // A capture's owner, else the claim's: the focused component's own, then its arena root's, then its - // menu level's, then the registered menu bar's (keytips hold their letters with no focus). + // menu level's, then the registered menu bar's (keytips hold their letters with no focus). With nothing + // focused, the window's canvas declares the rest (`KeyUse::claims`). let held = |owner: Option| held_claims.iter().find(|(id, held)| Some(*id) == owner && held == chord).map(|(id, _)| *id); let owner = captures.iter().find(|(_, held)| held == chord).map(|(owner, _)| *owner); claimed.extend( @@ -197,6 +198,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { .or_else(|| held(menu)) .or_else(|| held(menu_bar)) .or(focused) + .or_else(|| canvas.as_ref().map(|canvas| canvas.stop.id)) .map(|id| (id, *chord)), ); } diff --git a/crates/ui-contract/tests/it/runtime/alt_code.rs b/crates/ui-contract/tests/it/runtime/alt_code.rs index a09b7aa6d6..560d7cd3a8 100644 --- a/crates/ui-contract/tests/it/runtime/alt_code.rs +++ b/crates/ui-contract/tests/it/runtime/alt_code.rs @@ -6,9 +6,10 @@ use craft_host::target::Os; use craft_ui::contract::{Common, Component, Cx, Input, PaintUi, PartsCx, Props as _, Role, Show as _}; use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState}; use craft_ui::runtime::env::{AltCodePages, RootEnv}; -use craft_ui::runtime::focus::KeyUse; +use craft_ui::runtime::focus::{FocusTarget, KeyUse, host_canvas, request}; use craft_ui::runtime::frame::take_output; use craft_ui::style::StyleCx; +use craft_ui::testing::focus::{named_id, widget}; use craft_ui::testing::input::{key_press, key_repeat, text}; use craft_ui::testing::pointer::click; use craft_ui::testing::{Frames, trial}; @@ -248,3 +249,67 @@ fn an_alt_numpad_code_types_its_character_once() { assert!(!option.text.contains('é'), "macOS has no Alt codes: {option:?}"); assert!(!option.lone_alt, "macOS has no lone Alt either"); } + +/// Alt with the digit 3, which the host canvas of the next trial claims. +const ALT_3: craft_keymap::Chord = craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num3); + +/// An app's Alt+digit shortcut on Windows and Linux: the app's own egui canvas (`host_canvas`) claims Alt+3. With +/// nothing focused the canvas is the window's key target, so Alt-code entry leaves the claimed press and egui's input +/// keeps it for the app, while an unclaimed Alt+5 still folds into a code. With the canvas focused, the claimed press +/// still reaches egui. A focused text field types Alt codes again, with the claimed digit among them. +#[trial] +fn an_alt_digit_a_host_canvas_claims_reaches_the_app_and_a_field_still_types_codes() { + for os in [Os::Windows, Os::Linux] { + let canvas = named_id("alt digit canvas"); + let typed = Rc::new(RefCell::new(String::new())); + let reached = Rc::new(RefCell::new(Vec::::new())); + let mut show = { + let (typed, reached) = (Rc::clone(&typed), Rc::clone(&reached)); + move |ui: &mut egui::Ui| { + let alt_digits: Vec = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + Event::Key { key, pressed: true, modifiers, .. } if modifiers.alt => Some(*key), + _ => None, + }) + .collect() + }); + reached.borrow_mut().extend(alt_digits); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS.with_claims(&[ALT_3])); + Probe::new(&typed).label("Text").id_salt("alt_code_field").show_at(ui, AT); + } + }; + let mut frames = Frames::new(); + craft_ui::testing::windows::set_os(&frames.ctx, os); + frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437))); + frames.idle(3, &mut show); + // Plays `sequence`, then a frame with none; returns the Alt presses that reached egui and the field's text. + let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec>| { + reached.borrow_mut().clear(); + typed.borrow_mut().clear(); + for events in sequence { + frames.frame(events, &mut *show); + } + frames.frame(Vec::new(), &mut *show); + (reached.take(), typed.take()) + }; + + let (keys, _) = send(&mut frames, &mut show, code("3")); + assert!(keys.contains(&Key::Num3), "{os:?}: with nothing focused, the canvas's claimed Alt+3 reaches egui: {keys:?}"); + let (keys, _) = send(&mut frames, &mut show, code("5")); + assert!(!keys.contains(&Key::Num5), "{os:?}: an unclaimed Alt+5 folds into an Alt code: {keys:?}"); + + request(&frames.ctx, FocusTarget::Id(canvas)); + let (keys, _) = send(&mut frames, &mut show, code("3")); + assert!(keys.contains(&Key::Num3), "{os:?}: the focused canvas's claimed Alt+3 reaches egui: {keys:?}"); + + click(&mut frames, AT.center(), &mut show); + frames.idle(1, &mut show); + let (keys, text) = send(&mut frames, &mut show, code("0233")); + assert_eq!(text, "é", "{os:?}: the focused field types the code, its 3 included"); + assert!(keys.is_empty(), "{os:?}: no digit of the code reaches egui: {keys:?}"); + } +} diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index 477e0ae07a..71ebd017f8 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -100,6 +100,13 @@ fn a_fractional_ctrl_wheel_is_a_pinch_and_a_whole_notch_stays_a_scroll() { assert!(native.len() == 1 && (native[0].zoom - 1.1).abs() < 1e-4, "{os:?}: a native pinch reaches the view as sent: {native:?}"); let after_native = step(&mut fixture, vec![ctrl_lines(1.0)]); assert!(scrolled(&after_native), "{os:?}: a whole notch after a native pinch is a wheel notch: {after_native:?}"); + + // A host whose Ctrl+wheel does something else (Zoom with Trackpad Pinch off, or its own Ctrl-scroll zoom rate) + // turns the fold off: the fractional step stays a wheel event. + fixture.root(RootEnv::default().ctrl_wheel_pinch(false)); + fixture.advance(0.5); + let unfolded = step(&mut fixture, vec![ctrl_lines(0.4)]); + assert!(scrolled(&unfolded), "{os:?}: with `ctrl_wheel_pinch` off a fractional Ctrl+wheel is a wheel event: {unfolded:?}"); } } diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index d3a007528e..953fb2ba1f 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -69,7 +69,9 @@ pub trait DockPanels

{ /// Shows `panel`'s body in `ui`: the group's body, inset from its edges by the panel padding. The group is the /// body's panel and its tab the body's title, so the body shows no framework `Panel` or padding of its own; content /// taller than the group scrolls in the body's own scrolling container. A document panel's body - /// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. + /// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. The body lays out with the group's + /// spacing, or with the style of the `Ui` the dock was shown in where the panel's body is the app's own egui code + /// (`PanelSpec::host_body`). fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>); /// Shows the fixed trailing controls of the rail containing `panel`, in top-to-bottom order. The dock calls this diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index 8fdb6c8dd1..9b17177a30 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -179,6 +179,12 @@ pub struct PanelSpec { pub count: Option, /// A line of small faint text under the header row while the panel is the one its group shows ("2 replies"). pub caption: Option

)], rail_footer: Option<&'s P>, + /// The style of the `Ui` the area was shown in, which the bodies of `PanelSpec::host_body` panels lay out with. + host_style: &'s HostStyle, } /// The spec of `panel` in `specs`, or an unnamed one. @@ -341,6 +344,19 @@ impl DockModel

{ } impl Scene<'_, P> { + /// Runs `run`, which shows host code of `panel`, on `ui`: with the style of the `Ui` the area was shown in when the + /// panel's body is the app's own egui code (`PanelSpec::host_body`), and `ui`'s own style back after it. + fn hosted(&self, panel: &P, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { + if !self.specs.get(panel).is_some_and(|spec| spec.host_body) { + return run(ui); + } + let own = HostStyle::of(ui); + self.host_style.apply(ui); + let shown = run(ui); + own.apply(ui); + shown + } + fn spec(&self, panel: &P) -> PanelSpec { spec_in(self.specs, panel) } @@ -463,6 +479,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { let DockArea { label, mut workspace, specs, panels, config, hide, maximized, auto_collapse, locked, mut flyout, rail_footer, top_inset } = self; let ctx = ui.ctx().clone(); + let host_style = HostStyle::of(ui); let (rtl, window) = { let env = Env::of(ui); (env.direction.is_rtl(), env.get::().0.map(|shell| shell.window().clone())) @@ -521,6 +538,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { rtl, rail_footer: rail_footer.as_ref(), top_inset, + host_style: &host_style, }; let mut result = show_area(ui, body, &input, rights, &mut *panels, flyout.as_mut()); for edit in &result.edit { @@ -625,6 +643,7 @@ struct Input<'i, P> { rtl: bool, rail_footer: Option<&'i P>, top_inset: f32, + host_style: &'i HostStyle, } /// `bounds` without its top `inset` points, never past its bottom. @@ -655,7 +674,8 @@ fn show_area( panels: &mut dyn DockPanels

, mut flyout: Option<&mut Bind<'_, Option

>>, ) -> Passed

{ - let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, sizes, rtl, rail_footer, top_inset } = *input; + let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, sizes, rtl, rail_footer, top_inset, host_style } = + *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected()); @@ -680,6 +700,7 @@ fn show_area( rtl, floated: current.floated(), rail_footer, + host_style, }; let open = open_of(&mut flyout, body, &memory); let mut pass = Pass { @@ -1018,7 +1039,7 @@ impl Pass<'_, P> { // column bar, as the references' toolbar: the host's view takes the room under it. let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 }; if let GroupAt::Measure(_) = at - && let Some(height) = self.panels.group_view(members, active, ui, at, body) + && let Some(height) = scene.hosted(&members[active], ui, |ui| self.panels.group_view(members, active, ui, at, body)) { return Some(height + grip); } @@ -1062,7 +1083,7 @@ impl Pass<'_, P> { let words = &words; let GroupParts { titles, hosted, states } = parts_of(); let mut group = DockGroup::new(anchor.clone(), titles.clone(), PanelKey::of(&members[at])) - .extra(move |ui, body| panels.borrow_mut().group_header(members, at, ui, body)) + .extra(move |ui, body| scene.hosted(&members[at], ui, |ui| panels.borrow_mut().group_header(members, at, ui, body))) .dock(self.dock) .zones(scene.config.zone_rule()) .movable(scene.permissions(shown).movable) @@ -1079,7 +1100,7 @@ impl Pass<'_, P> { group = group.pad(Pad::Regular); } if spec.footer { - group = group.footer(move |ui, body| panels.borrow_mut().footer(&members[at], ui, body)); + group = group.footer(move |ui, body| scene.hosted(&members[at], ui, |ui| panels.borrow_mut().footer(&members[at], ui, body))); } if scene.config.tab_close_buttons { group = group.closable(); @@ -1094,7 +1115,8 @@ impl Pass<'_, P> { }; let rect = match at { GroupAt::Measure(width) => { - let measured = make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(&panels, shown, ui, body)); + let measured = + make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(scene, &panels, shown, ui, body)); return Some(measured.y); } GroupAt::Show(rect) => rect, @@ -1108,10 +1130,12 @@ impl Pass<'_, P> { let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { // The view is a layout room of its own: a view that fills takes the whole group. - let taken = in_room(ui, view, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)); + let taken = in_room(ui, view, |ui| { + scene.hosted(&members[active], ui, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)) + }); match taken { Some(_) => None, - None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output), + None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(scene, &panels, shown, ui, body)).output), } }) .inner; @@ -1128,7 +1152,7 @@ impl Pass<'_, P> { let at = members.iter().position(|member| member == panel).unwrap_or(active); let room = Vec2::new(rect.width(), scene.space.content_room()); let measured = make(at, false).id(output.response.id).measure_in(ui, Proposal::Size(room), |ui, body| { - panel_body(&panels, &members[at], ui, body); + panel_body(scene, &panels, &members[at], ui, body); }); Vec2::new(rect.width(), measured.y) }; @@ -1321,7 +1345,10 @@ impl Pass<'_, P> { .pad(Pad::None) .footer(|ui, _| { // Compact rail controls leave room for the scrolling panel icons in short windows. - Stack::new().fill_width().gap(Gap::None).show(ui, |ui, body| pass.borrow_mut().panels.rail_footer(panel, ui, body)); + Stack::new() + .fill_width() + .gap(Gap::None) + .show(ui, |ui, body| scene.hosted(panel, ui, |ui| pass.borrow_mut().panels.rail_footer(panel, ui, body))); }) .show_at(ui, cell, |ui, _| { // design: allow[contract/allocate](the rail lays its icons out in a rect of its own: the panel body claims their height, so the host's footer sits under them) @@ -1700,9 +1727,16 @@ fn window_edit( } } -/// Shows `panel`'s body in a group's body. It runs every pass the group shows; the host memoizes inside it. -fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { - panels.borrow_mut().body(panel, ui, body); +/// Shows `panel`'s body in a group's body, in the host's style where the body is the app's own egui code +/// (`Scene::hosted`). It runs every pass the group shows; the host memoizes inside it. +fn panel_body<'p, P: Clone + Eq + Hash>( + scene: &Scene<'_, P>, + panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, + panel: &P, + ui: &mut Ui, + body: &mut BodyCx<'_>, +) { + scene.hosted(panel, ui, |ui| panels.borrow_mut().body(panel, ui, body)); } /// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to, with diff --git a/crates/ui-patterns/tests/it/docking/host_body.rs b/crates/ui-patterns/tests/it/docking/host_body.rs new file mode 100644 index 0000000000..1f9368c207 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/host_body.rs @@ -0,0 +1,57 @@ +//! A panel whose body is the app's own egui code (`PanelSpec::host_body`) lays out with the style of the `Ui` the dock +//! was shown in; any other body keeps the group's spacing. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::{Fixture, trial}; +use egui::{Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +/// The app's own egui panel; the other is a plain panel. +const HOSTED: usize = 0; + +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + let spec = PanelSpec::new(format!("Panel {panel}")); + if *panel == HOSTED { spec.host_body() } else { spec } + } +} + +/// Records the item spacing each body's `Ui` has, by panel. +struct Panels { + seen: Rc; 2]>>, +} + +impl DockPanels for Panels { + fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + self.seen.borrow_mut()[*panel] = Some(ui.spacing().item_spacing); + } +} + +#[trial] +fn a_host_body_lays_out_with_the_style_outside_the_dock_and_other_bodies_keep_the_groups() { + let seen = Rc::new(RefCell::new([None; 2])); + let outside = Rc::new(RefCell::new(None)); + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (Panels { seen: seen.clone() }, Tracked::new(Specs)); + let outer = outside.clone(); + let mut fixture = Fixture::new(move |ui| { + *outer.borrow_mut() = Some(ui.spacing().item_spacing); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + let outside = outside.borrow().expect("the dock was shown"); + let [hosted, plain] = *seen.borrow(); + assert_eq!(hosted, Some(outside), "the app's own egui body lays out as it does outside the dock"); + let plain = plain.expect("the plain body was shown"); + assert_ne!(plain, outside, "a framework body keeps the group's spacing"); +} diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 17d129e898..41092c294c 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -23,6 +23,7 @@ pub(crate) mod hidden; pub(crate) mod columns; pub(crate) mod dock_back; pub(crate) mod group_view; +pub(crate) mod host_body; pub(crate) mod workspace_dialogs; pub(crate) mod native; diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 95238f40c4..dc7b81b13d 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -155,6 +155,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | F6 | F6 and Shift+F6 move between panes and never reach egui. They are the defaults of the commands `window.nextPane` and `window.previousPane` (`NavCommand`): a default chord that another command binds is that command's, and the overrides move or unbind them (`CommandInput::overrides`). An app whose own shortcut table keeps F6 unbinds them there. | | Escape | Plain Escape (Alt and Shift may be held) goes to the focused framework stop and its scopes; with no framework stop focused, it goes to the window as `Intent::Cancel`. It reaches egui only while an app's own widget has the focus (below). An Escape the runtime takes outside a captured framework press also ends egui's own drag in that pass, as egui's Escape does. | | F10, Alt+letter | Taken while a framework menu bar is registered: F10 (`window.focusMenuBar`, bound and yielded as F6 is) focuses the bar, Alt+letter opens a menu (not on macOS). | +| Claimed chords | The chords the app's canvas claims (`KeyUse::CANVAS.with_claims(..)` in `host_canvas`) stay in egui's input for it while it has the focus and, with nothing focused, while it is the window's key target; no command fires with them. On Windows and Linux, Alt+numpad code entry takes every other Alt+digit (egui reports keypad and top-row digits alike), so an app's Alt+digit shortcut works only when its canvas claims the chord. | | Edit chords | Taken while a framework editor is focused. With nothing focused, the edit chords and egui's copy, cut and paste events of the commands in the window canvas's edit set (`KeyUse::edits`, `host_canvas`) stay in egui's input for it, and no command fires with them. Otherwise egui's copy, cut and paste events become the ⌘C/X/V chord for the app's commands, unless an app's own widget has the focus (below). While egui holds a label text selection, copy and cut stay egui's, and egui copies the selection. | | IME | Taken while a framework editor owns the IME: its events and `PlatformOutput.ime` are the runtime's. Otherwise they stay egui's, for the app's own `TextEdit` or IME code. | | An app's own focused widget | While egui focus is on a widget no framework component made, or an egui popup is open, and no framework press or drag is captured, Tab, Shift+Tab, Escape and egui's clipboard events stay in egui's input for it, and the runtime routes nothing for them. While egui focus is on such a widget, the arrows and Tab move egui focus among the app's widgets as egui does; while a framework stop has the focus, egui's arrow moves are off. | @@ -164,6 +165,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Zoom keys | egui's keyboard zoom is off. The interface scale is `RootEnv::scale`. | | Quit shortcuts | egui's quit shortcuts are cleared. Quit goes through the close path. | | Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). | +| Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. | | Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu and goes no further. After an OS resize of the window, the held pointer is released. | The window's keys are the ones the runtime routes to no component: an Escape or a plain Enter while no framework stop is focused, and the arrows' nudge. `with_window_intents` offers them to its closure while nothing has framework focus. The closure takes what it handles (`Intents::take(Intent::Cancel)`; `Intent` and the other types `Intents` reads are in `ui::runtime::keys`) and returns whether it took anything; the rest stays for later readers. A framework scope that ran earlier in the pass takes them first (an open dialog takes the Escape that closes it), so the app reads them last in its UI to see what no component took. App code that read `Key::Escape`, `Key::Tab`, F6 or F10 from egui while none of its own widgets had focus reads these intents and `FrameOutput::chrome_toggles` instead; its own focused widgets and popups keep reading Tab and Escape from egui. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index e1716ceefa..a1b478e07a 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -56,7 +56,7 @@ The host keeps its panels' specs in a plain-data model that implements `PanelSpe | Method | Does | | --- | --- | -| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`. | +| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`, `host_body`. | | `permissions` | The panel's `Permissions` (default `ALL`). | The area reads them only when the model's revision, the workspace's revision or the lock changes (`runtime::derived`), and keeps what it read otherwise, so an idle pass reads no spec. A host changes a label or a limit by editing the model. A spec reads no style: a tool rail's grid is `DockGrid::rail(cells)`, which the dock sizes from its own tokens. @@ -70,6 +70,8 @@ The host implements `DockPanels

` for the views: | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | +A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports. + The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply. From 1b0ffe1ada4d1e5957739d10e316f987c169e812 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 00:31:19 +0000 Subject: [PATCH 02/13] Hosted egui apps on next: dock tabs keep key focus, floats stack with app windows, host bodies keep the app's background - A pointer press on a dock's panel tab (a click, a drag's press, the tab menu's secondary press) leaves key focus where it was (`TabStrip::keeps_focus`), so an app's own shortcuts keep working after a tab drag or the tab menu; Tab still reaches the tabs. A press on a `host_body` panel's body is the app's and no longer focuses the group's tabs. - Floating windows leave the overlay's `set_layer_order` list and stack in egui's own area order, which raises a layer when it first shows and when it is pressed: an app's own egui dialog opened over a floating panel shows above it. - A `host_body` panel's body is filled with the host style's panel fill (`HostStyle::paint_panel`) and gets no body padding, as it showed outside the dock. - Trials: tab presses keep focus, float order against an app window, the host body's fill and room, and an unbound F6 reaching a hosted canvas (alone, and in a dock of host_body panels). --- crates/ui-contract/src/runtime/egui/style.rs | 6 ++ crates/ui-contract/src/runtime/overlay.rs | 10 ++- .../src/testing/host_key_trials.rs | 35 +++++++- crates/ui-panels/src/docking/group.rs | 14 ++- crates/ui-patterns/src/patterns/dock/area.rs | 11 ++- .../tests/it/docking/float_order.rs | 54 ++++++++++++ .../ui-patterns/tests/it/docking/host_body.rs | 30 +++++-- .../ui-patterns/tests/it/docking/host_keys.rs | 86 ++++++++++++++++++ crates/ui-patterns/tests/it/docking/mod.rs | 3 + .../tests/it/docking/panel_menu.rs | 10 ++- .../ui-patterns/tests/it/docking/tab_focus.rs | 88 +++++++++++++++++++ crates/ui-widgets/src/tabs/strip.rs | 8 ++ docs/ui-docking.md | 4 +- 13 files changed, 338 insertions(+), 21 deletions(-) create mode 100644 crates/ui-patterns/tests/it/docking/float_order.rs create mode 100644 crates/ui-patterns/tests/it/docking/host_keys.rs create mode 100644 crates/ui-patterns/tests/it/docking/tab_focus.rs diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index b4d095956e..ae59c526c6 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -81,4 +81,10 @@ impl HostStyle { pub fn apply(&self, ui: &mut Ui) { ui.set_style(Arc::clone(&self.0)); } + + /// Fills `rect` on `ui` with the kept style's panel fill (`Visuals::panel_fill`), as an egui panel of the app paints + /// its background: the app's own code shown in a framework region keeps the background it has outside it. + pub fn paint_panel(&self, ui: &Ui, rect: egui::Rect) { + ui.painter().rect_filled(rect, 0.0, self.0.visuals.panel_fill); + } } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index a3af205bb7..2c1373dae6 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -810,8 +810,8 @@ fn families(entries: &[OpenEntry], raised: &IdMap) -> Vec> { groups.into_iter().map(|(_, members)| members).collect() } -/// The end hook: raises the families that appeared or were pressed, hands egui the whole order, and records the -/// open-modal fact. +/// The end hook: raises the families that appeared or were pressed, hands egui the order of every layer above the +/// floating windows (which keep egui's own area order), and records the open-modal fact. pub(crate) fn end_pass(ctx: &Context) { let viewport = pass::current_viewport(ctx); let (current, last_ids) = with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::>())); @@ -849,7 +849,11 @@ pub(crate) fn end_pass(ctx: &Context) { persist.stack.clear(); for members in &families { for member in members { - if !member.window { + // A floating window or panel (`Rank::Window`) is left to egui's own area order, which raises a layer + // when it first shows and when it is pressed: the app's own egui windows stack with it in that one + // order, so a dialog the app opens later shows above it. Listed layers would go above every unlisted + // layer of their egui order. An OS window has no egui layer here. + if !member.window && member.rank != Rank::Window { order.extend(member.cover); order.push(member.layer); } diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 587ae5d007..13574fc395 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -521,17 +521,22 @@ fn a_pasted_image_runs_the_paste_a_pasted_text_runs() { /// What an F6 press did under `overrides`: whether it reached egui, and the ids of the commands it fired. fn f6_under(overrides: Option) -> (bool, Vec) { - let (host, mut show) = host_window(); + let (host, show) = host_window(); + f6_in(&host, show, overrides) +} + +/// What an F6 press did under `overrides` in the window `show` draws, whose host records what reached egui in `host`. +fn f6_in(host: &RefCell, mut show: impl FnMut(&mut Ui), overrides: Option) -> (bool, Vec) { let mut frames = Frames::new(); if let Some(overrides) = overrides { frames.commands(CommandInput::new().overrides(Arc::new(overrides))); } frames.frame(Vec::new(), &mut show); take_output(&frames.ctx); - seen(&host); + seen(host); press_key(&mut frames, &mut show, Key::F6); let fired = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect(); - (seen(&host).0.contains(&Key::F6), fired) + (seen(host).0.contains(&Key::F6), fired) } #[trial] @@ -545,6 +550,30 @@ fn an_app_binding_on_f6_beats_the_pane_move() { assert_eq!(f6_under(Some(unbound)), (true, Vec::new()), "with the pane move unbound, F6 is egui's"); } +/// The Alt+digit chords the hosted canvas of `an_unbound_f6_reaches_a_host_canvas_with_claims` claims. +const CANVAS_CLAIMS: [craft_keymap::Chord; 2] = [ + craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num1), + craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num2), +]; + +/// A hosted app whose own egui canvas is the window's key target, with Tab, the edit chords and Alt+digit claims kept +/// (SoundCraft's session view), and whose shortcut table uses F6: with both pane moves unbound, F6 reaches egui. +#[trial] +fn an_unbound_f6_reaches_a_host_canvas_with_claims() { + const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(&CANVAS_CLAIMS); + let canvas = named_id("host canvas"); + let (host, mut base) = host_window(); + let show = move |ui: &mut Ui| { + base(ui); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KEYS); + }; + let mut unbound = craft_keymap::Overrides::default(); + unbound.insert(NavCommand::NextPane.id(), Vec::new()); + unbound.insert(NavCommand::PreviousPane.id(), Vec::new()); + assert_eq!(f6_in(&host, show, Some(unbound)), (true, Vec::new()), "the canvas's app reads F6 from egui"); +} + /// The panes the pane trials show, in order: the scope's name, its stop and its label. const PANES: [(&str, &str, &str); 2] = [("left pane", "left", "Left"), ("right pane", "right", "Right")]; diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 60581b8e3f..182dc3c2dc 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -361,6 +361,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// sides take no drop, and its top, bottom and middle zones reach across them. #[prop(flag)] in_window: bool, + /// The shown panel's body is the app's own egui code (`PanelSpec::host_body`): a press on the body is the app's, + /// and its widgets take egui focus themselves, so the press does not focus the group's tabs. + #[prop(flag)] + host_body: bool, /// The rows of the group menu, read while it is open: the panel menu button and a context request on a tab open /// it. #[prop(func = "FnMut() -> Vec")] @@ -403,6 +407,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< dock: None, zones: ZoneRule::Fraction, in_window: false, + host_body: false, menu: None, panel_menu_shown: true, command_states: Vec::new(), @@ -671,8 +676,11 @@ impl Container for }) .inner; self.extra = extra; - // A press on the group's empty body focuses its panel, as in Photoshop. - if surface_pressed && let Some(strip) = strip { + // A press on the group's empty body focuses its panel, as in Photoshop; an app's own egui body keeps its presses. + if surface_pressed + && !self.host_body + && let Some(strip) = strip + { focus::request(ui.ctx(), FocusTarget::Id(strip)); } let size = self.size; @@ -762,8 +770,10 @@ fn tab_row(row: &mu let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); let closes = |panel: &PanelTitle| closable && panel.closable; let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; + // A press on a panel tab leaves key focus where it is, as in Photoshop: the document's keys keep working. let mut strip = TabStrip::new(name) .kind(kind) + .keeps_focus() .shown(active) .tear_off() .natural_height(true) diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index d5c3844121..60d7704687 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1096,9 +1096,13 @@ impl Pass<'_, P> { let spec = scene.spec(&members[at]); if minimized { group = group.minimized(); - } else if !document(&spec) { + } else if !document(&spec) && !spec.host_body { + // The app's own egui body lays out in the whole body, as it did outside the dock. group = group.pad(Pad::Regular); } + if spec.host_body { + group = group.host_body(); + } if spec.footer { group = group.footer(move |ui, body| scene.hosted(&members[at], ui, |ui| panels.borrow_mut().footer(&members[at], ui, body))); } @@ -1736,6 +1740,11 @@ fn panel_body<'p, P: Clone + Eq + Hash>( ui: &mut Ui, body: &mut BodyCx<'_>, ) { + // The app's own egui body keeps its background: the host's panel fill over the group's surface, as it showed + // outside the dock. A measuring run paints nothing. + if scene.spec(panel).host_body && !crate::runtime::measure::active(ui.ctx()) { + scene.host_style.paint_panel(ui, ui.max_rect()); + } scene.hosted(panel, ui, |ui| panels.borrow_mut().body(panel, ui, body)); } diff --git a/crates/ui-patterns/tests/it/docking/float_order.rs b/crates/ui-patterns/tests/it/docking/float_order.rs new file mode 100644 index 0000000000..07a6651ca6 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/float_order.rs @@ -0,0 +1,54 @@ +//! A dock's floating windows stack with the app's own egui windows in egui's area order: the window shown or pressed +//! last is on top, so a dialog the app opens over a floating panel shows above it. + +use super::Numbered; +use craft_behavior::dock::{Floating, Layout, Node, Workspace}; +use craft_ui::contract::{Bind, BodyCx, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::Cell; +use std::rc::Rc; +use std::sync::Arc; + +const WINDOW_AT: Rect = Rect { min: Pos2::new(130.0, 90.0), max: Pos2::new(330.0, 210.0) }; +/// The app's dialog: it covers the floating window's right part. +const DIALOG_AT: Pos2 = Pos2::new(220.0, 120.0); +/// Inside both the floating window and the dialog. +const BOTH: Pos2 = Pos2::new(260.0, 170.0); +/// Inside the floating window only. +const WINDOW_ONLY: Pos2 = Pos2::new(160.0, 190.0); + +struct Panels; + +impl DockPanels for Panels { + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} +} + +#[trial] +fn an_app_dialog_opened_over_a_floating_window_shows_above_it_until_the_window_is_pressed() { + let layout = Layout::new(Some(Node::tabs(vec![1], 0)), vec![Floating::single(100, vec![2], 0, WINDOW_AT)]); + let mut workspace = Arc::new(Workspace::new(layout)); + let dialog = Rc::new(Cell::new(false)); + let shows = Rc::clone(&dialog); + let specs = Tracked::new(Numbered); + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); + if shows.get() { + egui::Window::new("App dialog").fixed_pos(DIALOG_AT).fixed_size(Vec2::new(300.0, 200.0)).collapsible(false).show(ui.ctx(), |ui| { + ui.label("Dialog"); + }); + } + }); + fixture.room(Vec2::new(800.0, 600.0)).settle(); + let float = fixture.ctx().layer_id_at(BOTH).expect("the floating window shows"); + dialog.set(true); + fixture.settle(); + let top = fixture.ctx().layer_id_at(BOTH).expect("a layer shows there"); + assert_ne!(top, float, "the dialog the app opened last is above the floating window"); + assert_eq!(fixture.ctx().layer_id_at(WINDOW_ONLY), Some(float), "the floating window still shows beside the dialog"); + fixture.frame(vec![moved(WINDOW_ONLY)]).frame(vec![press(WINDOW_ONLY)]).frame(vec![release(WINDOW_ONLY)]).settle(); + assert_eq!(fixture.ctx().layer_id_at(BOTH), Some(float), "a press raises the floating window above the dialog"); +} diff --git a/crates/ui-patterns/tests/it/docking/host_body.rs b/crates/ui-patterns/tests/it/docking/host_body.rs index 1f9368c207..2cb67a0115 100644 --- a/crates/ui-patterns/tests/it/docking/host_body.rs +++ b/crates/ui-patterns/tests/it/docking/host_body.rs @@ -1,5 +1,6 @@ //! A panel whose body is the app's own egui code (`PanelSpec::host_body`) lays out with the style of the `Ui` the dock -//! was shown in; any other body keeps the group's spacing. +//! was shown in, on that style's panel fill and without the group's body padding; any other body keeps the group's +//! spacing, padding and surface. use craft_behavior::Axis; use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; @@ -7,7 +8,7 @@ use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; -use egui::{Ui, Vec2}; +use egui::{Color32, Rect, Shape, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; @@ -25,14 +26,17 @@ impl PanelSpecs for Specs { } } -/// Records the item spacing each body's `Ui` has, by panel. +/// The app's panel fill, which no theme surface has. +const APP_FILL: Color32 = Color32::from_rgb(3, 140, 7); + +/// Records the item spacing and the room each body's `Ui` has, by panel. struct Panels { - seen: Rc; 2]>>, + seen: Rc; 2]>>, } impl DockPanels for Panels { fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { - self.seen.borrow_mut()[*panel] = Some(ui.spacing().item_spacing); + self.seen.borrow_mut()[*panel] = Some((ui.spacing().item_spacing, ui.max_rect())); } } @@ -45,13 +49,25 @@ fn a_host_body_lays_out_with_the_style_outside_the_dock_and_other_bodies_keep_th let (mut panels, specs) = (Panels { seen: seen.clone() }, Tracked::new(Specs)); let outer = outside.clone(); let mut fixture = Fixture::new(move |ui| { + ui.visuals_mut().panel_fill = APP_FILL; *outer.borrow_mut() = Some(ui.spacing().item_spacing); DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(1200.0, 600.0)).settle(); + fixture.record_paint().frame(Vec::new()); let outside = outside.borrow().expect("the dock was shown"); let [hosted, plain] = *seen.borrow(); - assert_eq!(hosted, Some(outside), "the app's own egui body lays out as it does outside the dock"); - let plain = plain.expect("the plain body was shown"); + let (hosted, hosted_room) = hosted.expect("the hosted body was shown"); + let (plain, plain_room) = plain.expect("the plain body was shown"); + assert_eq!(hosted, outside, "the app's own egui body lays out as it does outside the dock"); assert_ne!(plain, outside, "a framework body keeps the group's spacing"); + assert!(hosted_room.width() > plain_room.width(), "the app's body has the group's whole width, a framework body its padding less"); + + let mut paint = fixture.take_paint().expect("the frame recorded its paint"); + paint.textures_delta.clear(); + let filled = |room: Rect| { + paint.shapes.iter().any(|clipped| matches!(&clipped.shape, Shape::Rect(rect) if rect.fill == APP_FILL && rect.rect.contains(room.center()))) + }; + assert!(filled(hosted_room), "the app's body shows on the app's panel fill"); + assert!(!filled(plain_room), "a framework body keeps the theme's surface"); } diff --git a/crates/ui-patterns/tests/it/docking/host_keys.rs b/crates/ui-patterns/tests/it/docking/host_keys.rs new file mode 100644 index 0000000000..d113aca13c --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/host_keys.rs @@ -0,0 +1,86 @@ +//! An app that hosts its own egui UI in the dock: its canvas is a group the host draws (`group_view`) and the window's +//! key target, and its other panels are its own egui code (`PanelSpec::host_body`). Keys its shortcut table reads reach +//! egui's input. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_keymap::{Chord, Key as KeyChord, Mods, Overrides}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::commands::{CommandSet as _, NavCommand}; +use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse, host_canvas}; +use craft_ui::testing::input::{key_press, key_reached}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Id, Key, Modifiers, Sense, Ui, Vec2}; +use std::cell::Cell; +use std::rc::Rc; +use std::sync::Arc; + +/// Panel 0 is the app's canvas; panels 1 and 2 are its own egui panels. +const CANVAS: usize = 0; + +/// The Alt+digit chords the canvas claims. +const CLAIMS: [Chord; 2] = [Chord::new(Mods::ALT, KeyChord::Num1), Chord::new(Mods::ALT, KeyChord::Num2)]; + +/// The canvas's keys: Tab, the edit chords and its Alt+digit claims stay in egui's input for the app. +const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(&CLAIMS); + +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + let spec = PanelSpec::new(format!("Panel {panel}")).host_body(); + if *panel == CANVAS { spec.canvas() } else { spec } + } +} + +/// The app's panels; `f6` records whether an F6 press reached egui's input in a pass the canvas ran in. +struct Panels { + f6: Rc>, +} + +impl DockPanels for Panels { + fn body(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + ui.label("rows"); + } + + fn group_view(&mut self, panels: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if !panels.contains(&CANVAS) { + return None; + } + let GroupAt::Show(rect) = at else { return Some(0.0) }; + let id = Id::unique("app canvas"); + ui.interact(rect, id, Sense::click_and_drag()); + host_canvas(ui.ctx(), id, KEYS); + if key_reached(ui.ctx(), Key::F6) { + self.f6.set(true); + } + Some(rect.height()) + } +} + +/// With both pane moves unbound, F6 reaches the app's canvas in a dock of `host_body` panels. +#[trial] +fn an_unbound_f6_reaches_a_hosted_canvas_in_the_dock() { + let f6 = Rc::new(Cell::new(false)); + let root = Node::split( + Axis::X, + SplitSize::Ratio(0.25), + Node::tabs(vec![1], 0), + Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), Node::tabs(vec![2], 0)), + ); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (Panels { f6: f6.clone() }, Tracked::new(Specs)); + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + }); + let mut unbound = Overrides::default(); + unbound.insert(NavCommand::NextPane.id(), Vec::new()); + unbound.insert(NavCommand::PreviousPane.id(), Vec::new()); + fixture.overrides(Arc::new(unbound)).room(Vec2::new(1200.0, 600.0)).settle(); + f6.set(false); + fixture.frame(vec![key_press(Key::F6, Modifiers::NONE)]); + assert!(f6.get(), "the app reads F6 from egui"); +} diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 41092c294c..fc30a9bab6 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -15,6 +15,7 @@ pub(crate) mod drop; pub(crate) mod drop_preview; pub(crate) mod drop_session; +pub(crate) mod float_order; pub(crate) mod floating; pub(crate) mod floating_area; pub(crate) mod floating_rail; @@ -24,6 +25,8 @@ pub(crate) mod columns; pub(crate) mod dock_back; pub(crate) mod group_view; pub(crate) mod host_body; +pub(crate) mod host_keys; +pub(crate) mod tab_focus; pub(crate) mod workspace_dialogs; pub(crate) mod native; diff --git a/crates/ui-patterns/tests/it/docking/panel_menu.rs b/crates/ui-patterns/tests/it/docking/panel_menu.rs index b3b76895e2..80f7f648d6 100644 --- a/crates/ui-patterns/tests/it/docking/panel_menu.rs +++ b/crates/ui-patterns/tests/it/docking/panel_menu.rs @@ -47,8 +47,9 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { *held.borrow_mut() = shown; }); fixture.room(Vec2::new(1200.0, 600.0)).settle(); - let first = fixture.by_label("Panel 0").expect("the first group's tab"); - fixture.click(&first).idle(1); + // Tab from nothing focuses the first group's tabs; a click on a tab leaves focus where it is. + fixture.key(Key::Tab, Modifiers::NONE).idle(1); + assert!(fixture.focused_stop().is_some(), "Tab focused the first group's tabs"); let buttons: Vec<_> = fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Panel Menu")).collect(); assert_eq!(buttons.len(), 2, "each group shows its panel menu button"); @@ -71,8 +72,9 @@ fn tab_reaches_the_tabs_then_the_drag_band_then_the_panel_menu_button() { DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(800.0, 600.0)).settle(); - let tab = fixture.by_label("Panel 0").expect("the group's tab"); - fixture.click(&tab).idle(1); + // Tab from nothing reaches the tabs first. + fixture.key(Key::Tab, Modifiers::NONE).idle(1); + assert!(fixture.focused_stop().is_some(), "Tab focused the tabs"); let mut parts = Vec::new(); for _ in 0..2 { fixture.key(Key::Tab, Modifiers::NONE).idle(1); diff --git a/crates/ui-patterns/tests/it/docking/tab_focus.rs b/crates/ui-patterns/tests/it/docking/tab_focus.rs new file mode 100644 index 0000000000..c4c21d266d --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/tab_focus.rs @@ -0,0 +1,88 @@ +//! A pointer press on a dock's panel tab leaves key focus where it was, so a hosted app's own shortcuts keep working +//! after a tab click, a tab drag or the tab menu; a press on an app's own egui body is the app's. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::{Fixture, trial}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +/// Panel 2's body is the app's own egui code; panels 0 and 1 are plain panels in the other group. +const HOSTED: usize = 2; + +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + let spec = PanelSpec::new(format!("Panel {panel}")); + if *panel == HOSTED { spec.host_body() } else { spec } + } +} + +struct Panels; + +impl DockPanels for Panels { + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} +} + +/// A dock of the plain group [0, 1] beside the hosted group [2], and the workspace it edits. +fn dock() -> (Fixture, Rc>>>) { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![HOSTED], 0)); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs)); + let mut fixture = Fixture::new(move |ui| { + let mut shown = held.borrow().clone(); + DockArea::new("Dock", Bind::bound(&mut shown), &specs, &mut Panels, DockConfig::default()).show(ui); + *held.borrow_mut() = shown; + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + (fixture, workspace) +} + +/// A secondary press and release at `at`, then an idle frame. +fn secondary_click(fixture: &mut Fixture, at: Pos2) { + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + fixture.frame(vec![moved(at)]).frame(vec![button(true)]).frame(vec![button(false)]).idle(1); +} + +#[trial] +fn a_press_on_a_panel_tab_leaves_key_focus_where_it_was() { + let (mut fixture, workspace) = dock(); + let tab = fixture.by_label("Panel 1").expect("the first group's second tab"); + fixture.click(&tab).idle(1); + let shows_one = + matches!(workspace.borrow().layout().root.as_ref(), Some(Node::Split { first, .. }) if matches!(&**first, Node::Tabs { active: 1, .. })); + assert!(shows_one, "the click shows panel 1"); + assert!(fixture.focused_stop().is_none(), "a click on a tab takes no key focus"); + + let tab = fixture.by_label("Panel 1").expect("the tab to drag"); + let hosted = fixture.by_label("Panel 2").expect("the hosted group's tab").rect; + let by = Pos2::new(hosted.center().x, hosted.bottom() + 100.0) - tab.center(); + fixture.drag(&tab, by).idle(2); + assert!(fixture.focused_stop().is_none(), "a tab drag takes no key focus"); + + let tab = fixture.by_label("Panel 0").expect("a tab for the menu"); + secondary_click(&mut fixture, tab.center()); + assert!(fixture.by_label("Float").is_some(), "the tab menu opened"); + fixture.key(Key::Escape, Modifiers::NONE).idle(2); + assert!(fixture.by_label("Float").is_none(), "Escape closed the menu"); + assert!(fixture.focused_stop().is_none(), "with the tab menu closed, no key focus is left behind"); +} + +#[trial] +fn a_press_on_an_app_body_is_the_apps_and_one_on_a_plain_body_focuses_its_panel() { + let (mut fixture, _) = dock(); + let hosted = fixture.by_label("Panel 2").expect("the hosted group's tab").rect; + fixture.click_at(Pos2::new(hosted.center().x, hosted.bottom() + 200.0)).idle(1); + assert!(fixture.focused_stop().is_none(), "a press on the app's own body takes no framework focus"); + let plain = fixture.by_label("Panel 0").expect("the plain group's tab").rect; + fixture.click_at(Pos2::new(plain.center().x, plain.bottom() + 200.0)).idle(1); + assert!(fixture.focused_stop().is_some(), "a press on a framework panel's empty body focuses its panel"); +} diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 69b493a597..be0ae33c01 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -600,6 +600,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri .label(label) } + /// A pointer press on a tab (primary or secondary, a drag's press too) leaves key focus where it is; the keyboard + /// still reaches the strip by Tab. A dock's panel tabs: clicking one leaves the document's keys working. + #[must_use] + pub fn keeps_focus(mut self) -> Self { + self.items = self.items.focus_on_press(false); + self + } + /// A tab drag carries `map` of it, for the drop targets of type `P`; a tab the map gives `None` for does not drag /// unless a reorder rule is set. The drag stays one session with one ghost. #[must_use] diff --git a/docs/ui-docking.md b/docs/ui-docking.md index a1b478e07a..44073a3047 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -70,7 +70,7 @@ The host implements `DockPanels

` for the views: | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | -A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports. +A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. Its body also keeps the app's background and room: the dock fills the body with that style's panel fill (`Visuals::panel_fill`) and gives it no body padding, and a press on the body is the app's, so it does not focus the group's tabs. The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports. The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. @@ -121,6 +121,8 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. +- A pointer press on a panel tab (a click, a drag's press, the tab menu's secondary press) leaves key focus where it was, so the document's keys keep working; Tab still reaches the tab row. +- Floating windows stack with the app's own egui windows in egui's area order: the one shown or pressed last is on top, so a dialog the app opens over a floating panel shows above it. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. ## Commands and workspaces From 48e798653c9ef61c251b35af84081884990d3375 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 00:40:10 +0000 Subject: [PATCH 03/13] HostStyle moves to primitives: the dock pattern reaches the host style through the contract - primitives::HostStyle keeps an app's own egui style and runs its code with it (run) on its panel fill (paint_panel); runtime::egui::style keeps the adapter's style_of and set_style, which only it and the primitive call. - The dock pattern uses the primitive; the adapter type it imported is gone. - host_body trial: a named type for what each body saw. --- crates/ui-contract/src/primitives/host.rs | 34 +++++++++++++++++++ crates/ui-contract/src/primitives/mod.rs | 2 ++ crates/ui-contract/src/runtime/egui/style.rs | 29 +++++----------- crates/ui-patterns/src/patterns/dock/area.rs | 8 ++--- .../ui-patterns/tests/it/docking/host_body.rs | 7 ++-- 5 files changed, 51 insertions(+), 29 deletions(-) create mode 100644 crates/ui-contract/src/primitives/host.rs diff --git a/crates/ui-contract/src/primitives/host.rs b/crates/ui-contract/src/primitives/host.rs new file mode 100644 index 0000000000..b3960f6caf --- /dev/null +++ b/crates/ui-contract/src/primitives/host.rs @@ -0,0 +1,34 @@ +//! `HostStyle`: an app's own egui code shown inside a framework part keeps the style and the background it has outside. + +use crate::runtime::egui::style; +use egui::{Rect, Ui}; +use std::sync::Arc; + +/// The egui style of an app's own `Ui`, kept where a framework part takes the app's egui code into a `Ui` of its own: +/// the framework's regions set their layout spacing on the `Ui`s they hand out, and app code shown in one (a dock +/// panel's body that the app draws with egui) lays out and paints as it would outside the part when it runs through +/// [`HostStyle::run`] on [`HostStyle::paint_panel`]'s background. +#[derive(Clone, Debug)] +pub struct HostStyle(Arc); + +impl HostStyle { + /// The style `ui` has now. + pub fn of(ui: &Ui) -> Self { + HostStyle(style::style_of(ui)) + } + + /// Runs `run` on `ui` with the kept style, and gives `ui` its own style back after it. + pub fn run(&self, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { + let own = style::style_of(ui); + style::set_style(ui, &self.0); + let shown = run(ui); + style::set_style(ui, &own); + shown + } + + /// Fills `rect` on `ui` with the kept style's panel fill (`Visuals::panel_fill`), as an egui panel of the app paints + /// its background. + pub fn paint_panel(&self, ui: &Ui, rect: Rect) { + ui.painter().rect_filled(rect, 0.0, self.0.visuals.panel_fill); + } +} diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 2c9c8ae7ba..09d109c718 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -9,6 +9,7 @@ mod focus_ring; #[doc(hidden)] pub mod glyph; mod handle; +mod host; mod icon; mod ime_surface; mod kit; @@ -38,6 +39,7 @@ pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; +pub use host::HostStyle; pub(crate) use icon::SvgIcon; pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub use ime_surface::ImeSurface; diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index ae59c526c6..d2a7f9dc6e 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -65,26 +65,13 @@ pub(crate) fn set_item_spacing(ui: &mut Ui, gap: egui::Vec2) { ui.spacing_mut().item_spacing = gap; } -/// The egui style of an app's own `Ui`, kept where a framework part takes the app's egui code into a `Ui` of its own: -/// the framework's regions set their layout spacing on the `Ui`s they hand out, and app code shown in one (a dock -/// panel's body that the app draws with egui) lays out as it would outside the part when the part applies this. -#[derive(Clone, Debug)] -pub struct HostStyle(Arc); +/// The egui style `ui` has now, for a framework part that shows an app's own egui code in a `Ui` of its own +/// (`primitives::HostStyle`). +pub(crate) fn style_of(ui: &Ui) -> Arc { + Arc::clone(ui.style()) +} -impl HostStyle { - /// The style `ui` has now. - pub fn of(ui: &Ui) -> Self { - HostStyle(Arc::clone(ui.style())) - } - - /// Gives `ui` the kept style. - pub fn apply(&self, ui: &mut Ui) { - ui.set_style(Arc::clone(&self.0)); - } - - /// Fills `rect` on `ui` with the kept style's panel fill (`Visuals::panel_fill`), as an egui panel of the app paints - /// its background: the app's own code shown in a framework region keeps the background it has outside it. - pub fn paint_panel(&self, ui: &Ui, rect: egui::Rect) { - ui.painter().rect_filled(rect, 0.0, self.0.visuals.panel_fill); - } +/// Gives `ui` the style `style`: an app's own egui style kept by `primitives::HostStyle`, or `ui`'s own back after it. +pub(crate) fn set_style(ui: &mut Ui, style: &Arc) { + ui.set_style(Arc::clone(style)); } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 60d7704687..32d8243f12 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -20,10 +20,10 @@ use crate::docking::{ }; use crate::layout_components::Stack; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; +use crate::primitives::HostStyle; use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within}; use crate::runtime::derived::derived; use crate::runtime::drag; -use crate::runtime::egui::style::HostStyle; use crate::runtime::env::{Env, Label, RevealEdge, ShellCx, ShellEntry, in_room}; use crate::runtime::memory::Remember as _; use crate::runtime::windows::{ResizeEdge, WindowHost}; @@ -350,11 +350,7 @@ impl Scene<'_, P> { if !self.specs.get(panel).is_some_and(|spec| spec.host_body) { return run(ui); } - let own = HostStyle::of(ui); - self.host_style.apply(ui); - let shown = run(ui); - own.apply(ui); - shown + self.host_style.run(ui, run) } fn spec(&self, panel: &P) -> PanelSpec { diff --git a/crates/ui-patterns/tests/it/docking/host_body.rs b/crates/ui-patterns/tests/it/docking/host_body.rs index 2cb67a0115..f3b6b88d09 100644 --- a/crates/ui-patterns/tests/it/docking/host_body.rs +++ b/crates/ui-patterns/tests/it/docking/host_body.rs @@ -29,9 +29,12 @@ impl PanelSpecs for Specs { /// The app's panel fill, which no theme surface has. const APP_FILL: Color32 = Color32::from_rgb(3, 140, 7); -/// Records the item spacing and the room each body's `Ui` has, by panel. +/// What a body's `Ui` had: its item spacing and its room. +type Seen = Option<(Vec2, Rect)>; + +/// Records what each body's `Ui` had, by panel. struct Panels { - seen: Rc; 2]>>, + seen: Rc>, } impl DockPanels for Panels { From 22e82c930ec7062fba45757a8cac8ba5e3cb94bc Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 00:49:06 +0000 Subject: [PATCH 04/13] Keymap: warn about shortcut overrides that name no command; framework doc names the pane and menu-bar command ids --- crates/ui-contract/src/runtime/commands/board.rs | 11 +++++++++-- docs/craft-framework.md | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 5945040d0a..e2f5b41b4b 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -16,8 +16,8 @@ use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler}; use craft_behavior::{EditCommand, KeyOwner, OwnerClass, pick_instance, resolve_flags}; use craft_keymap::{ - Active, Chord, CommandDef, CommandKind, CommandRef, Hit, KeyInput, Keymap, Layout, Matcher, ModalRule, Overrides, Platform, Press, Scopes, - Trigger, TypingRule, + Active, Chord, CommandDef, CommandKind, CommandRef, Hit, KeyInput, Keymap, Layout, Matcher, ModalRule, Overrides, Platform, Press, Problem, + Scopes, Trigger, TypingRule, }; use egui::{Context, Id, ViewportId}; use std::collections::{HashMap, HashSet}; @@ -976,6 +976,13 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor } keymap = keymap_of(joined(defs.as_slice()), scopes, platform, overrides, typing); } + // An override whose key names no command binds nothing and leaves that command's defaults in place; a misspelt id in + // an app's own table otherwise fails without a trace. + for problem in keymap.problems() { + if let Problem::UnknownCommand { key } = problem { + log::warn!("shortcut override `{key}` names no command and binds nothing"); + } + } let window_shortcuts = registry .defs() .iter() diff --git a/docs/craft-framework.md b/docs/craft-framework.md index dc7b81b13d..bda0a918ba 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -152,9 +152,9 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | What | Effect on the app's own egui code | | --- | --- | | Tab | Bare Tab moves framework focus and never reaches egui, unless the focused framework stop keeps Tab or an app's own widget has the focus (below), or nothing has the focus in a window that registered no focus stop: egui then moves its own focus into the app's widgets. A window with stops but no Tab entry (on the Mac, where Tab reaches only text fields by default) keeps the Tab from egui, which would otherwise focus framework controls the platform's rule skips. With `RootEnv::tab_toggles_chrome`, Tab toggles the chrome in a window that shows a document canvas, with nothing focused or the canvas focused, and arrives in `FrameOutput::chrome_toggles`. The canvas is a framework canvas, or the app's own egui canvas declared each pass with `ui::runtime::focus::host_canvas`. With nothing focused, the canvas is the key target: a canvas that keeps Tab (`KeyUse::CANVAS.with_keep(KeepKeys::Tab)`) gets the press in egui's input, as when it is focused, and nothing toggles. A focused canvas whose editor part keeps Tab reads Shift+Tab as `Intent::BackTab` (`EditorInput::BackTab`); no other stop gets it as an intent, and a text field keeps Shift+Tab as a focus move. | -| F6 | F6 and Shift+F6 move between panes and never reach egui. They are the defaults of the commands `window.nextPane` and `window.previousPane` (`NavCommand`): a default chord that another command binds is that command's, and the overrides move or unbind them (`CommandInput::overrides`). An app whose own shortcut table keeps F6 unbinds them there. | +| F6 | F6 and Shift+F6 move between panes and never reach egui. They are the defaults of the commands `NavCommand::NextPane` and `NavCommand::PreviousPane` (ids `window.next_pane` and `window.previous_pane`; name them by `NavCommand::NextPane.id()` in code): a default chord that another command binds is that command's, and the overrides move or unbind them (`CommandInput::overrides`). An app whose own shortcut table keeps F6 unbinds them there. | | Escape | Plain Escape (Alt and Shift may be held) goes to the focused framework stop and its scopes; with no framework stop focused, it goes to the window as `Intent::Cancel`. It reaches egui only while an app's own widget has the focus (below). An Escape the runtime takes outside a captured framework press also ends egui's own drag in that pass, as egui's Escape does. | -| F10, Alt+letter | Taken while a framework menu bar is registered: F10 (`window.focusMenuBar`, bound and yielded as F6 is) focuses the bar, Alt+letter opens a menu (not on macOS). | +| F10, Alt+letter | Taken while a framework menu bar is registered: F10 (`NavCommand::FocusMenuBar`, id `window.focus_menu_bar`, bound and yielded as F6 is) focuses the bar, Alt+letter opens a menu (not on macOS). | | Claimed chords | The chords the app's canvas claims (`KeyUse::CANVAS.with_claims(..)` in `host_canvas`) stay in egui's input for it while it has the focus and, with nothing focused, while it is the window's key target; no command fires with them. On Windows and Linux, Alt+numpad code entry takes every other Alt+digit (egui reports keypad and top-row digits alike), so an app's Alt+digit shortcut works only when its canvas claims the chord. | | Edit chords | Taken while a framework editor is focused. With nothing focused, the edit chords and egui's copy, cut and paste events of the commands in the window canvas's edit set (`KeyUse::edits`, `host_canvas`) stay in egui's input for it, and no command fires with them. Otherwise egui's copy, cut and paste events become the ⌘C/X/V chord for the app's commands, unless an app's own widget has the focus (below). While egui holds a label text selection, copy and cut stay egui's, and egui copies the selection. | | IME | Taken while a framework editor owns the IME: its events and `PlatformOutput.ime` are the runtime's. Otherwise they stay egui's, for the app's own `TextEdit` or IME code. | From 5d9f4b62cb7d62817cfa799e9451222bde7d6591 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 02:14:13 +0000 Subject: [PATCH 05/13] Hosted egui apps on next: host code runs once per pass, and the app's own modal blocks its other windows A dock panel's egui code (PanelSpec::host_body) ran in the framework's measuring runs too, so egui saw its widgets twice per pass at two rects and painted ID-clash warnings. HostStyle::show runs it in the real run only; a measuring run takes the size its last real run took. FrameInput::app_modal names the window where the app's own egui code shows a modal; the app's other windows (native floats among them) are blocked through the same path as under a framework app-modal layer. --- crates/ui-contract/src/primitives/host.rs | 48 ++++++++- crates/ui-contract/src/runtime/frame.rs | 19 +++- crates/ui-contract/src/runtime/overlay.rs | 12 ++- crates/ui-panels/src/docking/spec.rs | 3 +- crates/ui-patterns/src/patterns/dock/area.rs | 70 ++++++++---- .../ui-patterns/tests/it/docking/app_modal.rs | 81 ++++++++++++++ .../ui-patterns/tests/it/docking/host_runs.rs | 100 ++++++++++++++++++ crates/ui-patterns/tests/it/docking/mod.rs | 2 + crates/ui-test-kit/src/windows.rs | 10 +- docs/craft-framework.md | 1 + docs/ui-docking.md | 2 +- 11 files changed, 314 insertions(+), 34 deletions(-) create mode 100644 crates/ui-patterns/tests/it/docking/app_modal.rs create mode 100644 crates/ui-patterns/tests/it/docking/host_runs.rs diff --git a/crates/ui-contract/src/primitives/host.rs b/crates/ui-contract/src/primitives/host.rs index b3960f6caf..ad12a5e912 100644 --- a/crates/ui-contract/src/primitives/host.rs +++ b/crates/ui-contract/src/primitives/host.rs @@ -1,23 +1,33 @@ -//! `HostStyle`: an app's own egui code shown inside a framework part keeps the style and the background it has outside. +//! `HostStyle`: an app's own egui code shown inside a framework part keeps the style and the background it has outside, +//! and runs once per pass. -use crate::runtime::egui::style; -use egui::{Rect, Ui}; +use crate::runtime::egui::{alloc, memory, style}; +use crate::runtime::{layout_memory, measure}; +use egui::{Id, Rect, Ui, UiBuilder, Vec2}; use std::sync::Arc; /// The egui style of an app's own `Ui`, kept where a framework part takes the app's egui code into a `Ui` of its own: /// the framework's regions set their layout spacing on the `Ui`s they hand out, and app code shown in one (a dock /// panel's body that the app draws with egui) lays out and paints as it would outside the part when it runs through -/// [`HostStyle::run`] on [`HostStyle::paint_panel`]'s background. +/// [`HostStyle::show`] on [`HostStyle::paint_panel`]'s background. #[derive(Clone, Debug)] pub struct HostStyle(Arc); +/// What the last real run of the app's code under an id took and returned (`HostStyle::show`). +#[derive(Clone, Default)] +struct LastRun { + size: Option, + out: R, +} + impl HostStyle { /// The style `ui` has now. pub fn of(ui: &Ui) -> Self { HostStyle(style::style_of(ui)) } - /// Runs `run` on `ui` with the kept style, and gives `ui` its own style back after it. + /// Runs `run` on `ui` with the kept style, and gives `ui` its own style back after it. For code the framework asks + /// for a measure itself (a host view measured at a width); code a part shows goes through [`HostStyle::show`]. pub fn run(&self, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { let own = style::style_of(ui); style::set_style(ui, &self.0); @@ -26,6 +36,34 @@ impl HostStyle { shown } + /// Shows the app's code `run` in `ui` as [`HostStyle::run`] runs it, in the real run of a pass only: in a child of + /// `ui` with its layout and the rest of its room, scoped by `id`, which `ui` then takes. A measuring run + /// (`runtime::measure`) does not run it: `ui` takes the size the code took in its last real run, and the call + /// returns what that run returned (nothing and `R::default()` before the first). The app's code registers its + /// widgets with egui and acts on input, so a run in a measuring run would show egui each widget twice in one pass, + /// at two places. + pub fn show(&self, ui: &mut Ui, id: Id, run: impl FnOnce(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + if measure::active(&ctx) { + let last = memory::peek_clone::>(&ctx, id).unwrap_or_default(); + if let Some(size) = last.size { + alloc::space(ui, size); + } + return last.out; + } + let mut child = alloc::child(ui, UiBuilder::new().max_rect(ui.available_rect_before_wrap()).layout(*ui.layout()).scope_id(id)); + let out = self.run(&mut child, run); + let rect = child.min_rect(); + // The child writes its widget rect when it drops. + drop(child); + alloc::advance_past(ui, rect); + let size = rect.size(); + // A pass a kept measurement serves learns here that the code took another size since, and runs again. + layout_memory::backstop(&ctx, id, size); + memory::put(&ctx, id, LastRun { size: Some(size), out: out.clone() }); + out + } + /// Fills `rect` on `ui` with the kept style's panel fill (`Visuals::panel_fill`), as an egui panel of the app paints /// its background. pub fn paint_panel(&self, ui: &Ui, rect: Rect) { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 2476846d4b..198aca1bb6 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -32,12 +32,18 @@ pub struct FrameInput { pub host: Option>, /// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input. pub latched: Mods, + /// The window in which the app's own egui code shows a modal this frame (a dialog the app draws itself, not a + /// framework layer). It blocks the app's other windows as a framework app-modal layer open in it does: their + /// presses, keys, wheel and text go nowhere, a press there brings the modal's window forward, and they refuse to + /// close. A panel floated into a window of its own is one of them. `None` (the default) when the app shows no such + /// modal; set every frame from the app's own state. + pub app_modal: Option, } impl FrameInput { /// A frame with `root` and no host. pub fn new(root: RootEnv) -> Self { - FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE } + FrameInput { root, commands: CommandInput::new(), host: None, latched: Mods::NONE, app_modal: None } } /// Sets the command input. @@ -52,6 +58,12 @@ impl FrameInput { self } + /// Sets the window in which the app's own egui code shows a modal ([`FrameInput::app_modal`](Self::app_modal)). + pub fn app_modal(mut self, viewport: Option) -> Self { + self.app_modal = viewport; + self + } + /// Sets the host: the same `Arc` every frame, a new one to switch (see [`FrameInput::host`](Self::host)). pub fn host(mut self, host: Arc) -> Self { self.host = Some(host); @@ -420,6 +432,11 @@ pub(crate) fn root_input(ctx: &Context) -> RootInput { .unwrap_or_else(|| RootInput::of(&RootEnv::default())) } +/// The window in which the app's own egui code shows a modal this frame (`FrameInput::app_modal`). +pub(crate) fn app_modal(ctx: &Context) -> Option { + pass_state::with::(ctx, |state| state.input.as_ref().and_then(|input| input.app_modal)) +} + /// How far a press may move and still be a click, in points: the app's hit tolerances (`HitSizes::slop`). egui's own /// click options stay the app's. pub(crate) fn slop(ctx: &Context) -> f32 { diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 2c1373dae6..8e779be00c 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -976,17 +976,21 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option) { (root.is_some() || modal_in_other_viewports(ctx, viewport), root) } -/// The live viewports with a modal layer open as of their last finished pass. +/// The live viewports with a modal open: a modal layer as of their last finished pass, or the app's own egui modal +/// this frame (`FrameInput::app_modal`), which blocks the app's other windows as a modal layer does. fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { - pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal)) + let app_modal = crate::runtime::frame::app_modal(ctx); + pass::live_viewports(ctx) + .into_iter() + .filter(move |viewport| app_modal == Some(*viewport) || with_persist(ctx, *viewport, |persist| persist.modal)) } -/// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises. +/// A viewport other than `viewport` that has a modal open (`modal_viewports`): the window a blocked press raises. pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option { modal_viewports(ctx).find(|other| *other != viewport) } -/// A viewport that has a modal layer open: the window that blocks the app's other windows. +/// A viewport that has a modal open (`modal_viewports`): the window that blocks the app's other windows. pub(crate) fn app_modal_viewport(ctx: &Context) -> Option { modal_viewports(ctx).next() } diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index 9b17177a30..debf1ab95a 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -181,7 +181,8 @@ pub struct PanelSpec { pub caption: Option

{ } } +/// The parts of a group that show the host's code (`Scene::hosted`). +#[derive(Clone, Copy, Debug, Hash)] +enum HostPart { + Body, + Footer, + Header, + RailFooter, + View, +} + impl Scene<'_, P> { - /// Runs `run`, which shows host code of `panel`, on `ui`: with the style of the `Ui` the area was shown in when the - /// panel's body is the app's own egui code (`PanelSpec::host_body`), and `ui`'s own style back after it. - fn hosted(&self, panel: &P, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { - if !self.specs.get(panel).is_some_and(|spec| spec.host_body) { + /// Runs `run`, which shows host code of `panel` as its `part`, on `ui`. Where the panel's body is the app's own egui + /// code (`PanelSpec::host_body`), it runs with the style of the `Ui` the area was shown in, and only in the pass's + /// real run: a measuring run takes what its last real run took (`HostStyle::show`). + fn hosted(&self, panel: &P, part: HostPart, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { + if !self.host_body(panel) { + return run(ui); + } + self.host_style.show(ui, self.dock.with(("host", part, PanelKey::of(panel))), run) + } + + /// Runs `run`, which measures `panel`'s host view at a width (`GroupAt::Measure`), on `ui`: with the style of the + /// `Ui` the area was shown in where the panel's body is the app's own egui code. + fn hosted_measure(&self, panel: &P, ui: &mut Ui, run: impl FnOnce(&mut Ui) -> R) -> R { + if !self.host_body(panel) { return run(ui); } self.host_style.run(ui, run) } + fn host_body(&self, panel: &P) -> bool { + self.specs.get(panel).is_some_and(|spec| spec.host_body) + } + fn spec(&self, panel: &P) -> PanelSpec { spec_in(self.specs, panel) } @@ -1035,7 +1059,7 @@ impl Pass<'_, P> { // column bar, as the references' toolbar: the host's view takes the room under it. let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 }; if let GroupAt::Measure(_) = at - && let Some(height) = scene.hosted(&members[active], ui, |ui| self.panels.group_view(members, active, ui, at, body)) + && let Some(height) = scene.hosted_measure(&members[active], ui, |ui| self.panels.group_view(members, active, ui, at, body)) { return Some(height + grip); } @@ -1079,7 +1103,7 @@ impl Pass<'_, P> { let words = &words; let GroupParts { titles, hosted, states } = parts_of(); let mut group = DockGroup::new(anchor.clone(), titles.clone(), PanelKey::of(&members[at])) - .extra(move |ui, body| scene.hosted(&members[at], ui, |ui| panels.borrow_mut().group_header(members, at, ui, body))) + .extra(move |ui, body| scene.hosted(&members[at], HostPart::Header, ui, |ui| panels.borrow_mut().group_header(members, at, ui, body))) .dock(self.dock) .zones(scene.config.zone_rule()) .movable(scene.permissions(shown).movable) @@ -1100,7 +1124,9 @@ impl Pass<'_, P> { group = group.host_body(); } if spec.footer { - group = group.footer(move |ui, body| scene.hosted(&members[at], ui, |ui| panels.borrow_mut().footer(&members[at], ui, body))); + group = group.footer(move |ui, body| { + scene.hosted(&members[at], HostPart::Footer, ui, |ui| panels.borrow_mut().footer(&members[at], ui, body)) + }); } if scene.config.tab_close_buttons { group = group.closable(); @@ -1131,7 +1157,9 @@ impl Pass<'_, P> { .scope_builder(UiBuilder::new().max_rect(rect), |ui| { // The view is a layout room of its own: a view that fills takes the whole group. let taken = in_room(ui, view, |ui| { - scene.hosted(&members[active], ui, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)) + scene.hosted(&members[active], HostPart::View, ui, |ui| { + panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body) + }) }); match taken { Some(_) => None, @@ -1345,10 +1373,9 @@ impl Pass<'_, P> { .pad(Pad::None) .footer(|ui, _| { // Compact rail controls leave room for the scrolling panel icons in short windows. - Stack::new() - .fill_width() - .gap(Gap::None) - .show(ui, |ui, body| scene.hosted(panel, ui, |ui| pass.borrow_mut().panels.rail_footer(panel, ui, body))); + Stack::new().fill_width().gap(Gap::None).show(ui, |ui, body| { + scene.hosted(panel, HostPart::RailFooter, ui, |ui| pass.borrow_mut().panels.rail_footer(panel, ui, body)) + }); }) .show_at(ui, cell, |ui, _| { // design: allow[contract/allocate](the rail lays its icons out in a rect of its own: the panel body claims their height, so the host's footer sits under them) @@ -1727,8 +1754,8 @@ fn window_edit( } } -/// Shows `panel`'s body in a group's body, in the host's style where the body is the app's own egui code -/// (`Scene::hosted`). It runs every pass the group shows; the host memoizes inside it. +/// Shows `panel`'s body in a group's body, in the host's style and once per pass where the body is the app's own egui +/// code (`Scene::hosted`). It runs every pass the group shows; the host memoizes inside it. fn panel_body<'p, P: Clone + Eq + Hash>( scene: &Scene<'_, P>, panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, @@ -1736,12 +1763,15 @@ fn panel_body<'p, P: Clone + Eq + Hash>( ui: &mut Ui, body: &mut BodyCx<'_>, ) { - // The app's own egui body keeps its background: the host's panel fill over the group's surface, as it showed - // outside the dock. A measuring run paints nothing. - if scene.spec(panel).host_body && !crate::runtime::measure::active(ui.ctx()) { - scene.host_style.paint_panel(ui, ui.max_rect()); - } - scene.hosted(panel, ui, |ui| panels.borrow_mut().body(panel, ui, body)); + let host = scene.host_body(panel); + scene.hosted(panel, HostPart::Body, ui, |ui| { + // The app's own egui body keeps its background: the host's panel fill over the group's surface, as it showed + // outside the dock. + if host { + scene.host_style.paint_panel(ui, ui.max_rect()); + } + panels.borrow_mut().body(panel, ui, body); + }); } /// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to, with diff --git a/crates/ui-patterns/tests/it/docking/app_modal.rs b/crates/ui-patterns/tests/it/docking/app_modal.rs new file mode 100644 index 0000000000..10b7f52996 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/app_modal.rs @@ -0,0 +1,81 @@ +//! While the app's own egui code shows a modal (`FrameInput::app_modal`), a panel floated into a window of its own takes +//! no press and no key, as under a framework app-modal layer. + +use craft_behavior::dock::{Floating, Layout, Workspace}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::trial; +use craft_ui_test_kit::windows::Windows; +use egui::{Event, Key, Modifiers, Pos2, Rect, Ui, ViewportId, ViewportInfo}; +use std::sync::Arc; + +const MAIN_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(900.0, 700.0) }; +const FLOAT_AT: Rect = Rect { min: Pos2::new(1000.0, 150.0), max: Pos2::new(1300.0, 350.0) }; +/// A point of the float's body, in its window's coordinates. +const IN_BODY: Pos2 = Pos2::new(150.0, 120.0); + +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, _: &u32) -> PanelSpec { + PanelSpec::new("Palette").host_body() + } +} + +/// The float's body: records whether a press or a key reached the egui input of a window of its own. +#[derive(Default)] +struct Probe { + reached: bool, +} + +impl DockPanels for Probe { + fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if ui.ctx().viewport_id() == ViewportId::ROOT { + return; + } + let pressed = |event: &Event| matches!(event, Event::PointerButton { pressed: true, .. } | Event::Key { pressed: true, .. }); + self.reached |= ui.ctx().input(|input| input.events.iter().any(pressed)); + } +} + +fn info(rect: Rect) -> ViewportInfo { + ViewportInfo { + focused: Some(true), + inner_rect: Some(rect), + outer_rect: Some(rect), + native_pixels_per_point: Some(1.0), + ..ViewportInfo::default() + } +} + +#[trial] +fn a_native_float_takes_no_press_or_key_while_the_apps_own_modal_shows() { + for modal in [None, Some(ViewportId::ROOT)] { + let windows = Windows::new(); + windows.root_info(info(MAIN_AT)); + windows.child_info(info(FLOAT_AT)); + let float = Floating::single(100, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float]))); + let (specs, mut probe) = (Tracked::new(Specs), Probe::default()); + let mut frame = |child: Vec, probe: &mut Probe| { + windows.frame(vec![], child, |ui| { + let config = DockConfig::default().native_windows(true); + let _ = DockArea::new("Dock", Bind::bound(&mut workspace), &specs, probe, config).show(ui); + }); + }; + for _ in 0..3 { + frame(vec![moved(IN_BODY)], &mut probe); + } + windows.app_modal(modal); + frame(vec![], &mut probe); + probe.reached = false; + frame(vec![press(IN_BODY)], &mut probe); + frame(vec![release(IN_BODY)], &mut probe); + frame(vec![key_press(Key::A, Modifiers::NONE)], &mut probe); + assert_eq!(probe.reached, modal.is_none(), "app modal in {modal:?}: a press or key reached the floating window"); + } +} diff --git a/crates/ui-patterns/tests/it/docking/host_runs.rs b/crates/ui-patterns/tests/it/docking/host_runs.rs new file mode 100644 index 0000000000..334b74fdea --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/host_runs.rs @@ -0,0 +1,100 @@ +//! The app's own egui code in a dock (`PanelSpec::host_body`: a panel's body, or the view it takes its group with) runs +//! once per pass, in the real run: a measuring run takes the size its last real run took. egui then sees each of the +//! app's widgets once per pass, so it reports no id clash. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::measure; +use craft_ui::testing::{Fixture, trial}; +use egui::{Id, Sense, Shape, Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +/// The app's egui panel, its canvas (a view that takes its group) and a framework panel. +const HOSTED: usize = 0; +const CANVAS: usize = 1; + +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + let spec = PanelSpec::new(format!("Panel {panel}")); + match *panel { + HOSTED => spec.host_body(), + CANVAS => spec.canvas().host_body(), + _ => spec, + } + } +} + +/// One run of the app's code: what ran, in which pass, and whether a measuring run was open. +type Ran = (&'static str, u64, bool); + +struct Panels { + runs: Rc>>, +} + +impl DockPanels for Panels { + fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel != HOSTED { + return; + } + self.runs.borrow_mut().push(("body", ui.ctx().cumulative_pass_nr(), measure::active(ui.ctx()))); + let _ = ui.button("Apply"); + egui::CollapsingHeader::new("Section").default_open(true).show(ui, |ui| { + let _ = ui.button("Inside"); + }); + } + + fn group_view(&mut self, panels: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + let GroupAt::Show(rect) = at else { return None }; + if !panels.contains(&CANVAS) { + return None; + } + self.runs.borrow_mut().push(("view", ui.ctx().cumulative_pass_nr(), measure::active(ui.ctx()))); + let _ = ui.interact(rect, Id::unique("host canvas"), Sense::click_and_drag()); + Some(rect.height()) + } +} + +#[trial] +fn the_apps_egui_code_in_a_dock_runs_once_per_pass_and_raises_no_id_clash() { + let runs = Rc::new(RefCell::new(Vec::new())); + let left = Node::split(Axis::Y, SplitSize::Ratio(0.5), Node::tabs(vec![HOSTED], 0), Node::tabs(vec![2], 0)); + let root = Node::split(Axis::X, SplitSize::Ratio(0.3), left, Node::tabs(vec![CANVAS], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (Panels { runs: runs.clone() }, Tracked::new(Specs)); + let mut fixture = Fixture::new(move |ui| { + ui.ctx().options_mut(|options| options.warn_on_id_clash = true); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + }); + // From the first frame on, through a new room, so the dock measures its groups again. + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + fixture.room(Vec2::new(1000.0, 700.0)).settle(); + fixture.record_paint().frame(Vec::new()); + + let runs = runs.borrow().clone(); + for part in ["body", "view"] { + let ran: Vec<_> = runs.iter().filter(|(name, ..)| *name == part).collect(); + assert!(!ran.is_empty(), "the app's {part} ran"); + assert!(ran.iter().all(|(.., measuring)| !measuring), "the app's {part} ran in a measuring run: {ran:?}"); + let mut passes: Vec<_> = ran.iter().map(|(_, pass, _)| *pass).collect(); + passes.dedup(); + assert_eq!(passes.len(), ran.len(), "the app's {part} ran more than once in a pass: {ran:?}"); + } + let paint = fixture.take_paint().expect("the frame recorded its paint"); + let clashes: Vec = paint + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + Shape::Text(text) if text.galley.job.text.contains("use of widget ID") => Some(text.galley.job.text.clone()), + _ => None, + }) + .collect(); + assert!(clashes.is_empty(), "egui reported id clashes: {clashes:?}"); +} diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index fc30a9bab6..a132a76e40 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -21,11 +21,13 @@ pub(crate) mod floating_area; pub(crate) mod floating_rail; pub(crate) mod hidden; +pub(crate) mod app_modal; pub(crate) mod columns; pub(crate) mod dock_back; pub(crate) mod group_view; pub(crate) mod host_body; pub(crate) mod host_keys; +pub(crate) mod host_runs; pub(crate) mod tab_focus; pub(crate) mod workspace_dialogs; diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index 4c50cc229d..6941095b14 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -255,6 +255,7 @@ pub struct Windows { /// The installed context. pub ctx: Context, root_info: RefCell, + app_modal: Cell>, } impl Default for Windows { @@ -283,7 +284,7 @@ impl Windows { COMMANDS.with(|kept| kept.borrow_mut().clear()); BUILDERS.with(|kept| kept.borrow_mut().clear()); NOW.with(|now| now.set(0.0)); - Windows { ctx, root_info: RefCell::new(ViewportInfo::default()) } + Windows { ctx, root_info: RefCell::new(ViewportInfo::default()), app_modal: Cell::new(None) } } /// The window facts child passes report from now on. @@ -297,6 +298,11 @@ impl Windows { with_facts(viewport, |info| info.clone()) } + /// The window in which the app's own egui code shows a modal (`FrameInput::app_modal`), from the next frame on. + pub fn app_modal(&self, viewport: Option) { + self.app_modal.set(viewport); + } + /// The window facts the root viewport reports from now on. pub fn root_info(&self, info: ViewportInfo) { *self.root_info.borrow_mut() = info; @@ -325,7 +331,7 @@ impl Windows { let root_hovered = hovered.clone(); CHILD_FILES.with(|files| *files.borrow_mut() = (hovered, dropped)); TREES.with(|kept| kept.borrow_mut().clear()); - set_input(&self.ctx, FrameInput::new(RootEnv::default())); + set_input(&self.ctx, FrameInput::new(RootEnv::default()).app_modal(self.app_modal.get())); let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)), events: root, diff --git a/docs/craft-framework.md b/docs/craft-framework.md index bda0a918ba..e1779ac8a4 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -166,6 +166,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Quit shortcuts | egui's quit shortcuts are cleared. Quit goes through the close path. | | Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). | | Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. | +| App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, and they refuse to close). | | Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu and goes no further. After an OS resize of the window, the held pointer is released. | The window's keys are the ones the runtime routes to no component: an Escape or a plain Enter while no framework stop is focused, and the arrows' nudge. `with_window_intents` offers them to its closure while nothing has framework focus. The closure takes what it handles (`Intents::take(Intent::Cancel)`; `Intent` and the other types `Intents` reads are in `ui::runtime::keys`) and returns whether it took anything; the rest stays for later readers. A framework scope that ran earlier in the pass takes them first (an open dialog takes the Escape that closes it), so the app reads them last in its UI to see what no component took. App code that read `Key::Escape`, `Key::Tab`, F6 or F10 from egui while none of its own widgets had focus reads these intents and `FrameOutput::chrome_toggles` instead; its own focused widgets and popups keep reading Tab and Escape from egui. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 44073a3047..37c2b70c7c 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -70,7 +70,7 @@ The host implements `DockPanels

` for the views: | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | -A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. Its body also keeps the app's background and room: the dock fills the body with that style's panel fill (`Visuals::panel_fill`) and gives it no body padding, and a press on the body is the app's, so it does not focus the group's tabs. The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports. +A body lays out with the group's spacing, which framework components expect. A panel whose body is the app's own egui code sets `PanelSpec::host_body()`: the dock then hands its `body`, `footer`, `group_header`, `rail_footer` and, while it is the panel its group shows, its group's `group_view` a `Ui` with the style of the `Ui` the area was shown in, so that code lays out as it does outside the dock. Its body also keeps the app's background and room: the dock fills the body with that style's panel fill (`Visuals::panel_fill`) and gives it no body padding, and a press on the body is the app's, so it does not focus the group's tabs. That code runs once per pass, in the pass's real run: where the framework measures a group before it shows it, the code's parts take the size they took when they last ran, and egui sees each of the app's widgets once (`HostStyle::show`). The dock's own parts keep the framework style. An app hosting its old egui panels moves onto the framework panel by panel, clearing `host_body` on each panel it ports. The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. From 3a10c49a2c108db0f70ffd130aceeaf9e0c521dd Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 02:30:10 +0000 Subject: [PATCH 06/13] Quit is a framework command, and the update dialogs show the icon the app gives its host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - QuitCommand::Quit (window.quit, Cmd+Q) replaces egui's quit shortcut, which the runtime clears at install. The runtime runs it from any source through the root window's close path, so the app's close decision asks about unsaved work. Its default yields to another command bound to the chord, as the window shortcuts' defaults do (library::yields_default). - HostBuilder::icon_png gives the app's icon once, beside its AppInfo; the update dialogs show it in their head instead of the name's initial. - Docs: craft-framework.md §2.2 Quit and Zoom keys rows, craft-host README. --- crates/host/README.md | 5 +- crates/host/src/lib.rs | 17 ++++++- .../ui-contract/src/runtime/commands/board.rs | 11 +++-- .../src/runtime/commands/library.rs | 22 +++++++++ .../ui-contract/src/runtime/commands/mod.rs | 4 +- crates/ui-contract/src/runtime/egui/input.rs | 3 +- crates/ui-contract/src/runtime/frame.rs | 5 +- crates/ui-contract/src/runtime/install.rs | 4 +- crates/ui-contract/src/testing/frames.rs | 6 +++ .../src/testing/host_key_trials.rs | 36 +++++++++++++- crates/update/Cargo.toml | 4 +- crates/update/src/stack_dialogs.rs | 41 +++++++++------- crates/update/tests/it/update.rs | 47 ++++++++++++++++++- docs/craft-framework.md | 4 +- 14 files changed, 172 insertions(+), 37 deletions(-) diff --git a/crates/host/README.md b/crates/host/README.md index cbb6a45c61..bf93f8c2b9 100644 --- a/crates/host/README.md +++ b/crates/host/README.md @@ -1,12 +1,13 @@ # craft-host -The services every Craft library feature reads from the app: who the app is (`AppInfo`), the -catalogs and current language, settings sections, command words and background jobs. The app builds +The services every Craft library feature reads from the app: who the app is (`AppInfo`, and its +icon), the catalogs and current language, settings sections, command words and background jobs. The app builds one `Host` at startup and installs it on the egui context; features read it with `Host::of(ui)` and never take services as parameters. ```ignore let host = craft_host::Host::builder(craft_host::AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" }) + .icon_png(include_bytes!("../assets/icon-128.png")) .i18n(i18n) .settings(settings) .build(); diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 420af889be..1586c9d72a 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -24,6 +24,7 @@ pub use ui::HostScope; #[derive(Clone)] pub struct Host { app: AppInfo, + icon_png: Option<&'static [u8]>, i18n: Option>, lang: Lang, settings: Arc, @@ -43,6 +44,7 @@ fn next_generation() -> u64 { /// Collects a [`Host`]'s services; each one defaults when not set. pub struct HostBuilder { app: AppInfo, + icon_png: Option<&'static [u8]>, i18n: Option>, lang: Option, settings: Option>, @@ -54,7 +56,7 @@ pub struct HostBuilder { impl Host { /// Starts a host for `app`; every service not set on the builder gets its default. pub fn builder(app: AppInfo) -> HostBuilder { - HostBuilder { app, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None } + HostBuilder { app, icon_png: None, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None } } /// Which host this is: a host and its clones hold the same services and language, and one built anew @@ -69,6 +71,11 @@ impl Host { &self.app } + /// The app's icon as PNG bytes ([`HostBuilder::icon_png`]); `None` when the app gave none. + pub fn icon_png(&self) -> Option<&'static [u8]> { + self.icon_png + } + /// The app's catalogs; `None` until the app uses craft-i18n (library words are English then). pub fn i18n(&self) -> Option<&I18n> { self.i18n.as_deref() @@ -134,6 +141,13 @@ impl Host { } impl HostBuilder { + /// The app's icon as PNG bytes, its 128 px app icon: the library dialogs that name the app (the update dialogs) + /// show it beside the name. Default: none; those dialogs then show the name's first letter in its place. + pub fn icon_png(mut self, png: &'static [u8]) -> Self { + self.icon_png = Some(png); + self + } + /// Default: none (English). pub fn i18n(mut self, i18n: Arc) -> Self { self.i18n = Some(i18n); @@ -175,6 +189,7 @@ impl HostBuilder { let lang = self.lang.or_else(|| self.i18n.as_ref().map(|i18n| i18n.system_lang())).unwrap_or(Lang::EN); Host { app: self.app, + icon_png: self.icon_png, i18n: self.i18n, lang, settings: self.settings.unwrap_or_else(|| Arc::new(MemorySections::default())), diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index e2f5b41b4b..b43262e66b 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -3,7 +3,7 @@ use super::{ AppCatalog, CommandChain, CommandGate, CommandInput, CommandScope, CommandSet, CommandState, EditCommands, FirePhase, FireSource, Fired, - ResolvedCommand, WindowShortcut, registry, + ResolvedCommand, WindowShortcut, registry, yields_default, }; use crate::contract::Revision; use crate::runtime::egui::sizing::{Rerun, request_discard}; @@ -922,8 +922,9 @@ pub fn keymap_builds() -> u64 { /// definition, and the catalog's default bindings join the registry's after them (an app's alternate keys, such as /// F2/F3/F4 for Cut/Copy/Paste). /// -/// A window shortcut's default chord that another command also binds is that command's: the window shortcut loses it, so the -/// app's binding beats the framework's default. A window shortcut the overrides name keeps what they give it. +/// A yielding library command's default chord (a window shortcut's, Quit's: `yields_default`) that another command also +/// binds is that command's: the library command loses it, so the app's binding beats the framework's default. One the +/// overrides name keeps what they give it. fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platform: Platform, overrides: Option<&Arc>) -> BuiltKeymap { #[cfg(feature = "testing")] KEYMAP_BUILDS.with(|builds| builds.set(builds.get() + 1)); @@ -964,9 +965,9 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor let overridden = |def: &CommandDef| overrides.is_some_and(|overrides| overrides.get(&def.command.id).is_some()); let yielded: Vec<(CommandRef, Trigger)> = defs .iter() - .filter(|def| WindowShortcut::of(&def.command).is_some() && !overridden(def)) + .filter(|def| yields_default(&def.command) && !overridden(def)) .flat_map(|def| keymap.conflicts_with(&def.command)) - .filter(|conflict| WindowShortcut::of(&conflict.b.0).is_none()) + .filter(|conflict| !yields_default(&conflict.b.0)) .map(|conflict| (conflict.a.0, conflict.chord)) .collect(); if !yielded.is_empty() { diff --git a/crates/ui-contract/src/runtime/commands/library.rs b/crates/ui-contract/src/runtime/commands/library.rs index 42592a920e..949d3b0c83 100644 --- a/crates/ui-contract/src/runtime/commands/library.rs +++ b/crates/ui-contract/src/runtime/commands/library.rs @@ -122,6 +122,28 @@ pub enum NavCommand { FocusMenuBar, } +/// The `window` command that quits the app (egui's own quit shortcut, which the runtime clears at install, had the same +/// default). The runtime runs it: it asks the root window to close through the window's close path +/// (`WindowAction::Close`), so the app's close decision (`embed::logic`) asks about unsaved work as it does for the +/// window's close button. It fires whatever is open; under an app-modal layer the close path refuses the close and +/// brings the modal forward. Its default chord, like the window shortcuts', yields to another command that binds the +/// same chord; an app that reads its quit key from egui itself unbinds it in its overrides. +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)] +#[command(prefix = "window")] +#[non_exhaustive] +pub enum QuitCommand { + /// Quit the app. + #[command(label = "Quit", default = "Cmd+Q", modal = "always")] + Quit, +} + +/// Whether `command` is a library command whose default chords yield to another command that binds the same chord: +/// the window shortcuts and Quit. An app's binding beats the framework's default. +pub(crate) fn yields_default(command: &CommandRef) -> bool { + use super::CommandSet as _; + WindowShortcut::of(command).is_some() || QuitCommand::from_ref(command).is_some() +} + /// A key the window owns before any component: a chrome toggle (Tab), a pane move (F6) or the menu bar's focus (F10), /// as the commands of `ChromeCommand` and `NavCommand` are bound. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 040047bc6c..18c5eeb215 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -9,8 +9,8 @@ pub use clipboard::{ClipContent, ClipError, ClipItem, ClipboardHandle}; pub use craft_behavior::EditCommand; pub use craft_keymap::{Binding, CommandDef, CommandKind, CommandRef, CommandScope, ModalRule, Platform, Scope, TypingRule}; pub use library::ChromeCommand; -pub(crate) use library::WindowShortcut; -pub use library::{EditCommands, NavCommand, WindowCommand}; +pub use library::{EditCommands, NavCommand, QuitCommand, WindowCommand}; +pub(crate) use library::{WindowShortcut, yields_default}; pub use registry::CommandDefError; #[doc(hidden)] pub use registry::{SetEntry, sets}; diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index db024b66fd..f2c3c6189b 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -126,7 +126,8 @@ pub(crate) fn request_repaint_of(ctx: &Context, viewport: ViewportId) { ctx.request_repaint_of(viewport); } -/// The options the runtime owns at install: interface scale and quit are commands, so egui's own shortcuts go. +/// The options the runtime owns at install: the interface scale is the app's `RootEnv::scale` and quit is a command +/// (`QuitCommand`), so egui's own keyboard zoom and quit shortcuts go. pub(crate) fn clear_shortcuts(ctx: &Context) { ctx.options_mut(|options| { options.zoom_with_keyboard = false; diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 198aca1bb6..259ccd65b6 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -468,9 +468,12 @@ pub fn take_output(ctx: &Context) -> FrameOutput { output.declined = commands::take_declined(ctx); // The menu, palette and automation fires of the chrome and nav commands reach the app as ordinary fires with no // window: the focused window's shell takes a toggle, and its focus service a pane move, in the next pass. A key fire - // already acted in the key stage. + // already acted in the key stage. Quit, from any source, asks the root window to close through its close path. let focused = crate::runtime::egui::viewports::reported(ctx).into_iter().find(|(_, facts)| facts.focused).map(|(viewport, _)| viewport); for fired in &output.fired { + if fired.phase == commands::FirePhase::Press && commands::QuitCommand::from_ref(&fired.command).is_some() { + windows::act(ctx, ViewportId::ROOT, windows::WindowAction::Close); + } if fired.source == commands::FireSource::Key { continue; } diff --git a/crates/ui-contract/src/runtime/install.rs b/crates/ui-contract/src/runtime/install.rs index c8bcbc7989..3c9ed79fe2 100644 --- a/crates/ui-contract/src/runtime/install.rs +++ b/crates/ui-contract/src/runtime/install.rs @@ -204,8 +204,8 @@ fn with_browser_caps(shell: ShellInfo) -> ShellInfo { shell } -/// Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: interface scale is a command, quit goes -/// through the close guard, and the wheel's modifiers are the spec's. A second call on the same context is an error, +/// Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: the interface scale is the app's +/// (`RootEnv::scale`), quit is a command that goes through the close guard, and the wheel's modifiers are the spec's. A second call on the same context is an error, /// checked first so an app that installs again (a language change) gets that answer; a call inside a pass is one too. pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError> { if plugin::is_registered(ctx) { diff --git a/crates/ui-contract/src/testing/frames.rs b/crates/ui-contract/src/testing/frames.rs index f4d04ea493..4f05eeaf11 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -201,6 +201,12 @@ impl Frames { passes } + /// One frame with `events`, as [`frame`](Self::frame); returns whether the frame sent a window a close command. + pub fn frame_closing(&mut self, events: Vec, ui: impl FnMut(&mut Ui)) -> bool { + set_input(&self.ctx, self.input()); + self.run(egui::ViewportId::ROOT, events, ui) + } + /// One frame with no `set_input`, as an app that never calls it would drive it: the root values and the /// interface scale stay as they were. Returns whether the frame sent a close command. pub fn frame_without_input(&mut self, events: Vec, ui: impl FnMut(&mut Ui)) -> bool { diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index 13574fc395..a8353ded19 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -1,7 +1,9 @@ //! Trials of the keys and presses a host's own egui widgets keep while the runtime is installed on the whole window. use crate::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; -use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, Scope, TypingRule}; +use crate::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, QuitCommand, Scope, TypingRule, +}; use crate::runtime::drag::{self, DragPreview}; use crate::runtime::egui::{areas, fixture}; use crate::runtime::env::{Env, RootEnv}; @@ -550,6 +552,38 @@ fn an_app_binding_on_f6_beats_the_pane_move() { assert_eq!(f6_under(Some(unbound)), (true, Vec::new()), "with the pane move unbound, F6 is egui's"); } +/// What a ⌘Q (Ctrl+Q off the Mac) did in the host window under `overrides`: how many frames sent a close command, the +/// app taking each frame's output before the next as `embed::before_input` does, and the ids of the commands it fired. +fn quit_under(overrides: Option) -> (usize, Vec) { + let (_, mut show) = host_window(); + let mut frames = Frames::new(); + if let Some(overrides) = overrides { + frames.commands(CommandInput::new().overrides(Arc::new(overrides))); + } + frames.frame(Vec::new(), &mut show); + take_output(&frames.ctx); + let mut closes = usize::from(frames.frame_closing(vec![key_press(Key::Q, Modifiers::COMMAND)], &mut show)); + let mut fired = Vec::new(); + for _ in 0..3 { + fired.extend(take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id)); + closes += usize::from(frames.frame_closing(Vec::new(), &mut show)); + } + (closes, fired) +} + +/// egui's own quit shortcut is cleared at install; the runtime's Quit command takes its place, through the root window's +/// close path, and an app's own binding of the chord replaces it. +#[trial] +fn quit_asks_the_root_window_to_close_once_and_an_app_binding_replaces_it() { + assert_eq!(quit_under(None), (1, vec![QuitCommand::Quit.id().to_owned()]), "the quit chord asks the root window to close once"); + let mut bound = craft_keymap::Overrides::default(); + bound.insert(EditCommands::Delete.id(), vec!["Cmd+Q".to_owned()]); + assert_eq!(quit_under(Some(bound)), (0, vec![EditCommands::Delete.id().to_owned()]), "a command bound to the chord takes it"); + let mut unbound = craft_keymap::Overrides::default(); + unbound.insert(QuitCommand::Quit.id(), Vec::new()); + assert_eq!(quit_under(Some(unbound)), (0, Vec::new()), "with Quit unbound, nothing closes the window"); +} + /// The Alt+digit chords the hosted canvas of `an_unbound_f6_reaches_a_host_canvas_with_claims` claims. const CANVAS_CLAIMS: [craft_keymap::Chord; 2] = [ craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num1), diff --git a/crates/update/Cargo.toml b/crates/update/Cargo.toml index 0325ea8f91..059a7e3c1a 100644 --- a/crates/update/Cargo.toml +++ b/crates/update/Cargo.toml @@ -30,9 +30,9 @@ egui = { workspace = true, optional = true } craft-ui = { workspace = true, optional = true } # `Tone` for the dialogs' notices. craft-theme = { workspace = true, optional = true } -# `Host::app`: the name the update dialogs show. +# `Host::app` and `Host::icon_png`: the name and icon the update dialogs show. craft-host = { workspace = true, features = ["ui"], optional = true } -# Decodes the app icon the update dialogs show (`App::icon_png`); PNG only. +# Decodes the app icon the update dialogs show (`Host::icon_png`); PNG only. image = { version = "0.25", default-features = false, features = ["png"], optional = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/update/src/stack_dialogs.rs b/crates/update/src/stack_dialogs.rs index bd88604e91..9ac6c0cc7a 100644 --- a/crates/update/src/stack_dialogs.rs +++ b/crates/update/src/stack_dialogs.rs @@ -1,6 +1,6 @@ //! The update dialogs on craft-ui's dialog host: [`UpdatePromptDialog`] (a release is available) -//! and [`UpdateCheckDialog`] (the result of a manual check), on [`Dialog`], with the app's name from the -//! host's `AppInfo` and the words from [`UpdateWords`]. +//! and [`UpdateCheckDialog`] (the result of a manual check), on [`Dialog`], with the app's name and icon from the +//! host (`Host::app`, `Host::icon_png`) and the words from [`UpdateWords`]. use std::hash::{Hash as _, Hasher as _}; use std::sync::{Arc, OnceLock}; @@ -102,29 +102,36 @@ pub fn icon_image(png: &[u8]) -> Option { /// The app's decoded icon, kept for the life of the dialog; `None` inside when it has none or it does not decode. type IconCell = OnceLock>; -/// The app the dialogs are for: the installed host's name and the suite entry that carries its icon and -/// developer. +/// The app the dialogs are for: the installed host's name and icon, and the suite entry that carries its developer. struct Subject { + id: &'static str, name: &'static str, + icon_png: Option<&'static [u8]>, app: Option<&'static App>, } impl Subject { fn of(env: &Env) -> Self { - let info = env.view().host().map(|host| host.app().clone()); - Self { name: info.as_ref().map_or("", |info| info.name), app: info.and_then(|info| App::by_id(info.id)) } + let host = env.view().host(); + let info = host.map(|host| host.app().clone()); + Self { + id: info.as_ref().map_or("", |info| info.id), + name: info.as_ref().map_or("", |info| info.name), + icon_png: host.and_then(|host| host.icon_png()), + app: info.and_then(|info| App::by_id(info.id)), + } } /// The icon, the name, the developer and `version_line`, as the head of both dialogs. An app without a /// decodable icon shows its initial in the icon's place. fn head(&self, ui: &mut Ui, words: &UpdateWords, icon: &IconCell, version_line: &str) { - let image = icon.get_or_init(|| self.app.and_then(|app| app.icon_png).and_then(icon_image)).as_ref(); + let image = icon.get_or_init(|| self.icon_png.and_then(icon_image)).as_ref(); Row::new().show(ui, |ui, _| { - match (image, self.app) { - (Some(image), Some(app)) => { - Picture::new("", icon_key(app), &|| image.clone()).extent(PictureSize::Icon).show(ui); + match image { + Some(image) => { + Picture::new("", self.icon_key(), &|| image.clone()).extent(PictureSize::Icon).show(ui); } - _ => { + None => { Text::new(self.name.chars().next().map_or_else(|| "A".to_owned(), String::from)).show(ui); } } @@ -137,13 +144,13 @@ impl Subject { }); }); } -} -/// The picture key of `app`'s icon. -fn icon_key(app: &App) -> u64 { - let mut hasher = std::hash::DefaultHasher::new(); - app.id.hash(&mut hasher); - hasher.finish() + /// The picture key of the app's icon. + fn icon_key(&self) -> u64 { + let mut hasher = std::hash::DefaultHasher::new(); + self.id.hash(&mut hasher); + hasher.finish() + } } /// The spinner with the progress word, shown while an install runs. diff --git a/crates/update/tests/it/update.rs b/crates/update/tests/it/update.rs index 2ba1965432..3304f3467a 100644 --- a/crates/update/tests/it/update.rs +++ b/crates/update/tests/it/update.rs @@ -21,12 +21,21 @@ fn newer() -> Release { Release { tag: "v9.0.0".into(), version: craft_update::parse_version("9.0.0"), ..Release::default() } } +fn photocraft() -> craft_host::HostBuilder { + Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" }) +} + /// A fixture running `dialogs` every pass for an app named PhotoCraft. fn rig(dialogs: DialogHost) -> (Fixture, Dialogs) { + rig_for(dialogs, photocraft().build()) +} + +/// A fixture running `dialogs` every pass for the app `host` names. +fn rig_for(dialogs: DialogHost, host: Host) -> (Fixture, Dialogs) { let dialogs: Dialogs = Rc::new(RefCell::new(dialogs)); let shown = dialogs.clone(); let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); - fixture.host(Arc::new(Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "1.0" }).build())); + fixture.host(Arc::new(host)); fixture.settle(); (fixture, dialogs) } @@ -119,6 +128,42 @@ fn check_dialog_shows(status: Status, text: &str) -> bool { fixture.texts().iter().any(|t| t.text.contains(text)) || fixture.by_label(text).is_some() } +/// The check dialog's head for the app `host` names: how many textured shapes the dialog paints (the dialog's own +/// chrome paints some), and whether it shows the app name's initial in the icon's place. +fn check_dialog_head(host: Host) -> (usize, bool) { + let mut dialog = UpdateCheckDialog::new("0.1.0"); + dialog.set_status(Status::UpToDate); + let mut dialogs = DialogHost::new(); + dialogs.open(dialog); + let (mut fixture, _) = rig_for(dialogs, host); + let textured = fixture + .frame_shapes() + .iter() + .filter(|shape| match shape { + egui::Shape::Mesh(mesh) => mesh.texture_id != egui::TextureId::default(), + egui::Shape::Rect(rect) => rect.brush.is_some(), + _ => false, + }) + .count(); + (textured, fixture.texts().iter().any(|t| t.text == "P")) +} + +/// The app gives its icon once, to its host beside its name, and the check dialog shows it in its head, which the +/// prompt shares; an app without one shows its name's initial. +#[trial] +fn the_update_dialogs_show_the_icon_the_app_gives_its_host() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(8, 8, image::Rgba([240, 122, 30, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap_or_else(|error| panic!("the icon encodes: {error}")); + let icon: &'static [u8] = Box::leak(png.into_boxed_slice()); + let (with_icon, initial_with_icon) = check_dialog_head(photocraft().icon_png(icon).build()); + let (without, initial_without) = check_dialog_head(photocraft().build()); + assert!(with_icon > without, "the icon paints a picture: {with_icon} textured shapes against {without}"); + assert!(!initial_with_icon, "the icon takes the initial's place"); + assert!(initial_without, "no icon: the initial"); +} + #[trial] fn the_check_dialog_words_a_rate_limit_itself_and_passes_other_reasons_through() { let words = UpdateWords::default(); diff --git a/docs/craft-framework.md b/docs/craft-framework.md index e1779ac8a4..05cd0d5fe2 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -162,8 +162,8 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Releases | The release of every key the runtime took is taken too. | | Focus surrender | The runtime moves its own focus on press (8.3): a press a framework component takes moves focus to it; a press no component takes drops the framework's focus. egui's click-away never takes the framework's focus. egui's surrender option (`InputOptions::surrender_focus_on`) stays the app's and governs the focus of the app's own widgets, as in egui alone: a press no component takes leaves that focus to egui's rule. | | Clicks | egui's click options (`InputOptions::max_click_dist`, `max_click_duration`) stay the app's, for its own widgets. A framework component clicks and drags by the framework's press lifecycle: a release within the slop (`HitSizes::slop`), whatever its duration. Read a component's click with `contract::clicked(&response)` or its output's `clicked()`; egui's `Response::clicked()` on a component's response also needs a click by egui's options. | -| Zoom keys | egui's keyboard zoom is off. The interface scale is `RootEnv::scale`. | -| Quit shortcuts | egui's quit shortcuts are cleared. Quit goes through the close path. | +| Zoom keys | egui's keyboard zoom is off and nothing takes its place: the interface scale is `RootEnv::scale`, and an app whose ⌘= and ⌘- changed it binds them itself. | +| Quit | egui's quit shortcuts are cleared. ⌘Q (Ctrl+Q on Windows and Linux) is the default of the command `QuitCommand::Quit` (id `window.quit`), which the runtime runs from any source: it asks the root window to close through the close path below, so the app's close decision asks about unsaved work. It fires with a modal open; the close path then refuses under an app-modal layer. Its default is bound and yielded as F6 is; an app whose own shortcut table reads its quit key from egui unbinds it there. | | Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). | | Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. | | App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, and they refuse to close). | From cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 02:45:21 +0000 Subject: [PATCH 07/13] theme: DeckCraft and SoundCraft accents in the suite theme's app pins --- crates/theme/themes/artcraft.json | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/theme/themes/artcraft.json b/crates/theme/themes/artcraft.json index 1e96bc4e8a..aec135debe 100644 --- a/crates/theme/themes/artcraft.json +++ b/crates/theme/themes/artcraft.json @@ -139,6 +139,30 @@ "text.muted": "#aeaeb6", "text.normal": "#ececef" } + }, + "deckcraft": { + "light": { + "accent.solid": "#d95a1a", + "accent.text": "#b54b16", + "text.on_accent": "#ffffff" + }, + "dark": { + "accent.solid": "#f26b1d", + "accent.text": "#fbcdb2", + "text.on_accent": "#ffffff" + } + }, + "soundcraft": { + "light": { + "accent.solid": "#3e74b4", + "accent.text": "#3b6eab", + "text.on_accent": "#ffffff" + }, + "dark": { + "accent.solid": "#4084c4", + "accent.text": "#c4d9ed", + "text.on_accent": "#ffffff" + } } } } From ef7239a97b28744c6bd90b5c200a1561b78a5acc Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 16:34:04 +0000 Subject: [PATCH 08/13] A host canvas holding egui focus keeps Escape and its clipboard in egui A focused `Stop::host` (`focus::host_canvas`), whether the framework or the app's own egui request focused it, is the app's own widget for Escape and its edit set: Escape, the clipboard events and the edit chords of its edit set stay in egui's input, as they do for the canvas with nothing focused, instead of arriving as its `Intent::Cancel` and `Intent::Edit`. egui keeps its focus over the Escape, and a menu's edit command is the app's. Tab, the arrows and F6 still follow its `KeyUse`. --- crates/ui-contract/src/runtime/focus.rs | 18 +++--- crates/ui-contract/src/runtime/focus/nav.rs | 4 +- crates/ui-contract/src/runtime/keys/input.rs | 30 ++++++---- crates/ui-contract/src/runtime/keys/route.rs | 4 +- .../src/testing/host_key_trials.rs | 60 +++++++++++++++++++ 5 files changed, 94 insertions(+), 22 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 414c51e5ae..405187cd98 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -239,15 +239,15 @@ pub(crate) fn register_stop(ctx: &Context, stop: Stop) { /// Registers the app's own egui widget `id`, drawn in the running pass, as its window's document canvas: a focus stop /// with `keys`, marked as the canvas (`KeyUse::chrome_key`). The window then shows a document, so with /// `RootEnv::tab_toggles_chrome` a bare Tab with nothing focused toggles its panels, as with a framework canvas. Focus -/// reaches the canvas by Tab, F6 or `request`; while it has focus, its keys route as `keys` says (the arrows as -/// nudges, Escape as its `Intent::Cancel`). `keys` is `KeyUse::CANVAS`, or a variant such as -/// `KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(..)` while the canvas edits text in place and Tab and the -/// clipboard are its own. With nothing focused the canvas is the key target: a bare Tab it keeps, the chords it claims -/// (`KeyUse::with_claims`; Alt+numpad code entry leaves a claimed Alt+digit alone), and the clipboard events and edit -/// chords of its edit set, stay in egui's input for the app, and nothing toggles or fires with them; Page Up and Down, -/// Home and End arrive as its `Intent::Move`, as while it has the focus. With the canvas focused, Tab it keeps and the -/// chords it claims stay in egui too, and its edit set arrives as `Intent::Edit` -/// (`keys::intents_of`), as for any focused stop. Call it each pass the canvas shows. +/// reaches the canvas by Tab, F6, `request` or the app's own egui focus request; while it has focus, Tab and the arrows +/// route as `keys` says (the arrows as nudges, Tab moving focus on or toggling the panels unless it keeps Tab). `keys` +/// is `KeyUse::CANVAS`, or a variant such as `KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(..)` while Tab and the +/// clipboard are the canvas's own. The canvas reads its keys from egui: with nothing focused it is the key target, and +/// a bare Tab it keeps, the chords it claims (`KeyUse::with_claims`; Alt+numpad code entry leaves a claimed Alt+digit +/// alone), and the clipboard events and edit chords of its edit set stay in egui's input for the app, and nothing +/// toggles or fires with them; Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus. +/// With the canvas focused, the same keys stay in egui, and Escape too, as for any focused widget of the app's own; +/// Escape with nothing focused is the window's cancel. Call it each pass the canvas shows. pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) { register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host()); } diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index ab676cceb3..58924165b3 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -262,7 +262,9 @@ impl State { let stop = &rec.stop; let roving = stop.group.is_some(); let keys = stop.keys; - let escape = keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); + // An app's own widget (`Stop::host`) reads its Escape from egui, as a stop that claims it does: egui keeps its + // focus on it. + let escape = stop.host || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape); let filter = egui_focus::filter( keys.keep == super::KeepKeys::Tab, roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows), diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 87e8fcace9..f1f0c09e1f 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -5,7 +5,7 @@ use super::{AltTrack, Batch, EscapePress, LastPress, MenuKey, NavKeys, Press, Sh use crate::runtime::commands::{self, EditCommands, FirePhase, NavCommand, WindowShortcut}; use crate::runtime::egui::input::{self as raw_input, Arrived, KeyEvent, RawInput}; use crate::runtime::env::Env; -use crate::runtime::focus::{self, EndKey, KeyUse}; +use crate::runtime::focus::{self, EditSet, EndKey, KeyUse}; use crate::runtime::frame::{ChromeToggle, request_chrome_toggle}; use crate::runtime::overlay; use crate::runtime::sampler; @@ -26,6 +26,7 @@ struct Strip<'a> { /// A press or a drag session is open: an Escape cancels it whatever the modifiers. press_captured: bool, claims: &'a Claims, + /// The edit commands the focused framework component takes as `Intent::Edit`. edits: &'a dyn Fn(EditCommand) -> bool, /// The chords bound to the edit commands that are the platform's text-editing chords. edit_chords: &'a [(EditCommand, Chord)], @@ -44,10 +45,17 @@ struct Strip<'a> { /// An app's own egui widget or popup has the focus (`FocusedRecord::foreign`): Tab, Escape and the clipboard /// events are its own. foreign: bool, + /// The focused stop is the app's own egui widget (`Stop::host`, `FocusedRecord::host`), which reads its keys from + /// egui: its Escape stays there, as an app's own focused widget's does. Tab and the arrows follow its `KeyUse`, as + /// the framework's navigation reads it. + host: bool, /// The keys of the window's canvas while nothing has the focus, neither a framework stop nor an app's own widget /// or popup: the canvas is then the key target, as the chrome gate takes it, and reads from egui the keys its - /// `KeyUse` keeps (Tab with `KeepKeys::Tab`) and the clipboard events and edit chords of its edit set. + /// `KeyUse` keeps (Tab with `KeepKeys::Tab`). canvas: Option, + /// The edit set whose clipboard events and edit chords stay in egui's input: the focused stop's when it is the + /// app's own widget (`host`), else the canvas's with nothing focused (`canvas`). + egui_edits: EditSet, /// egui holds no focus and the window registered no focus stop in its last pass: a framework focus move has /// nowhere to go, so a bare Tab is egui's. Focus on a component's widget without a stop is focus: egui would take /// a Tab from it as a move to the next widget it shows, in a later pass. @@ -214,7 +222,7 @@ impl Strip<'_> { false } KeyEvent::Clip { .. } if self.foreign => true, - KeyEvent::Clip { command, .. } if self.canvas.is_some_and(|canvas| canvas.edits.contains(command)) => true, + KeyEvent::Clip { command, .. } if self.egui_edits.contains(command) => true, KeyEvent::Clip { command: EditCommand::Copy | EditCommand::Cut, .. } if self.label_selection => true, // A clipboard event behind an open menu reaches nothing: the menu keeps it, as a platform menu does. The // chord's own key press still runs its command, which closes the menu. @@ -354,9 +362,8 @@ impl Strip<'_> { && key.is_letter() && ((mods == Mods::ALT && !self.shortcut_text(input)) || on_bar); let edit = self.edit_chords.iter().find(|(command, chord)| (self.edits)(*command) && self.layout.matches(chord, input, self.os)); - let canvas_edit = self.canvas.is_some_and(|canvas| { - self.edit_chords.iter().any(|(command, chord)| canvas.edits.contains(*command) && self.layout.matches(chord, input, self.os)) - }); + let egui_edit = + self.edit_chords.iter().any(|(command, chord)| self.egui_edits.contains(*command) && self.layout.matches(chord, input, self.os)); let canvas_tab = bare_tab && self.canvas.is_some_and(|canvas| canvas.keep == focus::KeepKeys::Tab); // The chrome keys are Tab's, which the bare-Tab arm and `take_nav` read. let window_shortcut = self @@ -370,7 +377,7 @@ impl Strip<'_> { PressUse::Edit(*command) } else if key == Key::Space && self.canvas_space { PressUse::CanvasSpace - } else if (self.foreign && (bare_tab || escape)) || canvas_tab || canvas_edit { + } else if (self.foreign && (bare_tab || escape)) || (self.host && escape && !self.press_captured) || canvas_tab || egui_edit { PressUse::Egui } else if bare_tab && self.no_stops { PressUse::TabToEgui @@ -430,8 +437,9 @@ impl Strip<'_> { } false } - // The app's own focused widget or popup, or the canvas with nothing focused, reads the key from egui; the - // runtime routes nothing for it, so no shortcut toggles the chrome or fires an edit command with it either. + // The app's own focused widget (a host stop included) or popup, or the canvas with nothing focused, reads + // the key from egui; the runtime routes nothing for it, so no shortcut toggles the chrome or fires an edit + // command with it either. PressUse::Egui => true, PressUse::TabToEgui => { // egui moves its own focus with it, from nothing focused into the app's own widgets (`focus::begin`). @@ -670,7 +678,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec Shortcuts { } /// Asks the focused component of the running viewport to take `command` as `Intent::Edit` in the next pass. -/// `false` when it does not list the command. A paste asks the platform for the clipboard text, which arrives as +/// `false` when it does not list the command, or is the app's own widget (`Stop::host`), whose edits are the app's. A paste asks the platform for the clipboard text, which arrives as /// the paste event that becomes the intent. Focus is read as it is now: a menu pick returns focus in its pass /// before its command fires, and the command goes where focus returned. pub(crate) fn queue_edit(ctx: &Context, command: EditCommand) -> bool { let viewport = crate::runtime::egui::pass::current_viewport(ctx); - if !focus::focused_rec(ctx).is_some_and(|rec| rec.stop.keys.edits.contains(command)) { + if !focus::focused_rec(ctx).is_some_and(|rec| !rec.stop.host && rec.stop.keys.edits.contains(command)) { return false; } if command == EditCommand::Paste { diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index dff07ee73c..b8ac5d3943 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -511,6 +511,66 @@ fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() { assert!(!clipboard_with_canvas(KeyUse::CANVAS, chord).1.is_empty(), "a canvas without the command: the chord fires the app's Paste"); } +/// What a host canvas with GridCraft's keys saw of a copy and an Escape while it held egui focus: whether the copy +/// reached egui's input with no command fired, the keys that reached egui and the window cancels, and egui's focus +/// after the Escape. `app_focus` gives it egui focus by the app's own request, else by the framework's `request`. +fn focused_host_canvas_keys(app_focus: bool) -> (bool, (Vec, usize), Option) { + const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL); + let canvas = named_id("host canvas"); + let events = Rc::new(RefCell::new(Vec::new())); + let seen_events = Rc::clone(&events); + let (host, mut base) = host_window(); + let mut show = move |ui: &mut Ui| { + seen_events.borrow_mut().extend(ui.input(|input| input.events.clone())); + base(ui); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KEYS); + }; + let mut frames = Frames::new(); + frames.frame(Vec::new(), &mut show); + if app_focus { + fixture::host_focus(&frames.ctx, canvas); + } else { + request(&frames.ctx, FocusTarget::Id(canvas)); + } + frames.frame(Vec::new(), &mut show); + assert_eq!(egui_focused(&frames.ctx), Some(canvas), "the canvas holds egui focus"); + take_output(&frames.ctx); + seen(&host); + events.borrow_mut().clear(); + frames.frame(vec![Event::Copy], &mut show); + frames.frame(Vec::new(), &mut show); + let copied = events.borrow().contains(&Event::Copy) && take_output(&frames.ctx).fired.is_empty(); + press_key(&mut frames, &mut show, Key::Escape); + let escape = seen(&host); + frames.frame(Vec::new(), &mut show); + (copied, escape, egui_focused(&frames.ctx)) +} + +/// A host canvas holding egui focus is the app's own focused widget: its clipboard events and Escape stay in egui's +/// input, and no window cancel comes of the Escape. With nothing focused, Escape is the window's cancel. +#[trial] +fn a_host_canvas_with_egui_focus_reads_escape_and_the_clipboard_from_egui() { + let canvas = named_id("host canvas"); + let (copied, escape, focused) = focused_host_canvas_keys(false); + assert!(copied, "the copy of a canvas the framework focused stays in egui and fires nothing"); + assert_eq!(escape, (vec![Key::Escape], 0), "its Escape is egui's, and no window cancel"); + assert_eq!(focused, Some(canvas), "egui keeps the framework's focus on the canvas over its Escape"); + let (copied, escape, _) = focused_host_canvas_keys(true); + assert!(copied, "the copy of a canvas the app focused stays in egui and fires nothing"); + assert_eq!(escape, (vec![Key::Escape], 0), "and its Escape"); + let (host, mut base) = host_window(); + let mut show = move |ui: &mut Ui| { + base(ui); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL)); + }; + let mut frames = Frames::new(); + frames.frame(Vec::new(), &mut show); + press_key(&mut frames, &mut show, Key::Escape); + assert_eq!(seen(&host), (Vec::new(), 1), "with nothing focused, Escape is the window's cancel"); +} + /// A clipboard with a picture and no text sends a paste with no text: it fires the app's Paste as the chord does, and /// `textless_paste` reads it in that pass only. #[trial] From 77ce5025479a912a578177d5457c6fa470e7054b Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 16:34:04 +0000 Subject: [PATCH 09/13] fonts::load records the facts of the definitions it installs `StackFacts` (system face, semibold family, line ratio) come from one function, `record_facts`, which `fonts::load` runs on every definitions it gives egui; a stack's install loads through it with its own providers. Definitions an app loads without the `semibold` family draw framework titles in the proportional family. --- crates/ui-contract/src/fonts/mod.rs | 36 +++++++++++++- crates/ui-contract/src/fonts/stack.rs | 1 + crates/ui-contract/src/fonts/stack/install.rs | 48 +++++++++---------- 3 files changed, 59 insertions(+), 26 deletions(-) diff --git a/crates/ui-contract/src/fonts/mod.rs b/crates/ui-contract/src/fonts/mod.rs index 08674cc0e6..28124e0bc7 100644 --- a/crates/ui-contract/src/fonts/mod.rs +++ b/crates/ui-contract/src/fonts/mod.rs @@ -76,10 +76,44 @@ impl FontRef { /// Gives the UI `definitions`, as when on-demand script coverage loads the glyphs of another script. Text /// measured in this pass used the old metrics, so the pass asks for one discard pass: layout memory and the /// new metrics agree when the frame is shown. Between frames nothing was measured with the old metrics, and -/// the next frame measures with the new ones. +/// the next frame measures with the new ones. What text layout reads of the definitions follows them: framework text +/// in a semibold role draws in the [`SEMIBOLD`] family only when `definitions` have it, else in the proportional one. pub fn load(ctx: &Context, definitions: FontDefinitions) { + load_with(ctx, definitions, Vec::new()); +} + +/// [`load`], with `providers` serving the characters the faces lack to the probe that measures the definitions' line +/// ratio: a stack's own providers. +pub(crate) fn load_with(ctx: &Context, definitions: FontDefinitions, providers: Vec>) { + stack::record_facts(ctx, &definitions, providers); egui_fonts::set_definitions(ctx, definitions); if frame::in_pass(ctx) { layout_memory::ask_discard(ctx); } } + +#[cfg(all(feature = "testing", any(test, feature = "suite")))] +pub(crate) mod facts_tests { + use crate::fonts::{SEMIBOLD, deflated_default_definitions, load, stack_facts}; + use crate::testing::trial; + use craft_theme::{Contrast, Mode, TypeRole}; + use egui::{Context, FontFamily}; + + /// Definitions an app gives in place of the stack's carry what text layout reads: without the semibold family, a + /// framework title draws in a family the definitions have. + #[trial] + fn a_title_draws_in_a_family_the_loaded_definitions_have() { + let ctx = Context::default(); + let tokens = crate::testing::style::tokens(Mode::Light, Contrast::Standard); + let semibold = FontFamily::Name(SEMIBOLD.into()); + let mut definitions = deflated_default_definitions(); + load(&ctx, definitions.clone()); + assert!(stack_facts(&ctx).semibold, "the default definitions have the semibold family"); + assert_eq!(tokens.font(stack_facts(&ctx), TypeRole::Title, false).family, semibold, "and a title draws in it"); + definitions.families.remove(&semibold); + load(&ctx, definitions.clone()); + assert!(!stack_facts(&ctx).semibold, "definitions without it say so"); + let title = tokens.font(stack_facts(&ctx), TypeRole::Title, false).family; + assert!(definitions.families.contains_key(&title), "a title draws in a family the definitions have, not {title:?}"); + } +} diff --git a/crates/ui-contract/src/fonts/stack.rs b/crates/ui-contract/src/fonts/stack.rs index 672f27a705..909304edc0 100644 --- a/crates/ui-contract/src/fonts/stack.rs +++ b/crates/ui-contract/src/fonts/stack.rs @@ -49,6 +49,7 @@ use craft_theme::InterfaceFont; use egui::{FontData, FontDefinitions, FontFamily, FontProvider}; pub(super) use chain::{EM_SQUARE_SCRIPTS, covers, is_cjk}; +pub(in crate::fonts) use install::record_facts; pub(crate) use install::{StackFacts, stack_facts}; use super::FontRef; diff --git a/crates/ui-contract/src/fonts/stack/install.rs b/crates/ui-contract/src/fonts/stack/install.rs index 3d7c9ea455..7bf9d06f50 100644 --- a/crates/ui-contract/src/fonts/stack/install.rs +++ b/crates/ui-contract/src/fonts/stack/install.rs @@ -2,29 +2,25 @@ use std::sync::Arc; -use egui::{Context, FontFamily, FontProvider}; +use egui::{Context, FontDefinitions, FontFamily, FontProvider}; use super::{SEMIBOLD, Stack, SystemFonts}; use crate::fonts::faces::{Installed, on_baseline}; use crate::fonts::served::loader; use crate::fonts::system::installed_system_font_provider; use crate::fonts::system::ui_face::{self, SYSTEM_UI_REGULAR, SYSTEM_UI_SEMIBOLD, SystemUiFace}; -use crate::fonts::{FontRef, RegularWeight, load, system_font_provider}; +use crate::fonts::{FontRef, RegularWeight, load_with, system_font_provider}; use crate::runtime::egui::fonts::{self as egui_fonts, GlyphProbe}; use crate::runtime::egui::memory; /// Starts building the system font index for a context. type StartIndex = fn(&Context); -/// What a context remembers of the stack installed in it. +/// What a context remembers of the stack installed in it and of the font definitions it was given last. #[derive(Default)] struct State { - /// Whether the OS's interface face draws in the proportional family of that stack. - system_ui: bool, - /// Whether that stack has the semibold family. - semibold: bool, - /// The line height per point of text of the face that leads the proportional family, measured at install. - line_ratio: f32, + /// The facts of the definitions given last ([`record_facts`]). + facts: StackFacts, /// The provider that serves the stack's faces after the system fonts, swapped in place by every install. installed: Option>, /// A stack installed before the OS face resolved, to install again with it. @@ -35,21 +31,34 @@ struct State { /// height is negligible in the ratio. const LINE_PROBE_SIZE: f32 = 100.0; -/// What text layout and control sizing read of the stack last installed in a context, read once per layout or pass. +/// What text layout and control sizing read of the font definitions a context was given last ([`crate::fonts::load`], +/// which a stack's install calls), read once per layout or pass. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(crate) struct StackFacts { /// Whether the OS's interface face draws in the proportional family ([`craft_theme::InterfaceFont::System`], once /// the face resolved). pub system_ui: bool, - /// Whether the semibold family exists. + /// Whether the semibold family ([`SEMIBOLD`]) exists. pub semibold: bool, /// The line height per point of text of the face that leads the proportional family; 0 before a stack installs. pub line_ratio: f32, } -/// The facts of the stack last installed in `ctx`. +/// The facts of the font definitions `ctx` was given last. pub(crate) fn stack_facts(ctx: &Context) -> StackFacts { - memory::with::(ctx, |state| StackFacts { system_ui: state.system_ui, semibold: state.semibold, line_ratio: state.line_ratio }) + memory::with::(ctx, |state| state.facts) +} + +/// Records the facts of `definitions`, which `ctx` is given now: `providers` serve the characters their faces lack, to +/// the probe that measures the line ratio. +pub(in crate::fonts) fn record_facts(ctx: &Context, definitions: &FontDefinitions, providers: Vec>) { + let proportional = definitions.families.get(&FontFamily::Proportional).map(Vec::as_slice).unwrap_or_default(); + let facts = StackFacts { + system_ui: proportional.iter().any(|name| name == SYSTEM_UI_REGULAR) && definitions.font_data.contains_key(SYSTEM_UI_REGULAR), + semibold: definitions.families.contains_key(&FontFamily::Name(SEMIBOLD.into())), + line_ratio: GlyphProbe::new(definitions.clone(), providers).row_height(&FontRef::proportional(), LINE_PROBE_SIZE) / LINE_PROBE_SIZE, + }; + memory::with::(ctx, |state| state.facts = facts); } /// Installs the stack kept for `ctx` once the OS face has resolved: the first pass after it resolves. @@ -96,16 +105,10 @@ impl Stack { /// [`Self::install`] without fetching; `miss` is asked for characters no face has. pub(in crate::fonts) fn install_faces(&self, ctx: &Context, miss: Option>) { - load(ctx, self.checked_definitions()); - let system_ui = self.has_system_ui(); - let semibold = self.definitions.families.contains_key(&FontFamily::Name(SEMIBOLD.into())); - let line_ratio = self.probe(false).row_height(&FontRef::proportional(), LINE_PROBE_SIZE) / LINE_PROBE_SIZE; + load_with(ctx, self.checked_definitions(), self.providers(false)); let (system, start_index) = self.context_lookup(); let (installed, added, replaced) = memory::with::(ctx, |state| { let replaced = state.pending.take(); - state.system_ui = system_ui; - state.semibold = semibold; - state.line_ratio = line_ratio; state.pending = self.system_ui_pending.then(|| self.clone()); match &state.installed { Some(installed) => (Arc::clone(installed), false, replaced), @@ -160,11 +163,6 @@ impl Stack { } } - /// Whether the system face draws in the proportional family: its slot is there, with data. - fn has_system_ui(&self) -> bool { - self.chain_of(&FontFamily::Proportional).iter().any(|n| n == SYSTEM_UI_REGULAR) && self.definitions.font_data.contains_key(SYSTEM_UI_REGULAR) - } - /// A glyph probe over the stack, for coverage checks. `with_system` adds the system font /// provider. pub(in crate::fonts) fn probe(&self, with_system: bool) -> GlyphProbe { From 3ad64a26ea8a72c03c416681e14f7744393790b1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 16:38:18 +0000 Subject: [PATCH 10/13] craft-keymap: DeleteKeys says whether Delete and Backspace are one key A keymap takes Delete and Backspace as one key by default (`DeleteKeys::OneKey`, Photoshop's rule): a press runs its own key's binding, else the other key's. `Keymap::with_delete_keys(DeleteKeys::Apart)` keeps them two keys, for an app that gives them different jobs, and `Matcher` then runs only the pressed key's binding. --- crates/keymap/src/keymap.rs | 15 ++++++++++++- crates/keymap/src/keymap/command.rs | 13 +++++++++++ crates/keymap/src/lib.rs | 2 +- crates/keymap/src/matcher.rs | 35 ++++++++++++++++------------- crates/keymap/tests/keymap.rs | 26 +++++++++++++++++++-- 5 files changed, 71 insertions(+), 20 deletions(-) diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index f5ff3edc47..a9c242783a 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -27,7 +27,7 @@ mod binding; mod command; pub use binding::{Binding, BindingError}; -pub use command::{CommandDef, CommandKind, ModalRule, TypingRule}; +pub use command::{CommandDef, CommandKind, DeleteKeys, ModalRule, TypingRule}; mod editing; pub use editing::text_editing_chords; @@ -267,6 +267,7 @@ pub struct Keymap { scopes: Scopes, platform: Platform, typing: TypingRule, + delete_keys: DeleteKeys, reserved: Vec, overrides: Overrides, /// Tools of different groups may share a chord ([`Keymap::with_shared_tool_keys`]). @@ -294,6 +295,7 @@ impl Keymap { scopes, platform, typing: TypingRule::default(), + delete_keys: DeleteKeys::default(), reserved: Vec::new(), overrides: Overrides::new(), shared_tool_keys: false, @@ -324,6 +326,12 @@ impl Keymap { self } + /// Sets how a press of Delete or Backspace finds its binding ([`DeleteKeys`]). + pub fn with_delete_keys(mut self, keys: DeleteKeys) -> Keymap { + self.delete_keys = keys; + self + } + /// Chords that cannot be assigned or bound, e.g. [`reserved::system`](crate::reserved::system). /// Without this call the keymap reserves no chord. A default binding on a reserved chord is dropped. pub fn with_reserved(mut self, chords: Vec) -> Keymap { @@ -367,6 +375,11 @@ impl Keymap { self.typing } + /// How a press of Delete or Backspace finds its binding. + pub fn delete_keys(&self) -> DeleteKeys { + self.delete_keys + } + /// Every command the user can bind, in catalog order. pub fn catalog(&self) -> &[CommandDef] { &self.catalog diff --git a/crates/keymap/src/keymap/command.rs b/crates/keymap/src/keymap/command.rs index e20a87fbda..e29300cdd7 100644 --- a/crates/keymap/src/keymap/command.rs +++ b/crates/keymap/src/keymap/command.rs @@ -179,6 +179,19 @@ pub enum TypingRule { AllWait, } +/// How a press of Delete or Backspace finds its binding. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum DeleteKeys { + /// Delete and Backspace are one key, as in Photoshop: a press runs its own key's binding, else the other key's + /// with the same modifiers. The Mac's key labelled "delete" sends Backspace, so a Delete binding runs from it. + #[default] + OneKey, + /// Delete and Backspace are two keys: a press runs only its own key's binding, for an app that gives them + /// different jobs (Delete removes the layer, Backspace a path tool's point). + Apart, +} + impl TypingRule { /// Whether `chord` may fire while typing on `platform`. pub fn fires(self, chord: &Chord, platform: Platform) -> bool { diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index 2b4943cc82..02a8abc3e2 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -158,7 +158,7 @@ pub use import::{ ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan, }; pub use keymap::{ - AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DropReason, Holder, Keymap, Lookup, + AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, }; pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout}; diff --git a/crates/keymap/src/matcher.rs b/crates/keymap/src/matcher.rs index ef687a70e3..3976c40741 100644 --- a/crates/keymap/src/matcher.rs +++ b/crates/keymap/src/matcher.rs @@ -4,7 +4,7 @@ use crate::DOUBLE_PRESS; use crate::chord::{Chord, Key, Mods, PressKind, Trigger}; use crate::command::CommandRef; -use crate::keymap::{Keymap, Lookup}; +use crate::keymap::{DeleteKeys, Keymap, Lookup}; use crate::layout::{KeyInput, Layout}; use crate::scope::Active; @@ -72,7 +72,7 @@ pub struct Matcher { } impl Matcher { - /// A matcher with Delete and Backspace standing for each other. + /// A matcher with no previous press. pub fn new() -> Matcher { Matcher::default() } @@ -87,7 +87,7 @@ impl Matcher { /// scope or of its next chord candidate, as if the refused one were not bound. pub fn press_where(&mut self, layout: &Layout, keymap: &Keymap, press: &Press<'_>, accept: &dyn Fn(&CommandRef) -> bool) -> Option { let Press { input, repeat, now, active, outer } = *press; - let chords = Chords::of(layout, input)?; + let chords = Chords::of(layout, keymap, input)?; let m = Match { keymap, active, outer, accept }; if repeat { return chords.single(&m); @@ -105,13 +105,13 @@ impl Matcher { /// The command a press of `input` runs on its own, as [`press`](Self::press) matches a press that completes no /// double press: for a key that is held down rather than pressed now (a key automation holds). Keeps no state. pub fn single(layout: &Layout, keymap: &Keymap, input: &KeyInput, active: &Active<'_>, outer: &[&str]) -> Option { - Chords::of(layout, input)?.single(&Match { keymap, active, outer, accept: &|_| true }) + Chords::of(layout, keymap, input)?.single(&Match { keymap, active, outer, accept: &|_| true }) } /// The command a hold of `input` runs: for a key that stays down past the hold time. Keeps no state. // PLAN: `Keymap::hold_of` ranks without the outer panels, so `outer` has no effect yet. pub fn hold(layout: &Layout, keymap: &Keymap, input: &KeyInput, active: &Active<'_>, _outer: &[&str]) -> Option { - Chords::of(layout, input)?.hold(keymap, active) + Chords::of(layout, keymap, input)?.hold(keymap, active) } } @@ -126,12 +126,13 @@ struct Match<'a> { } /// The chords one press can run, most specific first: the chord with the Shift the layout dropped kept (rule 3's -/// exception), the layout's candidates, then Delete and Backspace standing for each other. +/// exception), the layout's candidates, then, where the keymap takes them as one key ([`DeleteKeys::OneKey`]), Delete +/// and Backspace standing for each other. struct Chords(Vec, Chord); impl Chords { /// `None` when the press names no key. - fn of(layout: &Layout, input: &KeyInput) -> Option { + fn of(layout: &Layout, keymap: &Keymap, input: &KeyInput) -> Option { let mut chords = layout.candidates(input); let meant = chords.first().copied()?; // Rule 3's exception (`layout` docs): where the layout dropped the Shift the person held for a symbol that @@ -142,15 +143,17 @@ impl Chords { chords.retain(|chord| *chord != kept); chords.insert(0, kept); } - let twins: Vec = chords - .iter() - .filter_map(|c| match c.key { - Key::Delete => Some(Chord::new(c.mods, Key::Backspace)), - Key::Backspace => Some(Chord::new(c.mods, Key::Delete)), - _ => None, - }) - .collect(); - chords.extend(twins); + if keymap.delete_keys() == DeleteKeys::OneKey { + let twins: Vec = chords + .iter() + .filter_map(|c| match c.key { + Key::Delete => Some(Chord::new(c.mods, Key::Backspace)), + Key::Backspace => Some(Chord::new(c.mods, Key::Delete)), + _ => None, + }) + .collect(); + chords.extend(twins); + } Some(Chords(chords, meant)) } diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index fec6264cb3..d08ef54486 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -1,8 +1,8 @@ //! Integration tests of craft-keymap: keymap. use craft_keymap::{ - Active, Binding, Chord, CommandDef, CommandRef, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, Overrides, - Platform, Policy, Press, Problem, Scope, Scopes, Trigger, + Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, + Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, }; use serde_json::json; @@ -218,6 +218,28 @@ fn the_alt_variant_follows_the_commands_key_and_yields_to_a_bound_alt_chord() { assert!(hit(&km, &alt(Key::F2, false, false)).is_none(), "a command that did not opt in has no Alt variant"); } +/// Delete and Backspace: a press runs its own key's binding; with the keys one key (the default) a key with no +/// binding of its own runs the other's, and with the keys apart it runs nothing. +#[test] +fn delete_and_backspace_run_their_own_bindings_and_stand_in_only_as_one_key() { + let hit = |km: &Keymap, key: Key| { + let input = KeyInput::new(Mods::NONE).with_physical(key); + let press = Press { input: &input, repeat: false, now: 0.0, active: &Active::NONE, outer: &[] }; + Matcher::new().press(&Layout::new(), km, &press).map(|hit| hit.command) + }; + let both = || vec![app("layer.remove", &["Delete"]), app("path.removePoint", &["Backspace"])]; + for keys in [DeleteKeys::OneKey, DeleteKeys::Apart] { + let km = Keymap::new(both(), Scopes::new(), Platform::Linux).with_delete_keys(keys); + assert_eq!(hit(&km, Key::Delete), Some(cmd("layer.remove")), "{keys:?}: Delete runs its own binding"); + assert_eq!(hit(&km, Key::Backspace), Some(cmd("path.removePoint")), "{keys:?}: Backspace runs its own binding"); + } + let delete_only = || vec![app("layer.remove", &["Delete"])]; + let km = Keymap::new(delete_only(), Scopes::new(), Platform::Mac); + assert_eq!(hit(&km, Key::Backspace), Some(cmd("layer.remove")), "one key: Backspace runs the Delete binding"); + let km = Keymap::new(delete_only(), Scopes::new(), Platform::Mac).with_delete_keys(DeleteKeys::Apart); + assert_eq!(hit(&km, Key::Backspace), None, "apart: Backspace runs nothing"); +} + /// A press passes over the binding of a command the caller refuses (one disabled where it lands): the chord's binding /// in an outer scope runs instead, the lookup says the same, and with every holder refused the press runs nothing. #[test] From 859d801189cfcc662802a64c55137a417e6def97 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 17:34:55 +0000 Subject: [PATCH 11/13] A float opened from a listed layer stacks above it Floating windows stay out of the overlay's egui order so they stack with the app's own egui windows, but a listed layer goes above every unlisted one: a panel floated from a full-window container went beneath the container. A float whose parent is listed is listed too, above its parent. --- crates/ui-contract/src/runtime/overlay.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 72c8df9dbf..ab53bbff0e 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -906,16 +906,20 @@ pub(crate) fn end_pass(ctx: &Context) { } let families = families(¤t, &persist.raised); let mut order: Vec = Vec::new(); + let mut listed: Vec = Vec::new(); persist.stack.clear(); for members in &families { for member in members { // A floating window or panel (`Rank::Window`) is left to egui's own area order, which raises a layer // when it first shows and when it is pressed: the app's own egui windows stack with it in that one // order, so a dialog the app opens later shows above it. Listed layers would go above every unlisted - // layer of their egui order. An OS window has no egui layer here. - if !member.window && member.rank != Rank::Window { + // layer of their egui order, so a float opened from a listed layer (a panel floated from a full-window + // container) is listed too, above its parent. An OS window has no egui layer here. + let over_listed = member.parent.is_some_and(|parent| listed.contains(&parent)); + if !member.window && (member.rank != Rank::Window || over_listed) { order.extend(member.cover); order.push(member.layer); + listed.push(member.id); } persist.stack.push(member.id); } From 86ac6ac5f0f6d6cecb813298debadac7fc6cd79c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 17:34:55 +0000 Subject: [PATCH 12/13] ui-panels trial: the claims-after-focus stop is a canvas control The window's document canvas holds its declared claims with nothing focused, so a `KeyUse::CANVAS` stop claimed Up in the frame focus arrived in. The trial is about a focused component's claims; its stop is a canvas control that marks no document (`with_chrome_key(false)`). --- crates/ui-panels/tests/it/focus/keys.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-panels/tests/it/focus/keys.rs b/crates/ui-panels/tests/it/focus/keys.rs index cea11f5da9..10f86a96f9 100644 --- a/crates/ui-panels/tests/it/focus/keys.rs +++ b/crates/ui-panels/tests/it/focus/keys.rs @@ -63,14 +63,15 @@ fn a_held_escape_cancels_once() { } /// Static claims hold in the frame after focus arrives; the chord is withheld from egui and read once through -/// `take_claimed`, and a claimed Escape is no `Cancel`. +/// `take_claimed`, and a claimed Escape is no `Cancel`. The stop is a canvas control, not the window's document canvas, +/// whose claims hold with nothing focused too. #[trial] fn claimed_chords_hold_after_focus_arrives_and_a_claimed_escape_is_no_cancel() { const CLAIMS: &[Chord] = &[Chord::plain(craft_keymap::Key::Up), Chord::plain(craft_keymap::Key::Escape)]; let mut frames = Frames::new(); let reads = RefCell::new((Vec::new(), 0, true)); let mut show = |ui: &mut egui::Ui| { - stop_with(ui, "canvas", KeyUse::CANVAS.with_claims(CLAIMS)); + stop_with(ui, "canvas", KeyUse::CANVAS.with_chrome_key(false).with_claims(CLAIMS)); let ctx = ui.ctx(); let mut reads = reads.borrow_mut(); reads.0.push((take_claimed(ctx, id("canvas"), CLAIMS[0]), take_claimed(ctx, id("canvas"), CLAIMS[1]))); From ea3b99e892474928d315ba9f93784f3736ca52ed Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 18:32:25 +0000 Subject: [PATCH 13/13] ui-patterns: drop a dock-gaps trial file the merge picked up from the worktree --- crates/ui-patterns/tests/it/docking/documents.rs | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 crates/ui-patterns/tests/it/docking/documents.rs diff --git a/crates/ui-patterns/tests/it/docking/documents.rs b/crates/ui-patterns/tests/it/docking/documents.rs deleted file mode 100644 index e69de29bb2..0000000000