diff --git a/crates/ui-contract/src/contract/editor.rs b/crates/ui-contract/src/contract/editor.rs index 9f02d6f89f..cc2e326eba 100644 --- a/crates/ui-contract/src/contract/editor.rs +++ b/crates/ui-contract/src/contract/editor.rs @@ -42,6 +42,7 @@ pub(crate) struct EditorInfo { pub purpose: EditorPurpose, pub focused: bool, pub read_only: bool, + pub disabled: bool, pub commit_now: bool, } @@ -117,12 +118,13 @@ fn run_core(core: &mut CxCore<'_>, ui: &mut Ui, step: &mut super::text::TextStep can }); } - core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only, commit_now: step.commit_now }); + let disabled = !core.resolved.enabled; + core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only, disabled, commit_now: step.commit_now }); core.editor_inputs = inputs; } -/// The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a -/// component reports through for the component's editor part. +/// The editor part's widget, rect, purpose, focus, read-only and disabled state of this pass, which a body that runs +/// inside a component reports through for the component's editor part. #[derive(Clone, Debug, PartialEq)] pub struct EditorHandle { widget: egui::Id, @@ -130,12 +132,20 @@ pub struct EditorHandle { purpose: EditorPurpose, focused: bool, read_only: bool, + disabled: bool, } impl EditorHandle { /// The handle of the editor part step 8b set up. fn of(info: &EditorInfo) -> EditorHandle { - EditorHandle { widget: info.widget, rect: info.rect, purpose: info.purpose, focused: info.focused, read_only: info.read_only } + EditorHandle { + widget: info.widget, + rect: info.rect, + purpose: info.purpose, + focused: info.focused, + read_only: info.read_only, + disabled: info.disabled, + } } /// Whether the editor part holds the key focus this pass, whether or not its window has the system's. @@ -204,7 +214,7 @@ impl EditorHandle { .collect(); let text = state.lines.iter().map(|line| line.text).collect::>().join("\n"); let selection = state.selection.or(Some((state.caret_at, state.caret_at))); - Some(TextFacts { widget: self.widget, text, masked, editable: !self.read_only, disabled: false, lines, selection }) + Some(TextFacts { widget: self.widget, text, masked, editable: !self.read_only, disabled: self.disabled, lines, selection }) } } diff --git a/crates/ui-contract/tests/it/text/disabled_access.rs b/crates/ui-contract/tests/it/text/disabled_access.rs new file mode 100644 index 0000000000..7743def8c0 --- /dev/null +++ b/crates/ui-contract/tests/it/text/disabled_access.rs @@ -0,0 +1,311 @@ +//! A disabled or read-only text field or editor lists no editing action and takes no edit through AccessKit, while a +//! read-only one still takes focus and a selection. An editing request sent to a disabled editor, on its own node or +//! on one of its text runs, does not reach it. + +use craft_behavior::{AccessAction, AccessData, PartKey, PlainText, Sense, TextPos}; +use craft_ui::contract::{ + Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, +}; +use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, TextKey, TextOptions}; +use craft_ui::runtime::focus::KeyUse; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::accesskit::{self, ActionRequest, NodeId, TreeId}; +use egui::{Event, Id, Rect, Response, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +const TEXT: PartKey = PartKey::new("text"); +const EDITOR: PartKey = PartKey::new("editor"); +const LINE: &str = "fn main"; + +/// One text part over a string. +#[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; + + 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::::new(TEXT), rect, &PlainText, &shown, &TextOptions::default()); + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// The AccessKit requests that reached an editor in its runs. +#[derive(Default)] +struct Seen { + requests: RefCell>, +} + +/// A code editor that reports one line, `LINE`, and keeps the AccessKit requests that reach it. +#[derive(craft_ui::contract::Component)] +struct Editor { + #[common] + common: Common, + seen: Rc, +} + +impl Component for Editor { + const ROLE: Role = Role::MULTILINE_TEXT_INPUT; + const INPUT: Input = Input::Editor; + const KEYS: KeyUse = KeyUse::CODE; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: EditorStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(200.0, 40.0) + } + + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { + cx.editor(EDITOR, rect, EditorPurpose::Code); + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + cx.editor_input().for_each(drop); + while let Some(request) = cx.intents().take_access() { + self.seen.requests.borrow_mut().push(request.action); + } + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let positions: Vec = (0..LINE.len()).map(|at| at as f32 * 8.0).collect(); + let widths = vec![8.0; LINE.len()]; + let runs = [EditorRun::new(0..LINE.len(), false, &positions, &widths)]; + let line = Rect::from_min_size(cx.content_rect.min, egui::vec2(cx.content_rect.width(), 16.0)); + let lines = [EditorLine::new(LINE, line, line.bottom(), &runs)]; + let caret = Rect::from_min_size(line.min, egui::vec2(0.0, 16.0)); + cx.editor_state(EditorState::new(caret, &lines, TextPos::new(0, 0))); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// How a component is shown. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Mode { + Enabled, + ReadOnly, + Disabled, +} + +impl Mode { + const ALL: [Mode; 3] = [Mode::Enabled, Mode::ReadOnly, Mode::Disabled]; + + fn enabled(self) -> bool { + self != Mode::Disabled + } + + fn read_only(self) -> bool { + self == Mode::ReadOnly + } +} + +/// The node `id` in the fixture's latest tree, hidden nodes included. +fn node(fixture: &Fixture, id: NodeId) -> Option { + fixture.tree().update().nodes.iter().find(|(at, _)| *at == id).map(|(_, node)| node.clone()) +} + +/// The first `TextRun` node below the node of `owner`. +fn first_run(fixture: &Fixture, owner: Id) -> NodeId { + let owner = node(fixture, owner.accesskit_id()).expect("the owner's node"); + owner + .children() + .iter() + .copied() + .find(|child| node(fixture, *child).is_some_and(|run| run.role() == accesskit::Role::TextRun)) + .expect("a text run below the owner") +} + +/// A request to send: what it is, the node it targets and its action. +type Case = (&'static str, fn(&Fixture, Id) -> NodeId, AccessAction); + +fn request(target: NodeId, action: AccessAction, data: Option) -> Vec { + vec![Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: target, data })] +} + +fn text(value: &str) -> Option { + Some(AccessData::Value(value.into())) +} + +/// What the node of a field or an editor says about itself: disabled, the edit actions it lists, and whether it lists +/// the selection and focus. +fn listing(fixture: &Fixture, id: Id) -> [bool; 5] { + let owner = node(fixture, id.accesskit_id()).expect("the component's node"); + [ + owner.is_disabled(), + owner.supports_action(AccessAction::SetValue), + owner.supports_action(AccessAction::ReplaceSelectedText), + owner.supports_action(AccessAction::SetTextSelection), + owner.supports_action(AccessAction::Focus), + ] +} + +/// The listing a node in `mode` has: only an enabled one edits, every one takes a selection, and only a disabled one +/// takes no focus. +fn listed(mode: Mode) -> [bool; 5] { + let edits = mode == Mode::Enabled; + [!mode.enabled(), edits, edits, true, mode.enabled()] +} + +/// A text field over `"Before"` in `mode`, with its value and the id of its response. +fn field(mode: Mode) -> (Fixture, Rc>, Id) { + let value = Rc::new(RefCell::new(String::from("Before"))); + let id = Rc::new(Cell::new(Id::NULL)); + let (held, seen) = (value.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut text = held.borrow_mut(); + let out = Field { common: Common::new(), value: Bind::bound(&mut *text) } + .label("Name") + .enabled(mode.enabled()) + .read_only(mode.read_only()) + .show(ui); + seen.set(out.response.id); + }); + fixture.settle(); + (fixture, value, id.get()) +} + +/// An editor in `mode`, with the requests that reach it and the id of its response. +fn editor(mode: Mode) -> (Fixture, Rc, Id) { + let seen = Rc::new(Seen::default()); + let id = Rc::new(Cell::new(Id::NULL)); + let (shown, at) = (seen.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let response = + Editor { common: Common::new(), seen: shown.clone() }.label("Source").enabled(mode.enabled()).read_only(mode.read_only()).show(ui); + at.set(response.id); + }); + fixture.settle(); + (fixture, seen, id.get()) +} + +#[trial] +fn a_text_field_edits_through_access_only_while_enabled_and_editable() { + let mut wrong = Vec::new(); + for mode in Mode::ALL { + let (fixture, _, id) = field(mode); + if listing(&fixture, id) != listed(mode) { + wrong.push(format!("{mode:?}: lists {:?}, not {:?}", listing(&fixture, id), listed(mode))); + } + let sends: [Case; 3] = [ + ("SetValue on the field", |_, id| id.accesskit_id(), AccessAction::SetValue), + ("SetValue on its text run", first_run, AccessAction::SetValue), + ("ReplaceSelectedText on the field", |_, id| id.accesskit_id(), AccessAction::ReplaceSelectedText), + ]; + for (what, target, action) in sends { + // What ReplaceSelectedText does to an enabled field is not checked here. + if mode == Mode::Enabled && action == AccessAction::ReplaceSelectedText { + continue; + } + let (mut fixture, value, id) = field(mode); + let target = target(&fixture, id); + fixture.frame(request(target, action, text("After"))).settle(); + let changed = *value.borrow() != "Before"; + let edits = mode == Mode::Enabled; + if changed != edits { + wrong.push(format!("{mode:?}: {what} changed the value to {:?}", value.borrow())); + } + } + if mode == Mode::ReadOnly { + let (mut fixture, _, id) = field(mode); + fixture.frame(request(id.accesskit_id(), AccessAction::Focus, None)).settle(); + if fixture.tree().focused_key().raw() != id.accesskit_id().0 { + wrong.push("ReadOnly: Focus did not focus the field".to_owned()); + } + let run = first_run(&fixture, id); + let selection = accesskit::TextSelection { + anchor: accesskit::TextPosition { node: run, character_index: 1 }, + focus: accesskit::TextPosition { node: run, character_index: 3 }, + }; + fixture.frame(request(id.accesskit_id(), AccessAction::SetTextSelection, Some(AccessData::SetTextSelection(selection)))).settle(); + let selected = fixture.tree().text_selection(id).map(|((_, anchor), (_, focus))| (anchor, focus)); + if selected != Some((1, 3)) { + wrong.push(format!("ReadOnly: SetTextSelection left the selection at {selected:?}")); + } + } + } + assert!(wrong.is_empty(), "a field lists and takes edits only while enabled and editable: {wrong:#?}"); +} + +#[trial] +fn an_editor_lists_edits_only_while_enabled_and_editable() { + let mut wrong = Vec::new(); + for mode in Mode::ALL { + let (mut fixture, _, id) = editor(mode); + if listing(&fixture, id) != listed(mode) { + wrong.push(format!("{mode:?}: lists {:?}, not {:?}", listing(&fixture, id), listed(mode))); + } + if mode == Mode::ReadOnly { + fixture.frame(request(id.accesskit_id(), AccessAction::Focus, None)).settle(); + if fixture.tree().focused_key().raw() != id.accesskit_id().0 { + wrong.push("ReadOnly: Focus did not focus the editor".to_owned()); + } + } + } + assert!(wrong.is_empty(), "an editor lists edits only while enabled and editable: {wrong:#?}"); +} + +#[trial] +fn a_disabled_editor_takes_no_edit_request_on_its_node_or_its_text_runs() { + let mut wrong = Vec::new(); + let sends: [Case; 4] = [ + ("SetValue on the editor", |_, id| id.accesskit_id(), AccessAction::SetValue), + ("ReplaceSelectedText on the editor", |_, id| id.accesskit_id(), AccessAction::ReplaceSelectedText), + ("SetValue on its text run", first_run, AccessAction::SetValue), + ("ReplaceSelectedText on its text run", first_run, AccessAction::ReplaceSelectedText), + ]; + for (what, target, action) in sends { + let (mut fixture, seen, id) = editor(Mode::Disabled); + let target = target(&fixture, id); + seen.requests.borrow_mut().clear(); + fixture.frame(request(target, action, text("After"))).settle(); + if seen.requests.borrow().contains(&action) { + wrong.push(what); + } + } + // The same request reaches an enabled editor, so the check above can see one arrive. + let (mut fixture, seen, id) = editor(Mode::Enabled); + let run = first_run(&fixture, id); + fixture.frame(request(run, AccessAction::ReplaceSelectedText, text("After"))).settle(); + assert!(seen.requests.borrow().contains(&AccessAction::ReplaceSelectedText), "the request reaches an enabled editor"); + assert!(wrong.is_empty(), "no edit request reaches a disabled editor: {wrong:#?}"); +} diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index a30a7cbd14..3d06b5eb6e 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod band; +pub(crate) mod disabled_access; pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo;