mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
shell-w3: net change of 2 commits
- shell-w3: written by an agent - shell-w3: review fixes (review-1)
This commit is contained in:
1 parent
a1c3f13742
commit
ba91db2e7d
7 files changed
+368
-22
No files matched your search
@@ -671,6 +671,11 @@ impl Board {
|
||||
self.registry.get(&command.id).or_else(|| self.app.as_ref()?.get(command))
|
||||
}
|
||||
|
||||
/// Whether `command` is the frame's app catalog's own: no linked set defines it.
|
||||
fn from_catalog(&self, command: &CommandRef) -> bool {
|
||||
self.registry.get(&command.id).is_none() && self.app.as_ref().is_some_and(|app| app.get(command).is_some())
|
||||
}
|
||||
|
||||
/// The scope name of `command`; commands no definition names belong to the application.
|
||||
fn scope_of(&self, command: &CommandRef) -> &str {
|
||||
self.def(command).map_or(CommandScope::APP.name(), |def| def.scope.as_str())
|
||||
@@ -796,6 +801,8 @@ impl Board {
|
||||
let key = match declaring {
|
||||
Some(Declaration::Instance(id)) => self.numbers.get(command.id.as_str()).map(|&number| (number, Some(id))),
|
||||
Some(Declaration::Focused { .. }) => None,
|
||||
// The app's states (`CommandInput::states`) enable its catalog's commands; the instance only routes them.
|
||||
None if self.from_catalog(command) => self.state_key(command, None),
|
||||
None => self.state_key(command, instance),
|
||||
};
|
||||
// An app-scope state is the app's held one; an instance's is this frame's publish, else last frame's.
|
||||
@@ -998,6 +1005,10 @@ fn build_keymap(
|
||||
}
|
||||
let app_defs: Vec<CommandDef> =
|
||||
app.map(|app| app.defs().iter().filter(|def| registry.get(&def.command.id).is_none()).cloned().collect()).unwrap_or_default();
|
||||
// `AppCatalog::new` refuses a context scope, so an app def's scope is the app's or a panel's.
|
||||
for def in app_defs.iter().filter(|def| !def.scope.is_app()) {
|
||||
scopes = scopes.with_panel(def.scope.as_str());
|
||||
}
|
||||
// The window-shortcut yield and the edit chords below read the registry's definitions only.
|
||||
let joined = |defs: &[CommandDef]| -> Vec<CommandDef> { defs.iter().chain(&app_defs).cloned().collect() };
|
||||
let mut defs = registry.defs_for(platform);
|
||||
@@ -1771,7 +1782,14 @@ fn queue(ctx: &Context, fired: Fired) {
|
||||
crate::runtime::egui::clipboard::request_paste(ctx);
|
||||
return;
|
||||
}
|
||||
with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) });
|
||||
// An app catalog's command goes to the app (`FrameOutput.fired`), with the instance it was routed to as its target.
|
||||
let to_app = with(ctx, |board| fired.target.is_none() || board.from_catalog(&fired.command));
|
||||
// A command a chord fires at the app sees the focused field's typed text: its draft commits in this pass, before
|
||||
// the app reads it. A command the focused part or an instance takes itself keeps the draft; a release runs none.
|
||||
if to_app && fired.source == FireSource::Key && fired.phase != FirePhase::Release {
|
||||
focus::commit_focused(ctx);
|
||||
}
|
||||
with(ctx, |board| if to_app { board.out.push(fired) } else { board.queue.push(fired) });
|
||||
// A scoped entry is taken next pass, so the root viewport runs one.
|
||||
repaint::request_of(ctx, ViewportId::ROOT);
|
||||
}
|
||||
|
||||
@@ -59,9 +59,10 @@ use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Commands an app defines at run time (plug-ins, its tool list), all in the app scope ([`Scope::app`]). They join
|
||||
/// the linked command sets: their chords fire them into `FrameOutput.fired`, and surfaces resolve their label, icon,
|
||||
/// kind and chord. An id a linked set already defines stays that set's.
|
||||
/// Commands an app defines at run time (plug-ins, its tool list), each in the app scope ([`Scope::app`]) or in a panel
|
||||
/// scope. They join the linked command sets: their chords fire them into `FrameOutput.fired`, and surfaces resolve
|
||||
/// their label, icon, kind and chord. A panel-scope command fires only while the keyboard is inside a container whose
|
||||
/// `command_scope` is that scope. An id a linked set already defines stays that set's.
|
||||
#[derive(Clone)]
|
||||
pub struct AppCatalog {
|
||||
defs: Arc<[CommandDef]>,
|
||||
@@ -75,11 +76,12 @@ pub struct AppCatalog {
|
||||
|
||||
impl AppCatalog {
|
||||
/// A catalog of `defs`; `generation` changes when the app's rows do. Refuses two defs with one id (`Duplicate`) and a
|
||||
/// def in another scope (`NotApp`).
|
||||
/// def in a context scope, one a linked set holds by a momentary key or types in (`NotApp`): no instance carries a
|
||||
/// context scope, so the app could never fire it.
|
||||
pub fn new(defs: Vec<CommandDef>, generation: u64) -> Result<Self, CommandDefError> {
|
||||
let mut index = HashMap::with_capacity(defs.len());
|
||||
for (at, def) in defs.iter().enumerate() {
|
||||
if !def.scope.is_app() {
|
||||
if is_context_scope(&def.scope) {
|
||||
return Err(CommandDefError::NotApp { command: def.command.id.clone() });
|
||||
}
|
||||
registry::index_id(&mut index, &def.command.key_text(), at)?;
|
||||
@@ -127,8 +129,8 @@ impl AppCatalog {
|
||||
self.generation
|
||||
}
|
||||
|
||||
/// The catalog's rows in the order the app gave them, each with its scope (always [`Scope::app`]), kind and
|
||||
/// default bindings, as a shortcuts list reads them.
|
||||
/// The catalog's rows in the order the app gave them, each with its scope (the app scope or a panel scope), kind
|
||||
/// and default bindings, as a shortcuts list reads them.
|
||||
pub fn defs(&self) -> &[CommandDef] {
|
||||
&self.defs
|
||||
}
|
||||
@@ -140,6 +142,14 @@ impl AppCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `scope` is a context scope of a linked set: one its momentary commands hold or one it types in.
|
||||
fn is_context_scope(scope: &Scope) -> bool {
|
||||
let name = scope.as_str();
|
||||
registry::sets()
|
||||
.iter()
|
||||
.any(|set| set.typing.is_some_and(|typing| typing.name() == name) || (set.holds)().iter().any(|(_, held)| held.name() == name))
|
||||
}
|
||||
|
||||
/// A typed set of commands, written by `#[derive(CommandSet)]`.
|
||||
pub trait CommandSet: Copy + Send + Sync + 'static {
|
||||
/// The scope the set's commands belong to.
|
||||
|
||||
@@ -107,7 +107,7 @@ pub enum CommandDefError {
|
||||
/// The id.
|
||||
command: String,
|
||||
},
|
||||
/// An app command is defined in a scope other than the app's.
|
||||
/// An app command is not in the app scope or a panel scope: it names a linked set's held or typing scope.
|
||||
#[non_exhaustive]
|
||||
NotApp {
|
||||
/// The command's id.
|
||||
@@ -133,7 +133,7 @@ impl std::fmt::Display for CommandDefError {
|
||||
CommandDefError::Binding { command, error } => write!(f, "the default binding of {command}: {error}"),
|
||||
CommandDefError::Scope { command } => write!(f, "the scope of {command} is not a valid scope name"),
|
||||
CommandDefError::Duplicate { command } => write!(f, "two commands have the id {command}"),
|
||||
CommandDefError::NotApp { command } => write!(f, "the command {command} is not in the app scope"),
|
||||
CommandDefError::NotApp { command } => write!(f, "the command {command} is not in the app scope or a panel scope"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,10 @@ pub(crate) fn seen(ctx: &Context) -> Seen {
|
||||
}
|
||||
let (read, reading) = take_read(ctx, viewport);
|
||||
at_hand.extend(read);
|
||||
// The app reads the drop after this pass's components ran: the focused field's typed text commits first.
|
||||
if !at_hand.is_empty() {
|
||||
crate::runtime::focus::commit_focused(ctx);
|
||||
}
|
||||
Seen { hovered, dropped: at_hand, reading }
|
||||
}
|
||||
|
||||
|
||||
@@ -209,6 +209,11 @@ pub(crate) struct State {
|
||||
/// A text widget in a scope that gives focus back to its opener, held one more pass: the scope the Escape closes is
|
||||
/// closing by the next pass, and its restoration needs the widget to still hold the focus.
|
||||
surrender_deferred: Option<Id>,
|
||||
/// A commit of the focused draft asked for outside a pass or before this pass's focus stage (`commit_focused`);
|
||||
/// the next `begin` applies it once, after `PressState::rotate` cleared the last pass's.
|
||||
commit_requested: bool,
|
||||
/// This viewport's `begin` ran and its `end` has not: a commit asked for now applies to the running pass.
|
||||
in_pass: bool,
|
||||
}
|
||||
|
||||
fn viewport(ctx: &Context) -> ViewportId {
|
||||
@@ -1025,11 +1030,25 @@ pub(crate) fn commit_now(ctx: &Context) -> Option<Id> {
|
||||
}
|
||||
|
||||
/// Marks the focused text part's draft for commit in this pass: a command fired by a chord, a root close request or a
|
||||
/// file drop ends it as `End::Blur` before the app reads the pass's output.
|
||||
#[allow(dead_code)] // P3(shell-w3): sh.C10
|
||||
/// file drop ends it as `End::Blur` before the app reads the pass's output. Asked for before this pass's focus stage
|
||||
/// (the drop step) or between passes (the close hold), it applies in the next `begin`, so the first pass to run takes
|
||||
/// it once; asked for after it (the board's fire step), it applies at once.
|
||||
pub(crate) fn commit_focused(ctx: &Context) {
|
||||
let _ = ctx;
|
||||
todo!("sh.C10")
|
||||
with(ctx, |state| {
|
||||
if state.in_pass {
|
||||
commit_focused_stop(state);
|
||||
} else {
|
||||
state.commit_requested = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets `commit_now` to the focused stop when it is a text stop, as a press that leaves it does (`classify_press`),
|
||||
/// against the running pass's focus. A stop that is not text has no draft and nothing commits.
|
||||
fn commit_focused_stop(state: &mut State) {
|
||||
if let Some(rec) = state.stop_of_focus().filter(|rec| rec.stop.text) {
|
||||
state.press.commit_now = Some(rec.stop.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the component `owner` opened a layer that keeps the focus on it (a dropdown) and the layer is shown: its
|
||||
@@ -1122,6 +1141,11 @@ pub(crate) fn begin(ctx: &Context, tab_all_controls: bool, dialog_tab: TabReach)
|
||||
state.awaited = None;
|
||||
let host_focus = state.record.host_focus;
|
||||
let (acts, announcements) = nav::begin(state, input);
|
||||
state.in_pass = true;
|
||||
// After the press classification, which sets `commit_now` for a press only: a requested commit adds to it.
|
||||
if std::mem::take(&mut state.commit_requested) {
|
||||
commit_focused_stop(state);
|
||||
}
|
||||
(acts, announcements, host_focus)
|
||||
});
|
||||
// egui's direction (its arrows, a Tab the key stage left to egui) moves focus from the widget it holds when that is
|
||||
@@ -1202,6 +1226,7 @@ fn settle_given(ctx: &Context, app_widget: impl Fn(Id) -> bool) {
|
||||
/// moves it off a stop that was not registered, and records what the next input hook reads.
|
||||
pub(crate) fn end(ctx: &Context) {
|
||||
let viewport = viewport(ctx);
|
||||
with(ctx, |state| state.in_pass = false);
|
||||
take_app_widgets(ctx, None);
|
||||
report_undrawn_canvases(ctx);
|
||||
// A field held a pass for the scope it sits in lets go now, unless that scope is going away with focus in the field:
|
||||
|
||||
@@ -622,9 +622,11 @@ fn root_close_asked(ctx: &Context) -> bool {
|
||||
pass::current_viewport(ctx) == ViewportId::ROOT && viewports::current(ctx).close_requested && !viewports::close_cancelled(ctx)
|
||||
}
|
||||
|
||||
/// Keeps the root window open and brings it forward, so the app can ask before it closes.
|
||||
/// Keeps the root window open and brings it forward, so the app can ask before it closes. The focused field's typed
|
||||
/// text commits in the next pass, so the next close request finds the document modified.
|
||||
#[doc(hidden)]
|
||||
pub fn hold_close(ctx: &Context) {
|
||||
crate::runtime::focus::commit_focused(ctx);
|
||||
viewports::cancel_close(ctx);
|
||||
viewports::raise(ctx, ViewportId::ROOT);
|
||||
}
|
||||
|
||||
@@ -1,28 +1,33 @@
|
||||
//! A key press passes over a binding whose command is disabled where the press lands, and an app's catalog replaces
|
||||
//! or drops a linked set's default chords: in both cases the app's own binding of the chord runs. The case is a
|
||||
//! word processor's Alt+F7 (next misspelling) against the framework's `window.move` default, pressed inside a
|
||||
//! floating window.
|
||||
//! floating window. An app catalog's panel-scope commands fire only inside their scope, and a fired chord commits the
|
||||
//! focused draft first.
|
||||
|
||||
use craft_behavior::Input;
|
||||
use craft_behavior::{GesturePhase, Sense};
|
||||
use craft_behavior::{EditPolicy, GesturePhase, PartKey, PlainText, Sense};
|
||||
use craft_ui::contract::overlay::{PlacementChange, PlacementKind};
|
||||
use craft_ui::contract::{
|
||||
BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Overlay, Props as _, Role, Show as _,
|
||||
ShowContainer as _, Sizing,
|
||||
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, Edit as _, EditResponse, HeaderRegion, MeasureCx, Mount,
|
||||
Overlay, PartsCx, Props as _, Role, Show as _, ShowContainer as _, Sizing, Tracked,
|
||||
};
|
||||
use craft_ui::primitives::{TextKey, TextOptions};
|
||||
use craft_ui::runtime::commands::{
|
||||
AppCatalog, Binding, CommandDef, CommandInput, CommandSet, CommandState, Commands as _, Scope, TypingRule, WindowCommand,
|
||||
AppCatalog, Binding, CommandDef, CommandDefError, CommandInput, CommandScope, CommandSet, CommandState, CommandStates, Commands as _,
|
||||
EditCommands, FirePhase, Scope, TypingRule, WindowCommand,
|
||||
};
|
||||
use craft_ui::runtime::focus::{FocusTarget, KeyUse, request};
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::runtime::windows::{hold_close, root_close_requested};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::focus::{Stop, named_id, register_stop, widget};
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::layout::allocate;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
|
||||
use egui::{Event, Key, Modifiers, Pos2, Rect, Response, Ui, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use craft_ui_test_kit::windows::Windows;
|
||||
use egui::{Event, Id, Key, Modifiers, Pos2, Rect, Response, Ui, Vec2, ViewportEvent, ViewportInfo};
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
/// The app's command on Alt+F7.
|
||||
const SPELLING: &str = "chordTrial.spelling";
|
||||
@@ -219,3 +224,285 @@ fn a_press_on_a_chord_bound_only_to_a_disabled_command_reports_the_command() {
|
||||
assert_eq!(press_alt_f7(Focus::Inside, true, move_only()), (Vec::new(), moves, false), "the disabled Move is named and nothing runs");
|
||||
assert_eq!(press_alt_f7(Focus::Inside, false, move_only()), (Vec::new(), Vec::new(), true), "an enabled Move moves and is not named");
|
||||
}
|
||||
|
||||
/// The panel scope of the app's command on F8, as a node editor's canvas declares its own.
|
||||
const PANEL: CommandScope = CommandScope::new("chordTrial.panel");
|
||||
const PANEL_COMMAND: &str = "chordTrial.panelCommand";
|
||||
/// The scope `HoldCommand::Peek`'s held key makes work.
|
||||
const HELD: CommandScope = CommandScope::new("chordTrial.held");
|
||||
|
||||
/// A linked set whose scope is a typing scope: a context of the keymap, which no app def may sit in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::CommandSet)]
|
||||
#[command(prefix = "chordTyping", scope = "chordTrial.typing", typing)]
|
||||
#[non_exhaustive]
|
||||
enum TypingCommand {
|
||||
#[command(label = "Mark")]
|
||||
Mark,
|
||||
}
|
||||
|
||||
/// A linked set with a momentary command whose held key makes `HELD` work: a context of the keymap too.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::CommandSet)]
|
||||
#[command(prefix = "chordHold", scope = "chordTrial.holder")]
|
||||
#[non_exhaustive]
|
||||
enum HoldCommand {
|
||||
#[command(label = "Peek", kind = "momentary", holds = "chordTrial.held")]
|
||||
Peek,
|
||||
}
|
||||
|
||||
/// An inline container, an instance of the scope its props name.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(container)]
|
||||
struct Scoped {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
}
|
||||
|
||||
impl Component for Scoped {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = PlainStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: ScopedStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for Scoped {}
|
||||
|
||||
/// What F8 fires, command and phase, with the keyboard on the control inside the container of `PANEL` (`inside`) or
|
||||
/// on the one in a plain container beside it, under a catalog that binds F8 to `PANEL_COMMAND` in `PANEL`; with
|
||||
/// `disabled` the app's states disable the command.
|
||||
fn press_in_panel(inside: bool, disabled: bool) -> Vec<(String, FirePhase)> {
|
||||
let scope = PANEL.scope().expect("the trial's scope name is valid");
|
||||
let binding = Binding::parse("F8").expect("the trial's chord parses");
|
||||
let catalog =
|
||||
AppCatalog::new(vec![CommandDef::new(PANEL_COMMAND, "Panel command", scope).with_default(binding)], 1).expect("a panel-scope def is taken");
|
||||
let mut states = CommandStates::new();
|
||||
if disabled {
|
||||
states.set(PANEL_COMMAND, CommandState::new().enabled(false));
|
||||
}
|
||||
let (scoped, plain) = (RefCell::new(Seen::default()), RefCell::new(Seen::default()));
|
||||
let mut show = |ui: &mut Ui| {
|
||||
Scoped { common: Common::new(), props: ContainerProps::new().command_scope(PANEL) }.id_salt("scoped").show(ui, |ui, _| {
|
||||
Probe::new(&scoped).id_salt("in scope").size(BODY).sense(Sense::CLICK | Sense::FOCUS).show(ui);
|
||||
});
|
||||
Scoped { common: Common::new(), props: ContainerProps::new() }.id_salt("plain").show(ui, |ui, _| {
|
||||
Probe::new(&plain).id_salt("beside").size(BODY).sense(Sense::CLICK | Sense::FOCUS).show(ui);
|
||||
});
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.commands(CommandInput::new().catalog(catalog).states(&Tracked::new(states)));
|
||||
frames.idle(4, &mut show);
|
||||
let target = if inside { scoped.borrow().id } else { plain.borrow().id };
|
||||
request(&frames.ctx, FocusTarget::Id(target.expect("the probe showed")));
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(frames.ctx.memory(|memory| memory.focused()), target, "the probe has the focus");
|
||||
take_output(&frames.ctx);
|
||||
frames.frame(vec![key_press(Key::F8, Modifiers::NONE)], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
take_output(&frames.ctx).fired.into_iter().map(|fired| (fired.command.id, fired.phase)).collect()
|
||||
}
|
||||
|
||||
/// sh.C9: an app catalog's def in a panel scope fires only while the keyboard is inside a container of that scope,
|
||||
/// reaches the app as a press, and follows the app's state of it; a def in a linked set's held or typing scope is
|
||||
/// refused.
|
||||
#[trial]
|
||||
fn a_panel_scope_app_command_fires_only_while_the_keyboard_is_inside_its_container() {
|
||||
let pressed = vec![(PANEL_COMMAND.to_owned(), FirePhase::Press)];
|
||||
assert_eq!(press_in_panel(true, false), pressed, "inside its container F8 fires the panel command");
|
||||
assert_eq!(press_in_panel(false, false), Vec::new(), "in the plain container beside it F8 fires nothing");
|
||||
assert_eq!(press_in_panel(true, true), Vec::new(), "the app's state disables the panel command inside its container too");
|
||||
for context in [<TypingCommand as CommandSet>::SCOPE, HELD] {
|
||||
let def = CommandDef::new("chordTrial.contextual", "Contextual", context.scope().expect("the trial's scope name is valid"));
|
||||
assert!(
|
||||
matches!(AppCatalog::new(vec![def], 1), Err(CommandDefError::NotApp { .. })),
|
||||
"{}: a def in a linked set's context scope is refused",
|
||||
context.name()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's command on F9, a save.
|
||||
const SAVE: &str = "chordTrial.save";
|
||||
/// What the person types into the field before the save.
|
||||
const DRAFT: &str = "draft";
|
||||
const FIELD_TEXT: PartKey = PartKey::new("text");
|
||||
|
||||
/// A one-line text field over a string that keeps its typed text as a draft until the edit ends (`OnCommit`).
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Field<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Bind<'a, String>,
|
||||
}
|
||||
|
||||
impl Component for Field<'_> {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
const INPUT: Input = Input::Text;
|
||||
type Style = PlainStyle;
|
||||
type Output = EditResponse<String>;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: FieldStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(120.0, 24.0)
|
||||
}
|
||||
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect);
|
||||
cx.text(TextKey::<String>::new(FIELD_TEXT), rect, &PlainText, &shown, &TextOptions::default());
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, String>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// A draft field across a trial's frames: its value, the commits its output carried, and its id.
|
||||
#[derive(Default)]
|
||||
struct Draft {
|
||||
value: RefCell<String>,
|
||||
commits: RefCell<Vec<String>>,
|
||||
id: Cell<Option<Id>>,
|
||||
}
|
||||
|
||||
impl Draft {
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
let mut value = self.value.borrow_mut();
|
||||
let out = Field { common: Common::new(), value: Bind::bound(&mut *value).policy(EditPolicy::OnCommit) }.id_salt("draft").show(ui);
|
||||
self.commits.borrow_mut().extend(out.events.committed().cloned());
|
||||
self.id.set(Some(out.response.id));
|
||||
}
|
||||
|
||||
/// The typed text is still a draft: the field committed nothing.
|
||||
fn uncommitted(&self) -> bool {
|
||||
self.commits.borrow().is_empty() && self.value.borrow().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Focuses the draft field shown by `show` in `frames` and types `DRAFT` into it.
|
||||
fn type_draft(frames: &mut Frames, draft: &Draft, mut show: impl FnMut(&mut Ui)) {
|
||||
frames.idle(2, &mut show);
|
||||
request(&frames.ctx, FocusTarget::Id(draft.id.get().expect("the field showed")));
|
||||
frames.idle(2, &mut show);
|
||||
frames.frame(vec![Event::Text(DRAFT.into())], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
}
|
||||
|
||||
/// sh.C10: a command a chord fires, a held close of the root window and a file drop each commit the focused field's
|
||||
/// draft before the app reads them, as the press that leaves a field does.
|
||||
#[trial]
|
||||
fn a_chord_that_fires_a_command_commits_the_focused_text_draft_first() {
|
||||
// A chord: the firing frame runs a second pass, which neither fires nor commits again.
|
||||
let draft = Draft::default();
|
||||
let discard = Cell::new(false);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
draft.show(ui);
|
||||
if discard.take() {
|
||||
ui.ctx().request_discard("the firing frame runs twice");
|
||||
}
|
||||
};
|
||||
let binding = Binding::parse("F9").expect("the trial's chord parses");
|
||||
let save = CommandDef::new(SAVE, "Save", Scope::app()).with_default(binding);
|
||||
let catalog = AppCatalog::new(vec![save], 1).expect("the trial's catalog is taken");
|
||||
let mut frames = Frames::new();
|
||||
frames.commands(CommandInput::new().catalog(catalog));
|
||||
type_draft(&mut frames, &draft, &mut show);
|
||||
assert!(draft.uncommitted(), "the typed text is a draft before the chord");
|
||||
take_output(&frames.ctx);
|
||||
discard.set(true);
|
||||
let passes = frames.frame(vec![key_press(Key::F9, Modifiers::NONE)], &mut show);
|
||||
let fired: Vec<String> = take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect();
|
||||
assert!(passes > 1, "the firing frame ran a second pass");
|
||||
assert_eq!(fired, [SAVE], "the chord fired the save once");
|
||||
assert_eq!(*draft.commits.borrow(), [DRAFT], "the draft committed once, in the frame that fired the save");
|
||||
|
||||
// A close request the app holds, as `embed::logic` does before the UI: the commit lands by the frame after.
|
||||
let draft = Draft::default();
|
||||
let held = Cell::new(0);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
if root_close_requested(ui.ctx()) {
|
||||
hold_close(ui.ctx());
|
||||
held.set(held.get() + 1);
|
||||
}
|
||||
draft.show(ui);
|
||||
};
|
||||
let windows = Windows::new();
|
||||
for _ in 0..2 {
|
||||
windows.frame(Vec::new(), Vec::new(), &mut show);
|
||||
}
|
||||
request(&windows.ctx, FocusTarget::Id(draft.id.get().expect("the field showed")));
|
||||
for _ in 0..2 {
|
||||
windows.frame(Vec::new(), Vec::new(), &mut show);
|
||||
}
|
||||
windows.frame(vec![Event::Text(DRAFT.into())], Vec::new(), &mut show);
|
||||
windows.frame(Vec::new(), Vec::new(), &mut show);
|
||||
assert!(draft.uncommitted(), "the typed text is a draft before the close");
|
||||
windows.root_info(ViewportInfo { events: vec![ViewportEvent::Close], ..ViewportInfo::default() });
|
||||
windows.frame(Vec::new(), Vec::new(), &mut show);
|
||||
windows.root_info(ViewportInfo::default());
|
||||
windows.frame(Vec::new(), Vec::new(), &mut show);
|
||||
assert_eq!(held.get(), 1, "the app held the close once");
|
||||
assert_eq!(*draft.commits.borrow(), [DRAFT], "the held close committed the draft");
|
||||
|
||||
// A file drop: the drop step runs before the pass's focus stage, and the draft commits in the pass that reads it.
|
||||
let draft = Draft::default();
|
||||
let mut show = |ui: &mut Ui| draft.show(ui);
|
||||
let mut frames = Frames::new();
|
||||
type_draft(&mut frames, &draft, &mut show);
|
||||
assert!(draft.uncommitted(), "the typed text is a draft before the drop");
|
||||
let dropped = std::env::temp_dir().join("chord-trial-drop.txt").to_string_lossy().into_owned();
|
||||
frames.drop_files(&[dropped.as_str()]);
|
||||
frames.frame(Vec::new(), &mut show);
|
||||
assert_eq!(*draft.commits.borrow(), [DRAFT], "the draft committed in the pass that read the drop");
|
||||
|
||||
// A chord the focused field takes itself (Select All) is no command for the app: the draft stays.
|
||||
let draft = Draft::default();
|
||||
let mut show = |ui: &mut Ui| draft.show(ui);
|
||||
let mut frames = Frames::new();
|
||||
type_draft(&mut frames, &draft, &mut show);
|
||||
frames.frame(vec![key_press(Key::A, Modifiers::COMMAND)], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
assert!(draft.uncommitted(), "a chord the field takes itself leaves its draft uncommitted");
|
||||
}
|
||||
|
||||
/// The text the platform's paste event carries.
|
||||
const PASTED: &str = "pasted words";
|
||||
|
||||
/// The web sends a clipboard chord's key press and then the clipboard event for it, in one batch: the command runs
|
||||
/// once, and a paste carries the event's content.
|
||||
#[trial]
|
||||
fn a_web_press_and_its_clipboard_event_run_once() {
|
||||
let cases = [(Key::C, Event::Copy, EditCommands::Copy, None), (Key::V, Event::Paste(PASTED.into()), EditCommands::Paste, Some(PASTED))];
|
||||
for (key, clip, command, content) in cases {
|
||||
let mut frames = Frames::new();
|
||||
let mut show = |_: &mut Ui| {};
|
||||
frames.idle(2, &mut show);
|
||||
take_output(&frames.ctx);
|
||||
frames.frame(vec![key_press(key, Modifiers::COMMAND), clip], &mut show);
|
||||
frames.idle(1, &mut show);
|
||||
let fired: Vec<(String, Option<String>)> = take_output(&frames.ctx)
|
||||
.fired
|
||||
.into_iter()
|
||||
.map(|fired| (fired.command.id, fired.pasted.and_then(|pasted| pasted.text).map(|text| text.to_string())))
|
||||
.collect();
|
||||
let id = command.id().to_owned();
|
||||
assert_eq!(fired, [(id.clone(), content.map(str::to_owned))], "{id}: the press and its clipboard event run the command once");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user