Merge pull request #3566 from dotCooCoo/fix/command-states-index

ui-contract: CommandStates finds a command among the states with its id
This commit is contained in:
BFlat
2026-11-26 10:00:38 +07:00
committed by GitHub
3 changed files with 113 additions and 7 deletions
+59 -7
View File
@@ -57,6 +57,7 @@ use craft_keymap::{Chord, Overrides};
use egui::{Context, Id, ViewportId};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
/// Commands an app defines at run time (plug-ins, its tool list), all in the app scope ([`Scope::app`]). They join
@@ -448,10 +449,13 @@ impl CommandGate {
/// 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)]
#[derive(Clone, Default, 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)>>,
/// The positions in `states` of each command id's entries, so a lookup compares only the entries with its id.
#[plain_data(assume = "ids and positions are plain values; the map is copied on write")]
by_id: Arc<HashMap<String, Vec<usize>>>,
}
impl CommandStates {
@@ -463,27 +467,75 @@ impl CommandStates {
/// 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)),
match self.position(&command) {
Some(at) => {
if let Some((_, held)) = Arc::make_mut(&mut self.states).get_mut(at) {
*held = state;
}
}
None => {
let states = Arc::make_mut(&mut self.states);
Arc::make_mut(&mut self.by_id).entry(command.id.clone()).or_default().push(states.len());
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)?;
let at = self.position(command)?;
let by_id = Arc::make_mut(&mut self.by_id);
by_id.retain(|_, positions| {
positions.retain(|&p| p != at);
for p in positions.iter_mut().filter(|p| **p > at) {
*p -= 1;
}
!positions.is_empty()
});
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)
self.states.get(self.position(command)?).map(|(_, state)| state)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = &(CommandRef, CommandState)> {
self.states.iter()
}
/// Where `command`'s entry is in `states`: among the entries with its id, the one equal to it.
fn position(&self, command: &CommandRef) -> Option<usize> {
self.by_id.get(command.id.as_str())?.iter().copied().find(|&at| {
#[cfg(feature = "testing")]
STATE_COMPARISONS.with(|n| n.set(n.get() + 1));
self.states.get(at).is_some_and(|(held, _)| held == command)
})
}
}
impl PartialEq for CommandStates {
fn eq(&self, other: &CommandStates) -> bool {
self.states == other.states
}
}
impl fmt::Debug for CommandStates {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommandStates").field("states", &self.states).finish()
}
}
#[cfg(feature = "testing")]
thread_local! {
static STATE_COMPARISONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many held commands this thread's [`CommandStates`] lookups have compared with the command looked up.
#[cfg(feature = "testing")]
#[doc(hidden)]
pub fn command_state_comparisons() -> u64 {
STATE_COMPARISONS.with(std::cell::Cell::get)
}
/// App-scope command state for this frame, set from app state before the pass.
@@ -0,0 +1,53 @@
//! The app's command states (`CommandStates`): lookups by command, with and without parameters.
use craft_ui::runtime::commands::{CommandRef, CommandState, CommandStates, command_state_comparisons};
use craft_ui::testing::trial;
use serde_json::json;
/// The held commands `n` lookups compare, one for each of `n` commands set before.
fn comparisons_for(n: usize) -> u64 {
let mut states = CommandStates::new();
let commands: Vec<CommandRef> = (0..n).map(|i| CommandRef::new(format!("test.command{i}"))).collect();
for command in &commands {
states.set(command.clone(), CommandState::new().enabled(false));
}
let before = command_state_comparisons();
for command in &commands {
assert!(states.get(command).is_some(), "{command} has the state it was given");
}
command_state_comparisons() - before
}
// A menu bar of a few thousand commands looks each one up while it builds its states: the comparisons grow with the
// commands, not with their square.
#[trial]
fn looking_commands_up_compares_in_proportion_to_the_commands() {
let (small, large) = (comparisons_for(500), comparisons_for(1_000));
assert!(small > 0, "a lookup compares the command with what is held");
assert!(large <= 2 * small, "twice the commands compare at most twice as often: {small} for 500, {large} for 1,000");
}
#[trial]
fn commands_with_one_id_keep_their_own_states_through_a_removal() {
let plain = CommandRef::new("test.zoom");
let in_ = CommandRef::with_params("test.zoom", json!({ "by": 2 }));
let out = CommandRef::with_params("test.zoom", json!({ "by": 0.5 }));
let other = CommandRef::new("test.other");
let (off, on, unchecked) = (CommandState::new().enabled(false), CommandState::new().checked(true), CommandState::new().checked(false));
let mut states = CommandStates::new();
states.set(plain.clone(), off.clone());
states.set(other.clone(), off.clone());
states.set(in_.clone(), on.clone());
states.set(out.clone(), unchecked.clone());
assert_eq!(states.get(&CommandRef::with_params("test.zoom", json!({}))), Some(&off), "empty parameters are the command without parameters");
assert_eq!(states.remove(&plain), Some(off.clone()), "the plain command is held");
assert_eq!(states.get(&plain), None, "a removed command has no state");
assert_eq!(states.get(&other), Some(&off), "the command after it keeps its state");
assert_eq!(states.get(&in_), Some(&on), "each set of parameters keeps its own state");
assert_eq!(states.get(&out), Some(&unchecked), "each set of parameters keeps its own state");
states.set(out.clone(), on.clone());
assert_eq!(states.get(&out), Some(&on), "setting a held command replaces its state");
assert_eq!(states.remove(&plain), None, "a removed command is removed once");
}
@@ -1,5 +1,6 @@
pub(crate) mod alt_code;
pub(crate) mod chord_fallthrough;
pub(crate) mod command_states;
// `clipboard.rs` is platform-w3's trial (F-28); this file is shell-w1's, so its line is written here.
pub(crate) mod clipboard;
pub(crate) mod control_click;