Merge branch 'sync/next' into sync/delta11

This commit is contained in:
bflatastic committed 2026-11-23 17:32:13 +07:00
commit 503ccd4cd9
29 files changed
+563 -60

No files matched your search

@@ -156,14 +156,15 @@ impl TransformRow {
}
}
/// What each field's running gesture began from, so every value it reports is made from that row.
/// What each field's running gesture began from, so every value it reports is made from that row and is read against
/// the start box of that moment: the row and the start box.
#[derive(Clone, Debug, Default)]
struct Bases([Option<(GestureId, TransformRow)>; 7]);
struct Bases([Option<(GestureId, TransformRow, Rect)>; 7]);
impl Bases {
/// The row the gesture `id` of `field` began from; `fallback` when it has no record.
fn origin(&self, field: TransformField, id: GestureId, fallback: &TransformRow) -> TransformRow {
self.0[field as usize].filter(|(of, _)| *of == id).map_or(*fallback, |(_, row)| row)
self.0[field as usize].filter(|(of, ..)| *of == id).map_or(*fallback, |(_, row, _)| row)
}
}
@@ -526,12 +527,15 @@ impl Cells<'_> {
fn field(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, pass: &mut Pass, field: TransformField, form: Form) {
let (side, name) = self.side_and_name(field, form);
let sizing = form.sizing();
let conversion = &pass.conversion;
// A running gesture of this field is shown the value it began from, read against the start box it began with:
// the host's write-back of the gesture's own values, or a start box it moves with them, must not look like the
// app changing the field under it.
let running = pass.bases.0[field as usize];
let began = running.map(|(.., rect)| Conversion { rect, ..pass.conversion.clone() });
let conversion = began.as_ref().unwrap_or(&pass.conversion);
let (kind, decimals) = conversion.format(field);
let bound = conversion.bound(field);
// A running gesture of this field is shown the value it began from: the host's write-back of the gesture's own
// values must not look like the app changing the field under it.
let basis = pass.bases.0[field as usize].map_or(pass.before, |(_, row)| row);
let basis = running.map_or(pass.before, |(_, row, _)| row);
let current = conversion.shown(&basis.state, basis.skew_v, field);
let codec = conversion.codec(&self.units, field);
let unit = Label::from(self.units.symbol(kind));
@@ -806,7 +810,7 @@ fn lift(
let slot = field as usize;
match event {
EditEvent::Begin { id, label, doc_key, .. } => {
bases.0[slot] = Some((id, *before));
bases.0[slot] = Some((id, *before, conversion.rect));
Some(EditEvent::begin(id, Mixed::Same(*before), label, doc_key))
}
EditEvent::Update { id, value: Some(value), .. } => {
+24
View File
@@ -262,3 +262,27 @@ fn typing_50_into_w_of_a_distorted_box_equals_typing_50_once_from_the_start_box(
let (a, b) = (once.row(), by_digit.row());
assert!(a.state.quad.iter().zip(&b.state.quad).all(|(p, q)| p.distance(*q) < 1e-6), "{a:?} {b:?}");
}
/// A host that passes the box as it is now as the start box, so the start box moves with a scrub's own values, keeps
/// the scrub running to its release: the field reads it against the start box it began with. Guards against a field
/// that read the running scrub's value against each pass's start box, so the host's write-back looked like an outside
/// change and cancelled it (`HostChanged`).
#[trial]
fn a_start_box_that_moves_with_a_scrub_keeps_the_scrub_running() {
let host = Rc::new(RefCell::new((TransformRow::new(BoxState::from_rect(START), 0.0), Vec::new())));
let shown = Rc::clone(&host);
let mut linked = true;
let mut fixture = Fixture::new(move |ui| {
let (row, events) = &mut *shown.borrow_mut();
let start = Rect::from_points(row.state.quad[0], row.state.quad[2]);
events.extend(TransformFields::new("Transform", Bind::bound(row), start, Bind::bound(&mut linked)).show(ui).events);
});
fixture.record_paint().settle();
let glyph = fixture.texts().iter().find(|painted| painted.text == "W").map(|painted| painted.rect.center()).expect("W's caption shows");
fixture.drag_at(glyph, egui::vec2(40.0, 0.0));
let (row, events) = &*host.borrow();
assert!(events.iter().any(|event| matches!(event, EditEvent::Update { .. })), "the scrub ran: {events:?}");
assert!(!events.iter().any(|event| matches!(event, EditEvent::Cancel { .. })), "the scrub was not cancelled: {events:?}");
assert!(events.iter().any(|event| matches!(event, EditEvent::Commit { .. })), "the release committed it: {events:?}");
assert!(row.state.quad[0].distance(row.state.quad[1]) > START.width(), "the scrub widened the box: {row:?}");
}
+11 -5
View File
@@ -1339,11 +1339,17 @@ impl StackDialog for HostedPrint {
self.preset_name = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.to_owned();
}
"preset" => {
let known =
|name: &str| self.presets.as_ref().is_some_and(|presets| presets.rows.iter().any(|row| !row.is_group() && row.key == name));
let name = value.as_str().filter(|name| known(name));
let name = name.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.preset_events.push(NamedPresetEvent::Apply(name.to_owned()));
// A row's key, else its name in any case ("proofs" applies the saved "Proofs").
let rows =
self.presets.as_ref().map(|presets| presets.rows.iter().filter(|row| !row.is_group()).collect::<Vec<_>>()).unwrap_or_default();
let key = value.as_str().and_then(|name| {
rows.iter()
.find(|row| row.key == name)
.or_else(|| rows.iter().find(|row| row.label.eq_ignore_ascii_case(name)))
.map(|row| row.key.clone())
});
let key = key.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.preset_events.push(NamedPresetEvent::Apply(key));
}
_ => {
let section =
+5 -1
View File
@@ -178,7 +178,8 @@ fn done_by_automation_and_the_sheet_step() {
assert_eq!(dialog.confirm(&ctx).map(|answer| answer.finish), ready.then_some(PrintFinish::Print), "the choice is used up");
}
/// A refused held OK keeps the dialog open with the reason, and a preset the row does not list is refused by name.
/// A refused held OK keeps the dialog open with the reason, and a preset the row does not list is refused by name. A
/// preset is named by its key or by its name in any case, and applies by its key.
#[trial]
fn a_refused_print_keeps_the_dialog_open_and_presets_are_named() {
let ctx = egui::Context::default();
@@ -194,6 +195,9 @@ fn a_refused_print_keeps_the_dialog_open_and_presets_are_named() {
assert!(dialog.set_json_field(&ctx, "preset", serde_json::json!("missing")).is_err());
dialog.set_json_field(&ctx, "preset", serde_json::json!("proof")).expect("a listed preset applies");
assert_eq!(dialog.take_preset_events(), vec![NamedPresetEvent::Apply("proof".to_owned())]);
dialog.set_presets(vec![PresetRow::item("saved-7".to_owned(), "Proofs", 0)], None, Vec::new());
dialog.set_json_field(&ctx, "preset", serde_json::json!("proofs")).expect("a preset named in another case applies");
assert_eq!(dialog.take_preset_events(), vec![NamedPresetEvent::Apply("saved-7".to_owned())], "by its row's key");
}
/// The sections layout of a hosted print dialog shows its list of sections beside the shown section, and a click on
@@ -43,6 +43,7 @@ pub(crate) mod hosting {
use crate::dialog::{DialogHost, DialogResult, FieldRefusal, HeldOk, StackDialog};
use crate::runtime::env::Label;
use crate::testing::access::AccessTree;
use crate::testing::focus::key_release;
use crate::testing::input::key_press;
use crate::testing::pointer::{click, moved, press, release};
use crate::testing::{Frames, trial};
@@ -109,7 +110,8 @@ pub(crate) mod hosting {
host.borrow_mut().open(workspace());
frames.idle(10, &mut ui);
assert!(dialog_bounds(&mut frames).is_some(), "a reopened workspace shows");
frames.frame(vec![key_press(Key::Escape, Modifiers::NONE)], &mut ui);
// Each round releases its Escape: a second press with no release between is a repeat.
frames.frame(vec![key_press(Key::Escape, Modifiers::NONE), key_release(Key::Escape, Modifiers::NONE)], &mut ui);
frames.idle(2, &mut ui);
assert_eq!(host.borrow_mut().take::<Hosted>(), Some(DialogResult::Cancel), "Escape cancels");
}
@@ -247,6 +247,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U
entry.parent = parent;
entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor);
entry.side = placed.side;
entry.asked = placed.asked;
entry.exiting = layer.exiting;
entry.cover = cover;
entry.region = layer.region;
@@ -325,6 +326,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut
entry.parent = parent;
entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor);
entry.side = placed.side;
entry.asked = placed.asked;
entry.exiting = layer.exiting;
entry.scoped = scope.is_some();
entry.absorbs = overlay.dismiss.outside == Outside::Absorb;
@@ -406,6 +408,7 @@ fn show_in_popup(
overlay::end_layer(&ctx);
let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, shown.rect, shown.layer);
entry.side = placed.side;
entry.asked = placed.asked;
entry.exiting = layer.exiting;
entry.cover = cover;
entry.scoped = scope.is_some();
@@ -256,6 +256,8 @@ pub(super) struct Placed {
pub(super) at: Pos2,
/// The side of the anchor an anchored layer took by its size; `None` while its size is unknown.
pub(super) side: Option<Side>,
/// The side the layer asked for when it took `side`.
pub(super) asked: Option<Side>,
/// The most the body may take from `at`: what the viewport leaves, within the fit's cap.
pub(super) room: egui::Vec2,
}
@@ -263,7 +265,7 @@ pub(super) struct Placed {
/// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect
/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its
/// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side
/// while it stays open and the content fits there or that side is the larger. A layer that `covers` its anchor
/// while it stays open, asks for the same side, and the content fits there or that side is the larger. A layer that `covers` its anchor
/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor.
/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so
/// the size it measures decides the side.
@@ -275,11 +277,12 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op
let kept = layer_bounds(layer, bounds);
let Some(size) = size else {
let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl);
return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, room };
return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, asked: None, room };
};
// The side taken in an earlier pass is the preferred one while the layer stays open: it stays while the
// content fits there or that side is the larger, so a size measured later (a body that grew) still flips it.
let taken = overlay::entry(ctx, layer.id).and_then(|entry| entry.side).unwrap_or(*side);
// The side taken in an earlier pass is the preferred one while the layer stays open and asks for the same side:
// it stays while the content fits there or that side is the larger, so a size measured later (a body that
// grew) still flips it. A host that asks for another side gets that side's placement.
let taken = overlay::entry(ctx, layer.id).filter(|entry| entry.asked == Some(*side)).and_then(|entry| entry.side).unwrap_or(*side);
let request = PlaceRequest::new(anchor, size, kept)
.side(taken)
.align(*align)
@@ -293,14 +296,14 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op
// The room is what the side the layer took leaves for a body as large as the cap, or for a layer that covers
// its anchor, what the bounds leave.
let room = craft_behavior::overlay::place(&request.kept(Some(placed.side)).size(cap)).rect.size();
Placed { at: placed.rect.min, side: Some(placed.side), room }
Placed { at: placed.rect.min, side: Some(placed.side), asked: Some(*side), room }
}
Place::Float(float) => {
let kept = within_bounds(layer.overlay, bounds);
let size = size.unwrap_or(egui::Vec2::ZERO);
let min = float.top_left(size).unwrap_or_else(|| kept.center() - size / 2.0);
let at = crate::contract::body::keep_inside(Rect::from_min_size(min, size), kept).min;
Placed { at, side: None, room: (kept.max - at).max(egui::Vec2::ZERO).min(cap) }
Placed { at, side: None, asked: None, room: (kept.max - at).max(egui::Vec2::ZERO).min(cap) }
}
}
}
@@ -330,6 +330,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) -> bool {
let (pass_nr, focused) = (pass::pass_nr(ctx, viewport), crate::runtime::focus::record(ctx, viewport).focused);
let frame = pass::frame_nr(ctx, viewport);
let blurred = input.events.iter().any(|event| matches!(event, Event::WindowFocused(false)));
let held = crate::runtime::frame::held_for(ctx, viewport, frame);
let mut wake = None;
let follow = Service::<Injected>::run(ctx, |injected| {
if blurred {
@@ -358,7 +359,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) -> bool {
return false;
}
}
if let Some(flight) = &lane.flight {
if let Some(flight) = &mut lane.flight {
if flight.pass < pass_nr {
if let (Some(until), Some(now)) = (flight.until, input.time)
&& now < until
@@ -366,6 +367,12 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut egui::RawInput) -> bool {
wake = Some(until - now);
return false;
}
// Events of the step that the frame it entered held back (behind a real press there, H0) arrive in this
// pass: the step's pass is this one too, so it acts for the client, and the next step waits for it.
if flight.step.events.iter().any(|event| held.contains(event)) {
flight.pass = pass_nr;
return !lane.queue.is_empty();
}
lane.flight = None;
} else if flight.focus != focused {
withdraw_flight(injected, viewport, &mut input.events);
@@ -63,6 +63,11 @@ impl HeldInput {
pub(crate) fn holds(&self) -> bool {
!self.events.is_empty()
}
/// The held events the frame `frame`'s input gets: none once that frame took them.
pub(crate) fn delivered_in(&self, frame: u64) -> Vec<Event> {
if self.frame == Some(frame) { Vec::new() } else { self.events.iter().map(|arrived| arrived.event.clone()).collect() }
}
}
/// H0: this pass carries at most one pointer press, as its last pointer event. Events after the first press
+5 -1
View File
@@ -164,6 +164,8 @@ pub(crate) struct State {
pub(super) seen: FastMap<Id, u64>,
/// A scope moved focus to its initial stop in the running pass.
pub(super) entered: bool,
/// A component asked for the focus in the running pass (`request`), as an editor that appears under a press does.
pub(super) asked: bool,
pub(crate) visible: bool,
pub(crate) record: FocusedRecord,
pub(super) menu_bar: Option<Id>,
@@ -693,13 +695,15 @@ pub(crate) fn register_doc(ctx: &Context, key: DocKey, id: Id) {
/// Moves focus to `target`, leaves modality unchanged and asks the enclosing scroll owner to reveal it. Called
/// while a pass runs, it moves focus in that pass, so the rest of the pass reads the new focus; called between
/// passes, it moves focus at the next pass's begin hook. The one public path to programmatic focus. `false` in a measuring
/// passes, it moves focus at the next pass's begin hook; a pointer press of the pass moves it no further at the pass's
/// end. The one public path to programmatic focus. `false` in a measuring
/// run, which moves nothing: a caller that keeps a pending request keeps it until a run takes it.
pub fn request(ctx: &Context, target: FocusTarget) -> bool {
if !crate::runtime::measure::effect(ctx, "focus::request") {
return false;
}
if crate::runtime::frame::in_pass(ctx) {
with(ctx, |state| state.asked = true);
request_now(ctx, target);
return true;
}
+4 -2
View File
@@ -125,6 +125,7 @@ impl State {
self.open.clear();
self.body_from.clear();
self.entered = false;
self.asked = false;
}
/// The registrations of last pass, which Tab and the arrows move over.
@@ -712,8 +713,9 @@ pub(super) fn end(state: &mut State, focused: Option<Id>, on_app_widget: bool, f
// The moves below belong to the next frame's passes.
state.frame = frame + 1;
let mut acts = state.apply_press(focused, on_app_widget);
// A layer that appeared in this pass took focus already: the press that opened it does not take it back.
if state.entered {
// A layer that appeared in this pass took focus already, and a component that asked for it in this pass has it: the
// press of the pass does not take it back.
if state.entered || state.asked {
acts.clear();
}
if acts.is_empty() {
+7
View File
@@ -644,6 +644,12 @@ pub(crate) fn holds_input(ctx: &Context, viewport: ViewportId) -> bool {
PerViewport::<ViewportRecord>::with(ctx, viewport, |record| record.held.holds())
}
/// The events the one-press rule (H0) or the key stage held that the frame `frame` of `viewport` gets, read in its
/// input hook before H0 hands them on.
pub(crate) fn held_for(ctx: &Context, viewport: ViewportId, frame: u64) -> Vec<egui::Event> {
PerViewport::<ViewportRecord>::with(ctx, viewport, |record| record.held.delivered_in(frame))
}
/// The input hook: egui runs it before it pushes the viewport, so every step reads only `RawInput` and
/// records keyed by `input.viewport_id`.
pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
@@ -664,6 +670,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
// H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. The events sent
// to the focus are counted first, before the IME and key stages take theirs.
keys::count_sent(ctx, viewport, &events);
keys::note_ime_presses(ctx, viewport, &events);
ime::input_hook(ctx, &mut events, viewport);
let (stripped, later) = keys::input_hook(ctx, input, &mut events);
if !later.is_empty() {
+5 -1
View File
@@ -33,7 +33,7 @@ pub use input::held;
#[doc(hidden)]
pub use input::keyed;
pub use input::textless_paste;
pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, stirred, take_menu_keys, take_nav};
pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, note_ime_presses, queue_nav, sent, stirred, take_menu_keys, take_nav};
pub use intents::Intents;
#[doc(hidden)]
pub use intents::intents_of;
@@ -89,6 +89,8 @@ struct Press {
place: usize,
/// The keys down when it went down, itself not among them: what a nudge reads as held with its arrow.
held: Vec<Key>,
/// An input method committed text right after it: the press typed that text, which a text stop takes.
ime: bool,
}
/// An arrow press as a nudge of content: its unit direction, its modifiers and the keys down when it went down.
@@ -294,6 +296,8 @@ pub(crate) struct Stage {
textless_paste: bool,
/// How many inputs of the viewport held an event sent to the focus (`count_sent`).
sent: u64,
/// The key presses of this input that an input method's commit follows (`note_ime_presses`).
ime_presses: Vec<egui::Event>,
/// The keys whose press the strip took and whose release it is still to drop.
consumed: Vec<Key>,
shortcuts: Shortcuts,
+125 -23
View File
@@ -63,7 +63,51 @@ struct Strip<'a> {
bound: &'a dyn Fn(&Chord) -> bool,
}
/// How the strip reads one raw event beside its key reading: when it arrived, and what its neighbours say of it.
#[derive(Clone, Copy)]
struct Arrival {
/// The event's arrival time (`Arrived::at`).
at: Option<f64>,
/// An input method's commit follows the event: a press it follows typed through the input method.
ime_next: bool,
/// A key press follows the event: a text before it is that press's (the web sends a press's text first).
press_next: bool,
}
/// The key a typed `text` stands for: one character that names a key, or the US base key of a shifted character no key
/// names (`~` is typed on Backtick).
fn text_key(text: &str) -> Option<Key> {
let mut chars = text.chars();
let (Some(c), None) = (chars.next(), chars.next()) else { return None };
Key::from_char(c).or(match c {
'~' => Some(Key::Backtick),
_ => None,
})
}
/// The chord a clipboard event of `command` stands for with `mods` held: Cmd and the command's key, with the modifiers
/// held beside Cmd (Cmd+Shift+V pastes in place).
fn clip_chord(command: EditCommand, mods: Mods) -> (Key, KeyInput) {
let key = match command {
EditCommand::Cut => Key::X,
EditCommand::Paste => Key::V,
_ => Key::C,
};
let mut chord_mods = mods;
chord_mods.cmd = true;
(key, KeyInput::new(chord_mods).with_typed(key))
}
impl Strip<'_> {
/// Whether a clipboard event of `command` with `mods` held is the focused editor's edit: the platform sends it for
/// the edit's own chord, and for Cmd with Shift or Alt too (Cmd+Shift+X), which is another chord, the app's, unless
/// the editor lists that chord for the edit.
fn clip_is_edit(&self, command: EditCommand, mods: Mods) -> bool {
let (_, input) = clip_chord(command, mods);
!((mods.cmd || mods.ctrl) && (mods.shift || mods.alt))
|| self.edit_chords.iter().any(|(edit, chord)| *edit == command && self.layout.matches(chord, &input, self.os))
}
/// Whether the text the platform sends with the press `input` stands for is a shortcut's own and belongs to no
/// field: Alt is held and the keymap binds the press to a command that is enabled, so it fires (S-L177). A platform
/// sends its key's text with an Alt shortcut (Alt+Q on Linux). A bound Alt chord whose command is disabled does
@@ -77,9 +121,10 @@ impl Strip<'_> {
/// Records `event` in `batch` and returns whether egui keeps it.
///
/// `consumed` holds the keys whose press the strip took and whose release has not come yet: the release goes
/// with the press, in this pass or a later one. `down` holds the keys down before the event. `at` is the event's
/// arrival time (`Arrived::at`).
fn event(&self, batch: &mut Batch, alt: &mut AltTrack, consumed: &mut Vec<Key>, down: &[Key], event: KeyEvent, at: Option<f64>) -> bool {
/// with the press, in this pass or a later one. `down` holds the keys down before the event; a press of a key
/// already down is a repeat, as egui reads it, whatever the platform said.
fn event(&self, batch: &mut Batch, alt: &mut AltTrack, consumed: &mut Vec<Key>, down: &[Key], event: KeyEvent, arrival: Arrival) -> bool {
let at = arrival.at;
if matches!(event, KeyEvent::Clip { .. }) {
// A clipboard event stands for its chord's press, which types nothing.
batch.last_press = None;
@@ -87,10 +132,12 @@ impl Strip<'_> {
match event {
KeyEvent::Press { key, input, repeat } => {
alt.other_key = true;
let repeat = repeat || input.physical.or(input.typed).is_some_and(|held| down.contains(&held));
let pushed = batch.presses.len();
let claims = batch.claimed.len();
let menu_keys = batch.menu.len();
let shortcut_text = self.shortcut_text(&input);
// Text an input method commits for the press is typing, whatever the press's chord binds.
let shortcut_text = self.shortcut_text(&input) && !arrival.ime_next;
let kept = self.press(batch, key, &input, repeat, at);
// The canvas's Space keeps its text from every field, as a claim does.
let canvas = batch.presses.get(pushed).is_some_and(|press| press.canvas);
@@ -103,6 +150,7 @@ impl Strip<'_> {
// The release key is kept for withheld presses too: the held-over rule matches repeats by it.
if let Some(press) = batch.presses.get_mut(pushed) {
press.release = input.physical.or(input.typed);
press.ime = arrival.ime_next;
press.held = down.iter().copied().filter(|key| Some(*key) != press.release).collect();
if kept {
press.in_egui = Some(batch.egui_presses);
@@ -137,7 +185,8 @@ impl Strip<'_> {
KeyEvent::Text(text) => {
alt.other_key = true;
let mut claimed = false;
if let Some(last) = batch.last_press.take() {
let last = batch.last_press.take();
if let Some(last) = &last {
if let Some(physical) = last.input.physical.filter(|_| !alt.right) {
batch.learned.push((physical, last.input.mods, text.clone()));
}
@@ -146,12 +195,13 @@ impl Strip<'_> {
press.text = Some(batch.texts.len());
}
}
claimed |= self.text_as_key(batch, last.as_ref(), &text, alt, arrival);
// Every text stays for now: the begin hook's routing decides which reader gets it (`route::begin`).
batch.texts.push(Typed { text, claimed, in_egui: Some(batch.egui_texts), place: batch.place });
batch.egui_texts += 1;
true
}
KeyEvent::Clip { command, text, .. } if (self.edits)(command) => {
KeyEvent::Clip { command, text, mods } if (self.edits)(command) && self.clip_is_edit(command, mods) => {
batch.clips.push((command, batch.place));
if text.is_some() {
batch.paste = text;
@@ -162,20 +212,13 @@ impl Strip<'_> {
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,
KeyEvent::Clip { command, mods, .. } => {
// The platform sends the clipboard event in place of the chord: an unlisted one is the chord, with the
// modifiers held beside Cmd (Cmd+Shift+V pastes in place). The web sends the chord's press as well.
let key = match command {
EditCommand::Cut => Key::X,
EditCommand::Paste => Key::V,
_ => Key::C,
};
let mut chord_mods = mods;
chord_mods.cmd = true;
let input = KeyInput::new(chord_mods).with_typed(key);
// 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.
let (key, input) = clip_chord(command, mods);
let sent = batch
.shortcuts
.iter()
.any(|shortcut| shortcut.phase == FirePhase::Press && shortcut.input.mods == chord_mods && shortcut.input.typed == Some(key));
.any(|shortcut| shortcut.phase == FirePhase::Press && shortcut.input.mods == input.mods && shortcut.input.typed == Some(key));
if !sent && self.records {
// A component that reads every chord gets the event as the chord's press, the way the key made it.
self.press(batch, key, &input, false, at);
@@ -216,6 +259,40 @@ impl Strip<'_> {
}
}
/// Reads a one-character `text` as a press of the key it stands for (`text_key`) where no press typed it. A text
/// with no press before it (`last`) or after it is a tap of that key with the held modifiers, which a claim takes or
/// the shortcut dispatcher reads (Shift+~ arrives as `~` alone). A text Alt typed with a press no claim took is its
/// key's for a claim (Option+8 types `[` on a Turkish Mac). Cmd and Ctrl chords type nothing, and the Alt that typed
/// the character is no part of its key's chord. Returns whether a claim or a mnemonic took the text.
fn text_as_key(&self, batch: &mut Batch, last: Option<&LastPress>, text: &str, alt: &AltTrack, arrival: Arrival) -> bool {
let Some(key) = text_key(text) else { return false };
let lone = last.is_none() && !arrival.press_next;
let mods = match last {
None if lone => alt.last.unwrap_or(Mods::NONE),
Some(last) if !last.claimed && last.input.mods.alt => last.input.mods,
_ => return false,
};
if mods.cmd || mods.ctrl {
return false;
}
let input = KeyInput::new(Mods { alt: false, ..mods }).with_typed(key);
if !lone {
let PressUse::Claimed(chord) = self.use_of(key, &input) else { return false };
batch.claimed.push(chord);
return true;
}
let (pushed, claims, menu_keys) = (batch.presses.len(), batch.claimed.len(), batch.menu.len());
self.press(batch, key, &input, false, arrival.at);
if let Some(press) = batch.presses.get_mut(pushed) {
press.text = Some(batch.texts.len());
// The tap has no release event: it ends where it began.
if !press.canvas {
batch.shortcuts.push(Shortcut { input, phase: FirePhase::Release, press: None, canvas: false, at: arrival.at, place: batch.place });
}
}
batch.claimed.len() > claims || batch.menu.len() > menu_keys
}
/// A lone Alt press, pressed and released with no other key, pointer press, wheel turn, touch or Shift, Ctrl or Cmd
/// between, goes to the tool that claims it on every OS, else focuses the menu bar off a Mac (9.7). In a field that
/// holds drafts it only alerts, so the draft keeps its focus (L-52). A release that ended an Alt+numpad code is no
@@ -323,6 +400,7 @@ impl Strip<'_> {
canvas: true,
place: batch.place,
held: Vec::new(),
ime: false,
});
if !repeat {
batch.shortcuts.push(Shortcut {
@@ -359,6 +437,7 @@ impl Strip<'_> {
canvas: false,
place: batch.place,
held: Vec::new(),
ime: false,
});
false
}
@@ -389,6 +468,7 @@ impl Strip<'_> {
canvas: false,
place: batch.place,
held: Vec::new(),
ime: false,
});
if !repeat {
batch.shortcuts.push(Shortcut {
@@ -469,17 +549,18 @@ pub(super) fn focused_claims(record: &focus::FocusedRecord, stage: &Stage) -> Ve
///
/// A modal or dialog layer never toggles: Tab moves focus inside it. In a window with a canvas the toggle is on when
/// nothing is focused, the canvas is, or a press focused a component other than a text field, as clicking a panel's row
/// and pressing Tab hides the panels in Photoshop. Tab moves focus from a text field however it got the focus (Tab
/// and pressing Tab hides the panels in Photoshop; read-only text a press focused to select from (a stop only a press
/// reaches, a label's selection part) is no text field. Tab moves focus from a text field however it got the focus (Tab
/// commits a typed value and goes to the next field) and from a component the keyboard or a request focused. Elsewhere
/// it is on only when the canvas is focused. A component that keeps Tab never reaches this function: the press is its
/// own.
fn tab_toggles_chrome(enabled: bool, canvas: bool, layer: overlay::LayerKeys, focused: Option<&KeyUse>, pressed: bool) -> bool {
fn tab_toggles_chrome(enabled: bool, canvas: bool, layer: overlay::LayerKeys, focused: Option<&focus::Stop>, pressed: bool) -> bool {
let closed = matches!(layer, overlay::LayerKeys::Blocked | overlay::LayerKeys::Class(OwnerClass::Dialog));
if !enabled || closed {
return false;
}
let on_canvas = focused.is_some_and(|keys| keys.chrome_key);
let pressed_control = pressed && focused.is_some_and(|keys| keys.owner != OwnerClass::Text);
let on_canvas = focused.is_some_and(|stop| stop.keys.chrome_key);
let pressed_control = pressed && focused.is_some_and(|stop| stop.keys.owner != OwnerClass::Text || stop.press_only);
if canvas { focused.is_none() || on_canvas || pressed_control } else { on_canvas }
}
@@ -492,7 +573,7 @@ pub(super) fn tab_toggles_now(ctx: &Context) -> bool {
let canvas = focus::canvas_keys(ctx, viewport).is_some();
let layer = overlay::key_layer(ctx, &focused.as_ref().map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(), None);
let pressed = focused.as_ref().is_some_and(|rec| focus::origin(ctx, rec) == Some(focus::FocusOrigin::Press));
tab_toggles_chrome(enabled, canvas, layer, focused.as_ref().map(|rec| &rec.stop.keys), pressed)
tab_toggles_chrome(enabled, canvas, layer, focused.as_ref().map(|rec| &rec.stop), pressed)
}
/// Whether `chord` is the key of a chrome command (`ChromeCommand`), as the window's keymap binds it.
@@ -585,6 +666,10 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
stage.stirred = false;
stage.textless_paste = false;
let mut place = 0;
let ime_presses = std::mem::take(&mut stage.ime_presses);
let press_next: Vec<bool> = (0..events.len())
.map(|at| matches!(events.get(at + 1).map(|arrived| &arrived.event), Some(egui::Event::Key { pressed: true, .. })))
.collect();
events.retain(|arrived| {
// Every event the IME engine left counts, as the engine counts them (`ime::take_placed`).
batch.place = place;
@@ -606,7 +691,12 @@ pub(crate) fn input_hook(ctx: &Context, input: &RawInput, events: &mut Vec<Arriv
};
let down = stage.down.clone();
note_down(&mut stage.down, &read);
strip.event(&mut batch, &mut stage.alt, &mut stage.consumed, &down, read, arrived.at)
let arrival = Arrival {
at: arrived.at,
ime_next: ime_presses.contains(&arrived.event),
press_next: press_next.get(batch.place).copied().unwrap_or(false),
};
strip.event(&mut batch, &mut stage.alt, &mut stage.consumed, &down, read, arrival)
});
for (physical, mods, text) in std::mem::take(&mut batch.learned) {
stage.layout.observe(physical, mods, &text);
@@ -650,6 +740,18 @@ pub(crate) fn claims_press(ctx: &Context, input: &RawInput) -> impl Fn(&egui::Ev
}
}
/// Notes the key presses of `events` that an input method's commit follows, before the IME stage takes the commits out
/// of the input: the key stage reads such a press as typing through the input method (`Press::ime`).
pub(crate) fn note_ime_presses(ctx: &Context, viewport: ViewportId, events: &[Arrived]) {
let commit = |event: &egui::Event| matches!(event, egui::Event::Ime(egui::ImeEvent::Commit(text)) if !text.is_empty());
let presses = events
.windows(2)
.filter(|pair| matches!(pair[0].event, egui::Event::Key { pressed: true, .. }) && commit(&pair[1].event))
.map(|pair| pair[0].event.clone())
.collect();
with(ctx, viewport, |stage| stage.ime_presses = presses);
}
/// Updates the keys held after `event`: a press adds its key, a release removes it, and the window losing focus
/// (which also reads as the right Alt coming up) forgets them all, since their releases go to another window.
fn note_down(down: &mut Vec<Key>, event: &KeyEvent) {
+6 -1
View File
@@ -257,7 +257,11 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu
.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])))
.map(|(press, taken)| {
// Text an input method committed for the press goes to the text stop that has the IME.
let typed = press.text.is_some_and(|at| taken_texts[at]) || (press.ime && target.is_some_and(|rec| rec.stop.text));
!press.canvas && holds_press(owner, target, press, *taken == Taken::Yes, typed)
})
.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.
@@ -374,6 +378,7 @@ pub fn focus_holds(ctx: &Context, chord: Chord) -> bool {
canvas: false,
place: 0,
held: Vec::new(),
ime: false,
};
let driven = Driven::of(ctx, &rec);
let route = press_route(ctx, crate::runtime::windows::os_of(ctx), &rec, &press, driven.or_else(|| list_of_field(ctx, &rec)));
@@ -157,6 +157,8 @@ pub struct OpenEntry {
pub rect: Rect,
/// The side of the anchor it took by its size; `None` for a float and while its size is unknown.
pub side: Option<Side>,
/// The side its host asked for when it took `side`: a later pass keeps `side` only while the host asks for the same.
pub(crate) asked: Option<Side>,
/// It is fading out: not `top`, not counted by `any_open`, taking no input.
pub exiting: bool,
/// The layer's egui id and the cover under it, listed in the order.
@@ -217,6 +219,7 @@ impl OpenEntry {
peers: Vec::new(),
rect,
side: None,
asked: None,
exiting: false,
layer,
cover: None,
@@ -9,7 +9,7 @@ use crate::runtime::focus::{EditSet, FocusPolicy, FocusTarget, KeepKeys, KeyUse,
use crate::runtime::frame::{ChromeToggle, take_output};
use crate::runtime::keys::with_window_intents;
use crate::style::{ComponentStyle, StyleCx};
use crate::testing::focus::{Stop, egui_focused, named_id, pop_scope, push_scope, register_stop, widget};
use crate::testing::focus::{Stop, egui_focused, key_release, named_id, pop_scope, push_scope, register_stop, widget};
use crate::testing::input::{key_press, key_reached, slop};
use crate::testing::pointer::{self, moved, press, release};
use crate::testing::sensing::{self, ProbeRoot};
@@ -44,8 +44,9 @@ fn seen(host: &RefCell<Host>) -> (Vec<Key>, usize) {
(std::mem::take(&mut host.reached), std::mem::take(&mut host.cancels))
}
/// A press of `key` and its release, in one frame: a second press with no release between is a repeat.
fn press_key(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), key: Key) {
frames.frame(vec![key_press(key, Modifiers::NONE)], &mut *show);
frames.frame(vec![key_press(key, Modifiers::NONE), key_release(key, Modifiers::NONE)], &mut *show);
}
/// A window with a framework button and the host's own egui text field, with what the host saw.
@@ -660,7 +661,7 @@ fn a_window_shortcut_runs_from_a_pane_title_and_not_from_a_modal_dialog_or_a_tex
// The ids of the commands a press of the shortcut's key fired.
let fired = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| -> Vec<String> {
take_output(&frames.ctx);
frames.frame(vec![key_press(Key::Q, Modifiers::NONE)], &mut *show);
frames.frame(vec![key_press(Key::Q, Modifiers::NONE), key_release(Key::Q, Modifiers::NONE)], &mut *show);
frames.frame(Vec::new(), &mut *show);
take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect()
};
+25 -2
View File
@@ -5,7 +5,7 @@ use crate::runtime::env::RootEnv;
use crate::runtime::focus::{FocusTarget, KeyUse, request};
use crate::runtime::frame::{ChromeToggle, take_output};
use crate::runtime::keys::{focus_holds, intents_of, take_shortcuts};
use crate::testing::focus::{Stop, egui_focused, named_id, press_shape, register_stop, widget};
use crate::testing::focus::{Stop, egui_focused, key_release, named_id, press_shape, register_stop, widget};
use crate::testing::input::{key_press, key_repeat};
use crate::testing::pointer::click;
use crate::testing::{Frames, trial};
@@ -51,8 +51,9 @@ fn shown(enabled: bool, show: &mut impl FnMut(&mut Ui)) -> Frames {
frames
}
/// A press of `key` with `modifiers` and its release, in one frame: a second press with no release between is a repeat.
fn press(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), key: Key, modifiers: Modifiers) -> Vec<(ViewportId, ChromeToggle)> {
frames.frame(vec![key_press(key, modifiers)], &mut *show);
frames.frame(vec![key_press(key, modifiers), key_release(key, modifiers)], &mut *show);
take_output(&frames.ctx).chrome_toggles
}
@@ -139,6 +140,28 @@ fn tab_moves_focus_from_a_pressed_text_field() {
assert_ne!(egui_focused(&frames.ctx), Some(id("field")), "focus left the field");
}
/// Read-only text a press focused to select from (a label's selection part, a stop only a press reaches) is no text
/// field: Tab toggles the panels from it, as from any pressed control. Guards against a toggle that read every stop of
/// the text class as a field that keeps Tab for the next field.
#[trial]
fn tab_toggles_from_pressed_read_only_text() {
let at = Rc::new(Cell::new(Rect::NOTHING));
let seen = Rc::clone(&at);
let mut show = move |ui: &mut Ui| {
let rect = widget(ui, id("label"));
register_stop(ui.ctx(), Stop::new(id("label"), KeyUse::of(Input::Text)).press_only());
press_shape(ui, rect, Sense::CLICK | Sense::TAKE_FOCUS, id("label"));
seen.set(rect);
stop(ui, "canvas", KeyUse::CANVAS);
};
let mut frames = shown(true, &mut show);
click(&mut frames, at.get().center(), &mut show);
take_output(&frames.ctx);
assert_eq!(egui_focused(&frames.ctx), Some(id("label")), "the press focused the text");
assert_eq!(press(&mut frames, &mut show, Key::Tab, Modifiers::NONE), [(ViewportId::ROOT, ChromeToggle::Panels)], "pressed read-only text");
assert_eq!(egui_focused(&frames.ctx), Some(id("label")), "the toggle moved no focus");
}
#[trial]
fn tab_in_a_window_without_a_canvas_moves_focus() {
let mut show = without_canvas;
@@ -295,3 +295,29 @@ fn a_float_places_its_corner_at_the_position() {
}
}
}
/// An anchored layer that stays open takes the side its host asks for now: asked for End after Above, it hangs at the
/// anchor's end; asked for Above again, it sits above. Guards against a layer that kept the side an earlier pass took
/// while it stayed open, whatever side the host asked for since.
#[trial]
fn an_open_layer_takes_the_side_its_host_asks_for_now() {
let anchor = Rect::from_min_size(Pos2::new(200.0, 300.0), Vec2::new(40.0, 20.0));
let (shown, asked, log, seen) = (Cell::new(Rect::NOTHING), Cell::new(Side::Above), RefCell::new(Vec::new()), RefCell::new(Seen::default()));
let mut show = |ui: &mut Ui| {
let overlay = Overlay::popover().place(Place::anchored(Anchor::Rect(anchor), asked.get(), Align::Start));
let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content);
let out = Pane { common: Common::new(), props, log: &log }.id_salt("bar").show(ui, |ui, _| {
Probe::new(&seen).size(Vec2::new(60.0, 20.0)).show(ui);
});
shown.set(out.output.rect);
};
let mut frames = Frames::new();
frames.idle(4, &mut show);
assert!(shown.get().bottom() <= anchor.top() + SLACK, "asked for Above, the layer sits above: {:?}", shown.get());
asked.set(Side::End);
frames.idle(4, &mut show);
assert!(shown.get().left() >= anchor.right() - SLACK, "asked for End, the layer hangs at the anchor's end: {:?}", shown.get());
asked.set(Side::Above);
frames.idle(4, &mut show);
assert!(shown.get().bottom() <= anchor.top() + SLACK, "asked for Above again, the layer sits above: {:?}", shown.get());
}
@@ -45,3 +45,32 @@ fn a_removed_stop_hands_its_focus_to_no_neighbour_and_the_body_stays() {
assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), None, "no neighbour inherits the focus");
assert!((top.get() - start).abs() < 0.5, "the body keeps its offset: content top {} from {start}", top.get());
}
/// A component that asks for the focus in the pass of a press on another component keeps it: the press's own focus
/// move at the pass's end does not take it back, as a text editor that appears under a click on the canvas and asks
/// for the keys keeps them. Guards against the end hook's press move overriding every request of the pass but a
/// layer's that appeared in it.
#[trial]
fn a_request_in_a_press_pass_keeps_the_focus_from_the_press() {
use craft_behavior::{Input, Sense};
use craft_ui::runtime::focus::KeyUse;
use craft_ui::testing::focus::{Stop, egui_focused, named_id, press_shape, register_stop, widget};
let (canvas, editor) = (named_id("press_canvas"), named_id("press_editor"));
let at = Cell::new(Rect::NOTHING);
let mut show = |ui: &mut Ui| {
let ctx = ui.ctx().clone();
let rect = widget(ui, canvas);
register_stop(&ctx, Stop::new(canvas, KeyUse::CANVAS));
press_shape(ui, rect, Sense::CLICK | Sense::TAKE_FOCUS, canvas);
at.set(rect);
widget(ui, editor);
register_stop(&ctx, Stop::new(editor, KeyUse::of(Input::Text)));
if ctx.input(|input| input.pointer.primary_pressed()) {
request(&ctx, FocusTarget::Id(editor));
}
};
let mut frames = Frames::new();
frames.idle(2, &mut show);
craft_ui::testing::pointer::click(&mut frames, at.get().center(), &mut show);
assert_eq!(egui_focused(&frames.ctx), Some(editor), "the request of the press's pass holds");
}
@@ -15,6 +15,7 @@ pub(crate) mod memory;
pub(crate) mod pen;
pub(crate) mod pointer;
pub(crate) mod theme_app;
pub(crate) mod typed_keys;
pub(crate) mod wheel;
pub(crate) mod window_move;
pub(crate) mod windows;
@@ -356,6 +356,31 @@ fn a_rerun_pass_delivers_none_of_the_frames_input_again() {
assert!(log[0].stirred && log[0].injected && !log[1].stirred && !log[1].injected, "the first pass carries the input");
}
/// An injected step that enters a frame behind a real pointer press waits for the next frame (one press per pass), and
/// the pass that carries it acts for the automation client. Guards against a step whose flight ended with the frame it
/// entered, so the pass its text arrived in read as the user's (`injected_pass` false).
#[trial]
fn an_injected_step_held_behind_a_press_arrives_in_an_injected_pass() {
let log: Rc<RefCell<Vec<(bool, bool)>>> = Rc::default();
let sink = log.clone();
let mut show = move |ui: &mut Ui| {
let ctx = ui.ctx().clone();
let typed = ctx.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Text(text) if text == "x")));
sink.borrow_mut().push((typed, craft_ui::runtime::windows::WindowHost::of(&ctx).injected_pass()));
};
let mut frames = Frames::new();
frames.idle(2, &mut show);
craft_ui::runtime::windows::WindowHost::of(&frames.ctx).inject_text(egui::ViewportId::ROOT, "x");
log.borrow_mut().clear();
let at = Pos2::new(20.0, 20.0);
frames.frame(vec![pointer::moved(at), pointer::press(at)], &mut show);
frames.frame(vec![pointer::release(at)], &mut show);
frames.idle(2, &mut show);
let log = log.borrow();
let carrying: Vec<bool> = log.iter().filter(|(typed, _)| *typed).map(|(_, injected)| *injected).collect();
assert_eq!(carrying, [true], "one pass carries the text, and it is the client's: {log:?}");
}
fn downs(phases: &[PressPhase]) -> usize {
phases.iter().filter(|phase| matches!(phase, PressPhase::Down { .. })).count()
}
@@ -0,0 +1,132 @@
//! What the key stage makes of the events that carry text or a chord without a plain press of their own: a text with
//! no press, a press an input method typed through with Alt, a second press of a held key, and a clipboard event with
//! Shift held. Each trial binds the window's Toggle Panels command to the chord under test and
//! reads whether it ran.
use craft_behavior::{EditCommand, Input};
use craft_keymap::{Chord, Key as ChordKey, Mods, Overrides};
use craft_ui::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _};
use craft_ui::runtime::focus::{FocusTarget, KeyUse, request};
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::focus::{Stop, intents_of, key_release, named_id, register_stop, widget};
use craft_ui::testing::input::{key_press, text};
use craft_ui::testing::{Frames, trial};
use egui::{Event, ImeEvent, Key, Modifiers, Ui};
use std::cell::RefCell;
use std::sync::Arc;
/// What the window's text field read in a pass: the texts egui's input held for it and the edits routed to it.
#[derive(Default)]
struct Field {
typed: Vec<String>,
edits: Vec<EditCommand>,
}
/// Frames of a window with a document canvas and a text field, whose Toggle Panels command is bound to `chord` alone.
fn frames_for(chord: Chord) -> Frames {
let mut overrides = Overrides::default();
overrides.insert(ChromeCommand::TogglePanels.id(), vec![chord.to_string()]);
let mut frames = Frames::new();
frames.commands(CommandInput::new().overrides(Arc::new(overrides)));
frames
}
/// The window's pass: the canvas and the field, which records what it read into `field`.
fn window(field: &RefCell<Field>) -> impl FnMut(&mut Ui) + '_ {
move |ui: &mut Ui| {
let (canvas, id) = (named_id("typed_canvas"), named_id("typed_field"));
widget(ui, canvas);
register_stop(ui.ctx(), Stop::new(canvas, KeyUse::CANVAS));
widget(ui, id);
register_stop(ui.ctx(), Stop::new(id, KeyUse::of(Input::Text)).text());
let mut field = field.borrow_mut();
ui.input(|input| {
field.typed.extend(input.events.iter().filter_map(|event| match event {
Event::Text(text) => Some(text.clone()),
_ => None,
}))
});
let mut intents = intents_of(ui.ctx(), Some(id), false);
while let Some(edit) = intents.take_edit() {
field.edits.push(edit);
}
}
}
/// Runs one frame of `events` and returns whether the bound command ran, clearing what the field read before it.
fn ran(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), field: &RefCell<Field>, events: Vec<Event>) -> bool {
*field.borrow_mut() = Field::default();
frames.frame(events, &mut *show);
!take_output(&frames.ctx).chrome_toggles.is_empty()
}
/// Settles the window with the field focused, or nothing focused.
fn settle(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), focus_field: bool) {
frames.idle(2, &mut *show);
if focus_field {
request(&frames.ctx, FocusTarget::Id(named_id("typed_field")));
frames.idle(2, &mut *show);
}
take_output(&frames.ctx);
}
/// A text with no key press (Shift+~ arrives as `~` alone) runs the shortcut of the key it stands for with the held
/// modifiers, and a focused field types it instead. Guards against a key stage that read such a text as typing only,
/// so no shortcut and no claim ever saw it.
#[trial]
fn a_text_with_no_press_is_a_press_of_its_key() {
let field = RefCell::new(Field::default());
let mut frames = frames_for(Chord::new(Mods::SHIFT, ChordKey::Backtick));
let mut show = window(&field);
settle(&mut frames, &mut show, false);
assert!(ran(&mut frames, &mut show, &field, vec![Event::ModifiersChanged(Modifiers::SHIFT), text("~")]), "`~` alone ran Shift+`");
let mut frames = frames_for(Chord::new(Mods::SHIFT, ChordKey::Backtick));
settle(&mut frames, &mut show, true);
assert!(!ran(&mut frames, &mut show, &field, vec![Event::ModifiersChanged(Modifiers::SHIFT), text("~")]), "the field's typing");
assert_eq!(field.borrow().typed, ["~"], "the focused field types it");
}
/// A press of a key that is down already is a repeat, whatever the platform says: it runs no shortcut again. Guards
/// against a key stage that read the repeat flag from the raw event only.
#[trial]
fn a_second_press_of_a_held_key_runs_no_shortcut_again() {
let field = RefCell::new(Field::default());
let mut frames = frames_for(Chord::plain(ChordKey::S));
let mut show = window(&field);
settle(&mut frames, &mut show, false);
assert!(ran(&mut frames, &mut show, &field, vec![key_press(Key::S, Modifiers::NONE)]), "the first press runs the command");
assert!(!ran(&mut frames, &mut show, &field, vec![key_press(Key::S, Modifiers::NONE)]), "a second press with S still down is a repeat");
frames.frame(vec![key_release(Key::S, Modifiers::NONE)], &mut show);
assert!(ran(&mut frames, &mut show, &field, vec![key_press(Key::S, Modifiers::NONE)]), "a press after the release runs it again");
}
/// In a focused field, a bound Alt chord that an input method types through (its commit follows the press) is typing:
/// the field takes the commit and the command does not run. With its key's text the press runs the command. Guards
/// against a key stage that ran the command and let the input method's text through as well.
#[trial]
fn an_alt_chord_an_input_method_types_through_runs_no_command() {
let field = RefCell::new(Field::default());
let mut frames = frames_for(Chord::new(Mods::ALT, ChordKey::G));
let mut show = window(&field);
settle(&mut frames, &mut show, true);
let alt_g =
|then: Event| vec![Event::ModifiersChanged(Modifiers::ALT), key_press(Key::G, Modifiers::ALT), then, key_release(Key::G, Modifiers::ALT)];
assert!(ran(&mut frames, &mut show, &field, alt_g(text("g"))), "with its key's text the press runs the command");
assert!(!ran(&mut frames, &mut show, &field, alt_g(Event::Ime(ImeEvent::Commit("ğ".into())))), "an input method's commit is typing");
}
/// A Cut with Cmd and Shift held is Cmd+Shift+X, the app's chord, not the focused field's Cut; a plain Cmd+X Cut stays
/// the field's. Guards against a key stage that gave every clipboard event to a field that lists the edit, whatever
/// the modifiers.
#[trial]
fn a_cut_with_shift_held_is_the_apps_chord() {
let field = RefCell::new(Field::default());
let mut frames = frames_for(Chord::new(Mods { shift: true, ..Mods::CMD }, ChordKey::X));
let mut show = window(&field);
settle(&mut frames, &mut show, true);
let shifted = vec![Event::ModifiersChanged(Modifiers::COMMAND | Modifiers::SHIFT), Event::Cut];
assert!(ran(&mut frames, &mut show, &field, shifted), "Cmd+Shift+X ran its command");
assert!(field.borrow().edits.is_empty(), "the field cut nothing: {:?}", field.borrow().edits);
assert!(!ran(&mut frames, &mut show, &field, vec![Event::ModifiersChanged(Modifiers::COMMAND), Event::Cut]), "Cmd+X runs no command");
assert_eq!(field.borrow().edits, [EditCommand::Cut], "a plain Cut is the field's");
}
@@ -557,8 +557,9 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
let accepts = Cell::new(ok_enabled);
let body_pick = Cell::new(false);
let shown = dialog.show(ui, |ui, cx| {
// A measuring run sees no answers and no opening pass: the real run that follows still has both.
let measuring = measuring_run;
// A measuring run sees no answers and no opening pass: the real run that follows still has both. The dialog
// measures its body in a run of its own too (a re-layout under a child dialog), inside a real run of the form.
let measuring = measuring_run || crate::runtime::measure::active(ui.ctx());
let first = cx.appeared() && !measuring;
let mut held = bind.borrow_mut();
let before = match held.reborrow().read(cx) {
@@ -383,9 +383,15 @@ fn show_rows(ui: &mut Ui, input: &RowsInput<'_>, state: &mut Session, env: &crat
Some(Line::Entry(at)) if state.stamp == stamp => Some(at),
_ => None,
};
let fresh = state.stamp != stamp;
state.stamp = stamp;
let suggested = input.suggested.map(|(_, commands)| commands.as_slice());
let listed = layout(input, &state.query, suggested, active_before);
// A new query's active row is its first match, enabled or not: Enter on a disabled one runs nothing, and the footer
// says why, rather than Enter running the next match.
if fresh {
state.selection.lead = listed.keys.iter().copied().find(|key| matches!(key, Line::Entry(_)));
}
let heading = input.suggested.map(|(label, _)| env.resolve(label).as_str().to_owned()).unwrap_or_default();
let fallback_text = input.fallback.map(|template| template.fill(&[("text", found.as_str())])).unwrap_or_default();
let rows = row_data(input.ctx, input.entries, &listed.keys, &heading, &fallback_text, env);
@@ -400,3 +400,24 @@ fn four_up_webp_halves_the_quality_until_lossless() {
let [half, quarter] = four_up_options(&host);
assert_eq!((half.format, quarter.format), (WebFormat::Png8, WebFormat::Gif));
}
/// A palette answer that arrives as the child dialog that picked it closes and the room changes, so the dialog measures
/// its body again before it runs it, still shifts the opened entry. Guards against a body that took the host's answers
/// in whichever run of the pass came first: the measuring run used the answer up and the real run reported nothing.
#[trial]
fn a_palette_answer_survives_a_measuring_run_of_the_body() {
use craft_ui::dialog::{Alert, HostedAlert};
let (host, mut fixture) = open(HostedSaveForWeb::new("poster.psd", IMAGE, texture()).options(gif(8)));
show_palette(&host, &mut fixture);
let cell = fixture.by_label("1 #00ff00").expect("the Color Table lists the palette");
fixture.click(&cell).key(Key::Enter, Modifiers::NONE).idle(4);
let (id, _) = host.borrow_mut().take_color_request().expect("opening a cell asks for its colour");
let picker = host.borrow_mut().open_child(HostedAlert::new(Alert::new("Color Picker", "Pick a colour.")), id);
fixture.idle(4);
host.borrow_mut().close_by_id(picker);
host.borrow_mut().answer_color(id, PALETTE_COLOR_KEY, Srgba::rgb(1.0, 0.0, 1.0));
fixture.room(Vec2::new(1000.0, 700.0));
fixture.idle(4);
let shift = (ColorTableEdit::Shift([255, 0, 255]), vec![[0, 255, 0]]);
assert_eq!(table_events(&host), vec![shift], "the answer shifts the opened entry's colour");
}
@@ -502,3 +502,22 @@ fn the_active_row_marks_its_shown_control_and_a_hidden_home_goes_to_the_footer()
rig.fixture.settle();
assert_eq!(painted(&rig.fixture, "Toolbox"), 2, "the footer names the home of a command shown nowhere");
}
/// Enter on a query whose first match is disabled runs nothing, though an enabled match follows it: the first match is
/// the active row, the one the footer explains. Guards against an active row that skipped the disabled first match, so
/// Enter ran the match after it.
#[trial]
fn enter_on_a_disabled_first_match_runs_nothing() {
let entries = vec![HelpEntry::new(EditCommands::Undo, "Undo").with_path(["Edit"]), HelpEntry::new(TrialCommand::Rotate, "Undo Rotation")];
let (mut fixture, open, picked) = palette(entries, false);
fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false));
fixture.settle();
fixture.type_text("undo").settle();
let listed = rows(&fixture);
assert!(listed.len() == 2 && listed[0].0.starts_with("Undo") && listed[0].1 && !listed[1].1, "the disabled Undo matches first: {listed:?}");
let _ = take_output(fixture.ctx());
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*picked.borrow(), None, "Enter on the disabled first match picks nothing");
assert!(open.get(), "the palette stays open");
assert!(take_output(fixture.ctx()).fired.is_empty(), "nothing ran");
}
+5 -2
View File
@@ -4,6 +4,7 @@ use craft_ui::runtime::commands::{CommandState, Commands as _, EditCommands, Fir
use craft_ui::runtime::focus::{FocusTarget, request};
use craft_ui::runtime::frame::take_output;
use craft_ui::runtime::measure::chord_texts;
use craft_ui::testing::focus::key_release;
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Frames, trial};
@@ -73,10 +74,12 @@ fn an_enclosing_scopes_shortcut_beats_the_applications() {
let mut frames = Frames::new();
frames.idle(3, &mut show);
focus_on(&mut frames, tap.get().unwrap(), &mut show);
frames.frame(vec![key_press(Key::J, Modifiers::COMMAND | Modifiers::ALT)], &mut show);
// Each press is released: a second press with no release between is a repeat.
let chord = || vec![key_press(Key::J, Modifiers::COMMAND | Modifiers::ALT), key_release(Key::J, Modifiers::COMMAND | Modifiers::ALT)];
frames.frame(chord(), &mut show);
assert_eq!((closed.get(), take_output(&frames.ctx).fired.len()), (1, 0), "the dock takes it");
focus_on(&mut frames, outside.get().unwrap(), &mut show);
frames.frame(vec![key_press(Key::J, Modifiers::COMMAND | Modifiers::ALT)], &mut show);
frames.frame(chord(), &mut show);
assert_eq!((closed.get(), ids(&take_output(&frames.ctx).fired)), (1, vec!["trial.jump"]), "outside the dock the application's command fires");
}
@@ -40,3 +40,34 @@ fn the_fields_of_a_grid_column_share_a_left_edge() {
assert!((second.left() - fourth.left()).abs() <= 0.5, "the filling column's fields share a left edge: {second:?}, {fourth:?}");
assert!(first.right() <= second.left() && third.right() <= fourth.left(), "the sized column holds its fields: {rects:?}");
}
/// A filling column, then one sized by its cells.
static FILL_FIRST: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content];
/// A grid row is as tall as a field in it whose label stacks above its control for want of room: the next row's label
/// starts below the control. Guards against a grid that spaced its rows as if the label sat beside the control, so the
/// next row's label overlapped it.
#[trial]
fn a_grid_row_holds_a_field_whose_label_stacks() {
let rects: Rc<RefCell<Vec<Rect>>> = Rc::default();
let seen = rects.clone();
let mut fixture = Fixture::new(move |ui| {
let mut seen = seen.borrow_mut();
seen.clear();
Grid::new(&FILL_FIRST).show(ui, |ui, _| {
for i in 0..2 {
Field::new(format!("Top Left Corner {i}")).show(ui, |ui, _| {
seen.push(NumberField::new(format!("Radius {i}"), Bind::given(Some(10.0))).show(ui).response.rect);
});
craft_ui::display::Text::new("Round").show(ui);
}
});
});
fixture.room(egui::vec2(150.0, 400.0)).record_paint();
fixture.settle();
let rects = rects.borrow();
let [first, _] = rects[..] else { panic!("two fields show: {rects:?}") };
let label = fixture.texts().iter().find(|text| text.text == "Top Left Corner 1").map(|text| text.rect).expect("the second label shows");
assert!(label.bottom() <= rects[1].top() + 0.5, "the label stacks above its control: {label:?}, {:?}", rects[1]);
assert!(label.top() >= first.bottom() - 0.5, "the second row starts below the first row's control: {label:?}, {first:?}");
}