mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
shortcuts-w1: net change of 1 commits
- shortcuts-w1: written from its sheet
This commit is contained in:
1 parent
652067832e
commit
4e2a2db3b4
6 files changed
+562
-112
No files matched your search
@@ -4,6 +4,7 @@ use crate::contract::Mount;
|
||||
use crate::contract::cx::CxCore;
|
||||
use crate::runtime::commands::{self, FireSource};
|
||||
use crate::runtime::egui::response;
|
||||
use crate::runtime::pointer;
|
||||
use crate::runtime::{layout_memory, windows};
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use egui::{Context, Id, Response, Ui, Vec2};
|
||||
@@ -21,11 +22,12 @@ pub(crate) fn before_finish(core: &mut CxCore<'_>, activated: bool, injected: Op
|
||||
if activated && let Some(command) = &core.command {
|
||||
match injected {
|
||||
Some(source) => {
|
||||
// P3(shortcuts-w1): ap.AP9
|
||||
commands::fire_resolved(&core.ctx, command, source, craft_keymap::Mods::NONE);
|
||||
commands::fire_resolved(&core.ctx, command, source, pointer::frame(&core.ctx).mods);
|
||||
}
|
||||
None => {
|
||||
let mods = core.activation.map_or_else(|| pointer::frame(&core.ctx).mods, |activation| activation.mods);
|
||||
commands::fire_bound(&core.ctx, command, mods);
|
||||
}
|
||||
// P3(shortcuts-w1): ap.AP9
|
||||
None => commands::fire_bound(&core.ctx, command, craft_keymap::Mods::NONE),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ use crate::runtime::reads::{self, BindKey};
|
||||
use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler};
|
||||
use craft_behavior::{EditCommand, KeyOwner, OwnerClass, pick_instance, resolve_flags};
|
||||
use craft_keymap::{
|
||||
Active, Chord, CommandDef, CommandKind, CommandRef, Hit, KeyInput, Keymap, Layout, Matcher, ModalRule, Overrides, Platform, Press, Scopes,
|
||||
Trigger,
|
||||
Active, Chord, CommandDef, CommandKind, CommandRef, Hit, KeyInput, Keymap, Layout, Matcher, ModalRule, Overrides, Platform, Press, PressKind,
|
||||
Scopes, Trigger,
|
||||
};
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -103,6 +103,8 @@ struct KeymapCache {
|
||||
overrides: Option<Arc<Overrides>>,
|
||||
/// The generation of the app catalog the keymap joined, `None` for none.
|
||||
generation: Option<u64>,
|
||||
/// Whether hold bindings count in the keymap.
|
||||
holds: bool,
|
||||
/// The chords bound to the edit commands, which the input hook removes from the raw input when the focused
|
||||
/// component lists the command.
|
||||
edit_chords: Arc<[(EditCommand, Chord)]>,
|
||||
@@ -119,6 +121,21 @@ struct Held {
|
||||
target: Option<Id>,
|
||||
}
|
||||
|
||||
/// A key down that has a hold binding: its release or its deadline settles whether it was a tap or a hold. Interaction
|
||||
/// state like `Board::held`, set from a pass's own key events.
|
||||
struct HoldWait {
|
||||
key: craft_keymap::Key,
|
||||
/// What the hold runs once the delay passes with the key down.
|
||||
hold: Hit,
|
||||
/// When the key went down, by its own input time.
|
||||
since: f64,
|
||||
/// The hold delay at the press: a later change of the app's delay does not move this wait.
|
||||
delay: f64,
|
||||
/// What a release before the delay runs.
|
||||
tap: Option<Hit>,
|
||||
viewport: ViewportId,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Board {
|
||||
registry: Arc<registry::Registry>,
|
||||
@@ -165,6 +182,10 @@ pub(crate) struct Board {
|
||||
views: HashMap<ViewportId, View>,
|
||||
matcher: Matcher,
|
||||
held: Vec<Held>,
|
||||
/// The key whose tap or hold is still to be decided.
|
||||
hold_wait: Option<HoldWait>,
|
||||
/// The app's hold delay in seconds, from this frame's input.
|
||||
hold_delay: f64,
|
||||
/// The top modal layer's root container of each viewport that has one.
|
||||
modal_roots: HashMap<ViewportId, Id>,
|
||||
/// The states published this pass, and the pass before, by an instance inside the top modal layer.
|
||||
@@ -634,7 +655,12 @@ impl Board {
|
||||
|
||||
/// The scope name of `command`; commands no definition names belong to the application.
|
||||
fn scope_of(&self, command: &CommandRef) -> &str {
|
||||
self.def(command).map_or(CommandScope::APP.name(), |def| def.scope.as_str()) // P3(shortcuts-w1): kb.C3
|
||||
self.def(command).map_or(CommandScope::APP.name(), |def| def.scope.as_str())
|
||||
}
|
||||
|
||||
/// The app's state of `command`: the one set for its params, else the one set for its bare id.
|
||||
fn app_state(&self, number: u32, command: &CommandRef) -> Option<&CommandState> {
|
||||
params_key(command).and_then(|key| self.app_states.get(&(number, Some(key)))).or_else(|| self.app_states.get(&(number, None)))
|
||||
}
|
||||
|
||||
fn state_key(&self, command: &CommandRef, instance: Option<Id>) -> Option<StateKey> {
|
||||
@@ -727,7 +753,7 @@ impl Board {
|
||||
from: &Vantage,
|
||||
reads: &mut Reads,
|
||||
) -> (ResolvedCommand, Option<StateKey>) {
|
||||
let def = self.def(command); // P3(shortcuts-w1): kb.C3
|
||||
let def = self.def(command);
|
||||
let app = self.to_app(self.scope_of(command));
|
||||
let instance = if app { None } else { instance };
|
||||
let dialog_open = from.modal_open || from.dialog_keys;
|
||||
@@ -748,8 +774,7 @@ impl Board {
|
||||
};
|
||||
// An app-scope state is the app's held one; an instance's is this frame's publish, else last frame's.
|
||||
let (this, last) = match key {
|
||||
// P3(shortcuts-w1): op.F9
|
||||
Some((number, None)) => (self.app_states.get(&(number, None)), None),
|
||||
Some((number, None)) => (self.app_state(number, command), None),
|
||||
Some(key) => (self.this.get(&key), self.last.get(&key)),
|
||||
None => (None, None),
|
||||
};
|
||||
@@ -796,6 +821,12 @@ fn is_app(scope: &str) -> bool {
|
||||
scope == CommandScope::APP.name()
|
||||
}
|
||||
|
||||
/// The key of `command`'s app state when it carries params: `None` for a bare id, which answers every ref of its id.
|
||||
fn params_key(command: &CommandRef) -> Option<String> {
|
||||
let key = command.key_text();
|
||||
(key != command.id.as_str()).then(|| key.into_owned())
|
||||
}
|
||||
|
||||
/// The window's key matching: the keymap and the scopes a key matches in, innermost first. The key stage, the
|
||||
/// routing question whether a scoped command takes a key (`binds_scoped`) and a key automation holds at a canvas
|
||||
/// (`bound_around`) all match through it.
|
||||
@@ -809,18 +840,28 @@ struct KeyScopes {
|
||||
}
|
||||
|
||||
impl KeyScopes {
|
||||
/// What a press of `input` runs, read through `layout`, with `typing` when a text field has the keys. With
|
||||
/// `matcher` and the press's time the press counts toward a double press; without, it is matched on its own. A
|
||||
/// held scope's keys stay with the text while typing; a typing scope's keys are the text component's own.
|
||||
fn press(&self, layout: &Layout, input: &KeyInput, typing: bool, matcher: Option<(&mut Matcher, f64)>) -> Option<Hit> {
|
||||
/// Runs `f` with the active scopes and the outer ones a press matches in, with `typing` when a text field has the
|
||||
/// keys. A held scope's keys stay with the text while typing; a typing scope's keys are the text component's own.
|
||||
fn matching<R>(&self, typing: bool, f: impl FnOnce(&Active<'_>, &[&str]) -> R) -> R {
|
||||
let (panel, outer) = self.scopes.split_first().map_or((None, &[][..]), |(panel, outer)| (Some(*panel), outer));
|
||||
let held: &[&'static str] = if typing { &[] } else { &self.held };
|
||||
let contexts: Vec<&str> = self.typing.iter().chain(held).copied().collect();
|
||||
let active = Active { panel, contexts: &contexts, typing };
|
||||
match matcher {
|
||||
Some((matcher, now)) => matcher.press(layout, &self.keymap, &Press { input, repeat: false, now, active: &active, outer }),
|
||||
None => Matcher::single(layout, &self.keymap, input, &active, outer),
|
||||
}
|
||||
f(&Active { panel, contexts: &contexts, typing }, outer)
|
||||
}
|
||||
|
||||
/// What a press of `input` runs, read through `layout`. With `matcher` and the press's time the press counts toward
|
||||
/// a double press; without, it is matched on its own.
|
||||
fn press(&self, layout: &Layout, input: &KeyInput, typing: bool, matcher: Option<(&mut Matcher, f64)>) -> Option<Hit> {
|
||||
self.matching(typing, |active, outer| match matcher {
|
||||
Some((matcher, now)) => matcher.press(layout, &self.keymap, &Press { input, repeat: false, now, active, outer }),
|
||||
None => Matcher::single(layout, &self.keymap, input, active, outer),
|
||||
})
|
||||
}
|
||||
|
||||
/// What a hold of `input`'s key runs, when a hold binding applies.
|
||||
fn hold(&self, layout: &Layout, input: &KeyInput, typing: bool) -> Option<Hit> {
|
||||
// PLAN: assumed `Matcher::hold(layout, keymap, input, active, outer) -> Option<Hit>` (kb.C13f, shortcuts-w3)
|
||||
self.matching(typing, |active, outer| Matcher::hold(layout, &self.keymap, input, active, outer))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -849,9 +890,11 @@ struct BuiltKeymap {
|
||||
shown_text: Arc<HashMap<Chord, Arc<str>>>,
|
||||
}
|
||||
|
||||
/// The keymap of `defs` on `platform` under `overrides`.
|
||||
fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, overrides: Option<&Arc<Overrides>>) -> Keymap {
|
||||
let mut keymap = Keymap::new(defs, scopes, platform);
|
||||
/// The keymap of `defs` on `platform` under `overrides`, with the system chords reserved and hold bindings counting
|
||||
/// when `holds`.
|
||||
fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, overrides: Option<&Arc<Overrides>>, holds: bool) -> Keymap {
|
||||
let mut keymap = Keymap::new(defs, scopes, platform).with_reserved(craft_keymap::reserved::system(platform));
|
||||
keymap.set_holds(holds);
|
||||
if let Some(overrides) = overrides {
|
||||
keymap.set_overrides((**overrides).clone());
|
||||
}
|
||||
@@ -891,7 +934,13 @@ pub fn keymap_builds() -> u64 {
|
||||
///
|
||||
/// A window shortcut's default chord that another command also binds is that command's: the window shortcut loses it, so the
|
||||
/// app's binding beats the framework's default. A window shortcut the overrides name keeps what they give it.
|
||||
fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platform: Platform, overrides: Option<&Arc<Overrides>>) -> BuiltKeymap {
|
||||
fn build_keymap(
|
||||
registry: ®istry::Registry,
|
||||
app: Option<&AppCatalog>,
|
||||
platform: Platform,
|
||||
overrides: Option<&Arc<Overrides>>,
|
||||
holds: bool,
|
||||
) -> BuiltKeymap {
|
||||
#[cfg(feature = "testing")]
|
||||
KEYMAP_BUILDS.with(|builds| builds.set(builds.get() + 1));
|
||||
// A held scope and a typing scope are contexts of the keymap: their keys work while they are active, before any
|
||||
@@ -920,7 +969,7 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keymap = keymap_of(joined(defs.as_slice()), scopes.clone(), platform, overrides);
|
||||
let mut keymap = keymap_of(joined(defs.as_slice()), scopes.clone(), platform, overrides, holds);
|
||||
let overridden = |def: &CommandDef| overrides.is_some_and(|overrides| overrides.get(&def.command.id).is_some());
|
||||
let yielded: Vec<(CommandRef, Trigger)> = defs
|
||||
.iter()
|
||||
@@ -934,15 +983,14 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
def.defaults
|
||||
.retain(|binding| !yielded.iter().any(|(command, chord)| *command == def.command && binding.trigger.effective(platform) == *chord));
|
||||
}
|
||||
keymap = keymap_of(joined(defs.as_slice()), scopes, platform, overrides);
|
||||
keymap = keymap_of(joined(defs.as_slice()), scopes, platform, overrides, holds);
|
||||
}
|
||||
let window_shortcuts = registry
|
||||
.defs()
|
||||
.iter()
|
||||
.filter_map(|def| WindowShortcut::of(&def.command).map(|key| (key, &def.command)))
|
||||
.flat_map(|(key, command)| {
|
||||
// P3(shortcuts-w1): kb.C13b
|
||||
keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.is_double()).map(move |binding| (key, binding.trigger.chord))
|
||||
keymap.bindings(command).into_iter().filter(|binding| binding.trigger.press == PressKind::Single).map(move |binding| (key, binding.trigger.chord))
|
||||
})
|
||||
.collect();
|
||||
let edit_chords = registry
|
||||
@@ -952,8 +1000,7 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
// Delete's keys (Delete, Backspace) stay a focused text part's own deletion, which also deletes one character.
|
||||
.filter(|(edit, _)| *edit != EditCommand::Delete)
|
||||
.flat_map(|(edit, command)| {
|
||||
// P3(shortcuts-w1): kb.C13b
|
||||
keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.is_double()).map(move |binding| (edit, binding.trigger.chord))
|
||||
keymap.bindings(command).into_iter().filter(|binding| binding.trigger.press == PressKind::Single).map(move |binding| (edit, binding.trigger.chord))
|
||||
})
|
||||
.collect();
|
||||
let mut shown_text = HashMap::new();
|
||||
@@ -974,17 +1021,23 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
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.
|
||||
fn keymap_for(registry: &Arc<registry::Registry>, app: Option<&AppCatalog>, platform: Platform, overrides: Option<&Arc<Overrides>>) -> BuiltKeymap {
|
||||
if app.is_some() || overrides.is_some() || !registry::Registry::is_shared(registry) {
|
||||
return build_keymap(registry, app, platform, overrides);
|
||||
/// registry with no overrides, no catalog and holds off, else built here.
|
||||
fn keymap_for(
|
||||
registry: &Arc<registry::Registry>,
|
||||
app: Option<&AppCatalog>,
|
||||
platform: Platform,
|
||||
overrides: Option<&Arc<Overrides>>,
|
||||
holds: bool,
|
||||
) -> BuiltKeymap {
|
||||
if app.is_some() || overrides.is_some() || holds || !registry::Registry::is_shared(registry) {
|
||||
return build_keymap(registry, app, platform, overrides, holds);
|
||||
}
|
||||
let mut kept = DEFAULT_KEYMAPS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
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);
|
||||
let built = build_keymap(registry, None, platform, None, false);
|
||||
kept.push((platform, stories, built.clone()));
|
||||
built
|
||||
}
|
||||
@@ -1018,6 +1071,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
let platform = platform(ctx);
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let generation = input.catalog.as_ref().map(AppCatalog::generation);
|
||||
let holds = input.holds.is_some();
|
||||
let shadowed = with(ctx, |board| {
|
||||
// A published state resolves from this frame's, else the last frame's: one published last frame and not again
|
||||
// is gone now.
|
||||
@@ -1035,12 +1089,10 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
board.app_revision = revision;
|
||||
let mut states = HashMap::new();
|
||||
for (command, state) in input.states.iter().flat_map(|(_, states)| states.iter()) {
|
||||
// P3(shortcuts-w1): op.F9
|
||||
states.insert((board.number(&command.id), None), state.clone());
|
||||
states.insert((board.number(&command.id), params_key(command)), state.clone());
|
||||
}
|
||||
let changed: Vec<u32> = states
|
||||
.iter()
|
||||
// P3(shortcuts-w1): op.F9
|
||||
.filter(|(key, state)| board.app_states.get(*key) != Some(*state))
|
||||
.map(|(key, _)| key.0)
|
||||
.chain(board.app_states.keys().filter(|key| !states.contains_key(*key)).map(|key| key.0))
|
||||
@@ -1055,9 +1107,15 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
}
|
||||
board.gate = input.gate.clone();
|
||||
board.app = input.catalog.clone();
|
||||
board.hold_delay = input.holds.unwrap_or_default();
|
||||
// Turning holds off ends a wait: its key's hold no longer exists.
|
||||
if !holds {
|
||||
board.hold_wait = None;
|
||||
}
|
||||
let stale = board.keymap.as_ref().is_none_or(|cache| {
|
||||
cache.platform != platform
|
||||
|| cache.generation != generation
|
||||
|| cache.holds != holds
|
||||
|| match (&cache.overrides, &input.overrides) {
|
||||
(Some(a), Some(b)) => !Arc::ptr_eq(a, b),
|
||||
(None, None) => false,
|
||||
@@ -1067,9 +1125,9 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
let mut shadowed = Vec::new();
|
||||
if stale {
|
||||
let BuiltKeymap { keymap, edit_chords, window_shortcuts, shown_text } =
|
||||
keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref());
|
||||
keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref(), holds);
|
||||
board.keymap =
|
||||
Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text });
|
||||
Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, holds, edit_chords, window_shortcuts, shown_text });
|
||||
board.gens.shared += 1;
|
||||
for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) {
|
||||
if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) {
|
||||
@@ -1091,6 +1149,11 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> {
|
||||
with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The window's keymap; none before the first frame builds one.
|
||||
pub(crate) fn keymap(ctx: &Context) -> Option<Arc<Keymap>> {
|
||||
with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.keymap)))
|
||||
}
|
||||
|
||||
/// The bindings the window's keymap gives `command`; none before the first frame builds one.
|
||||
pub(crate) fn bindings(ctx: &Context, command: &CommandRef) -> Vec<craft_keymap::Binding> {
|
||||
with(ctx, |board| board.keymap.as_ref().map(|cache| cache.keymap.bindings(command)).unwrap_or_default())
|
||||
@@ -1238,7 +1301,7 @@ fn resolve_in(
|
||||
mut reads: Reads,
|
||||
) -> (ResolvedCommand, ResolveKey) {
|
||||
let (resolved, key, first_unknown) = with(ctx, |board| {
|
||||
let first_unknown = board.def(command).is_none() && board.unknown.insert(command.id.clone()); // P3(shortcuts-w1): kb.C3
|
||||
let first_unknown = board.def(command).is_none() && board.unknown.insert(command.id.clone());
|
||||
// A command no state named yet has a key too, so a state given later reaches the regions that read it.
|
||||
board.number(&command.id);
|
||||
let (mut resolved, state) = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here), &mut reads);
|
||||
@@ -1526,11 +1589,10 @@ pub(crate) fn fire_bound(ctx: &Context, command: &ResolvedCommand, mods: craft_k
|
||||
|
||||
/// Queues `command` for its instance with `source`; false when disabled.
|
||||
pub(crate) fn fire_resolved(ctx: &Context, command: &ResolvedCommand, source: FireSource, mods: craft_keymap::Mods) -> bool {
|
||||
let _ = mods; // P3(shortcuts-w1): ap.AP9
|
||||
if !command.enabled || !crate::runtime::measure::effect(ctx, "board::fire_resolved") {
|
||||
return false;
|
||||
}
|
||||
queue(ctx, Fired { target: command.instance, ..Fired::new(command.command.clone(), source, FirePhase::Press, pass::now(ctx)) });
|
||||
queue(ctx, Fired { target: command.instance, ..Fired::new(command.command.clone(), source, FirePhase::Press, pass::now(ctx)) }.mods(mods));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1577,7 +1639,7 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef,
|
||||
);
|
||||
let changed = with(ctx, |board| {
|
||||
let scope = board.scope_of(command);
|
||||
let declared = board.def(command).is_some_and(|def| def.modal == ModalRule::Declared); // P3(shortcuts-w1): kb.C3
|
||||
let declared = board.def(command).is_some_and(|def| def.modal == ModalRule::Declared);
|
||||
debug_assert!(
|
||||
!is_app(scope) || declared,
|
||||
"{command} is an app-scope command: its state comes from `FrameInput.commands`, unless the command is declared by an instance"
|
||||
@@ -1727,8 +1789,24 @@ impl Returning {
|
||||
}
|
||||
}
|
||||
|
||||
/// The release of the momentary or tool command `held`, fired when its key goes up or the window loses focus (the key's
|
||||
/// release then goes to another window).
|
||||
fn release_fired(held: Held, mods: craft_keymap::Mods, time: f64) -> Fired {
|
||||
Fired {
|
||||
command: held.command,
|
||||
target: held.target,
|
||||
source: FireSource::Key,
|
||||
phase: FirePhase::Release,
|
||||
cycle: false,
|
||||
alt_variant: false,
|
||||
mods,
|
||||
time,
|
||||
}
|
||||
}
|
||||
|
||||
/// H7: the key stage's shortcut events, matched against the keymap in the scopes around the focused component,
|
||||
/// through the gate, to their commands.
|
||||
/// through the gate, to their commands. A key with a hold binding waits (`HoldWait`) for its release, the next event
|
||||
/// or its deadline.
|
||||
pub(crate) fn begin(ctx: &Context) {
|
||||
let (arrived, changed) = with(ctx, |board| board.changed.clone());
|
||||
if arrived == pass::root_frame_nr(ctx) && changed.keymap {
|
||||
@@ -1796,7 +1874,8 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
}
|
||||
board.here.dialog_keys = view.dialog_keys;
|
||||
board.here.inside_modal.clone_from(&view.inside_modal);
|
||||
if shortcuts.keys.is_empty() {
|
||||
let waiting = board.hold_wait.as_ref().is_some_and(|wait| wait.viewport == viewport);
|
||||
if shortcuts.keys.is_empty() && shortcuts.mods.is_empty() && !shortcuts.focus_lost && !waiting {
|
||||
return None;
|
||||
}
|
||||
let mut keys = board.key_scopes(&chain)?;
|
||||
@@ -1816,63 +1895,113 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
check_kept(ctx, viewport);
|
||||
}
|
||||
let Some((keys, mut matcher)) = taken else { return };
|
||||
let modal_at_start = overlay::any_open(ctx, overlay::OpenFilter::Modal);
|
||||
let (delay, mut wait) = with(ctx, |board| {
|
||||
let wait = if board.hold_wait.as_ref().is_some_and(|wait| wait.viewport == viewport) { board.hold_wait.take() } else { None };
|
||||
(board.hold_delay, wait)
|
||||
});
|
||||
// A modal layer or a text field that has the keys ends the wait without firing: the key is no longer the shortcut's.
|
||||
// PLAN: a tool claim or an IME composition on the key also ends it; the claim stage (kb.C11c, shortcuts-w2) gives the board no signal for either yet.
|
||||
if modal_at_start || shortcuts.typing {
|
||||
wait = None;
|
||||
}
|
||||
// The fired press of `hit`, or `None` when its command is disabled now or blocked by a modal layer an earlier hit of
|
||||
// the pass opened (kb.C9). A momentary or tool command is kept with its key, whose release fires it again.
|
||||
let press = |hit: Hit, key: Option<craft_keymap::Key>, time: f64| -> Option<Fired> {
|
||||
let (blocked, holds_key) = with(ctx, |board| {
|
||||
board.def(&hit.command).map_or((false, false), |def| {
|
||||
(def.modal == ModalRule::Blocked, matches!(def.kind, CommandKind::Momentary | CommandKind::Tool { .. }))
|
||||
})
|
||||
});
|
||||
if blocked && !modal_at_start && overlay::any_open(ctx, overlay::OpenFilter::Modal) {
|
||||
return None;
|
||||
}
|
||||
let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here));
|
||||
let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None);
|
||||
if !resolved.enabled {
|
||||
return None;
|
||||
}
|
||||
// An app-scope command a modal layer's instance declares is delivered to that instance.
|
||||
let target = if app { resolved.instance } else { instance };
|
||||
if let Some(key) = key.filter(|_| holds_key) {
|
||||
with(ctx, |board| {
|
||||
board.held.retain(|held| held.key != key);
|
||||
board.held.push(Held { key, command: hit.command.clone(), target });
|
||||
});
|
||||
}
|
||||
Some(Fired {
|
||||
command: hit.command,
|
||||
target,
|
||||
source: FireSource::Key,
|
||||
phase: FirePhase::Press,
|
||||
cycle: hit.cycle.len() > 1,
|
||||
alt_variant: hit.alt_variant,
|
||||
mods: hit.trigger.chord.mods,
|
||||
time,
|
||||
})
|
||||
};
|
||||
// Settles a wait by the time of the event that ends it: the hold when the key was down for the delay, else the tap.
|
||||
let settle = |wait: Option<HoldWait>, time: f64| -> Option<Fired> {
|
||||
let wait = wait?;
|
||||
let hit = if time - wait.since >= wait.delay { Some(wait.hold) } else { wait.tap }?;
|
||||
press(hit, Some(wait.key), time)
|
||||
};
|
||||
let mut fired = Vec::new();
|
||||
for shortcut in &shortcuts.keys {
|
||||
let mut changes = shortcuts.mods.iter().map(|(index, _)| *index).peekable();
|
||||
for (index, shortcut) in shortcuts.keys.iter().enumerate() {
|
||||
// A change of Cmd, Ctrl or Alt before this key settles the wait first.
|
||||
while changes.next_if(|change| *change <= index).is_some() {
|
||||
fired.extend(settle(wait.take(), now));
|
||||
}
|
||||
// When the key event arrived: a frame may run it later, and a double press and a hold read the key's own times.
|
||||
let time = shortcut.at.unwrap_or(now);
|
||||
let key = shortcut.input.physical.or(shortcut.input.typed);
|
||||
match shortcut.phase {
|
||||
FirePhase::Release => {
|
||||
let key = shortcut.input.physical.or(shortcut.input.typed);
|
||||
let held = with(ctx, |board| key.and_then(|key| board.held.iter().position(|held| held.key == key)).map(|at| board.held.remove(at)));
|
||||
if let Some(held) = held {
|
||||
fired.push(Fired {
|
||||
command: held.command,
|
||||
target: held.target,
|
||||
source: FireSource::Key,
|
||||
phase: FirePhase::Release,
|
||||
cycle: false,
|
||||
alt_variant: false,
|
||||
mods: craft_keymap::Mods::NONE, // P3(shortcuts-w1): ap.AP9
|
||||
time,
|
||||
});
|
||||
if wait.as_ref().is_some_and(|wait| Some(wait.key) == key) {
|
||||
fired.extend(settle(wait.take(), time));
|
||||
}
|
||||
let held = with(ctx, |board| key.and_then(|key| board.held.iter().position(|held| held.key == key)).map(|at| board.held.remove(at)));
|
||||
fired.extend(held.map(|held| release_fired(held, shortcut.input.mods, time)));
|
||||
}
|
||||
_ => {
|
||||
let Some(hit) = keys.press(&shortcuts.layout, &shortcut.input, shortcuts.typing && !shortcut.canvas, Some((&mut matcher, time)))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here));
|
||||
let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None);
|
||||
if !resolved.enabled {
|
||||
continue;
|
||||
// Another key's press settles the wait first: keys act in the order they went down.
|
||||
fired.extend(settle(wait.take(), time));
|
||||
let typing = shortcuts.typing && !shortcut.canvas;
|
||||
let hold = key
|
||||
.filter(|_| !typing && !modal_at_start)
|
||||
.and_then(|key| keys.hold(&shortcuts.layout, &shortcut.input, typing).map(|hold| (key, hold)));
|
||||
let tap = keys.press(&shortcuts.layout, &shortcut.input, typing, Some((&mut matcher, time)));
|
||||
match hold {
|
||||
Some((key, hold)) => wait = Some(HoldWait { key, hold, since: time, delay, tap, viewport }),
|
||||
None => fired.extend(tap.and_then(|hit| press(hit, key, time))),
|
||||
}
|
||||
// An app-scope command a modal layer's instance declares is delivered to that instance.
|
||||
let target = if app { resolved.instance } else { instance };
|
||||
let key = shortcut.input.physical.or(shortcut.input.typed);
|
||||
with(ctx, |board| {
|
||||
if let Some(key) = key.filter(|_| {
|
||||
// P3(shortcuts-w1): kb.C3
|
||||
board.def(&hit.command).is_some_and(|def| matches!(def.kind, CommandKind::Momentary | CommandKind::Tool { .. }))
|
||||
}) {
|
||||
board.held.retain(|held| held.key != key);
|
||||
board.held.push(Held { key, command: hit.command.clone(), target });
|
||||
}
|
||||
});
|
||||
fired.push(Fired {
|
||||
command: hit.command,
|
||||
target,
|
||||
source: FireSource::Key,
|
||||
phase: FirePhase::Press,
|
||||
cycle: hit.cycle.len() > 1,
|
||||
alt_variant: hit.alt_variant,
|
||||
mods: craft_keymap::Mods::NONE, // P3(shortcuts-w1): ap.AP9
|
||||
time,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
with(ctx, |board| board.matcher = matcher);
|
||||
for _ in changes {
|
||||
fired.extend(settle(wait.take(), now));
|
||||
}
|
||||
// The key's release goes to another window: a momentary command ends and a wait drops.
|
||||
if shortcuts.focus_lost {
|
||||
wait = None;
|
||||
let held = with(ctx, |board| std::mem::take(&mut board.held));
|
||||
fired.extend(held.into_iter().map(|held| release_fired(held, craft_keymap::Mods::NONE, now)));
|
||||
}
|
||||
// The deadline is a time event: only the first pass of a frame, which has elapsed time, fires it.
|
||||
if let Some(due) = wait.as_ref().map(|wait| wait.since + wait.delay) {
|
||||
if now < due {
|
||||
frame::request_repaint_after(ctx, due - now);
|
||||
} else if frame::running(ctx).is_some_and(|pass| pass.elapsed > 0.0) {
|
||||
fired.extend(wait.take().and_then(|wait| press(wait.hold, Some(wait.key), now)));
|
||||
}
|
||||
}
|
||||
with(ctx, |board| {
|
||||
board.matcher = matcher;
|
||||
if wait.is_some() {
|
||||
board.hold_wait = wait;
|
||||
}
|
||||
});
|
||||
let pressed = fired.iter().any(|fired| fired.phase == FirePhase::Press);
|
||||
if pressed && let Some(returning) = returning {
|
||||
returning.give_back(ctx);
|
||||
@@ -1920,6 +2049,9 @@ pub(crate) fn end(ctx: &Context) {
|
||||
let ids = |id: Id| instances.contains(id);
|
||||
board.queue.retain(|fired| fired.target.is_some_and(ids));
|
||||
board.held.retain(|held| held.target.is_none_or(ids));
|
||||
if board.hold_wait.as_ref().is_some_and(|wait| !live.contains(&wait.viewport)) {
|
||||
board.hold_wait = None;
|
||||
}
|
||||
board.chains.retain(|viewport, _| live.contains(viewport));
|
||||
board.before.retain(|viewport, _| live.contains(viewport));
|
||||
board.views.retain(|viewport, _| live.contains(viewport));
|
||||
|
||||
@@ -7,7 +7,7 @@ mod registry;
|
||||
|
||||
pub use clipboard::{ClipContent, ClipError, ClipItem, ClipboardHandle};
|
||||
pub use craft_behavior::EditCommand;
|
||||
pub use craft_keymap::{Binding, CommandDef, CommandKind, CommandRef, CommandScope, ModalRule, Platform, Scope};
|
||||
pub use craft_keymap::{Binding, CommandDef, CommandKind, CommandRef, CommandScope, ModalRule, Platform, Scope, Trigger};
|
||||
pub use library::ChromeCommand;
|
||||
pub(crate) use library::WindowShortcut;
|
||||
pub use library::{EditCommands, NavCommand, WindowCommand};
|
||||
@@ -32,6 +32,10 @@ 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 crate::runtime::egui::{areas, pass};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::memory::Facts;
|
||||
use crate::runtime::overlay;
|
||||
use craft_behavior::CommandFlags;
|
||||
use craft_behavior::edit_history::Step;
|
||||
use craft_keymap::{Chord, Overrides};
|
||||
@@ -59,7 +63,7 @@ impl AppCatalog {
|
||||
if !def.scope.is_app() {
|
||||
return Err(CommandDefError::NotApp { command: def.command.id.clone() });
|
||||
}
|
||||
registry::index_id(&mut index, &def.command.id, at)?;
|
||||
registry::index_id(&mut index, &def.command.key_text(), at)?;
|
||||
}
|
||||
Ok(AppCatalog { defs: defs.into(), index: Arc::new(index), generation })
|
||||
}
|
||||
@@ -76,8 +80,8 @@ impl AppCatalog {
|
||||
|
||||
/// The def with the command's key, else the def with the bare id.
|
||||
pub(crate) fn get(&self, command: &CommandRef) -> Option<&CommandDef> {
|
||||
// P3(shortcuts-w1): kb.C2
|
||||
self.index.get(command.id.as_str()).and_then(|&at| self.defs.get(at))
|
||||
let at = self.index.get(command.key_text().as_ref()).or_else(|| self.index.get(command.id.as_str()))?;
|
||||
self.defs.get(*at)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,8 +158,7 @@ impl Fired {
|
||||
|
||||
/// The command with `mods` as the modifiers its firing input carried.
|
||||
pub fn mods(self, mods: craft_keymap::Mods) -> Fired {
|
||||
let _ = mods;
|
||||
todo!("ap.AP9")
|
||||
Fired { mods, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,6 +372,7 @@ pub struct CommandInput {
|
||||
pub(crate) overrides: Option<Arc<Overrides>>,
|
||||
pub(crate) gate: Option<CommandGate>,
|
||||
pub(crate) catalog: Option<AppCatalog>,
|
||||
pub(crate) holds: Option<f64>,
|
||||
}
|
||||
|
||||
impl CommandInput {
|
||||
@@ -395,9 +399,9 @@ impl CommandInput {
|
||||
/// Turns hold bindings on with the app's hold delay in seconds, `Some(delay)`; `None`, the default, turns them off.
|
||||
/// The keymap is rebuilt when this changes.
|
||||
#[must_use]
|
||||
pub fn holds(self, delay: Option<f64>) -> Self {
|
||||
let _ = delay;
|
||||
todo!("kb.C14")
|
||||
pub fn holds(mut self, delay: Option<f64>) -> Self {
|
||||
self.holds = delay;
|
||||
self
|
||||
}
|
||||
|
||||
/// The frame's app catalog; the keymap is rebuilt when the platform, the overrides or the catalog's generation change.
|
||||
@@ -560,30 +564,49 @@ pub fn holder(ctx: &Context, chord: &Chord) -> Option<CommandRef> {
|
||||
/// The runtime's keymap: the linked sets and the app catalog on the window's platform, under the overrides, with the
|
||||
/// system chords reserved. `None` before the first frame.
|
||||
pub fn keymap(ctx: &Context) -> Option<Arc<craft_keymap::Keymap>> {
|
||||
let _ = ctx;
|
||||
todo!("kb.C4")
|
||||
board::keymap(ctx)
|
||||
}
|
||||
|
||||
/// A command shown at `rect` in `layer`, as a pass registered it.
|
||||
#[derive(Clone)]
|
||||
struct ShownFact {
|
||||
command: CommandRef,
|
||||
layer: egui::LayerId,
|
||||
rect: egui::Rect,
|
||||
label: Label,
|
||||
holder: bool,
|
||||
}
|
||||
|
||||
/// Registers `command` as shown for the next pass of the running viewport.
|
||||
fn register_shown(ctx: &Context, layer: egui::LayerId, rect: egui::Rect, label: Label, command: &CommandRef, holder: bool) {
|
||||
Facts::register(ctx, ShownFact { command: command.clone(), layer, rect, label, holder });
|
||||
}
|
||||
|
||||
/// Records that a container at `rect` holds `commands`, for this pass and viewport. Not [`CommandInput::holds`], which
|
||||
/// turns hold bindings on.
|
||||
pub fn holds(ctx: &Context, layer: egui::LayerId, rect: egui::Rect, commands: &[CommandRef], label: crate::runtime::env::Label) {
|
||||
let _ = (ctx, layer, rect, commands, label);
|
||||
todo!("mn.M36")
|
||||
pub fn holds(ctx: &Context, layer: egui::LayerId, rect: egui::Rect, commands: &[CommandRef], label: Label) {
|
||||
for command in commands {
|
||||
register_shown(ctx, layer, rect, label.clone(), command, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that `command` was shown at `rect` in `layer`, with `label`, for this pass and viewport: [`holds`] calls it
|
||||
/// for a holder and the report step for a bound component wholly inside its clip.
|
||||
#[allow(dead_code)] // P3(shortcuts-w1): mn.M37
|
||||
pub(crate) fn note_shown(ctx: &Context, layer: egui::LayerId, rect: egui::Rect, label: crate::runtime::env::Label, command: &CommandRef) {
|
||||
let _ = (ctx, layer, rect, label, command);
|
||||
todo!("mn.M37")
|
||||
/// Records that the bound component of `command` was shown at `rect` in `layer`, with `label`, for this pass and
|
||||
/// viewport: the report step calls it for a component wholly inside its clip.
|
||||
// PLAN: the caller is the report step (menus-w3); until it lands nothing in this crate calls it.
|
||||
pub(crate) fn note_shown(ctx: &Context, layer: egui::LayerId, rect: egui::Rect, label: Label, command: &CommandRef) {
|
||||
register_shown(ctx, layer, rect, label, command, false);
|
||||
}
|
||||
|
||||
/// Where `command` was shown in the last pass: a bound component's clipped rect or a holder's rect. `None` unless it
|
||||
/// was wholly in view and not under another window.
|
||||
pub fn shown(ctx: &Context, command: &CommandRef) -> Option<Shown> {
|
||||
let _ = (ctx, command);
|
||||
todo!("mn.M37")
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let scrim = overlay::top_modal_in(ctx, viewport).and_then(|top| top.cover);
|
||||
Facts::<ShownFact>::of_last_pass(ctx)
|
||||
.into_iter()
|
||||
.filter(|fact| fact.command == *command)
|
||||
.find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect)))
|
||||
.map(|fact| Shown { rect: fact.rect, viewport, label: fact.label, holder: fact.holder })
|
||||
}
|
||||
|
||||
/// Where a command was shown, from [`shown`].
|
||||
|
||||
@@ -217,6 +217,89 @@ fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() {
|
||||
assert_eq!(fired(&frames), by_registry_key, "the catalog's alternate key does what the registry's key does");
|
||||
}
|
||||
|
||||
const PANEL: &str = "trialCatalog.panel";
|
||||
const CLOSE: &str = "trialCatalog.close";
|
||||
|
||||
/// A def of the parameterised `PANEL` command with `params` (a JSON object text), bound to `chord`.
|
||||
fn panel(params: &str, label: &str, chord: &str) -> CommandDef {
|
||||
let command = CommandRef::parse_key(&format!("{PANEL} {params}")).expect("the trial's key parses");
|
||||
CommandDef::new(command, label, Scope::app()).with_default(Binding::parse(chord).expect("the trial's chord parses"))
|
||||
}
|
||||
|
||||
/// Two defs with one id and different params build, each with its own chord and label; the bare id's def answers a ref
|
||||
/// with other params; two defs with one key are refused.
|
||||
#[trial]
|
||||
fn parameterised_catalog_rows_keep_their_own_kinds_and_defaults() {
|
||||
let layers = panel(r#"{"panel":"layers"}"#, "Layers", "Cmd+Alt+1");
|
||||
let info = panel(r#"{"panel":"info"}"#, "Info", "Cmd+Alt+2");
|
||||
let bare = def(PANEL, "Panel", "Cmd+Alt+3");
|
||||
assert!(AppCatalog::new(vec![layers.clone(), layers.clone()], 1).is_err(), "one key twice is a duplicate");
|
||||
let catalog = AppCatalog::new(vec![layers.clone(), info.clone(), bare], 1).expect("two params of one id are two rows");
|
||||
let mut show = |ui: &mut Ui| {
|
||||
AppShell::new(WindowKey::main()).show(ui, &mut ());
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.commands(CommandInput::new().catalog(catalog));
|
||||
frames.idle(3, &mut show);
|
||||
for (key, def) in [(Key::Num1, &layers), (Key::Num2, &info), (Key::Num3, &CommandDef::new(PANEL, "Panel", Scope::app()))] {
|
||||
let chord = Modifiers::COMMAND | Modifiers::ALT;
|
||||
frames.frame(vec![key_press(key, chord)], &mut show);
|
||||
frames.frame(vec![key_release(key, chord)], &mut show);
|
||||
let got: Vec<String> = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.key()).collect();
|
||||
assert_eq!(got, [def.command.key()], "the chord fires the row's own ref");
|
||||
}
|
||||
let label = |command: &CommandRef| craft_ui::runtime::commands::resolve(&frames.ctx, command.clone()).label.to_string();
|
||||
assert_eq!(label(&layers.command), "Layers");
|
||||
assert_eq!(label(&info.command), "Info");
|
||||
let unknown = CommandRef::parse_key(&format!(r#"{PANEL} {{"panel":"nope"}}"#)).expect("the trial's key parses");
|
||||
assert_eq!(label(&unknown), "Panel", "the bare id's def answers a ref with other params");
|
||||
}
|
||||
|
||||
/// The runtime's keymap reserves the system chords: a catalog default on one is not bound, and the keymap answers what
|
||||
/// `bindings` reads. It is `None` before the first frame.
|
||||
#[trial]
|
||||
fn the_runtime_keymap_reserves_the_system_chords() {
|
||||
let untouched = Frames::uninstalled();
|
||||
assert!(craft_ui::runtime::commands::keymap(&untouched.ctx).is_none(), "no keymap before the first frame");
|
||||
|
||||
let close = CommandRef::new(CLOSE);
|
||||
let defs = vec![def(CLOSE, "Alt+F4", "Alt+F4"), def(QUICK, "Quick Mask", "Q")];
|
||||
let mut frames = Frames::new();
|
||||
craft_ui::testing::windows::set_os(&frames.ctx, craft_host::target::Os::Windows);
|
||||
frames.commands(CommandInput::new().catalog(AppCatalog::new(defs, 1).expect("the trial's catalog is valid")));
|
||||
let mut show = |ui: &mut Ui| {
|
||||
AppShell::new(WindowKey::main()).show(ui, &mut ());
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
let keymap = craft_ui::runtime::commands::keymap(&frames.ctx).expect("a keymap after the first frame");
|
||||
assert!(keymap.bindings(&close).is_empty(), "Alt+F4 is reserved on Windows");
|
||||
assert_eq!(craft_ui::runtime::commands::bindings(&frames.ctx, &close), keymap.bindings(&close));
|
||||
assert!(!keymap.bindings(&CommandRef::new(QUICK)).is_empty(), "an ordinary chord stays bound");
|
||||
frames.frame(vec![key_press(Key::F4, Modifiers::ALT)], &mut show);
|
||||
frames.frame(vec![key_release(Key::F4, Modifiers::ALT)], &mut show);
|
||||
assert!(fired(&frames).is_empty(), "the reserved chord fires nothing");
|
||||
}
|
||||
|
||||
/// A holder recorded in a pass is shown in the next, never in its own or before any pass.
|
||||
#[trial]
|
||||
fn a_command_shown_in_view_is_found_and_one_under_a_layer_is_not() {
|
||||
use craft_ui::runtime::commands::{holds, shown};
|
||||
let command = CommandRef::new(QUICK);
|
||||
let rect = Rect::from_min_size(egui::pos2(20.0, 20.0), egui::vec2(60.0, 20.0));
|
||||
let seen = RefCell::new(Vec::new());
|
||||
let mut show = |ui: &mut Ui| {
|
||||
seen.borrow_mut().push(shown(ui.ctx(), &command));
|
||||
holds(ui.ctx(), ui.layer_id(), rect, &[command.clone()], "Quick".into());
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(3, &mut show);
|
||||
let seen = seen.into_inner();
|
||||
assert_eq!(seen[0], None, "before any pass");
|
||||
let last = seen.last().expect("passes ran").clone().expect("shown after a pass that recorded it");
|
||||
assert!(last.holder, "a holder's rect");
|
||||
assert_eq!(last.rect, rect);
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! The hold wait: a key with a single and a hold binding runs one or the other by how long it stayed down.
|
||||
|
||||
use craft_ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandKind, CommandRef, FirePhase, Scope, Trigger, keymap_builds};
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::shell::AppShell;
|
||||
use craft_ui::testing::focus::key_release;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use egui::{Key, Modifiers, Ui};
|
||||
|
||||
const TAP: &str = "trialHold.tap";
|
||||
const HOLD: &str = "trialHold.hold";
|
||||
const OTHER: &str = "trialHold.other";
|
||||
const MOMENT: &str = "trialHold.moment";
|
||||
const DELAY: f64 = 0.5;
|
||||
|
||||
fn def(id: &str, chord: &str) -> CommandDef {
|
||||
CommandDef::new(id, id, Scope::app()).with_default(Binding::parse(chord).expect("the trial's chord parses"))
|
||||
}
|
||||
|
||||
/// The hold binding of `chord`.
|
||||
fn hold_def(id: &str, chord: &str) -> CommandDef {
|
||||
let chord = Binding::parse(chord).expect("the trial's chord parses").trigger.chord;
|
||||
CommandDef::new(id, id, Scope::app()).with_default(Binding::new(Trigger::hold(chord)))
|
||||
}
|
||||
|
||||
/// X taps `TAP` and holds `HOLD`; Y runs `OTHER`; M is a momentary command.
|
||||
fn input(delay: Option<f64>) -> CommandInput {
|
||||
let defs = vec![
|
||||
def(TAP, "X"),
|
||||
hold_def(HOLD, "X"),
|
||||
def(OTHER, "Y"),
|
||||
def(MOMENT, "M").with_kind(CommandKind::Momentary),
|
||||
];
|
||||
CommandInput::new().catalog(AppCatalog::new(defs, 1).expect("the trial's catalog is valid")).holds(delay)
|
||||
}
|
||||
|
||||
fn show(ui: &mut Ui) {
|
||||
AppShell::new(WindowKey::main()).show(ui, &mut ());
|
||||
}
|
||||
|
||||
/// A frame source with a still clock, the catalog in and a few frames run.
|
||||
fn started(input: CommandInput) -> Frames {
|
||||
let mut frames = Frames::new();
|
||||
frames.still_clock();
|
||||
frames.commands(input);
|
||||
frames.idle(3, show);
|
||||
frames
|
||||
}
|
||||
|
||||
fn fired(frames: &Frames) -> Vec<(String, FirePhase)> {
|
||||
take_output(&frames.ctx).fired.into_iter().map(|fired| (fired.command.id, fired.phase)).collect()
|
||||
}
|
||||
|
||||
fn pressed(id: &str) -> (String, FirePhase) {
|
||||
(id.to_owned(), FirePhase::Press)
|
||||
}
|
||||
|
||||
fn down(frames: &mut Frames, key: Key) {
|
||||
frames.frame(vec![key_press(key, Modifiers::NONE)], show);
|
||||
}
|
||||
|
||||
fn up(frames: &mut Frames, key: Key) {
|
||||
frames.frame(vec![key_release(key, Modifiers::NONE)], show);
|
||||
}
|
||||
|
||||
/// A release before the delay runs the tap, a release after it the hold; a key still down at the deadline runs the hold
|
||||
/// once, and its later release runs nothing.
|
||||
#[trial]
|
||||
fn a_tap_runs_the_key_and_a_hold_runs_the_hold_once() {
|
||||
let mut frames = started(input(Some(DELAY)));
|
||||
down(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "the press waits");
|
||||
frames.advance(0.1);
|
||||
up(&mut frames, Key::X);
|
||||
assert_eq!(fired(&frames), [pressed(TAP)], "a release before the delay is a tap");
|
||||
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(DELAY + 0.2);
|
||||
up(&mut frames, Key::X);
|
||||
assert_eq!(fired(&frames), [pressed(HOLD)], "a release after the delay is a hold");
|
||||
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(DELAY + 0.2);
|
||||
frames.frame(vec![], show);
|
||||
assert_eq!(fired(&frames), [pressed(HOLD)], "the deadline fires the hold with the key still down");
|
||||
frames.frame(vec![], show);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "the hold fired once");
|
||||
}
|
||||
|
||||
/// A second key pressed while a wait runs settles the wait first: the tap fires before the second key's command.
|
||||
#[trial]
|
||||
fn keys_act_in_the_order_they_went_down() {
|
||||
let mut frames = started(input(Some(DELAY)));
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(0.1);
|
||||
down(&mut frames, Key::Y);
|
||||
assert_eq!(fired(&frames), [pressed(TAP), pressed(OTHER)]);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "the settled key's release runs nothing");
|
||||
}
|
||||
|
||||
/// A text field that has the keys ends the wait: the press starts none and the release runs neither the tap nor the hold.
|
||||
#[trial]
|
||||
fn a_modal_typing_or_a_claim_ends_the_wait_without_firing() {
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::text::TextField;
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
let name = RefCell::new(String::new());
|
||||
let field = Cell::new(egui::Rect::NOTHING);
|
||||
let mut with_field = |ui: &mut Ui| {
|
||||
AppShell::new(WindowKey::main())
|
||||
.body(|ui, _, _| {
|
||||
field.set(TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).id_salt("name").show(ui).response.rect);
|
||||
})
|
||||
.show(ui, &mut ());
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.still_clock();
|
||||
frames.commands(input(Some(DELAY)));
|
||||
frames.idle(3, &mut with_field);
|
||||
let at = field.get().center();
|
||||
frames.frame(vec![moved(at)], &mut with_field);
|
||||
frames.frame(vec![press(at)], &mut with_field);
|
||||
frames.frame(vec![release(at)], &mut with_field);
|
||||
frames.idle(2, &mut with_field);
|
||||
let _ = fired(&frames);
|
||||
frames.frame(vec![key_press(Key::X, Modifiers::NONE)], &mut with_field);
|
||||
frames.advance(DELAY + 0.2);
|
||||
frames.frame(vec![], &mut with_field);
|
||||
frames.frame(vec![key_release(Key::X, Modifiers::NONE)], &mut with_field);
|
||||
assert!(fired(&frames).is_empty(), "a focused text field has the key: no tap and no hold");
|
||||
}
|
||||
|
||||
/// Losing the window's focus drops the wait and ends a held momentary command once; the key's later release runs nothing.
|
||||
#[trial]
|
||||
fn focus_loss_drops_the_wait() {
|
||||
let mut frames = started(input(Some(DELAY)));
|
||||
down(&mut frames, Key::M);
|
||||
assert_eq!(fired(&frames), [pressed(MOMENT)]);
|
||||
down(&mut frames, Key::X);
|
||||
frames.frame(vec![egui::Event::WindowFocused(false)], show);
|
||||
assert_eq!(fired(&frames), [(MOMENT.to_owned(), FirePhase::Release)], "the momentary command ends at the focus loss");
|
||||
frames.advance(DELAY + 0.2);
|
||||
up(&mut frames, Key::X);
|
||||
up(&mut frames, Key::M);
|
||||
assert!(fired(&frames).is_empty(), "neither the tap, the hold nor a second release runs");
|
||||
}
|
||||
|
||||
/// A wait keeps the delay it started with; the next press reads the new one.
|
||||
#[trial]
|
||||
fn the_delay_is_read_at_the_press() {
|
||||
let mut frames = started(input(Some(DELAY)));
|
||||
down(&mut frames, Key::X);
|
||||
frames.commands(input(Some(5.0)));
|
||||
frames.advance(DELAY + 0.2);
|
||||
frames.frame(vec![], show);
|
||||
assert_eq!(fired(&frames), [pressed(HOLD)], "the running wait keeps its deadline");
|
||||
up(&mut frames, Key::X);
|
||||
let _ = fired(&frames);
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(DELAY + 0.2);
|
||||
up(&mut frames, Key::X);
|
||||
assert_eq!(fired(&frames), [pressed(TAP)], "the next press waits the new delay");
|
||||
}
|
||||
|
||||
/// With holds off the hold binding is ignored and the single binding fires on the press.
|
||||
#[trial]
|
||||
fn holds_off_fire_on_the_press() {
|
||||
let mut frames = started(input(None));
|
||||
down(&mut frames, Key::X);
|
||||
assert_eq!(fired(&frames), [pressed(TAP)], "no wait: the press fires");
|
||||
frames.advance(DELAY + 0.2);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty());
|
||||
}
|
||||
|
||||
/// Turning holds off while a wait runs ends it without firing, and builds the keymap once.
|
||||
#[trial]
|
||||
fn turning_holds_off_ends_a_running_wait() {
|
||||
let mut frames = started(input(Some(DELAY)));
|
||||
down(&mut frames, Key::X);
|
||||
let before = keymap_builds();
|
||||
frames.commands(input(None));
|
||||
frames.advance(DELAY + 0.2);
|
||||
frames.frame(vec![], show);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "no tap and no hold");
|
||||
assert_eq!(keymap_builds() - before, 1, "the keymap is rebuilt once");
|
||||
}
|
||||
|
||||
/// A gate that refuses the commands of the key leaves the output empty, as for a plain press.
|
||||
#[trial]
|
||||
fn a_wait_on_a_key_whose_command_a_gate_refuses_fires_nothing() {
|
||||
let gate = CommandGate::new(true, |refuses: &bool, command: &CommandRef| !*refuses || ![TAP, HOLD].contains(&command.id.as_str()));
|
||||
let mut frames = started(input(Some(DELAY)).gate(gate));
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(DELAY + 0.2);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "the refused hold fires nothing");
|
||||
down(&mut frames, Key::X);
|
||||
frames.advance(0.1);
|
||||
up(&mut frames, Key::X);
|
||||
assert!(fired(&frames).is_empty(), "the refused tap fires nothing");
|
||||
}
|
||||
@@ -3,5 +3,6 @@
|
||||
mod app_catalog;
|
||||
mod app_scope;
|
||||
mod board;
|
||||
mod hold;
|
||||
mod kit;
|
||||
mod resolve;
|
||||
Reference in new issue
Block a user