From 19cd2e1762439b35a624a888783a00b0481bbb5d Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 18:28:52 +0000 Subject: [PATCH] commands: a story's command set (#[command(story)]) loads only in an install that shows stories (the gallery, the story fixtures), so its keys never take an app's --- .../ui-contract/src/runtime/commands/board.rs | 17 +++--- .../src/runtime/commands/registry.rs | 58 +++++++++++++------ crates/ui-contract/src/runtime/install.rs | 12 +++- crates/ui-contract/src/testing/frames.rs | 8 ++- crates/ui-contract/src/testing/windows.rs | 4 +- crates/ui-gallery/src/main.rs | 2 +- crates/ui-macros/src/command_set.rs | 8 ++- crates/ui-macros/src/lib.rs | 3 +- crates/ui-panels/src/rails/tool/stories.rs | 2 +- .../ui-panels/src/sections/panel/stories.rs | 2 +- .../src/patterns/panels/palette/stories.rs | 2 +- crates/ui-shell/src/shell/app.rs | 12 ++++ .../ui-shell/tests/it/commands/app_catalog.rs | 27 +++++++++ 13 files changed, 119 insertions(+), 38 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index ed54cdd2b..ee6338466 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -429,9 +429,9 @@ fn chord_input(chord: &Chord) -> KeyInput { KeyInput::new(chord.mods).with_typed(chord.key).with_physical(chord.key) } -/// Loads the linked command sets. -pub(crate) fn install(ctx: &Context) -> Result<(), registry::CommandDefError> { - let registry = registry::Registry::shared()?; +/// Loads the linked command sets; the stories' sets only with `stories`. +pub(crate) fn install(ctx: &Context, stories: bool) -> Result<(), registry::CommandDefError> { + let registry = registry::Registry::shared(stories)?; with(ctx, |board| board.registry = registry); Ok(()) } @@ -535,9 +535,9 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts } } -/// The keymap of the shared registry on each platform with no overrides. It depends on nothing else, so every -/// context of the process shares it. -static DEFAULT_KEYMAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// The keymap of each shared registry (with or without the stories' sets) on each platform with no overrides. It +/// depends on nothing else, so every context of the process shares it. +static DEFAULT_KEYMAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// The keymap of `registry` and `app` on `platform` under `overrides`: built once per platform for the shared /// registry with no overrides and no catalog, else built here. @@ -546,11 +546,12 @@ fn keymap_for(registry: &Arc, app: Option<&AppCatalog>, plat return build_keymap(registry, app, platform, overrides); } let mut kept = DEFAULT_KEYMAPS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((_, built)) = kept.iter().find(|(on, _)| *on == platform) { + let stories = registry.has_stories(); + if let Some((.., built)) = kept.iter().find(|(on, with, _)| *on == platform && *with == stories) { return built.clone(); } let built = build_keymap(registry, None, platform, None); - kept.push((platform, built.clone())); + kept.push((platform, stories, built.clone())); built } diff --git a/crates/ui-contract/src/runtime/commands/registry.rs b/crates/ui-contract/src/runtime/commands/registry.rs index adccc9d0e..4a9951463 100644 --- a/crates/ui-contract/src/runtime/commands/registry.rs +++ b/crates/ui-contract/src/runtime/commands/registry.rs @@ -23,6 +23,8 @@ pub struct SetEntry { pub edits: fn() -> Vec<(&'static str, EditCommand)>, /// The defaults of one platform, which replace the command's other defaults there. pub platform_defaults: fn() -> Result, CommandDefError>, + /// A story's set (`#[command(story)]`): loaded only by an install that shows stories. + pub story: bool, } impl SetEntry { @@ -34,7 +36,13 @@ impl SetEntry { edits: fn() -> Vec<(&'static str, EditCommand)>, platform_defaults: fn() -> Result, CommandDefError>, ) -> Self { - SetEntry { name, defs, no_default_on, edits, platform_defaults } + SetEntry { name, defs, no_default_on, edits, platform_defaults, story: false } + } + + /// The entry as a story's set. + pub const fn story(mut self) -> Self { + self.story = true; + self } } @@ -48,20 +56,27 @@ pub fn sets() -> Vec<&'static SetEntry> { sets } -/// Registers the command set `$ty`, so `install` loads it. +/// Registers the command set `$ty`, so `install` loads it; `story` registers a story's set, which only an install +/// that shows stories loads. #[doc(hidden)] #[macro_export] macro_rules! __register_command_set { ($ty:ty) => { + $crate::__register_command_set!(@entry $ty, ::core::convert::identity); + }; + ($ty:ty, story) => { + $crate::__register_command_set!(@entry $ty, $crate::runtime::commands::SetEntry::story); + }; + (@entry $ty:ty, $mark:expr) => { const _: () = { $crate::__private::inventory::submit! { - $crate::runtime::commands::SetEntry::new( + $mark($crate::runtime::commands::SetEntry::new( ::std::any::type_name::<$ty>, <$ty as $crate::runtime::commands::CommandSet>::defs, <$ty as $crate::runtime::commands::CommandSet>::no_default_on, <$ty as $crate::runtime::commands::CommandSet>::edits, <$ty as $crate::runtime::commands::CommandSet>::platform_defaults, - ) + )) } }; }; @@ -124,7 +139,8 @@ impl std::fmt::Display for CommandDefError { impl std::error::Error for CommandDefError {} -static LOADED: OnceLock> = OnceLock::new(); +/// The shared registries: the app's sets, and the app's sets with the stories' (`[apps, with stories]`). +static LOADED: [OnceLock>; 2] = [OnceLock::new(), OnceLock::new()]; /// Indexes the definition at `at` under its id `id`; an id already in `index` is refused (`Duplicate`). The registry /// and an app's catalog index their definitions through it. @@ -146,13 +162,15 @@ pub(crate) struct Registry { edits: HashMap, /// Defaults that one platform has instead of the command's others. platform_defaults: Vec<(String, Platform, Binding)>, + /// Whether the stories' sets are loaded. + stories: bool, } impl Registry { - /// Loads every linked set. - pub(crate) fn load() -> Result { - let mut registry = Registry::default(); - for entry in sets() { + /// Loads every linked set; the stories' sets only with `stories`. + pub(crate) fn load(stories: bool) -> Result { + let mut registry = Registry { stories, ..Registry::default() }; + for entry in sets().into_iter().filter(|entry| stories || !entry.story) { for def in (entry.defs)()? { registry.add(def)?; } @@ -165,19 +183,25 @@ impl Registry { Ok(registry) } - /// The registry of every linked set, loaded once per process: the sets are static, so every context shares one. - /// A load that fails is not kept, so each install reports its error. - pub(crate) fn shared() -> Result, CommandDefError> { - if let Some(loaded) = LOADED.get() { + /// The registry of every linked set (the stories' sets only with `stories`), loaded once per process: the sets are + /// static, so every context shares one. A load that fails is not kept, so each install reports its error. + pub(crate) fn shared(stories: bool) -> Result, CommandDefError> { + let slot = &LOADED[usize::from(stories)]; + if let Some(loaded) = slot.get() { return Ok(loaded.clone()); } - let registry = Arc::new(Registry::load()?); - Ok(LOADED.get_or_init(|| registry).clone()) + let registry = Arc::new(Registry::load(stories)?); + Ok(slot.get_or_init(|| registry).clone()) } - /// Whether `registry` is the one [`Registry::shared`] loaded. + /// Whether `registry` is one [`Registry::shared`] loaded. pub(crate) fn is_shared(registry: &Arc) -> bool { - LOADED.get().is_some_and(|loaded| Arc::ptr_eq(loaded, registry)) + LOADED[usize::from(registry.stories)].get().is_some_and(|loaded| Arc::ptr_eq(loaded, registry)) + } + + /// Whether the stories' sets are loaded. + pub(crate) fn has_stories(&self) -> bool { + self.stories } fn add(&mut self, def: CommandDef) -> Result<(), CommandDefError> { diff --git a/crates/ui-contract/src/runtime/install.rs b/crates/ui-contract/src/runtime/install.rs index c9ba2d65d..69d4c0ebe 100644 --- a/crates/ui-contract/src/runtime/install.rs +++ b/crates/ui-contract/src/runtime/install.rs @@ -39,6 +39,9 @@ pub struct InstallSpec { pub app_id: String, /// The tablet readings the pointer feed pairs with each pointer move; none reports no pen. pub pen: Option, + /// Whether the stories' command sets (`#[command(story)]`) load: the gallery and the story fixtures show + /// stories, an app does not, so a story's keys never reach an app's keymap. + pub stories: bool, } /// The modifiers the mouse wheel zooms and scrolls sideways with. @@ -70,9 +73,16 @@ impl InstallSpec { wheel: WheelModifiers::default(), app_id: String::new(), pen: None, + stories: false, } } + /// Loads the stories' command sets too, for an install that shows stories. + pub fn stories(mut self) -> Self { + self.stories = true; + self + } + /// Sets the store viewport mounts save their window placement in. pub fn placement(mut self, store: Arc>) -> Self { self.placement = Some(store); @@ -177,7 +187,7 @@ pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError> { return Err(InstallError::DuringPass); } let looks = spec.looks.freeze().map_err(InstallError::DuplicateStyle)?; - commands::install(ctx).map_err(InstallError::Commands)?; + commands::install(ctx, spec.stories).map_err(InstallError::Commands)?; looks.store(ctx); input::clear_shortcuts(ctx); input::set_wheel_modifiers(ctx, spec.wheel.zoom, spec.wheel.sideways); diff --git a/crates/ui-contract/src/testing/frames.rs b/crates/ui-contract/src/testing/frames.rs index 1914dc168..7474aee89 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -88,11 +88,13 @@ impl Frames { } /// Frames on `ctx`, a context the caller made (an app's own, which its code reads outside the frames), with the - /// runtime installed on it unless it already is. The context keeps its own fonts and options. + /// runtime installed on it unless it already is, as an app installs it: without the stories' command sets. The + /// context keeps its own fonts and options. pub fn over(ctx: Context) -> Self { - let mut frames = Self::on(ctx); + let frames = Self::on(ctx); if !plugin::is_registered(&frames.ctx) { - frames.install(); + let installed = crate::install(&frames.ctx, crate::runtime::InstallSpec { stories: false, ..super::install_spec() }); + debug_assert!(installed.is_ok(), "the context takes the runtime once"); } frames } diff --git a/crates/ui-contract/src/testing/windows.rs b/crates/ui-contract/src/testing/windows.rs index e1208f53b..82fa515be 100644 --- a/crates/ui-contract/src/testing/windows.rs +++ b/crates/ui-contract/src/testing/windows.rs @@ -8,9 +8,9 @@ pub use crate::runtime::egui::fixture::{FullOutput, RawInput, dragged_id, record pub use craft_window::system::{FakeSystem, NoWindows}; -/// An install spec for the running build's shell and a system with no OS services. +/// An install spec for the running build's shell and a system with no OS services, with the stories' command sets. pub fn install_spec() -> InstallSpec { - InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)) + InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).stories() } /// Makes the shell of `ctx` run on `os`, for a test of the OS matrix: the key table, the chords shown, the chrome, diff --git a/crates/ui-gallery/src/main.rs b/crates/ui-gallery/src/main.rs index e3b32633a..e7343b4d8 100644 --- a/crates/ui-gallery/src/main.rs +++ b/crates/ui-gallery/src/main.rs @@ -9,7 +9,7 @@ const TITLE: &str = "craft-ui stories"; const WINDOW_MIN: [f32; 2] = [640.0, 480.0]; fn spec() -> AppSpec { - AppSpec::new("craft-ui-gallery", TITLE, Defaults::new(WINDOW, WINDOW_MIN)) + AppSpec::new("craft-ui-gallery", TITLE, Defaults::new(WINDOW, WINDOW_MIN)).stories() } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-macros/src/command_set.rs b/crates/ui-macros/src/command_set.rs index 86791d02e..f37265ee3 100644 --- a/crates/ui-macros/src/command_set.rs +++ b/crates/ui-macros/src/command_set.rs @@ -1,4 +1,4 @@ -//! `#[derive(CommandSet)]` with `#[command(prefix = "..", scope = "..")]` on the enum and +//! `#[derive(CommandSet)]` with `#[command(prefix = "..", scope = "..", story)]` on the enum and //! `#[command(label = "..", icon = "..", kind = "..", group = "..", modal = "..", edit = "..", default = "..", path = "..", alias = "..")]` on variants. //! `edit = ".."` links the command to the `EditCommand` a focused component takes it as. //! `default(mac = "..")` (or `windows`, `linux`) is a default of one platform: it replaces the unqualified defaults there. @@ -12,6 +12,7 @@ use syn::{Attribute, Data, DeriveInput, Fields, LitStr, Variant}; struct SetAttrs { prefix: Option, scope: Option, + story: bool, } #[derive(Default)] @@ -211,11 +212,14 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { set.prefix = Some(meta.value()?.parse()?); } else if meta.path.is_ident("scope") { set.scope = Some(meta.value()?.parse()?); + } else if meta.path.is_ident("story") { + set.story = true; } else { return Ok(false); } Ok(true) })?; + let register = if set.story { quote!(#k::__register_command_set!(#ident, story);) } else { quote!(#k::__register_command_set!(#ident);) }; let prefix = set.prefix.ok_or_else(|| syn::Error::new_spanned(ident, "a command set names its id prefix: `#[command(prefix = \"..\")]`"))?; check_prefix(&prefix)?; if let Some(scope) = &set.scope { @@ -316,7 +320,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { } const _: () = { - #k::__register_command_set!(#ident); + #register }; }) } diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 5022882ae..06c321c09 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -27,7 +27,8 @@ fn expanded(result: syn::Result) -> TokenStream { /// Writes `CommandSet` for an enum of unit variants and registers the set, which the command board loads at /// install. `#[command(prefix = "..", scope = "..")]` on the enum gives the id prefix and the scope (the -/// application scope without one). The prefix is one lower-camel segment naming the set's type, and ids are +/// application scope without one); `#[command(story)]` marks a story's set, which only an install that shows stories +/// loads (the gallery, the story fixtures), so its keys never reach an app. The prefix is one lower-camel segment naming the set's type, and ids are /// `prefix.variant_name`. Each variant takes `label`, `icon`, `kind`, `modal`, `edit` (the `EditCommand` a focused component takes the command as), `default`, `path` and `alias`. #[proc_macro_derive(CommandSet, attributes(command))] pub fn derive_command_set(input: TokenStream) -> TokenStream { diff --git a/crates/ui-panels/src/rails/tool/stories.rs b/crates/ui-panels/src/rails/tool/stories.rs index 335aeaaf7..94a208b4f 100644 --- a/crates/ui-panels/src/rails/tool/stories.rs +++ b/crates/ui-panels/src/rails/tool/stories.rs @@ -7,7 +7,7 @@ use std::num::NonZeroU8; /// The tools of the stories. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui_macros::CommandSet)] -#[command(prefix = "railStory")] +#[command(prefix = "railStory", story)] #[non_exhaustive] pub(crate) enum StoryTools { /// Move. diff --git a/crates/ui-panels/src/sections/panel/stories.rs b/crates/ui-panels/src/sections/panel/stories.rs index 18c5cc05f..398c31068 100644 --- a/crates/ui-panels/src/sections/panel/stories.rs +++ b/crates/ui-panels/src/sections/panel/stories.rs @@ -13,7 +13,7 @@ use egui::Ui; /// The header commands of the stories. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui_macros::CommandSet)] -#[command(prefix = "panelStory")] +#[command(prefix = "panelStory", story)] #[non_exhaustive] enum CardCommands { /// Open. diff --git a/crates/ui-patterns/src/patterns/panels/palette/stories.rs b/crates/ui-patterns/src/patterns/panels/palette/stories.rs index f90c10a2c..da81dbb08 100644 --- a/crates/ui-patterns/src/patterns/panels/palette/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/palette/stories.rs @@ -10,7 +10,7 @@ use std::sync::LazyLock; /// The PhotoCraft commands of the stories that the library's edit commands do not cover. #[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)] -#[command(prefix = "paletteStory")] +#[command(prefix = "paletteStory", story)] enum PhotoCraftCommand { #[command(label = "Search", icon = "search", default = "Cmd+F")] Search, diff --git a/crates/ui-shell/src/shell/app.rs b/crates/ui-shell/src/shell/app.rs index df0547967..0a56dcbe5 100644 --- a/crates/ui-shell/src/shell/app.rs +++ b/crates/ui-shell/src/shell/app.rs @@ -32,6 +32,8 @@ pub struct AppSpec { pub window_system: Arc, /// Who draws the root window's frame (`craft_window::policy::decide_for`). Unset: the OS draws it. pub frame: Option, + /// Whether the stories' command sets load ([`InstallSpec::stories`]): the gallery's spec sets it. + pub stories: bool, } impl AppSpec { @@ -46,9 +48,16 @@ impl AppSpec { placement: Arc::new(Mutex::new(Store::in_memory())), window_system: Arc::new(SystemWindows), frame: None, + stories: false, } } + /// Loads the stories' command sets too, for an app that shows stories (the gallery). + pub fn stories(mut self) -> Self { + self.stories = true; + self + } + /// Sets the placement store, shared by every window of the app. pub fn placement(mut self, store: Arc>) -> Self { self.placement = store; @@ -171,6 +180,9 @@ fn create( if let Some(decision) = spec.frame { install = install.frame(decision); } + if spec.stories { + install = install.stories(); + } // The suite's interface face; an app that installs its own fonts in `make` replaces it. let fonts = crate::fonts::UiFonts::new(&crate::fonts::I18nScripts); embed::install(&cc.egui_ctx, install, &fonts).map_err(|error| format!("the runtime could not be installed: {error}"))?; diff --git a/crates/ui-shell/tests/it/commands/app_catalog.rs b/crates/ui-shell/tests/it/commands/app_catalog.rs index d67e8ca47..f5b07488e 100644 --- a/crates/ui-shell/tests/it/commands/app_catalog.rs +++ b/crates/ui-shell/tests/it/commands/app_catalog.rs @@ -172,3 +172,30 @@ fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() { frames.frame(vec![key_release(Key::F2, Modifiers::NONE)], &mut show); assert_eq!(fired(&frames), by_registry_key, "the catalog's alternate key does what the registry's key does"); } + +/// A story's commands: only an install that shows stories loads them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::CommandSet)] +#[command(prefix = "trialStory", story)] +#[non_exhaustive] +enum StoryCommand { + #[command(label = "Story Eraser", default = "Cmd+Alt+Shift+E")] + Eraser, +} + +/// A story's command set binds its keys in an install that shows stories (the story fixtures, the gallery) and is absent +/// from an app's install, so a story's keys never take an app's. +#[trial] +fn a_story_command_set_loads_only_in_an_install_that_shows_stories() { + let eraser = CommandRef::from(StoryCommand::Eraser); + let mut stories = Frames::new(); + stories.idle(2, &mut |_: &mut Ui| {}); + assert!(!craft_ui::runtime::commands::bindings(&stories.ctx, &eraser).is_empty(), "the story fixture loads the story's set"); + + let mut app = Frames::uninstalled(); + let spec = craft_ui::InstallSpec::new(craft_host::target::ShellInfo::default(), std::sync::Arc::new(craft_ui::testing::windows::NoWindows)); + craft_ui::install(&app.ctx, spec).expect("the app's install"); + app.idle(2, &mut |_: &mut Ui| {}); + assert!(craft_ui::runtime::commands::bindings(&app.ctx, &eraser).is_empty(), "an app's install has no story's set"); + let save = CommandRef::new("trial.save"); + assert!(!craft_ui::runtime::commands::bindings(&app.ctx, &save).is_empty(), "the app's install keeps the other sets"); +}