Merge pull request #2358 from aiongg/memo-resolve

Command resolution only on change (#2336)
This commit is contained in:
aiongg authored and GitHub committed 2026-11-19 18:17:22 -05:00
commit ee73f4ef3f
30 files changed
+1376 -301

No files matched your search

+2 -2
View File
@@ -25,7 +25,7 @@
//! contrast without them). A value that is not one of these is refused. `stories.tsv` lists the scale of every image.
use craft_behavior::ColumnWidth;
use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface};
use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface, Tracked};
use craft_ui::fonts::{I18nScripts, UiFonts};
use craft_ui::layout_components::{Grid, Stack};
use craft_ui::runtime::commands::CommandInput;
@@ -312,7 +312,7 @@ fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options)
// The command states of the story shown, as the gallery gives them, before the first frame. The Overview gives its
// cards none, so a card is rendered under none.
frames.commands(match &job.shown {
Shown::Story(registration) => Story::command_input([&registration.story]),
Shown::Story(registration) => CommandInput::new().states(&Tracked::new(Story::command_states([&registration.story]))),
Shown::Card(_) => CommandInput::new(),
});
let (shown, dialog) = match &job.shown {
+1 -1
View File
@@ -1082,7 +1082,7 @@ fn a_held_space_pans_over_a_canvas_control_and_leaves_it_unchanged() {
fn a_queued_space_whose_hand_the_gate_refuses_leaves_the_press_to_the_selected_tool() {
let log = Log::default();
let (mut fixture, view, canvas) = momentary_canvas(Probe::new("main", &log));
fixture.gate(CommandGate::new(|command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle();
fixture.gate(CommandGate::new((), |_: &(), command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle();
let at = fixture.by_role(Role::CANVAS)[0].rect.center();
let before = view.get().expect("the canvas ran").center;
let space = craft_keymap::Key::Space;
@@ -52,7 +52,7 @@ impl<C: Component> MeasureCx<'_, C> {
/// `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above
/// the component, and the enabled state of its instance. `None` when the command is scoped and no instance of
/// its scope is above the component.
pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<ResolvedCommand> {
pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<std::sync::Arc<ResolvedCommand>> {
commands::resolve_scoped(self.ui.ctx(), self.env.command_chain(), &command.into())
}
+1 -1
View File
@@ -33,7 +33,7 @@ pub(crate) fn variants<C: Component>(asked: Option<Variant>) -> (Variant, Varian
/// size; variant; label.
/// `(requested, variant)` comes from `variants`.
pub(crate) fn env(ctx: &Context, env: &Env, common: &Common, (requested, variant): (Variant, Variant)) -> EnvStep {
let command = common.command.as_ref().map(|command| Arc::new(commands::resolve_bound(ctx, &env.commands, command)));
let command = common.command.as_ref().map(|command| commands::resolve_bound(ctx, &env.commands, command));
let label = match (&common.label, &command) {
(Label::Empty, Some(command)) => Label::Shared(command.label.clone()),
(label, _) => label.resolved(&env.words),
File diff suppressed because it is too large. Load diff
+71 -14
View File
@@ -31,6 +31,7 @@ pub use board::{bound_around, take_around};
pub use board::{chord_text_builds, keymap_builds};
pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped};
use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked};
use craft_behavior::CommandFlags;
use craft_behavior::edit_history::Step;
use craft_keymap::{Chord, Overrides};
@@ -280,17 +281,72 @@ pub struct ResolvedCommand {
/// The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an
/// operation is pending. A command the gate refuses resolves disabled and does not fire.
///
/// The gate is a `fn` of its props, as a memoized view's `show` is: the props hold everything the gate reads, so the
/// runtime asks it once per command while the props' key stays the same, and again only when it changes.
#[derive(Clone)]
pub struct CommandGate(Arc<dyn Fn(&CommandRef) -> bool + Send + Sync>);
pub struct CommandGate {
key: u128,
allows: Arc<dyn Fn(&CommandRef) -> bool + Send + Sync>,
}
impl CommandGate {
/// A gate that lets `allows` commands through.
pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self {
CommandGate(Arc::new(allows))
/// A gate that lets through the commands `allows` accepts under `props`.
pub fn new<P: MemoProps + Send + Sync + 'static>(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self {
let mut key = MemoKey::new();
key.feed_hash(&std::any::TypeId::of::<P>());
key.write(&(allows as usize).to_le_bytes());
props.key(&mut key);
CommandGate { key: key.finish(), allows: Arc::new(move |command| allows(&props, command)) }
}
/// The key of the gate's props and `fn`: equal keys give equal answers.
pub(crate) fn key(&self) -> u128 {
self.key
}
pub(crate) fn allows(&self, command: &CommandRef) -> bool {
(self.0)(command)
(self.allows)(command)
}
}
/// The app-scope command states an app holds, in a [`Tracked`] it hands to [`CommandInput::states`] every frame. The
/// runtime reads them again only when the revision moves.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
pub struct CommandStates {
#[plain_data(assume = "command refs and states are plain values; the list is copied on write")]
states: Arc<Vec<(CommandRef, CommandState)>>,
}
impl CommandStates {
/// No states.
pub fn new() -> Self {
CommandStates::default()
}
/// Gives `command` `state`, in place of the state it had.
pub fn set(&mut self, command: impl Into<CommandRef>, state: CommandState) {
let command = command.into();
let states = Arc::make_mut(&mut self.states);
match states.iter_mut().find(|(held, _)| *held == command) {
Some((_, held)) => *held = state,
None => states.push((command, state)),
}
}
/// Removes the state of `command`, which then resolves with its own label, enabled.
pub fn remove(&mut self, command: &CommandRef) -> Option<CommandState> {
let at = self.states.iter().position(|(held, _)| held == command)?;
Some(Arc::make_mut(&mut self.states).remove(at).1)
}
/// The state of `command`.
pub fn get(&self, command: &CommandRef) -> Option<&CommandState> {
self.states.iter().find(|(held, _)| held == command).map(|(_, state)| state)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = &(CommandRef, CommandState)> {
self.states.iter()
}
}
@@ -298,7 +354,7 @@ impl CommandGate {
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct CommandInput {
pub(crate) states: Vec<(CommandRef, CommandState)>,
pub(crate) states: Option<(Revision, CommandStates)>,
pub(crate) overrides: Option<Arc<Overrides>>,
pub(crate) gate: Option<CommandGate>,
pub(crate) catalog: Option<AppCatalog>,
@@ -310,10 +366,11 @@ impl CommandInput {
CommandInput::default()
}
/// The state of an app-scope command.
/// The app-scope command states the app holds. The runtime keeps the revision and reads the states again only
/// when it moves.
#[must_use]
pub fn state(mut self, command: impl Into<CommandRef>, state: CommandState) -> Self {
self.states.push((command.into(), state));
pub fn states(mut self, states: &Tracked<CommandStates>) -> Self {
self.states = Some((states.revision(), (**states).clone()));
self
}
@@ -331,8 +388,8 @@ impl CommandInput {
self
}
/// The one gate over commands. It answers from what the app knew before the frame: the runtime asks it once per
/// command per frame, whichever components and passes resolve the command.
/// The one gate over commands. The runtime asks it once per command while the gate's props keep their key, whichever
/// components, passes and frames resolve the command.
#[must_use]
pub fn gate(mut self, gate: CommandGate) -> Self {
self.gate = Some(gate);
@@ -438,7 +495,7 @@ pub trait Commands: CommandAccess {
/// `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above
/// the context, and the enabled state of its instance. `None` when the command is scoped and no instance of its
/// scope is above the context.
fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<ResolvedCommand> {
fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<Arc<ResolvedCommand>> {
board::resolve_scoped(self.command_ctx(), self.command_chain(), &command.into())
}
}
@@ -457,7 +514,7 @@ pub fn fire(ctx: &Context, command: impl Into<CommandRef>, source: FireSource) -
/// `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state
/// and hint, against the instance that [`fire`] would deliver it to. A scoped command with no live instance
/// resolves disabled.
pub fn resolve(ctx: &Context, command: impl Into<CommandRef>) -> ResolvedCommand {
pub fn resolve(ctx: &Context, command: impl Into<CommandRef>) -> Arc<ResolvedCommand> {
board::resolve_global(ctx, &command.into())
}
@@ -485,7 +542,7 @@ pub fn holder(ctx: &Context, chord: &Chord) -> Option<CommandRef> {
/// once the layer closes: for a surface that closes before its command runs (the command palette), whose own layer
/// does not block the command. Outside a modal layer it is [`resolve`].
#[doc(hidden)]
pub fn resolve_beneath(ctx: &Context, command: impl Into<CommandRef>) -> ResolvedCommand {
pub fn resolve_beneath(ctx: &Context, command: impl Into<CommandRef>) -> Arc<ResolvedCommand> {
match crate::runtime::overlay::modal_drawing(ctx) {
Some(layer) => board::resolve_beneath(ctx, layer, &command.into()),
None => resolve(ctx, command),
+62 -6
View File
@@ -137,6 +137,45 @@ fn window_focus_facts(ctx: &Context, events: &[Event], native_pixels_per_point:
#[derive(Default)]
struct WindowFocus(Option<bool>);
/// The child windows of the root that are open: each opens with its first frame and stays listed in every frame's
/// viewports, as eframe lists every open viewport, until a test closes it ([`close_viewport`]) or the app sends it
/// `ViewportCommand::Close`.
#[derive(Default)]
struct OpenChildren(Vec<egui::ViewportId>);
/// The open child windows, with `viewport` opened first when it is a child.
fn open_children(ctx: &Context, viewport: egui::ViewportId) -> Vec<egui::ViewportId> {
Service::<OpenChildren>::run(ctx, |open| {
if viewport != egui::ViewportId::ROOT && !open.0.contains(&viewport) {
open.0.push(viewport);
}
open.0.clone()
})
}
/// One run of `ui` on `input`; a root pass declares the open `children` after it, as an eframe app shows each of its
/// windows every frame: egui keeps a child viewport only while its parent's passes show it. Each child's content runs
/// in its own frames, so the declaration shows nothing.
fn run_ui(ctx: &Context, input: RawInput, children: &[egui::ViewportId], mut ui: impl FnMut(&mut Ui)) -> egui::FullOutput {
let root = input.viewport_id == egui::ViewportId::ROOT;
ctx.run_ui(input, |top| {
ui(top);
if root && !children.is_empty() {
let embedded = ctx.embed_viewports();
ctx.set_embed_viewports(false);
for child in children {
ctx.show_viewport_deferred(*child, egui::ViewportBuilder::default(), |_, _| {});
}
ctx.set_embed_viewports(embedded);
}
})
}
/// Closes the child window `viewport`: later frames no longer list it.
pub(crate) fn close_viewport(ctx: &Context, viewport: egui::ViewportId) {
Service::<OpenChildren>::run(ctx, |open| open.0.retain(|held| *held != viewport));
}
/// The fixture's reset bridge, as egui-winit keeps one per window: the reset request it holds for each viewport, and
/// the requests it dropped, which the next frame reports as `Event::ImeResetRetired`.
#[derive(Default)]
@@ -187,7 +226,8 @@ impl ImeResets {
}
/// Runs one pass of `viewport` at `time` seconds with `events` and `files`, on a window of `native_pixels_per_point`
/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live.
/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live; the
/// child stays open in every later frame, the root's included, until it is closed.
#[expect(clippy::too_many_arguments, reason = "the arguments are the facts of one frame, and every caller passes them all")]
pub(crate) fn run_frame(
ctx: &Context,
@@ -204,9 +244,10 @@ pub(crate) fn run_frame(
let dropped_files = files.dropped.iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect();
Service::<ImeResets>::run(ctx, |resets| resets.input(viewport, &mut events));
let mut viewports = window_focus_facts(ctx, &events, native_pixels_per_point);
if viewport != egui::ViewportId::ROOT {
let children = open_children(ctx, viewport);
for child in &children {
viewports
.insert(viewport, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() });
.insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() });
}
let input = RawInput {
screen_rect: Some(screen),
@@ -218,7 +259,7 @@ pub(crate) fn run_frame(
viewports,
..RawInput::default()
};
let mut output = drive(|| ctx.run_ui(input, ui));
let mut output = drive(|| run_ui(ctx, input, &children, ui));
Service::<ImeResets>::run(ctx, |resets| resets.output(viewport, &output.platform_output));
let mut flat = Vec::new();
for clipped in &output.shapes {
@@ -257,6 +298,15 @@ pub(crate) fn run_frame(
})
.collect();
let closed = output.viewport_output.values().any(|viewport| viewport.commands.iter().any(|command| matches!(command, ViewportCommand::Close)));
let closing: Vec<egui::ViewportId> = output
.viewport_output
.iter()
.filter(|(id, out)| **id != egui::ViewportId::ROOT && out.commands.iter().any(|command| matches!(command, ViewportCommand::Close)))
.map(|(id, _)| *id)
.collect();
for child in closing {
close_viewport(ctx, child);
}
let repaint_delay = output.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay);
let copied = output
.platform_output
@@ -366,8 +416,14 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions {
/// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened.
pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec<Shape> {
let screen = Rect::from_min_size(Pos2::ZERO, screen);
let input = RawInput { screen_rect: Some(screen), time: Some(time), ..RawInput::default() };
let mut output = drive(|| ctx.run_ui(input, ui));
let children = open_children(ctx, egui::ViewportId::ROOT);
let mut viewports = egui::ViewportIdMap::default();
viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default());
for child in &children {
viewports.insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..egui::ViewportInfo::default() });
}
let input = RawInput { screen_rect: Some(screen), time: Some(time), viewports, ..RawInput::default() };
let mut output = drive(|| run_ui(ctx, input, &children, ui));
output.textures_delta.clear();
let mut flat = Vec::new();
for clipped in output.shapes {
+64 -7
View File
@@ -297,6 +297,43 @@ pub fn chord_texts(ctx: &Context) -> u32 {
last_totals(ctx, |log| log.chord_texts, 0)
}
/// What a command resolution was for.
#[cfg(feature = "testing")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Resolve {
/// A resolution nothing kept: a reader's first, or one for a key press or a fire.
New,
/// A kept resolution made again because an input of it changed.
Again,
/// A kept resolution compared with a full one by the testing check every 100th pass.
Checked,
}
/// Counts a command resolution in this pass.
#[cfg(feature = "testing")]
pub(crate) fn count_resolve(ctx: &Context, what: Resolve) {
totals(ctx, |log| log.resolves[what as usize] += 1);
}
/// The command resolutions of the last pass of kind `what`.
#[cfg(feature = "testing")]
pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 {
last_totals(ctx, |log| log.resolves[what as usize], 0)
}
/// Counts a kept resolution a wake walked to compare its key.
#[cfg(feature = "testing")]
pub(crate) fn count_wake_walk(ctx: &Context) {
totals(ctx, |log| log.wake_walks += 1);
}
/// The kept resolutions the wakes of the last pass walked.
#[cfg(feature = "testing")]
pub fn last_pass_wake_walks(ctx: &Context) -> u32 {
last_totals(ctx, |log| log.wake_walks, 0)
}
/// Counts a sweep of the row `id` that asks its body units for their least widths in this pass.
#[cfg(feature = "testing")]
pub(crate) fn count_least(ctx: &Context, id: Id) {
@@ -362,29 +399,49 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> {
/// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass.
#[cfg(feature = "testing")]
#[derive(Default)]
pub(crate) struct PassTotals {
pub(crate) struct Totals {
pass: u64,
key_bytes: usize,
text_layouts: u32,
chord_texts: u32,
resolves: [u32; 3],
wake_walks: u32,
asks: Vec<(&'static str, u32)>,
}
/// The totals of the running pass and of the one before it, which a pass's own counting does not overwrite: a pass
/// that counts in its begin hook keeps the last pass readable.
#[cfg(feature = "testing")]
fn totals<R>(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R {
#[derive(Default)]
pub(crate) struct PassTotals {
current: Totals,
previous: Totals,
}
#[cfg(feature = "testing")]
fn totals<R>(ctx: &Context, f: impl FnOnce(&mut Totals) -> R) -> R {
let pass = ctx.cumulative_pass_nr();
pass_state::with::<PassTotals, _>(ctx, |log| {
if log.pass != pass {
*log = PassTotals { pass, ..PassTotals::default() };
if log.current.pass != pass {
let current = std::mem::replace(&mut log.current, Totals { pass, ..Totals::default() });
log.previous = current;
}
f(log)
f(&mut log.current)
})
}
#[cfg(feature = "testing")]
fn last_totals<R>(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R {
fn last_totals<R>(ctx: &Context, f: impl FnOnce(&Totals) -> R, none: R) -> R {
let last = ctx.cumulative_pass_nr().saturating_sub(1);
pass_state::with::<PassTotals, _>(ctx, |log| if log.pass == last { f(log) } else { none })
pass_state::with::<PassTotals, _>(ctx, |log| {
if log.current.pass == last {
f(&log.current)
} else if log.previous.pass == last {
f(&log.previous)
} else {
none
}
})
}
/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes
+2
View File
@@ -25,6 +25,8 @@ pub(crate) enum BindKey {
Record(Id),
/// A command's state on the board: the command's number and the instance whose state it is, `None` for the app's.
Command(u32, Option<Id>),
/// A command the focused stop answers for (an edit it takes): the command's number.
FocusedEdit(u32),
}
/// One measure a reader made from the value it read: what it was offered and the size it took.
+9 -5
View File
@@ -2,8 +2,9 @@
use super::Frames;
use super::story::{Story, StoryData, StoryOutput};
use crate::contract::Tracked;
use crate::runtime::access::Role;
use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState};
use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState, CommandStates};
use crate::runtime::egui::access::{AccessTree, NodeKey};
use crate::runtime::egui::fixture::{self, AccessActionKind};
use crate::runtime::egui::injected;
@@ -114,6 +115,8 @@ pub struct Fixture {
show: Box<dyn FnMut(&mut Ui)>,
root: RootEnv,
commands: CommandInput,
/// The app-scope command states, held as an app holds them.
states: Tracked<CommandStates>,
room: Vec2,
tree: AccessTree,
shown: Rect,
@@ -153,6 +156,7 @@ impl Fixture {
show: Box::new(show),
root: RootEnv::default(),
commands: CommandInput::new(),
states: Tracked::default(),
room: Vec2::new(400.0, 300.0),
tree: AccessTree::none(),
shown: Rect::NOTHING,
@@ -203,7 +207,8 @@ impl Fixture {
fixture.data = data;
fixture.outputs = outputs;
fixture.root_id = root_id;
fixture.commands = Story::command_input([story]);
fixture.states = Tracked::new(Story::command_states([story]));
fixture.commands = CommandInput::new().states(&fixture.states);
fixture.frames.commands(fixture.commands.clone());
fixture
}
@@ -230,9 +235,8 @@ impl Fixture {
/// Gives app-scope `command` this state in every following pass, as an app's `FrameInput.commands` does; a later
/// call for the same command replaces the earlier one.
pub fn command_state(&mut self, command: impl Into<CommandRef>, state: CommandState) -> &mut Self {
let command = command.into();
self.commands.states.retain(|(held, _)| *held != command);
self.commands.states.push((command, state));
self.states.set(command, state);
self.commands = self.commands.clone().states(&self.states);
self.frames.commands(self.commands.clone());
self
}
+11 -2
View File
@@ -186,9 +186,13 @@ impl Frames {
}
/// One frame of `viewport`, a child window of the root while the root stays live, with `events`; `ui` runs once
/// per pass. Returns the number of passes.
/// per pass. Returns the number of passes. The child opens with its first frame and stays open, listed in the root's
/// frames too, until [`close_viewport`](Self::close_viewport) or a `ViewportCommand::Close` for it.
pub fn frame_in_viewport(&mut self, viewport: egui::ViewportId, events: Vec<Event>, mut ui: impl FnMut(&mut Ui)) -> usize {
set_input(&self.ctx, self.input());
// The app's input is the root's, once per app frame: a child window's frame runs inside it.
if viewport == egui::ViewportId::ROOT {
set_input(&self.ctx, self.input());
}
let mut passes = 0;
self.run(viewport, events, |root| {
passes += 1;
@@ -253,6 +257,11 @@ impl Frames {
self.time += seconds;
}
/// Closes the child window `viewport`, as its user would: later frames no longer list it.
pub fn close_viewport(&mut self, viewport: egui::ViewportId) {
fixture::close_viewport(&self.ctx, viewport);
}
/// `n` frames with no events.
pub fn idle(&mut self, n: usize, mut ui: impl FnMut(&mut Ui)) {
for _ in 0..n {
+14 -10
View File
@@ -2,7 +2,7 @@
use super::Fixture;
use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec};
use crate::runtime::commands::CommandInput;
use crate::runtime::commands::CommandStates;
use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value};
use egui::{Id, Response, Ui, Vec2};
use std::any::{Any, TypeId};
@@ -102,9 +102,9 @@ pub struct Story {
pub drive: Drive,
/// The reason a disabled control shows (`disabled_text` of its tooltip), when the story gives its control one.
pub disabled_text: Option<&'static str>,
/// Adds this story's app-scope command states to the frame's command input; runners fold the shown stories'
/// functions over `CommandInput::new()` before the first frame.
pub commands: Option<fn(CommandInput) -> CommandInput>,
/// Sets this story's app-scope command states; runners apply the shown stories' functions in order to one
/// `CommandStates` before the first frame and hold it as the app's.
pub commands: Option<fn(&mut CommandStates)>,
/// The caption a viewer shows over the story; `None` for the title made of its name (`contract::story_title`).
pub title: Option<&'static str>,
/// The group a viewer shows the story in, with the other stories of the type that name it, as the cases of one
@@ -118,16 +118,20 @@ impl Story {
Story { name, covers: &[], show, drive: Drive::Auto, disabled_text: None, commands: None, title: None, group: None }
}
/// Sets the function that adds the story's command states to the frame's command input.
pub const fn commands(mut self, add: fn(CommandInput) -> CommandInput) -> Self {
/// Sets the function that sets the story's app-scope command states.
pub const fn commands(mut self, add: fn(&mut CommandStates)) -> Self {
self.commands = Some(add);
self
}
/// The command input of `stories` shown together: each story's command function applied in order over an empty
/// input, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame.
pub fn command_input<'a>(stories: impl IntoIterator<Item = &'a Story>) -> CommandInput {
stories.into_iter().filter_map(|story| story.commands).fold(CommandInput::new(), |input, add| add(input))
/// The command states of `stories` shown together: each story's command function applied in order to empty
/// states, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame.
pub fn command_states<'a>(stories: impl IntoIterator<Item = &'a Story>) -> CommandStates {
let mut states = CommandStates::new();
for add in stories.into_iter().filter_map(|story| story.commands) {
add(&mut states);
}
states
}
/// The caption a viewer shows over the story.
+2 -2
View File
@@ -94,9 +94,9 @@ enum Shown {
Apply,
}
/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new closure.
/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new gate.
fn gate(refuses: bool) -> CommandInput {
CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| !refuses || Shown::from_ref(command).is_none()))
CommandInput::new().gate(CommandGate::new(refuses, |refuses: &bool, command: &CommandRef| !*refuses || Shown::from_ref(command).is_none()))
}
/// A modal layer with an empty body.
+14 -6
View File
@@ -9,10 +9,11 @@ use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, PanelId,
use craft_behavior::dock::{PanelState, Workspace as Dock};
use craft_theme::AppSizes;
use craft_theme_editor::{ThemeSubject, parse_sizes};
use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _};
use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _, Tracked};
use craft_ui::docking::DockConfig;
use craft_ui::patterns::dock::DockArea;
use craft_ui::popover::DropVeil;
use craft_ui::runtime::commands::{CommandInput, CommandStates};
use craft_ui::runtime::drag::OsFile;
use craft_ui::runtime::env::WindowKey;
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
@@ -34,6 +35,9 @@ pub struct Gallery {
noted: HashSet<String>,
/// A command changed the viewer since the settings were last compared.
command_ran: bool,
/// The app-scope command states of the front component's stories, and that component: rebuilt only when another
/// component comes to the front, so an idle frame keeps one revision.
command_states: (Option<&'static str>, Tracked<CommandStates>),
}
impl Gallery {
@@ -45,7 +49,7 @@ impl Gallery {
/// The viewer of `catalog` over `persisted`.
pub fn new(catalog: Catalog, persisted: Persisted) -> Self {
let viewer = Viewer::new(catalog, persisted.get());
Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false }
Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false, command_states: (None, Tracked::default()) }
}
/// Shows what the settings and a dropped file have to say, once each, as toasts.
@@ -143,10 +147,14 @@ impl ShellApp for Gallery {
// App-scope command states are one input per frame, so only the stories of the component shown reach it; the
// Overview, the Theme dock and a frame with no such tab give none.
let browser = &self.viewer.browser;
let stories = front_component(&self.viewer)
.into_iter()
.flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story));
FrameInput::new(self.viewer.env.clone()).commands(craft_ui::testing::Story::command_input(stories))
let front = front_component(&self.viewer);
if front != self.command_states.0 {
let stories = front
.into_iter()
.flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story));
self.command_states = (front, Tracked::new(craft_ui::testing::Story::command_states(stories)));
}
FrameInput::new(self.viewer.env.clone()).commands(CommandInput::new().states(&self.command_states.1))
}
fn output(&mut self, output: FrameOutput) {
+1 -1
View File
@@ -212,7 +212,7 @@ fn pick(ui: &Ui, state: &mut MockState, tool: Tool, step: PickStep) {
/// Makes `tool` the current tool and says so in the status bar.
fn select(ui: &Ui, state: &mut MockState, tool: Tool) {
state.tool = tool;
let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label;
let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label.clone();
let text = Env::of(ui).words::<MockWords>().tool_status.fill(&[("tool", &*name)]);
state.status = Some(StatusMessage::new(text));
}
+1 -1
View File
@@ -223,7 +223,7 @@ impl Parse for StoryArgs {
/// reason to show while disabled, which the story takes from `StoryData::tooltip`. `title = ".."` is the caption a
/// viewer shows over the story. `group = ".."` puts the story in a named group with the type's other stories that
/// name it, in declaration order; a viewer shows a group together, each story under its caption.
/// `commands = <fn>` names a `fn(CommandInput) -> CommandInput` that sets the command states the story runs under.
/// `commands = <fn>` names a `fn(&mut CommandStates)` that sets the app-scope command states the story runs under.
/// The type's registration and the story meet by the type's registered name.
#[proc_macro_attribute]
pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream {
+3 -3
View File
@@ -167,11 +167,11 @@ enum DrawerKey {
/// headings.
struct Rows<'a> {
keys: Vec<DrawerKey>,
resolved: &'a [Vec<ResolvedCommand>],
resolved: &'a [Vec<std::sync::Arc<ResolvedCommand>>],
}
impl<'a> Rows<'a> {
fn new(resolved: &'a [Vec<ResolvedCommand>]) -> Self {
fn new(resolved: &'a [Vec<std::sync::Arc<ResolvedCommand>>]) -> Self {
let mut keys = Vec::new();
for (group, tools) in resolved.iter().enumerate().filter(|(_, tools)| !tools.is_empty()) {
keys.push(DrawerKey::Group(group));
@@ -221,7 +221,7 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
let words = env.words::<RailWords>();
let os = os_of(ui.ctx());
let ctx = ui.ctx().clone();
let resolved: Vec<Vec<ResolvedCommand>> =
let resolved: Vec<Vec<std::sync::Arc<ResolvedCommand>>> =
groups.iter().map(|group| group.tools.iter().map(|tool| commands::resolve(&ctx, tool.command.clone())).collect()).collect();
let mut edits: Vec<ToolbarEdit<T>> = dropped.and_then(|dropped| drop_edit(dropped.drag, dropped.at, groups, toolbar)).into_iter().collect();
let mut select: Option<T> = None;
+3 -3
View File
@@ -90,9 +90,9 @@ struct Held(bool);
/// What the parts step resolved for the tools this pass.
struct Laid {
resolved: Vec<Option<ResolvedCommand>>,
resolved: Vec<Option<std::sync::Arc<ResolvedCommand>>>,
/// The click command as resolved, when the button has one.
click: Option<ResolvedCommand>,
click: Option<std::sync::Arc<ResolvedCommand>>,
shown: usize,
}
@@ -185,7 +185,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> {
/// The command the face stands for: the click command when there is one, else the shown tool's.
fn lead<'l>(&self, laid: &'l Laid) -> Option<&'l ResolvedCommand> {
if self.click.is_some() { laid.click.as_ref() } else { laid.resolved.get(laid.shown).and_then(Option::as_ref) }
if self.click.is_some() { laid.click.as_deref() } else { laid.resolved.get(laid.shown).and_then(Option::as_deref) }
}
}
@@ -3,7 +3,7 @@
use super::CommandPalette;
use crate::contract::Bind;
use crate::menu::search::HelpEntry;
use crate::runtime::commands::{CommandInput, CommandRef, CommandState, EditCommands};
use crate::runtime::commands::{CommandRef, CommandState, CommandStates, EditCommands};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::sync::LazyLock;
@@ -69,8 +69,8 @@ fn palette(ui: &mut Ui, data: &mut StoryData, recents: Vec<CommandRef>) -> Story
}
/// The command states the stories run under: Redo is disabled, as the entries list it.
fn commands(input: CommandInput) -> CommandInput {
input.state(EditCommands::Redo, CommandState::new().enabled(false))
fn commands(states: &mut CommandStates) {
states.set(EditCommands::Redo, CommandState::new().enabled(false));
}
#[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "PhotoCraft", commands = commands)]
@@ -2,9 +2,10 @@
//! rules every app command follows, and a frame builds a keymap only for a catalog generation it has not built.
// The catalog is given through `Frames::commands`, which keeps it for every later frame.
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::contract::{Bind, Props as _, Show as _, Tracked};
use craft_ui::runtime::commands::{
AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, EditCommands, FirePhase, Scope, keymap_builds,
AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, CommandStates, EditCommands, FirePhase, Scope,
keymap_builds,
};
use craft_ui::runtime::env::WindowKey;
use craft_ui::runtime::frame::take_output;
@@ -198,11 +199,9 @@ fn a_press_without_a_physical_key_fires_its_command_once() {
fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() {
let cut = CommandRef::from(EditCommands::Cut);
let alternate = CommandDef::new(cut.clone(), "Cut", Scope::app()).with_default(Binding::parse("F2").expect("the trial's chord parses"));
let input = || {
CommandInput::new()
.catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid"))
.state(cut.clone(), CommandState::new())
};
let mut states = Tracked::new(CommandStates::new());
states.set(cut.clone(), CommandState::new());
let input = || CommandInput::new().catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")).states(&states);
let mut show = |ui: &mut Ui| {
AppShell::new(WindowKey::main()).show(ui, &mut ());
};
+1 -55
View File
@@ -1,8 +1,6 @@
use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap};
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _};
use craft_ui::runtime::commands::{
CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve,
};
use craft_ui::runtime::commands::{CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve};
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::runtime::frame::take_output;
use craft_ui::runtime::measure::chord_texts;
@@ -82,58 +80,6 @@ fn an_enclosing_scopes_shortcut_beats_the_applications() {
assert_eq!((closed.get(), ids(&take_output(&frames.ctx).fired)), (1, vec!["trial.jump"]), "outside the dock the application's command fires");
}
/// 1.8 and 7.2: the gate is app code, so it runs with no runtime lock held and may use the board.
#[trial]
fn the_gate_may_resolve_commands() {
let mut frames = Frames::new();
let ctx = frames.ctx.clone();
let inside = std::sync::atomic::AtomicBool::new(false);
frames.commands(CommandInput::new().gate(CommandGate::new(move |_: &CommandRef| {
// The nested `resolve` runs the gate again, which stops here.
inside.swap(true, std::sync::atomic::Ordering::SeqCst) || {
let enabled = resolve(&ctx, AppCommand::Go).enabled;
inside.store(false, std::sync::atomic::Ordering::SeqCst);
enabled
}
})));
let mut show = |ui: &mut Ui| {
Tap::new().id_salt("go").command(AppCommand::Save).show(ui);
};
frames.idle(2, &mut show);
frames.frame(vec![key_press(Key::K, Modifiers::COMMAND)], &mut show);
assert_eq!(ids(&take_output(&frames.ctx).fired), ["trial.save"]);
}
/// The gate answers from what the app knew before the frame: a frame asks it once per command, however many components
/// show the command and however many passes and readers resolve it.
#[trial]
fn a_frame_asks_the_gate_once_per_command() {
use std::sync::{Arc, Mutex};
let asked = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&asked);
let mut frames = Frames::new();
frames.commands(CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| {
log.lock().expect("the gate's log").push(command.key());
true
})));
let mut show = |ui: &mut Ui| {
for salt in ["a", "b", "c"] {
Tap::new().id_salt(salt).command(AppCommand::Save).show(ui);
}
};
frames.idle(2, &mut show);
for at in [5.0, 6.0, 7.0] {
asked.lock().expect("the gate's log").clear();
frames.frame(vec![moved(Pos2::new(at, at))], &mut show);
let asked = asked.lock().expect("the gate's log").clone();
let mut once = asked.clone();
once.sort();
once.dedup();
assert!(once.contains(&"trial.save".to_owned()), "the frame resolves the taps' command: {asked:?}");
assert_eq!(asked.len(), once.len(), "a frame asked the gate for a command twice: {asked:?}");
}
}
/// 11.3: a scoped entry waits for its instance and is dropped when the instance stops being live.
#[trial]
fn an_untaken_scoped_entry_is_dropped_with_its_instance() {
+1
View File
@@ -4,3 +4,4 @@ mod app_catalog;
mod app_scope;
mod board;
mod kit;
mod resolve;
@@ -0,0 +1,384 @@
//! Command resolution runs only when an input of it changed: count trials over fifty shown commands.
use super::kit::{AppCommand, DOCK, Dock, PANE, Pane, PaneCommand, Tap};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Lazy, Trigger};
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Tracked};
use craft_ui::dialog::Dialog;
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::runtime::commands::{
AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Commands as _, Scope,
};
use craft_ui::runtime::commands::{EditCommands, declare_child, resolve, resolve_beneath};
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::runtime::measure::last_pass_wake_walks;
use craft_ui::runtime::measure::{Resolve, last_pass_resolves};
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::pointer::{press, release};
use craft_ui::testing::{Frames, trial};
use craft_ui::text::TextField;
use egui::{Id, Pos2, Ui};
use egui::{Key, Modifiers, ViewportId};
use std::cell::{Cell, RefCell};
/// The panes: each is an instance of the pane scope, so each is its own reader of the commands its taps show.
const PANES: [&str; 5] = ["a", "b", "c", "d", "e"];
/// The commands the taps of a pane show, each by two taps.
fn shown(at: usize) -> CommandRef {
match at % 5 {
0 => AppCommand::Save.into(),
1 => AppCommand::Go.into(),
2 => AppCommand::Play.into(),
3 => AppCommand::Jump.into(),
_ => PaneCommand::ZoomIn.into(),
}
}
/// Readers kept: one per pane and command.
const KEPT: u32 = 25;
/// Readers of Save: one per pane.
const SAVE_READERS: u32 = 5;
/// Distinct commands shown.
const COMMANDS: u32 = 5;
/// Fifty taps in five panes; pane `a` publishes Zoom In enabled as `zoom` says. `ids` gets each tap's id. With
/// `global`, a surface with no component of its own reads Zoom In after the panes, which picks an instance by the focus.
struct Scene {
zoom: Cell<bool>,
ids: RefCell<Vec<Id>>,
global: bool,
/// Pane `a` is left out of the next pass.
skip_a: Cell<bool>,
/// Salts the panes' ids, so two windows show panes of their own.
window: &'static str,
}
impl Scene {
fn new() -> Self {
Scene { zoom: Cell::new(true), ids: RefCell::new(Vec::new()), global: false, skip_a: Cell::new(false), window: "" }
}
fn show(&self, ui: &mut Ui) {
self.ids.borrow_mut().clear();
let skip_a = self.skip_a.replace(false);
for (pane, salt) in PANES.iter().enumerate() {
if pane == 0 && skip_a {
continue;
}
Pane::new().id_salt((self.window, *salt)).show(ui, |ui, cx| {
if pane == 0 {
cx.publish(PaneCommand::ZoomIn, CommandState::new().enabled(self.zoom.get()));
}
for at in 0..10 {
let id = Tap::new().id_salt(at).command(shown(at)).show(ui).id;
self.ids.borrow_mut().push(id);
}
});
}
if self.global {
resolve(ui.ctx(), PaneCommand::ZoomIn);
}
}
}
fn counts(ctx: &egui::Context) -> (u32, u32) {
(last_pass_resolves(ctx, Resolve::New), last_pass_resolves(ctx, Resolve::Again))
}
/// One frame of `scene`, and its new and repeated resolutions summed over every pass of the frame: each pass after
/// the first reads the one before it as it starts, and the last is read after the frame.
fn frame(frames: &mut Frames, scene: &Scene) -> (u32, u32) {
let (new, again, _) = frame_walks(frames, ViewportId::ROOT, &mut |ui| scene.show(ui));
(new, again)
}
/// One frame of `viewport` running `show`, and its new and repeated resolutions and the kept resolutions its wakes
/// walked, summed over every pass of the frame.
fn frame_walks(frames: &mut Frames, viewport: ViewportId, show: &mut dyn FnMut(&mut Ui)) -> (u32, u32, u32) {
let ctx = frames.ctx.clone();
let (mut new, mut again, mut walks, mut pass) = (0, 0, 0, 0);
let mut add = |ctx: &egui::Context| {
let (n, a) = counts(ctx);
(new, again, walks) = (new + n, again + a, walks + last_pass_wake_walks(ctx));
};
frames.frame_in_viewport(viewport, vec![], |ui| {
if pass > 0 {
add(&ctx);
}
pass += 1;
show(ui);
});
add(&ctx);
(new, again, walks)
}
thread_local! {
static ASKS: Cell<u32> = const { Cell::new(0) };
}
/// The gate: refuses Save while `refuses`; counts its asks.
fn refuse_save(refuses: &bool, command: &CommandRef) -> bool {
ASKS.with(|asks| asks.set(asks.get() + 1));
!(*refuses && AppCommand::from_ref(command) == Some(AppCommand::Save))
}
fn gated(states: &Tracked<CommandStates>, refuses: bool) -> CommandInput {
CommandInput::new().states(states).gate(CommandGate::new(refuses, refuse_save))
}
/// An idle frame with fifty shown commands resolves nothing, and neither does a pointer move over none of them.
#[trial]
fn an_idle_frame_resolves_no_command() {
let scene = Scene::new();
let mut frames = Frames::new();
let states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
frames.idle(3, |ui| scene.show(ui));
assert_eq!(scene.ids.borrow().len(), 50, "fifty commands are shown");
assert_eq!(frames.frame(vec![], |ui| scene.show(ui)), 1, "an idle frame takes one pass");
assert_eq!(counts(&frames.ctx), (0, 0), "an idle frame resolves nothing");
assert_eq!(frames.frame(vec![moved(Pos2::new(900.0, 900.0))], |ui| scene.show(ui)), 1, "so does a pointer move");
assert_eq!(counts(&frames.ctx), (0, 0), "a pointer move away from the taps resolves nothing");
}
/// Two windows with frames alternating between them, idle: each frame resolves nothing and walks nothing, as the
/// child stays open across the root's frames and the root's across the child's.
#[trial]
fn idle_frames_alternating_between_two_windows_resolve_nothing() {
let root = Scene::new();
let other = Scene { window: "child", ..Scene::new() };
let child = ViewportId::from_hash_of("second window");
let mut frames = Frames::new();
let states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
for _ in 0..3 {
frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui));
frame_walks(&mut frames, child, &mut |ui| other.show(ui));
}
for round in 0..4 {
assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)), (0, 0, 0), "root frame {round}");
assert_eq!(frame_walks(&mut frames, child, &mut |ui| other.show(ui)), (0, 0, 0), "child frame {round}");
}
}
/// Editing one app-scope state resolves again only that command's readers, once.
#[trial]
fn one_state_change_resolves_only_its_readers() {
let scene = Scene::new();
let mut frames = Frames::new();
let mut states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
frames.idle(3, |ui| scene.show(ui));
states.set(AppCommand::Save, CommandState::new().enabled(false));
frames.commands(gated(&states, false));
assert_eq!(
frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)),
(0, SAVE_READERS, SAVE_READERS),
"the wake walks and resolves again only Save's readers"
);
assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "the next frame walks nothing");
}
/// An instance publishing a new state resolves again only the readers of that instance's state.
#[trial]
fn a_published_state_change_resolves_only_its_readers() {
let scene = Scene::new();
let mut frames = Frames::new();
let states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
frames.idle(3, |ui| scene.show(ui));
scene.zoom.set(false);
// The publish runs before its reader, which resolves again as it reads; a wake walks only that reader.
let (new, again, first) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui));
let (_, _, second) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui));
assert_eq!((new, again), (0, 1), "only pane a's Zoom In reader resolves again");
assert_eq!(first + second, 1, "the wakes walk only the reader of the published key");
assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "publishing the same state again walks nothing");
}
/// A change of the gate's props asks the gate once per shown command and resolves again only the readers whose answer
/// changed; a new gate with the same props asks nothing.
#[trial]
fn a_gate_props_change_resolves_only_the_readers_whose_answer_changed() {
let scene = Scene::new();
let mut frames = Frames::new();
let states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
frames.idle(3, |ui| scene.show(ui));
ASKS.with(|asks| asks.set(0));
frames.commands(gated(&states, true));
assert_eq!(frame(&mut frames, &scene), (0, SAVE_READERS), "only Save's readers, which the gate now refuses, resolve again");
assert_eq!(ASKS.with(Cell::get), COMMANDS, "the gate is asked once per shown command");
ASKS.with(|asks| asks.set(0));
frames.commands(gated(&states, true));
assert_eq!(frame(&mut frames, &scene), (0, 0), "a gate with the same props resolves nothing");
assert_eq!(ASKS.with(Cell::get), 0, "and is not asked");
}
/// Moving the focus between taps resolves none of them: each finds its command's instance in its own chain, or the
/// command is the app's, so none reads the focus.
#[trial]
fn a_focus_move_resolves_no_reader_that_does_not_read_the_focus() {
let scene = Scene::new();
let mut frames = Frames::new();
let states = Tracked::new(CommandStates::new());
frames.commands(gated(&states, false));
frames.idle(3, |ui| scene.show(ui));
for at in [0, 17, 42] {
let id = scene.ids.borrow()[at];
request(&frames.ctx, FocusTarget::Id(id));
for _ in 0..2 {
assert_eq!(frame(&mut frames, &scene), (0, 0), "focusing tap {at} resolves nothing");
}
}
}
/// An instance that misses exactly one pass and registers again is live again for every kept resolution in the
/// frame it comes back in: its return moves the inputs every resolution reads.
#[trial]
fn an_instance_back_after_one_missed_pass_is_live_again() {
let shown = Cell::new(true);
let enabled = Cell::new(false);
let mut show = |ui: &mut Ui| {
if shown.get() {
Pane::new().id_salt("b").show(ui, |ui, _| {
Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui);
});
}
enabled.set(resolve(ui.ctx(), PaneCommand::ZoomIn).enabled);
};
let mut frames = Frames::new();
frames.idle(3, &mut show);
assert!(enabled.get(), "Zoom In reaches the pane");
shown.set(false);
assert_eq!(frames.frame(vec![], &mut show), 1, "the pane misses one pass");
shown.set(true);
frames.frame(vec![], &mut show);
assert!(enabled.get(), "the pane is live again in the frame it comes back in");
frames.frame(vec![], &mut show);
assert!(enabled.get(), "and stays so");
}
/// A settled region that shows a command the focused stop answers for (Cut, which a text field takes) runs when that
/// stop's answer changes: with the focus moving from the field to a tap, which takes no edits, Cut no longer waits for a
/// selection.
#[trial]
fn a_settled_region_runs_when_the_focused_stops_answer_changes() {
let text = RefCell::new("hello".to_owned());
let (field, tap, cut) = (Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL));
let runs = Cell::new(0);
let mut show = |ui: &mut Ui| {
field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id);
tap.set(Tap::new().id_salt("plain").show(ui).id);
Lazy::new("edits", 0.0).settles(true).show(ui, |ui| {
runs.set(runs.get() + 1);
cut.set(Button::command(EditCommands::Cut).show(ui).id);
});
};
let mut frames = Frames::new();
frames.idle(2, &mut show);
request(&frames.ctx, FocusTarget::Id(field.get()));
frames.idle(30, &mut show);
assert!(frames.tree().is_disabled(cut.get()), "Cut does nothing with no text selected");
runs.set(0);
frames.idle(2, &mut show);
assert_eq!(runs.get(), 0, "the region is settled");
request(&frames.ctx, FocusTarget::Id(tap.get()));
frames.idle(2, &mut show);
assert_eq!(runs.get(), 1, "the new answer for Cut runs the region once");
assert!(!frames.tree().is_disabled(cut.get()), "which shows Cut enabled");
}
/// The testing check every 100th pass compares every kept resolution with a full one, and every kept gate answer with
/// the gate's. The script changes, a few passes before each check, every kind of input a resolution reads: app and
/// published states, the gate, the keymap, the focus and the focused stop's edits, a menu and a modal layer with readers
/// inside (a palette's reader under the layer), an instance that misses one pass and a scope's parent.
#[trial]
fn the_hundredth_pass_check_finds_every_kept_resolution_current() {
let scene = Scene { global: true, ..Scene::new() };
let text = RefCell::new("hello".to_owned());
let (field, opener) = (Cell::new(Id::NULL), Cell::new(Pos2::ZERO));
let modal = Cell::new(false);
let mut show = |ui: &mut Ui| {
scene.show(ui);
field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id);
Tap::new().id_salt("cut").command(EditCommands::Cut).show(ui);
Dock::new().id_salt("dock").show(ui, |ui, _| {
Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui);
});
let open = Tap::new().id_salt("opener").show(ui);
opener.set(open.rect.center());
Menu::new("Menu").opened_by(&open, Trigger::Click).show(ui, |ui, _| {
MenuItem::command(AppCommand::Save).show(ui);
MenuItem::command(EditCommands::Cut).show(ui);
});
let mut open = modal.get();
Dialog::new("Options").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, cx| {
cx.publish(EditCommands::Undo, CommandState::new());
resolve_beneath(ui.ctx(), AppCommand::Save);
Tap::new().id_salt("in dialog").command(EditCommands::Undo).show(ui);
});
modal.set(open);
};
let mut frames = Frames::new();
let mut states = Tracked::new(CommandStates::new());
let mut refuses = false;
// A new catalog generation rebuilds the keymap.
let mut generation = 1;
let input = |states: &Tracked<CommandStates>, refuses: bool, generation: u64| {
let extra = CommandDef::new(CommandRef::new("trial.extra"), "Extra", Scope::app())
.with_default(Binding::parse(if generation.is_multiple_of(2) { "F7" } else { "F6" }).expect("the trial's chord parses"));
gated(states, refuses).catalog(AppCatalog::new(vec![extra], generation).expect("the trial's catalog is valid"))
};
frames.commands(input(&states, refuses, generation));
// Each step at the pass it names, relative to a check at 100 and 200.
let script: Vec<(usize, &str)> = [100, 200]
.into_iter()
.flat_map(|check| {
let steps: &[(usize, &str)] = if check == 100 {
&[(14, "focus field"), (12, "select all"), (10, "press opener"), (9, "release opener"), (6, "parent"), (3, "skip a"), (1, "state")]
} else {
&[(14, "focus field"), (12, "collapse"), (10, "modal"), (8, "keymap"), (6, "gate"), (3, "skip a"), (1, "publish")]
};
steps.iter().map(move |(before, step)| (check - before, *step)).collect::<Vec<_>>()
})
.chain([(103, "escape"), (203, "close modal")])
.collect();
let mut script = script.into_iter().peekable();
let (mut passes, mut checked) = (0, Vec::new());
while passes < 260 {
let mut events = Vec::new();
if let Some((_, step)) = script.next_if(|(at, _)| passes + 1 >= *at) {
match step {
"focus field" => {
request(&frames.ctx, FocusTarget::Id(field.get()));
}
"select all" => events.push(key_press(Key::A, Modifiers::COMMAND)),
"collapse" => events.push(key_press(Key::ArrowRight, Modifiers::NONE)),
"press opener" => events.push(press(opener.get())),
"release opener" => events.push(release(opener.get())),
"escape" => events.push(key_press(Key::Escape, Modifiers::NONE)),
"skip a" => scene.skip_a.set(true),
"parent" => declare_child(&frames.ctx, DOCK, PANE),
"state" => states.set(AppCommand::Go, CommandState::new().checked(true)),
"gate" => refuses = !refuses,
"keymap" => generation += 1,
"publish" => scene.zoom.set(!scene.zoom.get()),
"modal" => modal.set(true),
_ => modal.set(false),
}
}
frames.commands(input(&states, refuses, generation));
passes += frames.frame(events, &mut show);
let compared = last_pass_resolves(&frames.ctx, Resolve::Checked);
if compared > 0 {
checked.push(compared);
}
}
assert_eq!(script.next().map(|(_, step)| step), None, "every step ran");
assert_eq!(checked.len(), 2, "two checks ran: {checked:?}");
assert!(checked.iter().all(|compared| *compared > KEPT), "each compared the panes' readers and the script's: {checked:?}");
}
+1 -1
View File
@@ -108,7 +108,7 @@ pub struct BarItemsStyle {
#[derive(Clone)]
struct Present {
item: BarItem,
resolved: ResolvedCommand,
resolved: std::sync::Arc<ResolvedCommand>,
}
/// Where the parts of a strip sit this pass.
+1 -1
View File
@@ -343,7 +343,7 @@ impl<'a> Notice<'a> {
self.actions
.iter()
.map(|action| match &action.command {
Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label)),
Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label.clone())),
None => action.label.clone(),
})
.collect()
+1 -1
View File
@@ -161,7 +161,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Table<'_, K> {
Divider::horizontal().show(ui);
}
for (command, enabled) in &commands {
let label = crate::runtime::commands::resolve(&ctx, *command).label;
let label = crate::runtime::commands::resolve(&ctx, *command).label.clone();
if MenuItem::new(label.to_string()).enabled(*enabled).show(ui).ran {
picks.push(ColumnRequest::Command(*command));
}
+10 -4
View File
@@ -6,10 +6,10 @@ use crate::values::kit::{AT, INITIAL, Scrub, Seen};
use craft_theme::{Contrast, Mode, Size};
use craft_ui::buttons::Button;
use craft_ui::choice::{Radio, RadioGroup};
use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing, Tracked};
use craft_ui::display::Spinner;
use craft_ui::layout_components::Stack;
use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _};
use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, CommandStates, Commands as _};
use craft_ui::runtime::{frame, inspect};
use craft_ui::testing::layout::in_region;
use craft_ui::testing::pointer::{moved, press, release};
@@ -381,7 +381,11 @@ fn an_app_command_state_runs_the_settled_child_that_shows_it() {
let mut frames = Frames::new();
scene.settle(&mut frames);
assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled");
let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled));
let mut states = Tracked::new(CommandStates::new());
let mut disable = |enabled: bool| {
states.set(Shown::Visible, CommandState::new().enabled(enabled));
CommandInput::new().states(&states)
};
frames.commands(disable(false));
let (_, [reader, beside]) = scene.frame(&mut frames);
assert!(reader > 0 && beside == 0, "only the child that shows Shown runs: {reader}, {beside}");
@@ -425,7 +429,9 @@ fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() {
let mut frames = Frames::new();
scene.settle(&mut frames);
assert_eq!(scene.frame(&mut frames).1, [0, 0], "the child holding the measured body settles");
frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false)));
let mut states = Tracked::new(CommandStates::new());
states.set(Shown::Measured, CommandState::new().enabled(false));
frames.commands(CommandInput::new().states(&states));
let (_, [reader, beside]) = scene.frame(&mut frames);
assert!(reader > 0 && beside == 0, "only the child that shows Measured runs: {reader}, {beside}");
assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it");
@@ -3,3 +3,8 @@ config_version = 1
[[module]]
path = "contract"
layer = 4
# memo depends only on std and runtime::env, so it sits with the runtime modules that use it.
[[module]]
path = "contract::memo"
layer = 2
+7 -5
View File
@@ -2134,7 +2134,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `craft_ui::contract::MeasureCx`: `pub struct MeasureCx<'a, C: Component> { pub env: EnvView<'a>, pub style: &'a C::Style, pub resolved: &'a Resolved<'a>, pub proposal: Proposal, pub room: Option<f32>, pub ui: &'a Ui, pub tokens: &'a UiTokens, pub id: Id }`. What `measure` reads: step 5's view of the environment, the style, the resolved props and the shown value.
- `pub fn value(&self) -> Option<&'a ValueOf<C>>`. The shown value; it has the stage's lifetime, so a borrow of `cx` is not held.
- `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component.
- `pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<ResolvedCommand>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above
- `pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<Arc<ResolvedCommand>>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above
- `pub fn column_room(&self) -> Option<f32>`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the
- `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up
- `pub fn label(&self) -> Label`. The label as given.
@@ -3107,10 +3107,12 @@ Per-pass and per-frame services and the one egui adapter.
The command board: the registry and typed sets, per-frame state, the queue, firing and the gate (spec 11).
- `craft_ui::runtime::commands::CommandGate`: `pub struct CommandGate`. The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an
- `pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self`. A gate that lets `allows` commands through.
- `pub fn new<P: MemoProps + Send + Sync + 'static>(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self`. A gate that lets through the commands `allows` accepts under `props`; the runtime asks it once per command while the props' key stays the same.
- `craft_ui::runtime::commands::CommandStates`: `pub struct CommandStates`. The app-scope command states an app holds, in a `Tracked` it hands to `CommandInput::states`.
- `pub fn new() -> Self`, `pub fn set(&mut self, command: impl Into<CommandRef>, state: CommandState)`, `pub fn remove(&mut self, command: &CommandRef) -> Option<CommandState>`, `pub fn get(&self, command: &CommandRef) -> Option<&CommandState>`.
- `craft_ui::runtime::commands::CommandInput`: `pub struct CommandInput`. App-scope command state for this frame, set from app state before the pass.
- `pub fn new() -> Self`. No state, no overrides and no gate.
- `pub fn state(mut self, command: impl Into<CommandRef>, state: CommandState) -> Self`. The state of an app-scope command.
- `pub fn states(mut self, states: &Tracked<CommandStates>) -> Self`. The app-scope command states the app holds; the runtime reads them again only when the revision moves.
- `pub fn overrides(mut self, overrides: Arc<Overrides>) -> Self`. The user's binding overrides; the keymap is rebuilt when the `Arc` changes.
- `pub fn gate(mut self, gate: CommandGate) -> Self`. The one gate over commands.
- `craft_ui::runtime::commands::CommandSet`: `pub trait CommandSet: Copy + Send + Sync + 'static`. A typed set of commands, written by `#[derive(CommandSet)]`.
@@ -3133,13 +3135,13 @@ The command board: the registry and typed sets, per-frame state, the queue, firi
- `fn publish(&mut self, command: impl Into<CommandRef>, state: CommandState)`. This frame's state of a scoped command, for this instance. Publishing an app-scope command here is a
- `fn take_command<S: CommandSet>(&mut self) -> Option<(S, Fired)>`. The next command of set `S` routed to this instance this pass; each is taken once, so a discard pass does
- `fn take_step(&mut self, can_undo: bool, can_redo: bool) -> Option<Step>`. Declares Undo and Redo on the innermost instance around this context, enabled as `can_undo` and `can_redo`
- `fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<ResolvedCommand>`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above
- `fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<Arc<ResolvedCommand>>`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above
- `craft_ui::runtime::commands::FirePhase`: `pub enum FirePhase { Press, Repeat, Release }`. The phase of the key press that fired a command.
- `craft_ui::runtime::commands::FireSource`: `pub enum FireSource { Key, Menu, Palette, Pointer, Automation, Access }`. Where a fired command came from.
- `craft_ui::runtime::commands::Fired`: `pub struct Fired { pub command: CommandRef, pub target: Option<Id>, pub source: FireSource, pub phase: FirePhase, pub cycle: bool, pub alt_variant: bool }`. A command a surface or a key fired, as the instance or the app takes it.
- `craft_ui::runtime::commands::ResolvedCommand`: `pub struct ResolvedCommand { pub label: Arc<str>, pub icon: Option<Cow<'static, str>>, pub chord: Option<Chord>, pub enabled: bool, pub checked: Option<bool>, pub marked: bool, pub hint: Option<Arc<str>>, pub kind: CommandKind, pub instance: Option<Id> }`. A command as a surface shows and fires it.
- `craft_ui::runtime::commands::fire`: `pub fn fire(ctx: &Context, command: impl Into<CommandRef>, source: FireSource) -> bool`. Fires `command` from a surface that has no component of its own: a menu, the palette or automation. Scoped
- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into<CommandRef>) -> ResolvedCommand`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state
- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into<CommandRef>) -> Arc<ResolvedCommand>`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state
- `craft_ui::runtime::commands::Binding`: re-export of `craft_keymap::Binding` (outside these crates).
- `craft_ui::runtime::commands::ChromeCommand`: `pub enum ChromeCommand { TogglePanels, TogglePanelsKeepTools }`. The `window` commands that hide the panels of the window they run in.
- `pub const ALL: [ChromeCommand; 2]`. Both commands.
+1 -1
View File
@@ -49,7 +49,7 @@ One row per name in the author table (Overview) and per `pub` item a component a
| `CommandGate` | The one gate that can disable commands (dialog open, workspace, recorder, pending operation) | `craft_ui::runtime::commands` | 11.3 |
| `Commands` | The context trait on `Cx`, `BodyCx` and `ItemCx` for commands and the clipboard | `craft_ui::runtime::commands` | 11.3 |
| `CommandSet` | A typed set of commands with one scope, written by `#[derive(CommandSet)]` and read with `take_command::<S>()` | craft-keymap (trait), `craft_ui::runtime::commands` (board) | 11.2, 11.3 |
| `CommandState`, `CommandInput` | A command's state this frame, and the app-scope states in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 |
| `CommandState`, `CommandStates`, `CommandInput` | A command's state, the app-scope states an app holds in a `Tracked`, and the frame's command input in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 |
| `Common` | The props every component has, with no public fields | `craft_ui::contract` | 3.1 |
| Component | Any type implementing the core trait | `craft_ui::contract` | 1.2 |
| `ComponentStyle` | The trait every `type Style` implements, usually with `#[derive(ComponentStyle)]` | `craft_ui::style` | 4.3 |