mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 02:32:33 +00:00
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
This commit is contained in:
@@ -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<Vec<(Platform, BuiltKeymap)>> = 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<Vec<(Platform, bool, BuiltKeymap)>> = 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<registry::Registry>, 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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Vec<PlatformDefault>, 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<Vec<PlatformDefault>, 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<Arc<Registry>> = OnceLock::new();
|
||||
/// The shared registries: the app's sets, and the app's sets with the stories' (`[apps, with stories]`).
|
||||
static LOADED: [OnceLock<Arc<Registry>>; 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<String, EditCommand>,
|
||||
/// 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<Registry, CommandDefError> {
|
||||
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<Registry, CommandDefError> {
|
||||
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<Arc<Registry>, 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<Arc<Registry>, 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<Registry>) -> 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> {
|
||||
|
||||
@@ -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<PenSource>,
|
||||
/// 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<Mutex<Store>>) -> 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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"))]
|
||||
|
||||
@@ -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<LitStr>,
|
||||
scope: Option<LitStr>,
|
||||
story: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -211,11 +212,14 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
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<TokenStream> {
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
#k::__register_command_set!(#ident);
|
||||
#register
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ fn expanded(result: syn::Result<proc_macro2::TokenStream>) -> 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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -32,6 +32,8 @@ pub struct AppSpec {
|
||||
pub window_system: Arc<dyn WindowSystem>,
|
||||
/// Who draws the root window's frame (`craft_window::policy::decide_for`). Unset: the OS draws it.
|
||||
pub frame: Option<Decision>,
|
||||
/// 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<Mutex<Store>>) -> Self {
|
||||
self.placement = store;
|
||||
@@ -171,6 +180,9 @@ fn create<A: ShellApp + 'static>(
|
||||
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}"))?;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user