Framework batch 4 a: port follow-ups (see runs/fwb4-a.md)

This commit is contained in:
Dylan M. Taylor
2026-11-19 18:25:02 -05:00
parent d552111634
commit d9c0813c95
18 changed files with 266 additions and 26 deletions
+10 -1
View File
@@ -40,6 +40,7 @@ use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContaine
use craft_ui::primitives::PaintSlot;
use craft_ui::primitives::textures::{Priority, TextureState, TextureStatistics, ThumbRequest, ThumbSource};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::NudgeMods;
use craft_ui::runtime::memory::Remember as _;
use craft_ui::style::DataColor;
use egui::{Rect, Ui, Vec2, pos2};
@@ -449,7 +450,8 @@ impl<'a> PageView<'a> {
// The canvas keeps the view inside the shown row, as the pass does, so a wheel share that cannot pan a row at its
// edge leaves the gesture unmoved and a page turn can follow it.
navigation.overscroll = false;
let canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).document(frame.document(&geo));
let canvas =
Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).body_nudges(KeyMoves::NUDGES).document(frame.document(&geo));
let mut held = Held::new(Bind::bound(state));
let mut seen: Option<Seen> = None;
let mut canvas_body = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
@@ -980,6 +982,13 @@ struct KeyMoves {
}
impl KeyMoves {
/// The arrow modifiers `of` reads besides the plain arrows: Cmd or Ctrl, alone or with Shift. Alt is the app's.
const NUDGES: NudgeMods = NudgeMods::NONE
.with(Mods::CMD)
.with(Mods::CTRL)
.with(Mods { shift: true, ..Mods::CMD })
.with(Mods { shift: true, ..Mods::CTRL });
/// Page Up and Down a screen less a key line (a row when not continuous, and with Cmd), Home and End the first
/// and last page, Up and Down a key line (not continuous, a turn once the row is at its edge that way), Left and
/// Right a key line sideways while the current page or spread has more to show that way, else a turn of a page or
+57
View File
@@ -1003,6 +1003,63 @@ fn an_arrow_the_tool_takes_leaves_the_page_and_one_it_leaves_turns_it() {
assert_eq!((taken.get(), state.borrow().current), (1, 1), "an arrow the tool leaves turns the page");
}
/// With nothing focused the view takes only the arrows it acts on: a plain arrow turns the page and is the view's
/// alone, while Alt with an arrow, which it does not read, stays in egui's input for the app's shortcuts (a view
/// history's Alt+Left). The view used to hold every arrow, whatever was held with it.
#[trial]
fn with_nothing_focused_the_view_leaves_alt_and_an_arrow_to_the_app() {
let reached: Rc<RefCell<Vec<Modifiers>>> = Rc::default();
let seen = Rc::clone(&reached);
let start = state_with(|s| {
s.continuous = false;
s.fit = Fit::Page;
});
let Rig { mut fixture, state, .. } = rig_with(DemoPages::new(5), start, NavigationOptions::default(), true, move |ui, _| {
let pressed = ui.input(|input| {
input.events.iter().find_map(|event| match event {
egui::Event::Key { key: Key::ArrowRight, pressed: true, modifiers, .. } => Some(*modifiers),
_ => None,
})
});
seen.borrow_mut().extend(pressed);
});
fixture.key(Key::ArrowRight, Modifiers::ALT);
fixture.idle(2);
assert_eq!(state.borrow().current, 0, "Alt+Right turns no page");
assert!(reached.borrow().iter().any(|mods| mods.alt), "Alt+Right reaches the app");
reached.borrow_mut().clear();
fixture.key(Key::ArrowRight, Modifiers::NONE);
fixture.idle(2);
assert_eq!(state.borrow().current, 1, "Right turns the page");
assert!(reached.borrow().is_empty(), "Right is the view's alone");
}
/// The page and end keys a focused control in the page body does not use (a button takes no moves) page the view,
/// as they do with the canvas focused: the control leaves them untaken and they go on to the view, its scroll owner.
#[trial]
fn page_keys_a_focused_control_in_the_body_leaves_page_the_view() {
let start = state_with(|s| {
s.continuous = false;
s.fit = Fit::Page;
});
let Rig { mut fixture, state, .. } = rig_with(DemoPages::new(5), start, NavigationOptions::default(), true, |ui, _| {
let _ = craft_ui::buttons::Button::new("Mark").show(ui);
});
for _ in 0..4 {
if fixture.focused_stop().is_some() && fixture.focused_role().is_some_and(|role| !role.nudge) {
break;
}
fixture.key(Key::Tab, Modifiers::NONE);
}
assert!(fixture.focused_role().is_some_and(|role| !role.nudge), "Tab reaches the button in the body");
fixture.key(Key::PageDown, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 1, "Page Down turns one page");
fixture.key(Key::End, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 4, "End goes to the last page");
}
/// Cmd with Page Down turns one page in a scrolling view, where plain Page Down scrolls a screen; Right turns a
/// spread in a scrolling two-page view, not to the other page of the spread already on screen.
#[trial]
+12 -1
View File
@@ -104,7 +104,7 @@ use crate::contract::{
};
use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _};
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::runtime::focus::{KeyUse, NudgeMods};
use crate::runtime::frame;
use crate::runtime::lock_keys;
use crate::runtime::measure;
@@ -206,6 +206,12 @@ pub struct Canvas<'a> {
/// itself (a page view).
#[prop]
keys_to_body: bool,
/// The arrow modifiers the body acts on besides the plain and Shift steps every tool and control reads
/// (`NudgeMods::STEPS`): with nothing in the window focused, those arrows are the canvas's alone, and an arrow with
/// modifiers neither lists stays the app's shortcut (`KeyUse::nudge_mods`). A page view lists the Cmd and Ctrl
/// arrows that turn its pages.
#[prop]
body_nudges: NudgeMods,
/// The rulers' units and zero point, published to the body in its [`CanvasSpace`].
rulers: Option<CanvasRulers>,
/// The snapping of the coordinates the pointer sets on this canvas (View > Snap To), as data over the document's
@@ -292,6 +298,7 @@ impl<'a> Canvas<'a> {
navigation: NavigationOptions::default(),
show_rulers: false,
keys_to_body: false,
body_nudges: NudgeMods::NONE,
pasteboard: PasteboardColor::Default,
precise_cursors: false,
rulers: None,
@@ -800,6 +807,10 @@ impl Component for Canvas<'_> {
type Style = CanvasStyle;
type Output = CanvasOutput;
fn keys(&self) -> KeyUse {
Self::KEYS.with_nudge_mods(NudgeMods::STEPS.union(self.body_nudges))
}
fn style(cx: &StyleCx<'_>, _: CanvasStyleKey) -> CanvasStyle {
let surface = SurfaceLook::new(Stateful::new(cx.color(cx.tokens.color.surface.canvas))).kind(SurfaceKind::Canvas);
// The rulers' own layout says where the view lies inside them.
@@ -118,6 +118,20 @@ fn a_fired_command_whose_key_the_tool_claims_reaches_the_tool_as_that_key() {
assert_eq!(canvas.tool().seen.len(), 1, "a tool that claims no delete gets none");
}
/// With nothing focused the window's canvas is the key target, as for its nudges: Edit ▸ Delete reaches the tool that
/// claims Delete (a Select All took the focus away), and no app command runs.
#[trial]
fn a_fired_command_whose_key_the_tool_claims_reaches_it_with_nothing_focused() {
let mut canvas = ToolFixture::new("Document", Outline::new(true));
canvas.fixture().settle();
assert_eq!(canvas.fixture().focused(), None, "nothing is focused");
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");
}
/// A tool that takes every key the host offers it.
#[derive(Default)]
struct Taker {
@@ -45,11 +45,14 @@ pub(crate) fn gesture_gate<C: Component>(comp: &C, cx: &mut Cx<'_, C>) {
}
/// Step 9, the edit intents the library takes before `C::update`: Escape or a cancelled press ends a running gesture
/// (Escape as `C::ESCAPE` says), and a reset becomes a `Set` of the binding's reset value.
/// (Escape as `C::ESCAPE` says), and a reset becomes a `Set` of the binding's reset value. In a dialog Escape is the
/// dialog's Cancel, which discards the gesture with the dialog's other edits: a gesture there ends on a cancelled press
/// only.
pub(crate) fn edit_intents<C: Component>(comp: &mut C, cx: &mut Cx<'_, C>) {
use crate::contract::cx::Edit as _;
if cx.gesture().is_some_and(|phase| matches!(phase, GesturePhase::Begin | GesturePhase::Update)) {
let reason = if !cx.core.escape_to_list && cx.core.intents.take(Intent::Cancel) {
let escapes = !cx.core.escape_to_list && !crate::runtime::keys::focus_in_dialog(&cx.core.ctx);
let reason = if escapes && cx.core.intents.take(Intent::Cancel) {
Some(CancelReason::Escape)
} else {
cx.core.press_cancelled().map(|reason| match reason {
@@ -370,9 +370,10 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
Some(DraftChange::Revert) => state.end = Some(End::Revert),
None => {}
}
// A clearing field takes Escape while it shows text, with or without a draft, and passes it on once it is empty.
let takes_escape =
if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { state.draft.is_some() || state.preedit.is_some() };
// A clearing field takes Escape while it shows text, with or without a draft, and passes it on once it is empty. In
// a dialog a draft leaves Escape to the dialog's Cancel, which discards it with the dialog's other edits.
let draft_takes = state.draft.is_some() && !(focused_before && keys::focus_in_dialog(ctx));
let takes_escape = if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { draft_takes || state.preedit.is_some() };
if focused_before && takes_escape && !state.completions.open && !input.list_open && input.intents.take(Intent::Cancel) {
// Escape over a composition alone ends the composition and leaves the text.
if state.draft.is_some() || state.preedit.is_none() {
@@ -1281,6 +1281,7 @@ pub(crate) fn begin(ctx: &Context) {
cycle: false,
alt_variant: false,
time,
pasted: None,
});
}
}
@@ -1304,6 +1305,7 @@ pub(crate) fn begin(ctx: &Context) {
cycle: hit.cycle.len() > 1,
alt_variant: hit.alt_variant,
time,
pasted: None,
};
with(ctx, |board| board.declined.push(declined));
}
@@ -1312,13 +1314,14 @@ pub(crate) fn begin(ctx: &Context) {
// 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| {
let pasted = with(ctx, |board| {
if let Some(key) = key.filter(|_| {
board.def(&hit.command.id).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 });
}
board.registry.edit_of(&hit.command.id) == Some(EditCommand::Paste)
});
fired.push(Fired {
command: hit.command,
@@ -1328,6 +1331,7 @@ pub(crate) fn begin(ctx: &Context) {
cycle: hit.cycle.len() > 1,
alt_variant: hit.alt_variant,
time,
pasted: shortcuts.pasted.clone().filter(|_| pasted),
});
}
}
@@ -142,13 +142,18 @@ pub struct Fired {
/// release arrived, also when the runtime held the event back to a later frame; the pass time for the other
/// sources. A key's hold is the time between its press and its release, however late a frame runs them.
pub time: f64,
/// The clipboard's content, for a paste the platform delivered with its event (the clipboard event that stands for
/// the paste chord) when no focused component lists Paste: the command that event fires carries it, so the app
/// pastes what the event held in the pass it runs the command. `None` for every other command, and for a paste
/// whose content the app reads from the clipboard itself.
pub pasted: Option<ClipContent>,
}
impl Fired {
/// `command` fired from `source` in `phase` at the input time `time`, for the app scope (no target), without a group
/// cycle or the Alt variant.
/// cycle, the Alt variant or paste content.
pub fn new(command: CommandRef, source: FireSource, phase: FirePhase, time: f64) -> Fired {
Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time }
Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time, pasted: None }
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
pub use crate::runtime::keys::Intents;
pub use craft_behavior::{Letters, Roving};
pub use policy::{ActivateKeys, EditSet, EndKey, EnterRule, FocusPolicy, FocusRequest, FocusTarget, Initial, KeepKeys, KeyUse, TabReach};
pub use policy::{ActivateKeys, EditSet, EndKey, EnterRule, FocusPolicy, FocusRequest, FocusTarget, Initial, KeepKeys, KeyUse, NudgeMods, TabReach};
/// The shape the focus ring takes around a part.
#[derive(Clone, Debug, PartialEq)]
+47 -1
View File
@@ -1,7 +1,7 @@
//! Focus scopes, key use and the programmatic focus target (spec 9.3, 9.4).
use craft_behavior::{CancelRule, DocKey, EditCommand, Input, OwnerClass, PartRef, ScopeKind};
use craft_keymap::Chord;
use craft_keymap::{Chord, Mods};
use egui::Id;
/// Where focus goes the first time a scope is pushed.
@@ -293,6 +293,10 @@ pub struct KeyUse {
/// The arrows are nudges for the component's content (a canvas tool or control), not moves: they arrive as
/// `Intents::take_nudge`.
pub nudge: bool,
/// The modifiers a document canvas (`chrome_key`) acts on with the arrows: while nothing in the window has the
/// focus, an arrow pressed with one of them is the canvas's nudge alone, and an arrow with any other is no nudge and
/// stays the app's shortcut (Alt+Left of a view history). A canvas lists what its tool and body act on.
pub nudge_mods: NudgeMods,
/// The component acts on Delete and Backspace (`Intent::Delete`: text edits, deleting a selection or a canvas
/// control's object). A component that does not leaves them to the commands around the focus; a canvas tool claims
/// them instead (`CanvasTool::claims`).
@@ -343,6 +347,7 @@ impl KeyUse {
moves: false,
chrome_key: true,
nudge: true,
nudge_mods: NudgeMods::STEPS,
deletes: false,
submits: false,
end: EndKey::LastItem,
@@ -384,6 +389,7 @@ impl KeyUse {
moves: false,
chrome_key: false,
nudge: false,
nudge_mods: NudgeMods::NONE,
deletes: owner_text,
submits: false,
end: EndKey::LastItem,
@@ -478,8 +484,48 @@ impl KeyUse {
self
}
/// The same use with `nudge_mods` as the modifiers a document canvas acts on with the arrows.
pub const fn with_nudge_mods(mut self, nudge_mods: NudgeMods) -> Self {
self.nudge_mods = nudge_mods;
self
}
/// Whether the component claims `chord`.
pub fn claims_chord(&self, chord: &Chord) -> bool {
self.claims.contains(chord)
}
}
/// A set of modifier combinations held with the arrows (`KeyUse::nudge_mods`): each is matched exactly, so Shift alone
/// does not admit Shift with Alt.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NudgeMods(u16);
impl NudgeMods {
/// No arrow.
pub const NONE: NudgeMods = NudgeMods(0);
/// The plain arrows and the arrows with Shift: the step and the large step every nudge reads.
pub const STEPS: NudgeMods = NudgeMods::NONE.with(Mods::NONE).with(Mods::SHIFT);
/// The same set with `mods` in it.
#[must_use]
pub const fn with(self, mods: Mods) -> Self {
NudgeMods(self.0 | Self::bit(mods))
}
/// Every combination of either set.
#[must_use]
pub const fn union(self, other: NudgeMods) -> Self {
NudgeMods(self.0 | other.0)
}
/// Whether `mods` is in the set.
pub const fn contains(self, mods: Mods) -> bool {
self.0 & Self::bit(mods) != 0
}
const fn bit(mods: Mods) -> u16 {
let at = (mods.cmd as u16) | ((mods.ctrl as u16) << 1) | ((mods.alt as u16) << 2) | ((mods.shift as u16) << 3);
1 << at
}
}
+7 -3
View File
@@ -44,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, pasted_text, queue_edit, routed_to, take_shortcuts};
pub(crate) use route::{activated_member, begin, focus_in_dialog, 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)]
@@ -103,8 +103,8 @@ 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.
/// With nothing focused, the window's document canvas took the press (a nudge it declares, `KeyUse::nudge_mods`,
/// 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,
}
@@ -118,6 +118,8 @@ pub(crate) struct Shortcuts {
pub(crate) dialog: bool,
/// The layout that reads the presses.
pub(crate) layout: Layout,
/// The content of a paste no focused component lists: the Paste command the keys fire carries it.
pub(crate) pasted: Option<ClipContent>,
}
/// What the input hook recorded for the next pass's begin hook.
@@ -129,6 +131,8 @@ struct Batch {
shortcuts: Vec<Shortcut>,
/// The content of the paste the focused component takes.
paste: Option<ClipContent>,
/// The content of a paste no focused component lists, for the command its chord fires (`Fired::pasted`).
app_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.
@@ -35,10 +35,11 @@ pub fn claim(ctx: &Context, owner: Id, chord: 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.
/// menu share one path. A menu pick returns focus in its pass before its command fires. With nothing focused the
/// window's document canvas stands for the focused component, as it takes the window's nudges
/// (`route::unfocused_canvas`). `false` when that 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 Some(rec) = crate::runtime::focus::focused_rec(ctx).or_else(|| super::route::unfocused_canvas(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| {
+7 -2
View File
@@ -143,9 +143,14 @@ impl Strip<'_> {
// 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, .. } => {
KeyEvent::Clip { command, pasted } => {
// 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.
// web sends the chord's press as well. A paste's content goes with the command the chord fires.
if let Some(pasted) = pasted.filter(|_| command == EditCommand::Paste) {
let content = batch.app_paste.get_or_insert_default();
content.text = pasted.text.or(content.text.take());
content.image = pasted.image.or(content.image.take());
}
let key = match command {
EditCommand::Cut => Key::X,
EditCommand::Paste => Key::V,
@@ -79,7 +79,10 @@ impl Intents {
}
}
/// Takes the next move.
/// Takes the next move, whichever it is: for a component that acts on every move. A move taken is the component's,
/// so the Page Up, Page Down, Home and End it takes never reach the scroll owner around it (a page view under a
/// focused page part); a component that acts on some moves takes those with [`take_move_where`](Self::take_move_where)
/// and leaves the rest.
pub fn take_move(&mut self) -> Option<(NavMove, MoveMods)> {
self.take_move_where(|_, _| true)
}
+23 -5
View File
@@ -35,6 +35,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
(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 canvas = if target.is_some() { None } else { unfocused_canvas(ctx) };
let stale_repeat = |stale: &mut bool, press: &Press| {
if press.key != Key::Enter || !press.mods.is_none() {
return false;
@@ -51,8 +52,6 @@ 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
@@ -90,12 +89,17 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
// 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. What the
// canvas takes is its alone, as while it has the focus: the app's shortcuts do not run with it too.
// canvas takes is its alone, as while it has the focus: the app's shortcuts do not run with it too. It takes the
// arrows with the modifiers it acts on (`KeyUse::nudge_mods`); the others are the app's.
let declared = |mods: Mods| canvas.as_ref().is_none_or(|canvas| canvas.stop.keys.nudge_mods.contains(mods));
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) {
} else if !modal
&& declared(press.mods)
&& let Some(nudge) = nudge_of(press.key, press.mods)
{
routed.entry(None).or_default().nudge = Some(nudge);
*taken = if canvas.is_some() { Taken::Canvas } else { Taken::Yes };
} else if let Some(canvas) = &canvas
@@ -184,6 +188,13 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
escapes
}
/// The window's document canvas as the key target of the running viewport while nothing has the focus: none while a
/// modal layer is open. It takes the window's nudges and page keys, and a fired command whose chord it claims, as it
/// does while it has the focus.
pub(super) fn unfocused_canvas(ctx: &Context) -> Option<StopRec> {
if overlay::any_open(ctx, overlay::OpenFilter::Modal) { None } else { focus::document_canvas(ctx) }
}
pub(super) fn push(routed: &mut HashMap<Option<Id>, Routed>, target: Option<Id>, intent: Intent, horizontal: bool) {
routed.entry(target).or_default().items.push(Item { intent, horizontal });
}
@@ -199,6 +210,13 @@ pub(crate) fn owner_at(ctx: &Context, target: Option<&StopRec>, scopes: &[Id], b
key_owner(layer == overlay::LayerKeys::Blocked, &present)
}
/// Whether the focused stop of the running viewport is in a dialog layer (`OwnerClass::Dialog`): Escape there is the
/// dialog's Cancel, which discards a field's draft with the rest of the dialog's edits, so a draft does not hold it.
pub(crate) fn focus_in_dialog(ctx: &Context) -> bool {
focus::focused_rec(ctx)
.is_some_and(|rec| overlay::key_layer(ctx, &focus::scope_chain(ctx, &rec), None) == overlay::LayerKeys::Class(OwnerClass::Dialog))
}
/// The shortcut events the key owner leaves to the app (9.3), and the presses the focused component holds
/// (`holds_press`). The owner is the focused component's class, or `Blocked` while a modal layer is stacked above the
/// focus; inside a layer its `Overlay.keys` class ranks with the component's. A `Recorder` keeps every key and a `Menu`
@@ -232,7 +250,7 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu
})
.copied()
.collect();
(Shortcuts { keys, typing, dialog, layout: Layout::default() }, held)
(Shortcuts { keys, typing, dialog, layout: Layout::default(), pasted: batch.app_paste.clone() }, held)
}
/// Whether the focused stop `target`, whose keys `owner` owns, holds `press`: the press is its own and reaches neither
@@ -5,6 +5,7 @@ mod env;
mod frame;
mod latch;
mod memory;
mod paste;
mod pen;
mod pointer;
mod wheel;
@@ -0,0 +1,24 @@
//! A paste the platform delivers as a clipboard event while no focused component lists Paste fires the app's Paste
//! command with the event's content, so the app pastes what the event held in the pass that runs the command.
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{Frames, trial};
use egui::{Event, Ui};
/// The content used to be dropped with the event, and the platform's offer of it lapsed a pass before the command ran,
/// so the app's paste found nothing.
#[trial]
fn an_app_paste_carries_the_content_of_its_clipboard_event() {
let mut frames = Frames::new();
let mut show = |_: &mut Ui| {};
frames.idle(2, &mut show);
take_output(&frames.ctx);
let mut pasted = Vec::new();
frames.frame(vec![Event::Paste("pasted words".into())], &mut show);
for _ in 0..2 {
pasted.extend(take_output(&frames.ctx).fired.into_iter().filter_map(|fired| fired.pasted?.text));
frames.idle(1, &mut show);
}
pasted.extend(take_output(&frames.ctx).fired.into_iter().filter_map(|fired| fired.pasted?.text));
assert_eq!(pasted.iter().map(|text| &**text).collect::<Vec<_>>(), ["pasted words"], "the Paste command carries the event's text, once");
}
@@ -799,3 +799,37 @@ fn a_typed_value_past_a_rows_range_is_clamped_and_the_host_takes_one_range_alert
assert_eq!(on_dialog(&host, |dialog| dialog.fields().int("size")).flatten(), Some(1), "text that is no number leaves the value");
assert!(!alert(), "and raises no alert");
}
/// Escape with the focus in a form's text field, plain or masked (a password), cancels the dialog at once, typed text or
/// not, as Escape does from any other control of the dialog: the dialog's Cancel discards the field's draft with the
/// rest, so the draft does not hold Escape (production closed its Protect dialog on one Escape after typing).
#[trial]
fn escape_in_a_text_field_closes_the_form_dialog_typed_or_not() {
for masked in [false, true] {
for typed in ["", "secret"] {
let open = Rc::new(Cell::new(true));
let closed = Rc::new(Cell::new(false));
let (shown, seen, value) = (Rc::clone(&open), Rc::clone(&closed), Rc::new(RefCell::new(String::new())));
let mut fixture = Fixture::new(move |ui| {
let mut is_open = shown.get();
let mut text = value.borrow_mut();
let out = craft_ui::patterns::form_dialogs::FormDialog::new("Protect", Bind::bound(&mut *text)).opened(Bind::bound(&mut is_open)).show(
ui,
|ui, _, text| {
let field = craft_ui::text::TextField::new("Type Password", Bind::bound(text));
let _ = if masked { field.masked() } else { field }.show(ui);
true
},
);
shown.set(is_open);
seen.set(seen.get() || out.closed.is_some());
});
fixture.idle(10);
let field = fixture.by_label("Type Password").expect("the field is shown");
fixture.click(&field).idle(2);
fixture.type_text(typed).idle(2);
fixture.key(Key::Escape, Modifiers::NONE).idle(6);
assert!(closed.get() && !open.get(), "Escape in the field closes the dialog (masked {masked}, typed {typed:?})");
}
}
}