Framework batch 3 a: port follow-ups (see runs/fwb3-a.md)

This commit is contained in:
Dylan M. Taylor
2026-11-19 15:48:27 -05:00
parent 019f0bc634
commit ebc242fe36
19 changed files with 416 additions and 50 deletions
+88 -2
View File
@@ -9,9 +9,15 @@ use craft_behavior::CanvasView;
use craft_behavior::kurbo::Point;
use craft_text::quotes::QuoteStyle;
use craft_text::ui::editor::{CaretLine, EditKind, EditorEnd, EditorMode, HostCx, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection};
use craft_ui::canvas::Canvas;
use craft_ui::contract::{Bind, FacesCx as _, Show as _, ShowContainer as _};
use craft_behavior::CancelReason;
use craft_ui::buttons::Button;
use craft_ui::canvas::{Canvas, CanvasTool, ToolAction, ToolContext, ToolHost, ToolKey, ToolPath, ToolPointer, tool_pass};
use craft_ui::contract::{Bind, FacesCx as _, Props as _, Show as _, ShowContainer as _};
use craft_ui::fonts::{FaceBytes, FaceState};
use craft_ui::primitives::Draw;
use craft_ui::runtime::focus::FocusRequest;
use craft_ui::testing::focus::key_release;
use craft_ui::testing::input::key_press;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Event, FontId, ImeEvent, Key, Modifiers, Rect, pos2, vec2};
@@ -450,3 +456,83 @@ fn the_host_lays_its_text_out_in_a_document_face_it_asks_the_editor_for() {
let font = FontId::new(14.0, face.family());
assert!(editor.fixture.ctx().fonts_mut(|fonts| fonts.has_glyph(&font, 'a')), "the face's family lays the text out");
}
/// A tool whose click opens a box (`opened`), and that counts the Escapes the canvas offers it as `Cancel`.
struct Leaver {
opened: Rc<Cell<bool>>,
cancels: usize,
}
impl CanvasTool for Leaver {
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
ToolAction::Claimed
}
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {
self.opened.set(true);
}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
if *key != ToolKey::Cancel {
return false;
}
self.cancels += 1;
true
}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
fn command_form(&self) -> ToolPath {
ToolPath::Command("the leaver's form")
}
}
/// A box a tool's click opens in the canvas body, its editor focused as it opens (a typed-text box): the first Escape
/// cancels the editor, which closes, and the next reaches the tool as `Cancel` (it leaves for Select). Each Escape
/// comes up in the frame it went down in.
#[trial]
fn after_escape_closes_a_focused_editor_in_the_canvas_body_the_next_escape_reaches_the_tool() {
let opened = Rc::new(Cell::new(false));
let open = Rc::new(Cell::new(false));
let tool = Rc::new(RefCell::new(Leaver { opened: Rc::clone(&opened), cancels: 0 }));
let (asked, shown, shown_tool) = (Rc::clone(&opened), Rc::clone(&open), Rc::clone(&tool));
let (mut host, mut selection) = (Host::default(), TextSelection::caret_at(0));
let mut fixture = Fixture::new(move |ui| {
let room = Rect::from_min_size(ui.max_rect().min, vec2(400.0, 300.0));
ui.scope_builder(egui::UiBuilder::new().max_rect(room), |ui| {
Canvas::new("Document").show(ui, |ui, body| {
// The box opens in the pass after the click, focused as it first shows.
let fresh = asked.take();
if fresh {
shown.set(true);
}
if shown.get() {
let rect = Rect::from_min_size(body.rect.min + vec2(20.0, 20.0), vec2(120.0, 20.0));
let editor = TextEditor::new("Text to place", &mut host, Bind::bound(&mut selection)).esc_commits(false);
let editor = if fresh { editor.request_focus(FocusRequest::Take) } else { editor };
if editor.show_at(ui, rect).ended == Some(EditorEnd::Cancel) {
shown.set(false);
}
}
if let Some(pass) = tool_pass(&body.env) {
let _ = ToolHost::new().run(ui, &pass, &mut *shown_tool.borrow_mut());
}
});
});
// A control after the canvas in the window's Tab order: the stop after the editor.
let _ = Button::new("After").show(ui);
});
let escape = || vec![key_press(Key::Escape, Modifiers::NONE), key_release(Key::Escape, Modifiers::NONE)];
fixture.settle();
fixture.click_at(pos2(200.0, 200.0)).settle();
assert!(open.get(), "the click opened the box");
fixture.frame(escape()).settle();
assert!(!open.get(), "the first Escape cancels the editor");
assert_eq!(tool.borrow().cancels, 0, "the editor's Escape is not the tool's");
fixture.frame(escape()).settle();
assert_eq!(tool.borrow().cancels, 1, "the next Escape reaches the tool");
}
@@ -18,6 +18,8 @@ use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAccess, ToolAction, ToolClai
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::popover::Popover;
use craft_ui::primitives::Draw;
use craft_ui::runtime::commands::{self, EditCommands, FireSource};
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::access::Declared;
use craft_ui::testing::focus::{AccessActionKind, key_release};
use craft_ui::testing::input::key_press;
@@ -96,6 +98,26 @@ fn a_tool_whose_release_opens_an_outline_takes_alt_backspace_in_the_next_frame()
assert_eq!(canvas.tool().seen, [Seen::Delete { forward: false }], "the outline the release opened takes Alt+Backspace");
}
/// Edit ▸ Delete from a menu or the palette, while the focused canvas's tool claims Delete, reaches the tool as that
/// key, as the key does, and runs no app command; a tool that claims no delete gets none.
#[trial]
fn a_fired_command_whose_key_the_tool_claims_reaches_the_tool_as_that_key() {
let mut canvas = ToolFixture::new("Document", Outline::new(true));
canvas.fixture().settle();
canvas.fixture().key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(canvas.fixture().focused(), Some(canvas.canvas_id()), "Tab focuses the canvas");
take_output(canvas.fixture().ctx());
commands::fire(canvas.fixture().ctx(), EditCommands::Delete, FireSource::Menu);
canvas.fixture().settle();
assert_eq!(canvas.tool().seen, [Seen::Delete { forward: true }], "the tool took Edit ▸ Delete as its Delete");
assert!(take_output(canvas.fixture().ctx()).fired.is_empty(), "no app command ran");
canvas.tool_mut().keeps = false;
canvas.fixture().settle();
commands::fire(canvas.fixture().ctx(), EditCommands::Delete, FireSource::Menu);
canvas.fixture().settle();
assert_eq!(canvas.tool().seen.len(), 1, "a tool that claims no delete gets none");
}
/// A tool that takes every key the host offers it.
#[derive(Default)]
struct Taker {
+1
View File
@@ -747,6 +747,7 @@ fn stops_step(at: StopsStep<'_>, e: &mut dyn ErasedPass<'_>, facts: &TypeFacts,
parts,
group: steps::member_group(ctx, env.roving, id),
body: env.roving,
arena: env.arena.map(|arena| arena.0).filter(|arena| *arena != id),
row: env.row,
item: env.item == Some(id),
default_stop: resolved.default_stop,
@@ -31,6 +31,8 @@ pub(crate) struct StopsIn<'a> {
pub group: Option<Id>,
/// The roving group of the innermost body this component is shown in, whether or not it joined it.
pub body: Option<Id>,
/// The arena root this component is shown in, whether or not it joined the arena.
pub arena: Option<Id>,
/// The roving group of the collection row the component is shown in: stops with no group of their own join it.
pub row: Option<Id>,
/// The component is the collection item of its row: its parts join the row's group instead of a group of their own.
@@ -93,7 +95,7 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec<Stop> {
focus::register_group(ctx, if let Some(arrival) = arrival { group.selected(arrival) } else { group });
}
let own = || {
let stop = Stop::new(input.id, input.keys).root(input.holder).role(input.role).in_body(input.body);
let stop = Stop::new(input.id, input.keys).root(input.holder).role(input.role).in_body(input.body).in_arena(input.arena);
let stop = if input.default_stop { stop.default_stop() } else { stop };
let stop = if input.press_only { stop.press_only() } else { stop };
if input.text { stop.text() } else { stop }
@@ -956,8 +956,16 @@ fn queue(ctx: &Context, fired: Fired) {
observed.push(fired.command.clone());
}
});
// An edit command goes to the focused component that lists it; otherwise it goes to the instance that declared
// it or, with none, stays an app command.
// A command whose key the focused component claims reaches it as that key, as the key's press does; an edit command
// goes to the focused component that lists it; otherwise it goes to the instance that declared it or, with none,
// stays an app command.
if fired.phase != FirePhase::Release {
let chords: Vec<Chord> =
bindings(ctx, &fired.command).into_iter().filter(|binding| !binding.trigger.double).map(|binding| binding.trigger.chord).collect();
if keys::fire_claimed(ctx, &chords) {
return;
}
}
if fired.phase != FirePhase::Release
&& let Some(edit) = with(ctx, |board| board.registry.edit_of(&fired.command.id))
&& keys::queue_edit(ctx, edit)
@@ -970,11 +978,23 @@ fn queue(ctx: &Context, fired: Fired) {
}
/// An undo or redo a text part or editor had nothing to do for goes to the instance that declares the command or,
/// with none, to the app command of the same id (11.3).
/// with none, to the app command of the same id (11.3), when it is enabled there as its key would be: the gate and the
/// modal rule hold, so an undo in a dialog's field never undoes the document under the dialog.
pub(crate) fn fall_through(ctx: &Context, command: craft_behavior::EditCommand) {
let Some(command) = EditCommands::of(command) else { return };
let command = CommandRef::from(command);
let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here).0.instance);
// The focused component already declined the command: it answers for it no more.
let from = with(ctx, |board| Vantage { edits: Some(EditSet::NONE), inactive: Some(EditSet::NONE), ..board.here.clone() });
let (app, instance) = with(ctx, |board| board.target_of(ctx, &command, &from));
if !app && instance.is_none() {
return;
}
let (resolved, _) = resolve_in(ctx, &command, instance, Reach::Focus, Some(&from));
if !resolved.enabled {
return;
}
// An app-scope command a modal layer's instance declares is delivered to that instance.
let target = if app { resolved.instance } else { instance };
let fired = Fired { target, ..Fired::new(command, FireSource::Key, FirePhase::Press, pass::now(ctx)) };
with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) });
repaint::request_of(ctx, ViewportId::ROOT);
@@ -1016,6 +1036,10 @@ fn fire_in(ctx: &Context, command: &CommandRef, source: FireSource, from: Option
}
// An app-scope command a modal layer's instance declares is delivered to that instance.
let target = if app { resolved.instance } else { instance };
// A command fired from no component of the window (a native menu, the palette) closes the open popups, as a key's
// command and a menu pick do, except the popup its instance is in and the popups it was opened from.
let inside: Vec<Id> = with(ctx, |board| target.and_then(|target| board.instances.iter().find(|i| i.id == target)?.layer).into_iter().collect());
overlay::close_popups_outside(ctx, &inside);
queue(ctx, Fired { target, ..Fired::new(command.clone(), source, FirePhase::Press, pass::now(ctx)) });
true
}
@@ -32,6 +32,8 @@ pub enum ClipItem {
pub struct ClipContent {
/// The clipboard's text, when it holds any.
pub text: Option<Arc<str>>,
/// The clipboard's image, when it holds one.
pub image: Option<Arc<ColorImage>>,
}
/// Why a paste has no content.
@@ -48,8 +50,8 @@ pub struct ClipboardHandle {
impl ClipboardHandle {
pub(crate) fn new(ctx: &Context, owner: Option<Id>) -> Self {
let slot = match owner.and_then(|id| keys::pasted_text(ctx, id)) {
Some(text) => Pending::Ready(ClipContent { text: Some(text) }),
let slot = match owner.and_then(|id| keys::pasted(ctx, id)) {
Some(content) => Pending::Ready(content),
None => Pending::Loading { progress: None },
};
ClipboardHandle { ctx: ctx.clone(), slot }
@@ -163,6 +163,8 @@ struct Step {
hold: Option<Hold>,
/// Files the step hovers over the window, or drops.
pub files: Option<InjectedFiles>,
/// The serial of the request that queued the step ([`Injected::requests`]).
request: u64,
}
/// Files an injected step hovers over a window, and whether the step after it drops them.
@@ -277,6 +279,8 @@ struct Lane {
entered: Option<u64>,
queue: VecDeque<Step>,
flight: Option<Flight>,
/// The request of the latest step handed to the input: a withdrawal keeps the rest of it once that step's pass ran.
running: Option<u64>,
/// The application withdrew the lane's input ([`withdraw`]); the next input hook carries it out.
withdrawn: bool,
}
@@ -287,6 +291,8 @@ struct Injected {
lanes: HashMap<ViewportId, Lane>,
/// What the steps handed to the input hold, per viewport; it outlives the lanes.
held: HashMap<ViewportId, Held>,
/// How many requests were queued: the serial of the latest.
requests: u64,
withdrawn: bool,
/// The Caps Lock state injected input sets in place of the platform's.
caps_lock: Option<bool>,
@@ -375,11 +381,14 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) -> bool {
return false;
}
lane.withdrawn = false;
if !lane.queue.is_empty() {
lane.queue.clear();
// The request whose step ran keeps its rest (a key's own release); the requests behind it go.
let running = lane.running;
let queued = lane.queue.len();
lane.queue.retain(|step| Some(step.request) == running);
if lane.queue.len() != queued {
injected.withdrawn = true;
}
if lane.flight.is_none() {
if lane.flight.is_none() && lane.queue.is_empty() {
injected.lanes.remove(&viewport);
return false;
}
@@ -414,6 +423,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) -> bool {
let held = injected.held.entry(viewport).or_default();
let before = held.clone();
held.apply(&step);
lane.running = Some(step.request);
lane.flight = Some(Flight { step, pass: pass_nr, focus: focused, until, before });
lane.entered = Some(frame);
return !lane.queue.is_empty();
@@ -431,7 +441,9 @@ fn queue(ctx: &Context, viewport: ViewportId, request: impl FnOnce(&mut Request)
Service::<Injected>::run(ctx, |injected| {
let mut writing = Request::new(injected.projected(viewport));
request(&mut writing);
injected.lane(viewport).queue.extend(writing.steps);
injected.requests = injected.requests.wrapping_add(1);
let serial = injected.requests;
injected.lane(viewport).queue.extend(writing.steps.into_iter().map(|step| Step { request: serial, ..step }));
});
repaint::request_of(ctx, viewport);
}
@@ -750,7 +762,8 @@ pub(crate) fn pen(ctx: &Context) -> Option<PointerSample> {
/// Withdraws the injected input of `viewport`: the application's document changed. The keys held with no event end at
/// once. The viewport's next input hook carries out the rest per step: a step handed to the input whose pass has not
/// run leaves the input with the queue behind it, and what was held before it is held again; after a step whose pass
/// has run, only the queue is dropped. Anything dropped counts as withdrawn ([`take_withdrawn`]). The application
/// has run, the rest of that step's request still runs (a key press's own release, when the press opened a dialog) and
/// the requests queued behind it are dropped. Anything dropped counts as withdrawn ([`take_withdrawn`]). The application
/// withdraws from its raw input hook, which runs right before the framework's, so every request queued before that
/// hook is dropped with the rest.
pub(crate) fn withdraw(ctx: &Context, viewport: ViewportId) {
+15 -5
View File
@@ -1,6 +1,7 @@
//! Raw input in the input hook, key events converted to craft-keymap's key types, `InputOptions`.
use super::control_click::ControlClick;
use crate::runtime::commands::ClipContent;
use crate::runtime::frame::PerViewport;
use crate::runtime::pen::PenPass;
use craft_behavior::one_press::split_after_first_press;
@@ -8,6 +9,7 @@ use craft_behavior::{Buttons, PointerButton, PointerEvent, PointerKind, PointerS
use craft_host::target::Os;
use craft_keymap::{KeyInput, Mods};
use egui::{Context, Event, Id, ImeEvent, Key, MouseWheelSource, MouseWheelUnit, Pos2, TouchPhase, Vec2, ViewportId};
use std::sync::Arc;
pub use egui::RawInput;
@@ -153,8 +155,8 @@ pub(crate) enum KeyEvent {
Release { input: KeyInput },
/// Typed text.
Text(String),
/// egui's own clipboard events; a paste carries its text.
Clip { command: craft_behavior::EditCommand, text: Option<String> },
/// egui's own clipboard events; a paste carries its text or image.
Clip { command: craft_behavior::EditCommand, pasted: Option<ClipContent> },
/// A pointer press, which ends keyboard modality.
PointerPress,
/// An AccessKit action request.
@@ -186,9 +188,17 @@ pub(crate) fn key_event(event: &Event, os: Os, latin: &[(egui::Key, char)]) -> K
Event::Key { pressed: false, .. } => read(event).map_or(KeyEvent::Other, |input| KeyEvent::Release { input }),
Event::Text(text) => KeyEvent::Text(text.clone()),
Event::ModifiersChanged(modifiers) => KeyEvent::Modifiers(Mods::from_egui(modifiers, os)),
Event::Copy => KeyEvent::Clip { command: craft_behavior::EditCommand::Copy, text: None },
Event::Cut => KeyEvent::Clip { command: craft_behavior::EditCommand::Cut, text: None },
Event::Paste(text) => KeyEvent::Clip { command: craft_behavior::EditCommand::Paste, text: Some(text.clone()) },
Event::Copy => KeyEvent::Clip { command: craft_behavior::EditCommand::Copy, pasted: None },
Event::Cut => KeyEvent::Clip { command: craft_behavior::EditCommand::Cut, pasted: None },
// A pasted image is the same Paste as pasted text: the command runs, and its reader takes the image.
Event::Paste(text) => KeyEvent::Clip {
command: craft_behavior::EditCommand::Paste,
pasted: Some(ClipContent { text: Some(Arc::from(text.as_str())), ..ClipContent::default() }),
},
Event::PasteImage(image) => KeyEvent::Clip {
command: craft_behavior::EditCommand::Paste,
pasted: Some(ClipContent { image: Some(Arc::clone(image)), ..ClipContent::default() }),
},
Event::PointerButton { pressed: true, .. } => KeyEvent::PointerPress,
Event::AccessKitActionRequest(request) => KeyEvent::Access(Action(request.clone())),
_ => KeyEvent::Other,
@@ -551,6 +551,11 @@ impl State {
{
return Some(owner);
}
// A removed stop in an arena (an editor or control in a canvas body) hands focus back to the arena root's own
// stop (the canvas), not to the next stop after the arena.
if let Some(arena) = gone.stop.arena.and_then(|arena| self.stops.iter().find(|rec| rec.stop.id == arena && rec.stop.part.is_none())) {
return Some(arena.clone());
}
// Press-only stops (selectable text) are outside the Tab order, so focus never falls to them either.
let order: Vec<StopKey> = self
.last_stops
@@ -34,6 +34,9 @@ pub struct Stop {
pub group: Option<Id>,
/// The roving group of the innermost body the stop sits in, whether or not the stop joined it.
pub body: Option<Id>,
/// The arena root the stop is shown in (a canvas whose body holds it), whether or not it joined the arena: a text
/// stop keeps its own egui widget. A removed stop hands focus back to it.
pub arena: Option<Id>,
/// The app's own egui widget (`focus::host_canvas`), which reads its keys from egui's input: the key stage leaves
/// the presses it routes to the stop there.
pub host: bool,
@@ -54,6 +57,7 @@ impl Stop {
name: None,
group: None,
body: None,
arena: None,
host: false,
}
}
@@ -112,6 +116,12 @@ impl Stop {
self
}
/// Sits in the arena of the root `arena` (a canvas body), if any, whether or not it joined it.
pub fn in_arena(mut self, arena: Option<Id>) -> Self {
self.arena = arena;
self
}
/// Marks the stop as the app's own egui widget.
pub fn host(mut self) -> Self {
self.host = true;
+14 -8
View File
@@ -2,14 +2,13 @@
//! every key event of the pass, the begin hook turns them into the `Intents` of the focused component,
//! and claims, menu-bar keys and AccessKit action requests are routed from the same record.
use crate::runtime::commands::FirePhase;
use crate::runtime::commands::{ClipContent, FirePhase};
use crate::runtime::egui::input::Action;
use crate::runtime::frame::PerViewport;
use craft_behavior::EditCommand;
use craft_keymap::{Chord, Key, KeyInput, Layout, Mods};
use egui::{Context, Id, IdMap, Vec2, ViewportId};
use std::collections::HashMap;
use std::sync::Arc;
mod claims;
mod input;
@@ -21,7 +20,7 @@ mod route;
pub use claims::capture;
#[doc(hidden)]
pub use claims::claim;
pub(crate) use claims::hold_escape;
pub(crate) use claims::{fire_claimed, hold_escape};
#[doc(hidden)]
pub use claims::take_claimed;
/// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`).
@@ -45,7 +44,7 @@ pub(crate) use intents::{
};
pub(crate) use nodes::{redirect_node, register_expanded, register_node};
pub use route::focus_holds;
pub(crate) use route::{activated_member, begin, layout_of, owner_at, pasted_text, queue_edit, routed_to, take_shortcuts};
pub(crate) use route::{activated_member, begin, layout_of, owner_at, pasted, pasted_text, queue_edit, routed_to, take_shortcuts};
/// A menu-bar key of an in-window bar (spec 9.7). F10 reaches the bar on every OS; Alt keys only off a Mac.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -104,6 +103,9 @@ enum Taken {
No,
/// The press became an intent, a focus move or an activation.
Yes,
/// With nothing focused, the window's document canvas took the press (a nudge or a page move): it is the canvas's
/// alone, as while the canvas has the focus, and no app shortcut runs with it.
Canvas,
}
/// The key events the owner leaves to the app this pass, with the facts the matching needs.
@@ -125,8 +127,8 @@ struct Batch {
/// How many key presses the strip left in egui's input.
egui_presses: usize,
shortcuts: Vec<Shortcut>,
/// The text of the paste the focused component takes.
paste: Option<String>,
/// The content of the paste the focused component takes.
paste: Option<ClipContent>,
/// Every text event of the pass, in order.
texts: Vec<Typed>,
/// How many text events the strip left in egui's input.
@@ -217,6 +219,10 @@ pub(crate) struct Stage {
routed: HashMap<Option<Id>, Routed>,
claimed: Vec<(Id, Chord)>,
claims: Vec<(Id, Chord)>,
/// The state-dependent claims the running pass holds: those registered in the pass before.
last_claims: Vec<(Id, Chord)>,
/// The claimed chords fired commands stand for (`fire_claimed`), for their owners in the next pass.
fired_claims: Vec<(Id, Chord)>,
/// Chords a container holds for itself while focus is anywhere in the viewport (a window mode), from the
/// pass that registered them.
captures: Vec<(Id, Chord)>,
@@ -233,8 +239,8 @@ pub(crate) struct Stage {
/// The keys whose press the strip took and whose release it is still to drop.
consumed: Vec<Key>,
shortcuts: Shortcuts,
/// The paste text the focused component reads through its clipboard handle.
pasted: Option<(Id, Arc<str>)>,
/// The paste the focused component reads through its clipboard handle.
pasted: Option<(Id, ClipContent)>,
/// Edit commands fired from the queue for the focused component.
queued_edits: Vec<EditCommand>,
/// The components that asked for a context menu in this pass, with the rect it opens at.
@@ -32,6 +32,28 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) {
current(ctx, |stage| stage.claims.push((owner, chord)));
}
/// Hands the first of `chords` (a fired command's keys, in binding order) that the focused component claims, as it is
/// focused now, to the claim's owner in the next pass, as a press of the chord arrives: a command run from a menu or
/// the palette whose key a component claims (a canvas tool's Delete) reaches the component as that key, so key and
/// menu share one path. A menu pick returns focus in its pass before its command fires. `false` when the focused
/// component claims none of them.
pub(crate) fn fire_claimed(ctx: &Context, chords: &[Chord]) -> bool {
let Some(rec) = crate::runtime::focus::focused_rec(ctx) else { return false };
let root = (rec.stop.root != rec.stop.id && !rec.stop.text).then_some(rec.stop.root);
let found = current(ctx, |stage| {
let held = |chord: &Chord| {
let owns = |owner: &Id| *owner == rec.stop.id || Some(*owner) == root;
let state = stage.last_claims.iter().chain(&stage.claims).find(|(owner, held)| held == chord && owns(owner));
state.map(|(owner, _)| *owner).or_else(|| rec.stop.keys.claims.contains(chord).then_some(rec.stop.id))
};
chords.iter().find_map(|chord| held(chord).map(|owner| (owner, *chord)))
});
let Some(claim) = found else { return false };
current(ctx, |stage| stage.fired_claims.push(claim));
crate::runtime::egui::repaint::request_of(ctx, crate::runtime::egui::pass::current_viewport(ctx));
true
}
/// Holds `chord` for `owner` from the next input hook on, whichever component has focus: the key stage withholds
/// it from every component and `take_claimed` reads it. Used while a container is in a mode that owns the arrow
/// keys, Enter and Escape (the window move and size modes, 16.3); the claim lapses when it is not renewed.
+12 -3
View File
@@ -47,6 +47,8 @@ struct Strip<'a> {
no_stops: bool,
/// egui holds a label text selection, which a copy or cut event copies.
label_selection: bool,
/// The focus is in a menu (`FocusedRecord::menu`).
in_menu: bool,
}
impl Strip<'_> {
@@ -125,16 +127,22 @@ impl Strip<'_> {
batch.egui_texts += 1;
true
}
KeyEvent::Clip { command, text } if (self.edits)(command) => {
KeyEvent::Clip { command, pasted } if (self.edits)(command) => {
batch.clips.push(command);
if text.is_some() {
batch.paste = text;
// A paste of text and one of an image in the same pass are one paste of both.
if let Some(pasted) = pasted {
let content = batch.paste.get_or_insert_default();
content.text = pasted.text.or(content.text.take());
content.image = pasted.image.or(content.image.take());
}
false
}
KeyEvent::Clip { .. } if self.foreign => true,
KeyEvent::Clip { command, .. } if self.canvas.is_some_and(|canvas| canvas.edits.contains(command)) => true,
KeyEvent::Clip { command: EditCommand::Copy | EditCommand::Cut, .. } if self.label_selection => true,
// A clipboard event behind an open menu reaches nothing: the menu keeps it, as a platform menu does. The
// chord's own key press still runs its command, which closes the menu.
KeyEvent::Clip { .. } if self.in_menu => false,
KeyEvent::Clip { command, .. } => {
// The platform sends the clipboard event in place of the chord: an unlisted one is the chord. The
// web sends the chord's press as well.
@@ -466,6 +474,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
canvas,
no_stops,
label_selection: record.label_selection,
in_menu: record.menu.is_some(),
};
let mut batch = Batch::default();
let mut visible = None;
+33 -19
View File
@@ -2,7 +2,7 @@
use super::input::chrome_toggle_of;
use super::{Batch, Item, MenuKey, Node, Press, Routed, Shortcuts, Taken, current, with};
use crate::runtime::commands::{self, FirePhase};
use crate::runtime::commands::{self, ClipContent, FirePhase};
use crate::runtime::egui::input::{Action, ActionKind};
use crate::runtime::focus::{self, StopRec};
use crate::runtime::frame::request_chrome_toggle;
@@ -22,15 +22,17 @@ use std::sync::Arc;
pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
let os = crate::runtime::windows::os_of(ctx);
let target = focus::focused_rec(ctx);
let (batch, nodes, captures, held_claims) = current(ctx, |stage| {
let (batch, nodes, captures, held_claims, fired_claims) = current(ctx, |stage| {
stage.routed.clear();
stage.contexts.clear();
stage.claimed.clear();
stage.activated.clear();
let held_claims = std::mem::take(&mut stage.claims);
stage.last_claims.clone_from(&held_claims);
stage.last_open_edits = std::mem::take(&mut stage.open_edits);
stage.last_nodes = std::mem::take(&mut stage.nodes);
(std::mem::take(&mut stage.batch), stage.last_nodes.clone(), std::mem::take(&mut stage.captures), held_claims)
let fired = std::mem::take(&mut stage.fired_claims);
(std::mem::take(&mut stage.batch), stage.last_nodes.clone(), std::mem::take(&mut stage.captures), held_claims, fired)
});
let modal = overlay::any_open(ctx, overlay::OpenFilter::Modal);
let stale_repeat = |stale: &mut bool, press: &Press| {
@@ -49,6 +51,8 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
let mut routed: HashMap<Option<Id>, Routed> = HashMap::new();
let mut activated = IdMap::default();
let mut consumed = vec![Taken::No; batch.presses.len()];
// With nothing focused, the window's document canvas is the key target unless a modal layer is open.
let canvas = if target.is_some() || modal { None } else { focus::document_canvas(ctx) };
let driven = target.as_ref().and_then(|rec| Driven::of(ctx, rec));
let field_list = target.as_ref().filter(|_| driven.is_none()).and_then(|rec| list_of_field(ctx, rec));
// Whether a component took each text of the pass, as typing, type-ahead or digits; and whether the framework took
@@ -85,21 +89,21 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
// With nothing focused, a plain Enter submits to the window, as an unfocused Escape cancels: a tool's pending
// edit or a dialog's default button takes it. The arrows nudge the window's canvas content (a tool or the
// session control on a canvas), unless a modal layer is open. The window's document canvas is its key target
// (`focus::host_canvas`): Page Up and Down, Home and End page it as they do while it has the focus.
let canvas = if modal { None } else { focus::document_canvas(ctx) };
// (`focus::host_canvas`): Page Up and Down, Home and End page it as they do while it has the focus. What the
// canvas takes is its alone, as while it has the focus: the app's shortcuts do not run with it too.
for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, _)| !press.canvas) {
if press.key == Key::Enter && press.mods.is_none() && !press.repeat {
push(&mut routed, None, Intent::Submit, false);
*taken = Taken::Yes;
} else if !modal && let Some(nudge) = nudge_of(press.key, press.mods) {
routed.entry(None).or_default().nudge = Some(nudge);
*taken = Taken::Yes;
*taken = if canvas.is_some() { Taken::Canvas } else { Taken::Yes };
} else if let Some(canvas) = &canvas
&& let Some(Intent::Move(mv @ (NavMove::PageUp | NavMove::PageDown | NavMove::Start | NavMove::End), mods)) =
keys::intent(os, press.key, press.mods, canvas.stop.role)
{
push(&mut routed, Some(canvas.stop.id), Intent::Move(mv, mods), false);
*taken = Taken::Yes;
*taken = Taken::Canvas;
}
}
}
@@ -117,8 +121,10 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
push(&mut routed, focused, Intent::Edit(command), false);
}
let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts);
withdraw_taken(ctx, target.as_ref(), &batch, &held, &withdrawn_texts);
let pasted = batch.paste.as_deref().zip(focused).map(|(text, id)| (id, Arc::<str>::from(text)));
// The app's own widget, focused or the window's canvas, reads its keys from egui.
let host = target.as_ref().or(canvas.as_ref()).is_some_and(|rec| rec.stop.host);
withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts);
let pasted = batch.paste.clone().zip(focused).map(|(content, id)| (id, content));
let escapes = craft_behavior::focus::route_escapes(batch.escapes, press_captured);
for _ in 0..escapes.to_components {
// A row's child that claims Escape keeps it; any other returns focus to its row.
@@ -130,8 +136,9 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
}
push(&mut routed, focused, Intent::Cancel, false);
}
// A text opener's list keys arrive as claimed chords, withheld from its text part: they go to the list.
let mut claimed = Vec::new();
// A text opener's list keys arrive as claimed chords, withheld from its text part: they go to the list. The chords
// fired commands stood for go to the owners of their claims.
let mut claimed = fired_claims;
for chord in &batch.claimed {
match driven.and_then(|driven| driven.intent_of(chord)) {
Some(intent) => push(&mut routed, driven.map(|driven| driven.list), intent, false),
@@ -208,8 +215,11 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu
.presses
.iter()
.zip(consumed)
// The canvas's Space is never the focused stop's.
.map(|(press, taken)| !press.canvas && holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at])))
// The canvas's Space is never the focused stop's; a press the unfocused window's canvas took is the canvas's.
.map(|(press, taken)| {
!press.canvas
&& (*taken == Taken::Canvas || holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at])))
})
.collect();
// A shortcut without a press of its own (a release, or the clipboard event that stands for ⌘C) follows the owner by
// its modifiers, as its press would.
@@ -328,11 +338,10 @@ pub fn focus_holds(ctx: &Context, chord: Chord) -> bool {
/// Takes what the framework handed to one taker out of the running pass's egui input, where the app and egui's text
/// widgets read their keys: one press, one action, and one text, one reader. `held` marks the presses the focused
/// component holds; the app's own widget (`Stop::host`) reads its keys from egui, so its presses stay. `texts` are the
/// places in `Batch::texts` of the texts a claim or a framework taker took. A held press whose release has not come yet
/// leaves its release to the strip.
fn withdraw_taken(ctx: &Context, target: Option<&StopRec>, batch: &Batch, held: &[bool], texts: &[usize]) {
let host = target.is_some_and(|rec| rec.stop.host);
/// component (or the unfocused window's canvas) holds; the app's own widget (`Stop::host`, `host`) reads its keys from
/// egui, so its presses stay. `texts` are the places in `Batch::texts` of the texts a claim or a framework taker took.
/// A held press whose release has not come yet leaves its release to the strip.
fn withdraw_taken(ctx: &Context, host: bool, batch: &Batch, held: &[bool], texts: &[usize]) {
let presses: Vec<&Press> =
batch.presses.iter().zip(held).filter(|(press, held)| !host && **held && press.in_egui.is_some()).map(|(press, _)| press).collect();
if presses.is_empty() && texts.is_empty() {
@@ -387,9 +396,14 @@ pub(crate) fn queue_edit(ctx: &Context, command: EditCommand) -> bool {
true
}
/// The paste the focused component `id` takes this pass.
pub(crate) fn pasted(ctx: &Context, id: Id) -> Option<ClipContent> {
current(ctx, |stage| stage.pasted.as_ref().filter(|(owner, _)| *owner == id).map(|(_, content)| content.clone()))
}
/// The text of the paste the focused component `id` takes this pass.
pub(crate) fn pasted_text(ctx: &Context, id: Id) -> Option<Arc<str>> {
current(ctx, |stage| stage.pasted.as_ref().filter(|(owner, _)| *owner == id).map(|(_, text)| Arc::clone(text)))
pasted(ctx, id).and_then(|content| content.text)
}
/// The collection that takes the list keys of the focused stop: the collection of an open `KeepAnchor` dropdown whose
@@ -475,6 +475,16 @@ fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() {
assert!(!clipboard_with_canvas(KeyUse::CANVAS, chord).1.is_empty(), "a canvas without the command: the chord fires the app's Paste");
}
/// A pasted image is the same Paste as pasted text: in a window whose canvas does not take it, the app's Paste runs,
/// and the app reads the image; a canvas that lists Paste reads it from egui, as it does text.
#[trial]
fn a_pasted_image_runs_the_paste_a_pasted_text_runs() {
let image = Event::PasteImage(Arc::new(egui::ColorImage::filled([2, 2], egui::Color32::RED)));
assert_eq!(clipboard_with_canvas(KeyUse::CANVAS, image.clone()).1, [EditCommands::Paste.id()], "the app's Paste runs");
let typing = KeyUse::CANVAS.with_edits(EditSet::NONE.with(EditCommand::Paste));
assert_eq!(clipboard_with_canvas(typing, image), (true, Vec::new()), "the canvas's paste stays in egui and fires nothing");
}
/// What an F6 press did under `overrides`: whether it reached egui, and the ids of the commands it fired.
fn f6_under(overrides: Option<craft_keymap::Overrides>) -> (bool, Vec<String>) {
let (host, mut show) = host_window();
+39 -1
View File
@@ -1,6 +1,6 @@
//! Trials of the bare-Tab chrome toggle: when a Tab press toggles a window's panels and when it moves focus.
use crate::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _};
use crate::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _, EditCommands};
use crate::runtime::env::RootEnv;
use crate::runtime::focus::{FocusTarget, KeyUse, request};
use crate::runtime::frame::{ChromeToggle, take_output};
@@ -208,6 +208,44 @@ fn a_recorder_reads_a_press_as_one_chord_and_no_command_runs() {
assert_eq!(press_k("button").0, Vec::new(), "no other role reads chords");
}
/// With nothing focused, the window's document canvas takes Page Down and the arrows' nudge, as while it has the focus;
/// the press is its alone, so no app shortcut runs with it as well (a page view would turn twice). Without a canvas the
/// press is the app's.
#[trial]
fn an_unfocused_press_the_window_canvas_takes_reaches_no_app_shortcut() {
let paged = Rc::new(Cell::new(0));
let canvas = Rc::new(Cell::new(true));
let (sink, shows) = (Rc::clone(&paged), Rc::clone(&canvas));
let mut show = move |ui: &mut Ui| {
stop(ui, "button", KeyUse::of(Input::Pointer));
if shows.get() {
stop(ui, "canvas", KeyUse::CANVAS);
}
let mut intents = intents_of(ui.ctx(), Some(id("canvas")), false);
if intents.take(Intent::Move(craft_behavior::NavMove::PageDown, craft_behavior::MoveMods::PLAIN)) {
sink.set(sink.get() + 1);
}
};
let mut bound = Overrides::default();
bound.insert(EditCommands::Delete.id(), vec!["PageDown".to_owned()]);
bound.insert(EditCommands::SelectAll.id(), vec!["Right".to_owned()]);
let mut frames = Frames::new();
frames.commands(CommandInput::new().overrides(Arc::new(bound)));
frames.frame(Vec::new(), &mut show);
take_output(&frames.ctx);
let fired = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| {
frames.frame(vec![key_press(Key::PageDown, Modifiers::NONE), key_press(Key::ArrowRight, Modifiers::NONE)], &mut *show);
frames.frame(Vec::new(), &mut *show);
take_output(&frames.ctx).fired.len()
};
assert_eq!(fired(&mut frames, &mut show), 0, "neither press reaches the app's commands");
assert_eq!(paged.get(), 1, "the canvas pages");
canvas.set(false);
frames.idle(2, &mut show);
take_output(&frames.ctx);
assert_eq!(fired(&mut frames, &mut show), 2, "without a canvas both presses are the app's");
}
/// A recorder holds every press: the app reads none from egui's input, and `focus_holds` answers so before the press.
#[trial]
fn a_recorder_holds_its_presses_from_the_app() {
@@ -599,6 +599,35 @@ fn a_window_focus_loss_releases_injected_held_keys() {
assert_eq!(held.get(), (false, false), "nothing stays held after the click");
}
/// A withdrawal after a step whose pass ran keeps the rest of that step's request (a key press's own release, when the
/// press opened a dialog that changed the document) and drops the requests queued behind it.
#[trial]
fn a_withdrawal_keeps_the_rest_of_the_request_whose_step_ran() {
let windows = Windows::new();
let host = WindowHost::of(&windows.ctx);
let (a_down, b_pressed) = (Cell::new(false), Cell::new(false));
let frame = || {
windows.frame(vec![], vec![], |ui| {
ui.ctx().input(|input| {
a_down.set(input.key_down(egui::Key::A));
b_pressed.set(b_pressed.get() || input.key_pressed(egui::Key::B));
});
});
};
frame();
host.inject_key(ViewportId::ROOT, Key::A, Mods::NONE, false);
host.inject_key(ViewportId::ROOT, Key::B, Mods::NONE, false);
frame();
assert!(a_down.get(), "the press of A ran");
host.withdraw_injected(ViewportId::ROOT);
for _ in 0..6 {
frame();
}
assert!(!a_down.get(), "A's own release still came");
assert!(!b_pressed.get(), "the request behind it was dropped");
assert!(host.injected_idle());
}
/// Injected input with a NaN or infinite point queues nothing, as a window never reports one, and a release at such a
/// point still lets the held button go.
#[trial]
+35
View File
@@ -9,7 +9,11 @@ use craft_ui::dialog::{
Alert, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, PromptKind, StackDialog, StandardPrompt, StartupStage,
UnsavedChangesDialog, dialog_id,
};
use craft_ui::contract::Bind;
use craft_ui::runtime::commands::{CommandSet as _, EditCommands};
use craft_ui::runtime::frame::take_output;
use craft_ui::runtime::windows::{WindowHit, WindowHost};
use craft_ui::text::TextField;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::testing::{Fixture, Frames, Story, StoryData, StoryOutput, trial};
@@ -327,3 +331,34 @@ fn each_open_of_a_dialog_has_its_own_serial() {
assert_eq!(again, id, "the reopened dialog has the same id");
assert_ne!(host.open_serial(id), Some(first), "the reopened dialog has a serial of its own");
}
/// The commands an Undo fired that a focused, unedited name field had nothing to do for, the field in a modal dialog
/// or in the window.
fn undo_with_nothing_to_undo(modal: bool) -> Vec<String> {
let mut name = String::new();
let mut fixture = Fixture::new(move |ui| {
if modal {
Dialog::new("Rename").show(ui, |ui, _| {
TextField::new("Name", Bind::bound(&mut name)).show(ui);
});
} else {
TextField::new("Name", Bind::bound(&mut name)).show(ui);
}
});
fixture.settle();
if !modal {
let field = fixture.by_label("Name").expect("the field shows");
fixture.click(&field).settle();
}
take_output(fixture.ctx());
fixture.key(egui::Key::Z, Modifiers::COMMAND).settle();
take_output(fixture.ctx()).fired.into_iter().map(|fired| fired.command.id).collect()
}
/// An Undo a focused text field has nothing to do for runs the window's Undo (11.3), but not past a modal dialog the
/// field is in: the modal rule holds for it as for the key itself, so the document under the dialog stays.
#[trial]
fn an_undo_a_dialogs_field_leaves_runs_no_command_under_the_dialog() {
assert_eq!(undo_with_nothing_to_undo(false), [EditCommands::Undo.id()], "in the window, the field's leftover Undo is the app's");
assert!(undo_with_nothing_to_undo(true).is_empty(), "under the dialog it reaches no command");
}
@@ -5,7 +5,9 @@ use craft_ui::buttons::{Button, IconButton, PopupMark};
use craft_ui::contract::{Bind, PopupKind, Props as _, Role, Show as _, ShowContainer as _, Trigger};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::popover::Popover;
use craft_ui::runtime::commands::{self, CommandSet as _, EditCommands, FireSource};
use craft_ui::runtime::env::Direction;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Rect, Shape, pos2};
use std::cell::Cell;
@@ -101,6 +103,32 @@ fn a_new_right_click_moves_an_open_context_menu_to_the_pointer() {
assert!(after.min.x > before.min.x + 40.0, "the menu moved to the second point: {before:?} then {after:?}");
}
/// With a context menu open, a paste event (the platform's answer to ⌘V) behind it reaches nothing: no Paste runs
/// and the menu stays. Edit ▸ Paste from a native menu, which no component of the window fires, closes the menu, as a
/// key's command does, and runs.
#[trial]
fn a_paste_behind_a_context_menu_runs_nothing_and_a_native_edit_paste_closes_it() {
let mut fixture = Fixture::new(|ui| {
let target = Button::new("Target").show(ui);
Menu::context("Target menu", &target).show(ui, |ui, _| {
MenuItem::new("Copy").show(ui);
});
});
fixture.settle();
let at = fixture.by_label("Target").expect("the target").center();
right_click(&mut fixture, at);
assert!(menu_rect(&fixture).is_some(), "the context menu is open");
let fired = |fixture: &Fixture| take_output(fixture.ctx()).fired.into_iter().map(|fired| fired.command.id).collect::<Vec<_>>();
fired(&fixture);
fixture.frame(vec![egui::Event::Paste("clipboard text".to_owned())]).settle();
assert!(fired(&fixture).is_empty(), "the paste behind the menu ran nothing");
assert!(menu_rect(&fixture).is_some(), "the menu stays open");
commands::fire(fixture.ctx(), EditCommands::Paste, FireSource::Menu);
fixture.settle();
assert!(menu_rect(&fixture).is_none(), "Edit ▸ Paste closed the menu");
assert_eq!(fired(&fixture), [EditCommands::Paste.id()], "and ran");
}
/// An icon button that opens a menu hangs the dropdown arrow under the end edge of its glyph, inside the button and
/// clear of the glyph, in either reading direction; a tool group's button shows the corner triangle instead.
#[trial]