mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
fwstub-1: a key press passes over a binding whose command is disabled where it lands (Keymap::lookup_where, Matcher::press_where; the key stage accepts enabled commands only), so the next binding of the chord runs; an app catalog replaces or drops a linked set's default chords (AppCatalog::replace_defaults) and sets the typing rule (AppCatalog::typing_rule); a bound Alt chord's withdrawn text is no text field's typing, so the field no longer holds the press (route::begin); trials
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
db60832d36
commit
eef70c8388
9 files changed
+304
-25
No files matched your search
@@ -376,6 +376,12 @@ impl Keymap {
|
||||
|
||||
/// [`lookup`](Self::lookup) with the panels around the focused one in `outer` ([`Scopes::rank_nested`]).
|
||||
pub fn lookup_nested(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str]) -> Lookup {
|
||||
self.lookup_where(chord, double, active, outer, &|_| true)
|
||||
}
|
||||
|
||||
/// [`lookup_nested`](Self::lookup_nested) among the commands `accept` takes: the bindings of a command it refuses
|
||||
/// (one disabled where the press lands) are passed over, so the chord's next binding, in an outer scope, runs.
|
||||
pub fn lookup_where(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str], accept: &dyn Fn(&CommandRef) -> bool) -> Lookup {
|
||||
let want = Trigger { chord: chord.effective(self.platform), double };
|
||||
let held = active.typing && !self.typing.fires(&want.chord, self.platform);
|
||||
let Some(holders) = self.by_trigger.get(&want) else { return Lookup::None };
|
||||
@@ -383,6 +389,9 @@ impl Keymap {
|
||||
let mut ranks: Vec<(usize, u8)> = Vec::new();
|
||||
for &(i, k) in holders {
|
||||
let Some(r) = self.at(i, k).and_then(|(_, s)| self.scopes.rank_nested(s, active, outer)) else { continue };
|
||||
if !accept(&self.catalog[i].command) {
|
||||
continue;
|
||||
}
|
||||
// The typing rule holds back everything except bindings of an active context (rank 0).
|
||||
if held && r != 0 {
|
||||
continue;
|
||||
|
||||
@@ -79,28 +79,46 @@ impl Matcher {
|
||||
|
||||
/// The command `press` runs, with `layout` reading the key.
|
||||
pub fn press(&mut self, layout: &Layout, keymap: &Keymap, press: &Press<'_>) -> Option<Hit> {
|
||||
self.press_where(layout, keymap, press, &|_| true)
|
||||
}
|
||||
|
||||
/// [`press`](Self::press) among the commands `accept` takes ([`Keymap::lookup_where`]): a binding of a refused
|
||||
/// command (one disabled where the press lands) is passed over, and the press matches the next binding, in an outer
|
||||
/// scope or of its next chord candidate, as if the refused one were not bound.
|
||||
pub fn press_where(&mut self, layout: &Layout, keymap: &Keymap, press: &Press<'_>, accept: &dyn Fn(&CommandRef) -> bool) -> Option<Hit> {
|
||||
let Press { input, repeat, now, active, outer } = *press;
|
||||
let chords = Chords::of(layout, input)?;
|
||||
let m = Match { keymap, active, outer, accept };
|
||||
if repeat {
|
||||
return chords.single(keymap, active, outer);
|
||||
return chords.single(&m);
|
||||
}
|
||||
let first = chords.first();
|
||||
let again = self
|
||||
.last
|
||||
.as_ref()
|
||||
.is_some_and(|l| l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS);
|
||||
let double = if again { chords.find(keymap, true, active, outer) } else { None };
|
||||
let double = if again { chords.find(&m, true) } else { None };
|
||||
self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some(), panel: active.panel.map(str::to_owned) });
|
||||
double.or_else(|| chords.single(keymap, active, outer))
|
||||
double.or_else(|| chords.single(&m))
|
||||
}
|
||||
|
||||
/// The command a press of `input` runs on its own, as [`press`](Self::press) matches a press that completes no
|
||||
/// double press: for a key that is held down rather than pressed now (a key automation holds). Keeps no state.
|
||||
pub fn single(layout: &Layout, keymap: &Keymap, input: &KeyInput, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
|
||||
Chords::of(layout, input)?.single(keymap, active, outer)
|
||||
Chords::of(layout, input)?.single(&Match { keymap, active, outer, accept: &|_| true })
|
||||
}
|
||||
}
|
||||
|
||||
/// What one press is matched against: the keymap, what has the keyboard, the panels around it, and the commands the
|
||||
/// press may run.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Match<'a> {
|
||||
keymap: &'a Keymap,
|
||||
active: &'a Active<'a>,
|
||||
outer: &'a [&'a str],
|
||||
accept: &'a dyn Fn(&CommandRef) -> bool,
|
||||
}
|
||||
|
||||
/// The chords one press can run, most specific first: the layout's candidates, then Delete and Backspace standing
|
||||
/// for each other.
|
||||
struct Chords(Vec<Chord>);
|
||||
@@ -128,27 +146,28 @@ impl Chords {
|
||||
}
|
||||
|
||||
/// The first chord with a binding, pressed twice when `double`.
|
||||
fn find(&self, keymap: &Keymap, double: bool, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
|
||||
fn find(&self, m: &Match<'_>, double: bool) -> Option<Hit> {
|
||||
let first = self.first();
|
||||
self.0
|
||||
.iter()
|
||||
.find_map(|&chord| Hit::from_lookup(keymap.lookup_nested(&chord, double, active, outer), Trigger { chord, double }, chord == first))
|
||||
self.0.iter().find_map(|&chord| {
|
||||
Hit::from_lookup(m.keymap.lookup_where(&chord, double, m.active, m.outer, m.accept), Trigger { chord, double }, chord == first)
|
||||
})
|
||||
}
|
||||
|
||||
/// The single press's binding, else its Alt variant.
|
||||
fn single(&self, keymap: &Keymap, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
|
||||
self.find(keymap, false, active, outer).or_else(|| self.alt_variant(keymap, active, outer))
|
||||
fn single(&self, m: &Match<'_>) -> Option<Hit> {
|
||||
self.find(m, false).or_else(|| self.alt_variant(m))
|
||||
}
|
||||
|
||||
/// Only when no binding owns the Alt chord itself, so a bound Alt chord runs its own command.
|
||||
fn alt_variant(&self, keymap: &Keymap, active: &Active<'_>, outer: &[&str]) -> Option<Hit> {
|
||||
fn alt_variant(&self, m: &Match<'_>) -> Option<Hit> {
|
||||
let Match { keymap, active, outer, accept } = *m;
|
||||
let (first, platform) = (self.first(), keymap.platform());
|
||||
self.0.iter().filter(|c| c.mods.alt).find_map(|&chord| {
|
||||
if active.typing && !keymap.typing_rule().fires(&chord, platform) {
|
||||
return None;
|
||||
}
|
||||
let plain = Chord::new(Mods { alt: false, ..chord.mods }, chord.key);
|
||||
match keymap.lookup_nested(&plain, false, &Active { typing: false, ..*active }, outer) {
|
||||
match keymap.lookup_where(&plain, false, &Active { typing: false, ..*active }, outer, accept) {
|
||||
Lookup::Run(command) if keymap.bindable(&command).is_some_and(|b| b.has_alt_variant) => {
|
||||
Some(Hit { command, cycle: Vec::new(), trigger: Trigger { chord, double: false }, exact: chord == first, alt_variant: true })
|
||||
}
|
||||
|
||||
@@ -195,3 +195,25 @@ fn the_alt_variant_follows_the_commands_key_and_yields_to_a_bound_alt_chord() {
|
||||
let km = Keymap::new(vec![app("layer.new.layer", &["F2"])], Scopes::new(), Platform::Mac);
|
||||
assert!(hit(&km, &alt(Key::F2, false, false)).is_none(), "a command that did not opt in has no Alt variant");
|
||||
}
|
||||
|
||||
/// A press passes over the binding of a command the caller refuses (one disabled where it lands): the chord's binding
|
||||
/// in an outer scope runs instead, the lookup says the same, and with every holder refused the press runs nothing.
|
||||
#[test]
|
||||
fn a_refused_command_leaves_its_chord_to_the_next_binding() {
|
||||
let km = Keymap::new(
|
||||
vec![in_scope("view.zoomIn", "Canvas", &["Cmd+="]), app("format.subscript", &["Cmd+="])],
|
||||
Scopes::new().with_panel("Canvas"),
|
||||
Platform::Linux,
|
||||
);
|
||||
let input = KeyInput::new(Mods { cmd: true, ctrl: false, alt: false, shift: false }).with_physical(Key::Equals);
|
||||
let active = Active::panel("Canvas");
|
||||
let press = Press { input: &input, repeat: false, now: 0.0, active: &active, outer: &[] };
|
||||
let hit = |accept: &dyn Fn(&CommandRef) -> bool| Matcher::new().press_where(&Layout::new(), &km, &press, accept).map(|hit| hit.command);
|
||||
assert_eq!(hit(&|_| true), Some(cmd("view.zoomIn")), "the canvas's binding ranks first");
|
||||
assert_eq!(hit(&|c| c.id != "view.zoomIn"), Some(cmd("format.subscript")), "refused, it leaves the chord to the app's binding");
|
||||
assert_eq!(hit(&|_| false), None, "with every holder refused the press runs nothing");
|
||||
let refused = |c: &CommandRef| c.id != "view.zoomIn";
|
||||
assert_eq!(km.lookup_where(&chord("Cmd+="), false, &active, &[], &refused), Lookup::Run(cmd("format.subscript")));
|
||||
let all = Matcher::new().press(&Layout::new(), &km, &press).map(|hit| hit.command);
|
||||
assert_eq!(all, Some(cmd("view.zoomIn")), "a plain press accepts every command");
|
||||
}
|
||||
@@ -14,7 +14,7 @@ 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,
|
||||
Trigger, TypingRule,
|
||||
};
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -442,13 +442,15 @@ 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> {
|
||||
/// With a matcher, a binding of a command `accept` refuses (disabled where the press lands) is passed over for the
|
||||
/// press's next binding.
|
||||
fn press(&self, layout: &Layout, input: &KeyInput, typing: bool, matcher: Option<(&mut Matcher, f64, &dyn Fn(&CommandRef) -> bool)>) -> Option<Hit> {
|
||||
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 }),
|
||||
Some((matcher, now, accept)) => matcher.press_where(layout, &self.keymap, &Press { input, repeat: false, now, active: &active, outer }, accept),
|
||||
None => Matcher::single(layout, &self.keymap, input, &active, outer),
|
||||
}
|
||||
}
|
||||
@@ -474,9 +476,12 @@ struct BuiltKeymap {
|
||||
window_shortcuts: Arc<[(WindowShortcut, Chord)]>,
|
||||
}
|
||||
|
||||
/// The keymap of `defs` on `platform` under `overrides`.
|
||||
fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, overrides: Option<&Arc<Overrides>>) -> Keymap {
|
||||
/// The keymap of `defs` on `platform` under `overrides`, with the app's typing rule when it set one.
|
||||
fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, overrides: Option<&Arc<Overrides>>, typing: Option<TypingRule>) -> Keymap {
|
||||
let mut keymap = Keymap::new(defs, scopes, platform);
|
||||
if let Some(rule) = typing {
|
||||
keymap = keymap.with_typing_rule(rule);
|
||||
}
|
||||
if let Some(overrides) = overrides {
|
||||
keymap.set_overrides((**overrides).clone());
|
||||
}
|
||||
@@ -522,6 +527,12 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
let joined = |defs: &[CommandDef]| -> Vec<CommandDef> { defs.iter().chain(&app_defs).cloned().collect() };
|
||||
let mut defs = registry.defs_for(platform);
|
||||
if let Some(app) = app {
|
||||
// The app's defaults for a linked set's command replace the set's, before the app's alternate keys join them.
|
||||
for def in &mut defs {
|
||||
if let Some(bindings) = app.replaced_defaults(&def.command.id) {
|
||||
def.defaults = bindings.to_vec();
|
||||
}
|
||||
}
|
||||
for extra in app.defs() {
|
||||
if let Some(def) = defs.iter_mut().find(|def| def.command == extra.command) {
|
||||
for binding in &extra.defaults {
|
||||
@@ -532,7 +543,8 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keymap = keymap_of(joined(defs.as_slice()), scopes.clone(), platform, overrides);
|
||||
let typing = app.and_then(AppCatalog::typing);
|
||||
let mut keymap = keymap_of(joined(defs.as_slice()), scopes.clone(), platform, overrides, typing);
|
||||
let overridden = |def: &CommandDef| overrides.is_some_and(|overrides| overrides.get(&def.command.id).is_some());
|
||||
let yielded: Vec<(CommandRef, Trigger)> = defs
|
||||
.iter()
|
||||
@@ -546,7 +558,7 @@ 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, typing);
|
||||
}
|
||||
let window_shortcuts = registry
|
||||
.defs()
|
||||
@@ -1267,8 +1279,15 @@ pub(crate) fn begin(ctx: &Context) {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let Some(hit) = keys.press(&shortcuts.layout, &shortcut.input, shortcuts.typing && !shortcut.canvas, Some((&mut matcher, time)))
|
||||
else {
|
||||
// A binding whose command is disabled where the press lands (a window command with no floating
|
||||
// window, a canvas's view command it does not offer) is passed over: the press runs the next binding
|
||||
// of its chord, in an outer scope, or of its next chord candidate, as if the disabled one were unbound.
|
||||
let enabled = |command: &CommandRef| {
|
||||
let (_, instance) = with(ctx, |board| board.target_of(ctx, command, &board.here));
|
||||
resolve_in(ctx, command, instance, Reach::Focus, None).0.enabled
|
||||
};
|
||||
let typing = shortcuts.typing && !shortcut.canvas;
|
||||
let Some(hit) = keys.press(&shortcuts.layout, &shortcut.input, typing, Some((&mut matcher, time, &enabled))) else {
|
||||
continue;
|
||||
};
|
||||
let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here));
|
||||
|
||||
@@ -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, TypingRule};
|
||||
pub use library::ChromeCommand;
|
||||
pub(crate) use library::WindowShortcut;
|
||||
pub use library::{EditCommands, NavCommand, WindowCommand};
|
||||
@@ -50,6 +50,10 @@ pub struct AppCatalog {
|
||||
defs: Arc<[CommandDef]>,
|
||||
index: Arc<HashMap<String, usize>>,
|
||||
generation: u64,
|
||||
/// The default chords the app gives a linked set's command in place of the set's own (`replace_defaults`).
|
||||
replaced: Arc<[(String, Vec<Binding>)]>,
|
||||
/// Which chords fire while a text component has the keyboard (`typing_rule`); `None` keeps the keymap's default.
|
||||
typing: Option<TypingRule>,
|
||||
}
|
||||
|
||||
impl AppCatalog {
|
||||
@@ -63,7 +67,41 @@ impl AppCatalog {
|
||||
}
|
||||
registry::index_id(&mut index, &def.command.id, at)?;
|
||||
}
|
||||
Ok(AppCatalog { defs: defs.into(), index: Arc::new(index), generation })
|
||||
Ok(AppCatalog { defs: defs.into(), index: Arc::new(index), generation, replaced: Arc::from([]), typing: None })
|
||||
}
|
||||
|
||||
/// Gives the linked set's command `id` the default chords `bindings` in place of the set's own; an empty list drops
|
||||
/// them. A component's chord that the app means for its own command (a canvas's `Ctrl+=` zoom where Word's
|
||||
/// `Ctrl+=` is Subscript) is dropped here, so the app's binding takes the key. They are defaults: the user's
|
||||
/// overrides still replace them, and resetting a command returns to them. A later call for the same id replaces
|
||||
/// the earlier one. An id no linked set defines is ignored; an app command's defaults are its def's.
|
||||
#[must_use]
|
||||
pub fn replace_defaults(mut self, id: impl Into<String>, bindings: Vec<Binding>) -> Self {
|
||||
let id = id.into();
|
||||
let mut replaced: Vec<(String, Vec<Binding>)> = self.replaced.iter().filter(|(at, _)| *at != id).cloned().collect();
|
||||
replaced.push((id, bindings));
|
||||
self.replaced = replaced.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets which chords fire while a text component has the keyboard. The keymap's default,
|
||||
/// [`TypingRule::CommandKeysOnly`], leaves Alt chords to the text; an app whose document editor fires Alt+letter
|
||||
/// commands while the person types (a word processor's Alt+Q) gives [`TypingRule::PlainKeysWait`]. It holds for
|
||||
/// every text component of the app's windows; a binding in an active context still always works.
|
||||
#[must_use]
|
||||
pub fn typing_rule(mut self, rule: TypingRule) -> Self {
|
||||
self.typing = Some(rule);
|
||||
self
|
||||
}
|
||||
|
||||
/// The default chords the app gives the linked set's command `id`, when it replaced them.
|
||||
pub(crate) fn replaced_defaults(&self, id: &str) -> Option<&[Binding]> {
|
||||
self.replaced.iter().find(|(at, _)| at == id).map(|(_, bindings)| bindings.as_slice())
|
||||
}
|
||||
|
||||
/// The typing rule the app set.
|
||||
pub(crate) fn typing(&self) -> Option<TypingRule> {
|
||||
self.typing
|
||||
}
|
||||
|
||||
/// The app's version of the catalog. The board rebuilds the keymap when it differs from the last frame's, and never
|
||||
|
||||
@@ -68,8 +68,10 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
|
||||
// own widget; any other taker reads the text as an intent only, and the text leaves egui's input.
|
||||
let reads_egui = rec.stop.host || rec.stop.keys.owner == OwnerClass::Text;
|
||||
for (at, (typed, taken)) in batch.texts.iter().zip(&mut taken_texts).enumerate() {
|
||||
// A claimed text (a claim's, or an Alt shortcut's that the keymap binds) is withdrawn and is no component's
|
||||
// typing: its press is not the focused stop's to hold, so the shortcut it comes with still reaches the
|
||||
// key stage from a text field or a list, as Alt+F7 or Alt+Q does from a word processor's page.
|
||||
if typed.claimed {
|
||||
*taken = true;
|
||||
continue;
|
||||
}
|
||||
let route = text_route(rec, driven, &typed.text);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Trials of the keys and presses a host's own egui widgets keep while the runtime is installed on the whole window.
|
||||
|
||||
use crate::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _};
|
||||
use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, Scope};
|
||||
use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, Scope, TypingRule};
|
||||
use crate::runtime::drag::{self, DragPreview};
|
||||
use crate::runtime::egui::{areas, fixture};
|
||||
use crate::runtime::env::RootEnv;
|
||||
@@ -670,3 +670,51 @@ fn a_window_shortcut_runs_from_a_pane_title_and_not_from_a_modal_dialog_or_a_tex
|
||||
focus_stop(&mut frames, &mut show, title);
|
||||
assert_eq!(fired(&mut frames, &mut show), replace, "with the dialog closed the title runs it again");
|
||||
}
|
||||
|
||||
/// The app command the typing-rule trial presses: Alt+Q, as a word processor's search.
|
||||
const SEARCH: &str = "hostKeyTrial.search";
|
||||
|
||||
/// The ids of the commands an Alt+`key` press, bound to `SEARCH`, fired while a text stop has the keyboard, with the
|
||||
/// text the platform sends with it, under the app catalog's typing rule `rule` (`None`: the keymap's default).
|
||||
fn alt_while_typing(key: Key, rule: Option<TypingRule>) -> Vec<String> {
|
||||
let field = named_id("document");
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
widget(ui, field);
|
||||
register_stop(ui.ctx(), Stop::new(field, KeyUse::of(Input::Text)));
|
||||
};
|
||||
let Ok(binding) = Binding::parse(&format!("Alt+{}", key.name())) else { return vec!["the trial's chord does not parse".to_owned()] };
|
||||
let Ok(catalog) = AppCatalog::new(vec![CommandDef::new(SEARCH, "Search", Scope::app()).with_default(binding)], 1) else {
|
||||
return vec!["the trial's catalog is refused".to_owned()];
|
||||
};
|
||||
let catalog = match rule {
|
||||
Some(rule) => catalog.typing_rule(rule),
|
||||
None => catalog,
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.commands(CommandInput::new().catalog(catalog));
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
focus_stop(&mut frames, &mut show, field);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(field), "the text stop has the keyboard");
|
||||
take_output(&frames.ctx);
|
||||
frames.frame(vec![key_press(key, Modifiers::ALT), Event::Text("x".into())], &mut show);
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect()
|
||||
}
|
||||
|
||||
/// An app sets the typing rule through its catalog: by default an Alt+letter chord waits while a text component has
|
||||
/// the keyboard (Option types characters on the Mac), and under `PlainKeysWait` it fires from there, as Word's Alt+Q
|
||||
/// opens search from the page, though the platform sends the key's text with it.
|
||||
#[trial]
|
||||
fn the_app_catalog_s_typing_rule_lets_an_alt_chord_fire_while_typing() {
|
||||
assert_eq!(alt_while_typing(Key::Q, None), Vec::<String>::new(), "by default the Alt chord stays with the text");
|
||||
assert_eq!(alt_while_typing(Key::Q, Some(TypingRule::CommandKeysOnly)), Vec::<String>::new(), "so it does under the default rule named");
|
||||
assert_eq!(alt_while_typing(Key::Q, Some(TypingRule::PlainKeysWait)), vec![SEARCH.to_owned()], "under PlainKeysWait it fires");
|
||||
}
|
||||
|
||||
/// The text a platform sends with a bound Alt chord is withdrawn and is not the text field's typing, so the field does
|
||||
/// not hold the press: an Alt+function-key chord, which fires while typing under every rule but `AllWait`, runs its
|
||||
/// command from a text field (Word's Alt+F7, next misspelling, from the page).
|
||||
#[trial]
|
||||
fn a_bound_alt_chord_s_text_leaves_the_press_to_its_command() {
|
||||
assert_eq!(alt_while_typing(Key::F7, None), vec![SEARCH.to_owned()], "Alt+F7 fires from the text field");
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! A key press passes over a binding whose command is disabled where the press lands, and an app's catalog replaces
|
||||
//! or drops a linked set's default chords: in both cases the app's own binding of the chord runs. The case is a
|
||||
//! word processor's Alt+F7 (next misspelling) against the framework's `window.move` default, pressed inside a
|
||||
//! floating window.
|
||||
|
||||
use craft_behavior::{GesturePhase, Sense};
|
||||
use craft_ui::contract::overlay::{PlacementChange, PlacementKind};
|
||||
use craft_ui::contract::{
|
||||
BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet, CommandState, Commands as _, Scope, WindowCommand};
|
||||
use craft_ui::runtime::focus::{FocusTarget, request};
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::layout::allocate;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Response, Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// The app's command on Alt+F7.
|
||||
const SPELLING: &str = "chordTrial.spelling";
|
||||
const HEADER: Vec2 = Vec2::new(100.0, 24.0);
|
||||
const BODY: Vec2 = Vec2::new(120.0, 60.0);
|
||||
const START: Rect = Rect { min: Pos2::new(60.0, 70.0), max: Pos2::new(280.0, 210.0) };
|
||||
|
||||
/// A floating window that can say its Move command is disabled, and logs the placement changes it is given.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(container)]
|
||||
struct Floating<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
move_disabled: bool,
|
||||
log: &'a RefCell<Vec<PlacementChange>>,
|
||||
}
|
||||
|
||||
impl Component for Floating<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = PlainStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: FloatingStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for Floating<'_> {
|
||||
fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
|
||||
allocate(ui, HEADER);
|
||||
if self.move_disabled {
|
||||
cx.publish(WindowCommand::Move, CommandState::new().enabled(false));
|
||||
}
|
||||
}
|
||||
|
||||
fn placement_changed(&mut self, change: &PlacementChange) {
|
||||
self.log.borrow_mut().push(*change);
|
||||
}
|
||||
}
|
||||
|
||||
/// What Alt+F7 does with the focus inside a floating window, whose Move is disabled with `move_disabled`, under an app
|
||||
/// catalog binding it to `SPELLING` that drops `window.move`'s defaults with `dropped`: the commands it fired into
|
||||
/// the output, and whether a keyboard move began.
|
||||
fn alt_f7(move_disabled: bool, dropped: bool) -> (Vec<String>, bool) {
|
||||
let Ok(binding) = Binding::parse("Alt+F7") else { return (vec!["the trial's chord does not parse".to_owned()], false) };
|
||||
let Ok(catalog) = AppCatalog::new(vec![CommandDef::new(SPELLING, "Spelling", Scope::app()).with_default(binding)], 1) else {
|
||||
return (vec!["the trial's catalog is refused".to_owned()], false);
|
||||
};
|
||||
let catalog = if dropped { catalog.replace_defaults(WindowCommand::Move.id(), Vec::new()) } else { catalog };
|
||||
let (log, seen) = (RefCell::new(Vec::new()), RefCell::new(Seen::default()));
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let props = ContainerProps::new()
|
||||
.mount(Mount::Layer(Overlay::floating().movable(true).placed(START)))
|
||||
.sizing(Sizing::Content)
|
||||
.header(HeaderRegion::new().band(DragBand::Move))
|
||||
.command_scope(<WindowCommand as CommandSet>::SCOPE);
|
||||
Floating { common: Common::new(), props, move_disabled, log: &log }.id_salt("floating").show(ui, |ui, _| {
|
||||
Probe::new(&seen).size(BODY).sense(Sense::CLICK | Sense::FOCUS).show(ui);
|
||||
});
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.commands(CommandInput::new().catalog(catalog));
|
||||
frames.idle(4, &mut show);
|
||||
// The focus goes into the window, where its commands are.
|
||||
let Some(inside) = seen.borrow().id else { return (vec!["the window's body never showed".to_owned()], false) };
|
||||
request(&frames.ctx, FocusTarget::Id(inside));
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(frames.ctx.memory(|memory| memory.focused()), Some(inside), "the window's body has the focus");
|
||||
take_output(&frames.ctx);
|
||||
log.borrow_mut().clear();
|
||||
frames.frame(vec![key_press(Key::F7, Modifiers::ALT)], &mut show);
|
||||
frames.idle(2, &mut show);
|
||||
let fired = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect();
|
||||
let began = log.borrow().iter().any(|change| change.kind == PlacementKind::Keyboard && change.phase == GesturePhase::Begin);
|
||||
(fired, began)
|
||||
}
|
||||
|
||||
/// By default Alt+F7 inside a floating window is its Move (16.3), ahead of the app's binding.
|
||||
#[trial]
|
||||
fn alt_f7_in_a_floating_window_moves_it_by_default() {
|
||||
assert_eq!(alt_f7(false, false), (Vec::new(), true), "the window's Move takes Alt+F7");
|
||||
}
|
||||
|
||||
/// A disabled Move leaves its chord to the next binding: the app's command runs, where the press used to be dropped.
|
||||
#[trial]
|
||||
fn a_disabled_binding_leaves_its_chord_to_the_next_one() {
|
||||
assert_eq!(alt_f7(true, false), (vec![SPELLING.to_owned()], false), "the disabled Move passes Alt+F7 to the app's command");
|
||||
}
|
||||
|
||||
/// An app that drops `window.move`'s default chords through its catalog gets Alt+F7 for its own command, even where
|
||||
/// Move is enabled.
|
||||
#[trial]
|
||||
fn an_app_catalog_drops_a_linked_set_s_default_chord() {
|
||||
assert_eq!(alt_f7(false, true), (vec![SPELLING.to_owned()], false), "with Move's defaults dropped, Alt+F7 is the app's");
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod alt_code;
|
||||
mod chord_fallthrough;
|
||||
// `clipboard.rs` is platform-w3's trial (F-28); this file is shell-w1's, so its line is written here.
|
||||
mod clipboard;
|
||||
mod control_click;
|
||||
|
||||
Reference in new issue
Block a user