From 57b7c457f3cd51593009a3eee4d2b39bfe6daa7b Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 14:03:47 +0000 Subject: [PATCH] canvas-w2: net change of 3 commits - canvas-w2: finished by an agent - canvas-w2: finished by an agent - canvas-w2: review fixes (review-1) --- crates/ui-contract/src/contract/editor.rs | 121 +++--- .../ui-contract/src/runtime/egui/fixture.rs | 10 + crates/ui-contract/src/runtime/egui/ime.rs | 9 +- crates/ui-contract/src/runtime/ime.rs | 187 +++++++-- crates/ui-contract/tests/it/text/editor.rs | 375 ++++++++++++++++-- 5 files changed, 598 insertions(+), 104 deletions(-) diff --git a/crates/ui-contract/src/contract/editor.rs b/crates/ui-contract/src/contract/editor.rs index 60683312d..9591077a4 100644 --- a/crates/ui-contract/src/contract/editor.rs +++ b/crates/ui-contract/src/contract/editor.rs @@ -6,6 +6,7 @@ use super::Component; use super::cx::{Cx, Edit as _, PartsCx}; use crate::primitives::{EditorPurpose, EditorState, ImeStamp, ImeSurface}; use crate::runtime::access::text::{self as text_access, Line, Run, TextFacts}; + use crate::runtime::egui::{editor as egui_editor, focus as egui_focus}; use crate::runtime::focus::KeyUse; use crate::runtime::{commands, ime}; @@ -90,65 +91,51 @@ pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe /// component reports through for the component's editor part. #[derive(Clone, Debug, PartialEq)] pub struct EditorHandle { - #[allow(dead_code)] // P3(canvas-w2): cv.K41 widget: egui::Id, - #[allow(dead_code)] // P3(canvas-w2): cv.K41 rect: Rect, - #[allow(dead_code)] // P3(canvas-w2): cv.K41 purpose: EditorPurpose, - #[allow(dead_code)] // P3(canvas-w2): cv.K41 focused: bool, - #[allow(dead_code)] // P3(canvas-w2): cv.K41 read_only: 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 } + } + /// Reports the caret and composition to the input-method engine and puts the text facts in the running pass's /// editor record, which the owning component's report step reads in the same pass. pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>) { - let _ = (ctx, state); - todo!("cv.K41") - } -} - -impl Cx<'_, C> { - /// The editor part of this pass, `None` when the component registered none. - pub fn editor_handle(&self) -> Option { - todo!("cv.K41") - } - - /// Notes the input-method receipt between the stamps `before` and `after` on the egui fork's tracker for this - /// viewport and frame; true when the stamps prove the engine applied it. - pub fn ime_receipt(&self, before: ImeStamp, after: ImeStamp) -> bool { - let _ = (before, after); - todo!("cv.K27") - } - - /// Notes an input-method application change on the egui fork's tracker for this viewport and frame. - pub fn ime_application_change(&self) { - todo!("cv.K27") - } - - /// The editor part's inputs of this pass in the order they arrived; call it in `update`. The editor applies them - /// to its own document. - pub fn editor_input(&mut self) -> impl Iterator + '_ { - std::mem::take(&mut self.core.editor_inputs).into_iter() - } - - /// Reports the editor's caret, visible lines, selection and undo state once per pass, from `update` or `paint`. - pub fn editor_state(&self, state: EditorState<'_>) { - let Some(info) = &self.core.editor else { - debug_assert!(false, "`editor_state` needs an editor part registered by `parts`"); - return; - }; - let ctx = &self.core.ctx; - let masked = info.purpose == EditorPurpose::Password; - if info.focused { - ime::note_caret(ctx, info.widget, info.rect, state.caret, masked); + if let Some(facts) = self.note(ctx, state) { + // PLAN: assumed `pub(crate) fn note_editor_facts(ctx: &egui::Context, widget: egui::Id, facts: TextFacts)` in `contract/steps/report.rs` (ribbon-w5): the pass-scoped slot step 16 reads for `core.editor`'s widget. + super::steps::report::note_editor_facts(ctx, self.widget, facts); } - ime::note_editor(ctx, info.widget, state.composing, (state.can_undo, state.can_redo)); - if !text_access::exposed(ctx, info.widget) { - return; + } + + /// Notes the input-method receipt between the stamps `before` and `after` for this editor part; true when the + /// stamps prove the engine applied it. A body that applies the input method's edits calls it with `ctx`. + pub fn ime_receipt(&self, ctx: &egui::Context, before: ImeStamp, after: ImeStamp) -> bool { + ime::note_receipt(ctx, self.widget, before, after) + } + + /// Notes an application change of this editor part's committed text. + pub fn ime_application_change(&self, ctx: &egui::Context) { + ime::note_application_change(ctx, self.widget); + } + + /// The one editor report path: notes the caret, the composition, the undo state and the surrounding text with the + /// IME engine, and returns the text facts when AccessKit reads the part. + fn note(&self, ctx: &egui::Context, state: EditorState<'_>) -> Option { + let masked = self.purpose == EditorPurpose::Password; + if self.focused { + ime::note_caret(ctx, self.widget, self.rect, state.caret, masked); + } + let surrounding = state.surrounding.as_ref().map(|(epoch, report)| (*epoch, report)); + ime::note_editor(ctx, self.widget, state.composing, (state.can_undo, state.can_redo), surrounding); + if !text_access::exposed(ctx, self.widget) { + return None; } let lines = state .lines @@ -167,6 +154,44 @@ impl Cx<'_, C> { .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))); - *self.core.text_access.borrow_mut() = Some(TextFacts { widget: info.widget, text, masked, editable: !info.read_only, lines, selection }); + Some(TextFacts { widget: self.widget, text, masked, editable: !self.read_only, lines, selection }) + } +} + +impl Cx<'_, C> { + /// The editor part of this pass, `None` when the component registered none. + pub fn editor_handle(&self) -> Option { + self.core.editor.as_ref().map(EditorHandle::of) + } + + /// Notes the input-method receipt between the stamps `before` and `after` on the egui fork's tracker for this + /// viewport and frame; true when the stamps prove the engine applied it. + pub fn ime_receipt(&self, before: ImeStamp, after: ImeStamp) -> bool { + self.editor_handle().is_some_and(|handle| handle.ime_receipt(&self.core.ctx, before, after)) + } + + /// Notes an input-method application change on the egui fork's tracker for this viewport and frame. + pub fn ime_application_change(&self) { + if let Some(handle) = self.editor_handle() { + handle.ime_application_change(&self.core.ctx); + } + } + + /// The editor part's inputs of this pass in the order they arrived; call it in `update`. The editor applies them + /// to its own document. + pub fn editor_input(&mut self) -> impl Iterator + '_ { + std::mem::take(&mut self.core.editor_inputs).into_iter() + } + + /// Reports the editor's caret, visible lines, selection and undo state once per pass, from `update` or `paint`. + pub fn editor_state(&self, state: EditorState<'_>) { + let Some(handle) = self.editor_handle() else { + debug_assert!(false, "`editor_state` needs an editor part registered by `parts`"); + return; + }; + // The component's own report reaches its report step directly; a body's goes through the record. + if let Some(facts) = handle.note(&self.core.ctx, state) { + *self.core.text_access.borrow_mut() = Some(facts); + } } } diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c5f87706f..5a1ed5bf0 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -93,6 +93,13 @@ pub struct ImeSeen { pub reset: Option, /// Where the candidate window opens. pub caret: Rect, + + /// The IME context the output belongs to; it changes with the owner, its epoch, its focus or its purpose. + pub generation: u64, + /// The bounded committed text around the caret, or `Unavailable`. + pub surrounding: egui::output::IMESurroundingText, + /// Whether the input method made the change to `surrounding`. + pub cause: egui::output::ImeChangeCause, } /// The files the OS hovers over or drops on a frame's window, by name; a hovered file also has the media type the OS gave. @@ -286,6 +293,9 @@ pub(crate) fn run_frame( interrupt: ime.should_interrupt_composition, reset: ime.reset_request, caret: ime.cursor_rect, + generation: ime.context_generation, + surrounding: ime.surrounding_text.clone(), + cause: ime.change_cause, }), textures: std::mem::take(&mut output.textures_delta), shapes: output.shapes, diff --git a/crates/ui-contract/src/runtime/egui/ime.rs b/crates/ui-contract/src/runtime/egui/ime.rs index d3892716c..a62d9b727 100644 --- a/crates/ui-contract/src/runtime/egui/ime.rs +++ b/crates/ui-contract/src/runtime/egui/ime.rs @@ -67,9 +67,14 @@ pub(crate) struct Output { pub caret: Rect, /// Interrupt the OS composition and ask for a reset. pub interrupt: bool, - /// Changes when the owner changes. + /// The context generation the tracker gave the owner: it changes when the owner, its epoch, its focus or its + /// purpose changes, and stays for ordinary edits. pub generation: u64, pub password: bool, + /// The bounded committed text around the caret, or `Unavailable`. + pub surrounding: egui::output::IMESurroundingText, + /// Whether the input method made the change to `surrounding`, as the tracker proved it from the receipts. + pub cause: egui::output::ImeChangeCause, } /// Writes the pass's IME output; egui reads it only when it is `Some` at the end of the pass. Returns the reset @@ -86,6 +91,8 @@ pub(crate) fn write(ctx: &Context, viewport: ViewportId, out: Output) -> Option< ); ime.should_interrupt_composition = out.interrupt; ime.reset_request = reset; + ime.surrounding_text = out.surrounding; + ime.change_cause = out.cause; output.ime = Some(ime); }); reset diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index 76de8536d..d8dda08b0 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -2,12 +2,15 @@ //! caret rect for the OS. While a framework editor owns the IME, the engine is the one reader of the IME events and //! the one writer of `PlatformOutput.ime`; otherwise both stay with egui and the app's own widgets. +use crate::primitives::EditorSurrounding; use crate::runtime::egui::ime as os; use crate::runtime::egui::input::Arrived; use crate::runtime::egui::pass; use crate::runtime::frame::{PerViewport, Stored}; use craft_behavior::EditorInput; -use egui::{Context, Event, Id, Key, Rect, ViewportId}; +use egui::ime_context::{CommittedText, ImeContextTracker, ImeContextUpdate, ImeMutationStamp, ImeObservation, ImeTarget}; +use egui::output::{IMESurroundingText, ImeChangeCause}; +use egui::{Context, Event, IMEPurpose, Id, Key, Rect, ViewportId}; /// Frames after a commit in which the keys that end a composition stay guarded. const GUARD_FRAMES: u8 = 1; @@ -17,10 +20,17 @@ struct Engine { /// Events taken from raw input, delivered at the begin hook. queue: Vec, owner: Option, - generation: u64, - /// The egui fork's input-method context tracker; replaces `generation`, which stays until canvas-w2 moves its readers. - #[allow(dead_code)] // P3(canvas-w2): cv.K28 - tracker: egui::ime_context::ImeContextTracker, + /// The egui fork's input-method context tracker of this viewport: each end hook observes the owner once, and the + /// tracker gives the output its context generation, its bounded surrounding text and the cause of a change. + tracker: ImeContextTracker, + /// The target the owner was observed as at the last end hook, and whether it was a password. A receipt or an + /// application change names this target, because the tracker accepts one only for the context it last observed; + /// a pass whose owner reports no caret keeps the purpose, so the context does not change for it. + observed: Option<(ImeTarget, bool)>, + /// The context generation of the last output written for an owner. The interrupt the old owner gets in the pass + /// it lost focus names this context: the one the OS is composing in. A new generation, or none, names a context + /// the OS never saw. + published: Option, composing: bool, guard: u8, /// A reset was asked for; events of the old composition are dropped until its completion arrives. @@ -43,15 +53,76 @@ struct Engine { impl Stored for Engine {} -#[derive(Clone, Copy)] +#[derive(Clone)] struct EditorFacts { owner: Id, composing: bool, can_undo: bool, can_redo: bool, + /// The committed text around the caret the owner reported this pass; the end hook takes it, so a pass whose + /// owner reports nothing observes no text. + surrounding: Option, +} + +/// An owner's surrounding report as the engine keeps it for one pass: an owned copy of at most +/// `MAX_IME_SURROUNDING_TEXT_BYTES` around the selection, never the whole document, and the epoch of the target. +#[derive(Clone)] +struct Surrounding { + epoch: u64, + text: IMESurroundingText, + /// The editor's revision of an unavailable report, which orders two unavailable stamps of one receipt. + revision: Option, +} + +impl Surrounding { + /// Copies the bounded window of `report`. Offsets that are not character boundaries give no text. + fn of(epoch: u64, report: &EditorSurrounding<'_>) -> Surrounding { + match report { + EditorSurrounding::Text { text, cursor, anchor, .. } => { + Surrounding { epoch, text: IMESurroundingText::from_text(text, *cursor, *anchor, None), revision: None } + } + EditorSurrounding::Unavailable { revision, .. } => Surrounding { epoch, text: IMESurroundingText::Unavailable, revision: *revision }, + } + } } impl Engine { + /// Observes this pass's owner on the tracker, once per pass. The owner's target is its id with the epoch of its + /// report; an owner that reported nothing this pass (a text field, an editor with no surrounding report) keeps its + /// last epoch (0 before any report) and is observed with no committed text (`committed(None)`). No owner observes `None`, so the next owner + /// starts a new context. + /// + /// A second pass of a frame is the tracker's next pass of the same frame: it applies only the receipts noted in + /// that pass, and an unchanged snapshot keeps the cause the frame's first pass found. + fn observe(&mut self, viewport: ViewportId, frame_nr: u64, pass_nr: u64, password: Option) -> Option { + let Some(owner) = self.owner else { + self.observed = None; + return self.tracker.observe(viewport, None); + }; + let kept = self.observed.is_some_and(|(target, password)| target.owner == owner && password); + let password = password.unwrap_or(kept); + let report = self.editor.as_mut().filter(|facts| facts.owner == owner).and_then(|facts| facts.surrounding.take()); + // Only a report moves the epoch: an owner that reports nothing this pass stays the same target. + let kept_epoch = self.observed.map(|(target, _)| target).filter(|target| target.owner == owner).map_or(0, |target| target.epoch); + let target = ImeTarget::new(owner, report.as_ref().map_or(kept_epoch, |report| report.epoch)); + let purpose = if password { IMEPurpose::Password } else { IMEPurpose::Normal }; + let mut observation = ImeObservation::new(frame_nr, pass_nr, target).purpose(purpose); + if let Some(report) = &report { + if let Some(payload) = report.text.available() { + observation = observation.committed(Some(CommittedText::new(&payload.text, payload.cursor, payload.anchor))); + } else if let Some(revision) = report.revision { + observation = observation.unavailable_revision(revision); + } + } + self.observed = Some((target, password)); + self.tracker.observe(viewport, Some(observation)) + } + + /// The target `owner` was observed as at the last end hook; `None` when it was not the observed owner. + fn target_of(&self, owner: Id) -> Option { + self.observed.map(|(target, _)| target).filter(|target| target.owner == owner) + } + /// Ends the composition of `owner` here and has the end hook interrupt the OS composition; its late events are /// dropped until the reset completes. fn interrupt(&mut self, owner: Id) { @@ -100,8 +171,8 @@ pub(crate) fn begin(ctx: &Context, owner: Option) { } engine.composing = false; engine.edits.clear(); + // The tracker starts the new owner's context when the end hook observes it. engine.owner = owner; - engine.generation += 1; } for raw in std::mem::take(&mut engine.queue) { match raw { @@ -166,22 +237,53 @@ pub(crate) fn take(ctx: &Context, owner: Id, read_only: bool) -> Vec)>) { current(ctx, |engine| { if engine.owner != Some(owner) { return; } - let ended = !composing && engine.editor.is_some_and(|last| last.owner == owner && last.composing); + let ended = !composing && engine.editor.as_ref().is_some_and(|last| last.owner == owner && last.composing); if ended && engine.composing { engine.interrupt(owner); } - engine.editor = Some(EditorFacts { owner, composing, can_undo: history.0, can_redo: history.1 }); + let surrounding = surrounding.map(|(epoch, report)| Surrounding::of(epoch, report)); + engine.editor = Some(EditorFacts { owner, composing, can_undo: history.0, can_redo: history.1, surrounding }); }); } /// Whether the editor `owner` had something to undo and to redo at its last report as the IME owner. pub(crate) fn editor_history(ctx: &Context, owner: Id) -> (bool, bool) { - current(ctx, |engine| engine.editor.filter(|facts| facts.owner == owner).map_or((false, false), |facts| (facts.can_undo, facts.can_redo))) + current(ctx, |engine| { + engine.editor.as_ref().filter(|facts| facts.owner == owner).map_or((false, false), |facts| (facts.can_undo, facts.can_redo)) + }) +} + +/// Notes that the editor `owner` applied an input-method commit or deletion, which took its committed text from +/// `before` to `after`. True when the tracker accepted the receipt: `owner` is the context it last observed and the +/// stamps prove the change. Only the pass that applied the input notes it; a second pass of the frame gets no input +/// and notes none. +pub(crate) fn note_receipt(ctx: &Context, owner: Id, before: ImeMutationStamp, after: ImeMutationStamp) -> bool { + let viewport = pass::current_viewport(ctx); + let frame_nr = ctx.cumulative_frame_nr_for(viewport); + with(ctx, viewport, |engine| { + let Some(target) = engine.target_of(owner) else { return false }; + engine.tracker.note_input_method_apply(viewport, frame_nr, target, before, after) + }) +} + +/// Notes that the editor `owner` changed its committed text for a reason other than the input method (typing, a +/// paste, undo, an app edit): the frame's change cause is `Other`. +pub(crate) fn note_application_change(ctx: &Context, owner: Id) { + let viewport = pass::current_viewport(ctx); + let frame_nr = ctx.cumulative_frame_nr_for(viewport); + with(ctx, viewport, |engine| { + if let Some(target) = engine.target_of(owner) { + engine.tracker.note_application_change(viewport, frame_nr, target); + } + }); } /// The preedit of `owner` when it lost focus while composing, once: its adapter appends it to the draft. @@ -202,11 +304,12 @@ pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, pas current(ctx, |engine| engine.caret = Some((owner, field, caret, password))); } -/// The end hook: writes the pass's IME output while a framework editor owns the IME or an interrupt is due. Otherwise -/// the output is egui's: an app's own `TextEdit` or IME reader writes it. +/// The end hook: observes the owner on the tracker, then writes the pass's IME output while a framework editor owns the +/// IME or an interrupt is due. Otherwise the output is egui's: an app's own `TextEdit` or IME reader writes it. pub(crate) fn end_pass(ctx: &Context) { let viewport = pass::current_viewport(ctx); - let (owner, interrupt, caret, generation) = with(ctx, viewport, |engine| { + let (frame_nr, pass_nr) = (ctx.cumulative_frame_nr_for(viewport), ctx.cumulative_pass_nr_for(viewport)); + let (owner, interrupt, caret, update, published) = with(ctx, viewport, |engine| { if !std::mem::take(&mut engine.ran) { engine.edits.clear(); } @@ -217,28 +320,56 @@ pub(crate) fn end_pass(ctx: &Context) { { engine.interrupt.get_or_insert(owner); } - (engine.owner, engine.interrupt.take(), engine.caret.take(), engine.generation) + let caret = engine.caret.take(); + let password = caret.filter(|(id, ..)| Some(*id) == engine.owner).map(|(.., password)| password); + let update = engine.observe(viewport, frame_nr, pass_nr, password); + (engine.owner, engine.interrupt.take(), caret, update, engine.published) }); let written = if owner.is_none() && interrupt.is_none() { None } else { os::clear(ctx); - match (caret, interrupt, owner) { - (Some((id, field, caret, password)), interrupt, _) if Some(id) == owner => { - Some(os::write(ctx, viewport, os::Output { owner: id, field, caret, interrupt: interrupt.is_some(), generation, password })) + match (caret, interrupt, update) { + (Some((id, field, caret, password)), interrupt, Some(update)) if Some(id) == owner => { + let generation = update.context_generation; + let out = os::Output { + owner: id, + field, + caret, + interrupt: interrupt.is_some(), + generation, + password, + surrounding: update.surrounding_text, + cause: update.change_cause, + }; + Some((os::write(ctx, viewport, out), Some(generation))) + } + // The old owner still gets an output in the pass it lost focus, or the OS never interrupts. It names the + // context the OS composes in, the last one published. + (_, Some(old), _) => { + let out = os::Output { + owner: old, + field: Rect::NOTHING, + caret: Rect::NOTHING, + interrupt: true, + generation: published.unwrap_or_default(), + password: false, + surrounding: IMESurroundingText::Unavailable, + cause: ImeChangeCause::Other, + }; + Some((os::write(ctx, viewport, out), None)) } - // The old owner still gets an output in the pass it lost focus, or the OS never interrupts. - (_, Some(old), _) => Some(os::write( - ctx, - viewport, - os::Output { owner: old, field: Rect::NOTHING, caret: Rect::NOTHING, interrupt: true, generation, password: false }, - )), _ => None, } }; - if let Some(published) = written - && interrupt.is_some() - { - with(ctx, viewport, |engine| engine.reset = published); + if let Some((reset, generation)) = written { + with(ctx, viewport, |engine| { + if generation.is_some() { + engine.published = generation; + } + if interrupt.is_some() { + engine.reset = reset; + } + }); } } diff --git a/crates/ui-contract/tests/it/text/editor.rs b/crates/ui-contract/tests/it/text/editor.rs index 0e94fd751..4029a6dd0 100644 --- a/crates/ui-contract/tests/it/text/editor.rs +++ b/crates/ui-contract/tests/it/text/editor.rs @@ -2,29 +2,43 @@ //! receives only inputs that change no text, and its visible lines become AccessKit run nodes. use craft_behavior::{EditorInput, PartKey, Sense, TextPos}; -use craft_ui::contract::{Common, Component, Cx, PaintUi, PartsCx, Props as _, Role, Show as _}; -use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState}; +use craft_ui::contract::{Common, Component, Cx, EditorHandle, PaintUi, PartsCx, Props as _, Role, Show as _}; +use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp}; use craft_ui::runtime::focus::KeyUse; +use craft_ui::runtime::frame::discard_pass; use craft_ui::style::StyleCx; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{click, moved, press, release}; +use craft_ui::testing::text::ImeSeen; use craft_ui::testing::{Frames, trial}; -use craft_ui_test_kit::contract::PlainStyle; +use craft_ui_test_kit::contract::{PlainStyle, Probe as Button, Seen}; +use egui::output::{IMESurroundingText, ImeChangeCause}; use egui::{Event, Id, ImeEvent, Key, Modifiers, Pos2, Rect, Response}; use std::cell::{Cell, RefCell}; const AT: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(210.0, 90.0) }; +/// Where the control after the probe sits, for the trials that Tab away from it. +const NEXT: Rect = Rect { min: Pos2::new(10.0, 110.0), max: Pos2::new(90.0, 130.0) }; const TEXT: &str = "fn main"; const EDITOR: PartKey = PartKey::new("editor"); -/// An editor that keeps no text: it logs the inputs it receives and, while `report` is set, reports `TEXT` as its one -/// line. +/// An editor that logs the inputs it receives and, while `report` is set, reports its one line: `TEXT`, or the text +/// of its `doc` when it keeps one. #[derive(craft_ui::contract::Component)] struct Probe<'a> { #[common] common: Common, log: &'a RefCell>, report: bool, + purpose: EditorPurpose, + doc: Option<&'a Doc>, +} + +impl<'a> Probe<'a> { + /// A code editor that logs into `log` and keeps no text. + fn new(log: &'a RefCell>, report: bool) -> Self { + Probe { common: Common::new(), log, report, purpose: EditorPurpose::Code, doc: None } + } } impl Component for Probe<'_> { @@ -38,30 +52,53 @@ impl Component for Probe<'_> { PlainStyle::default() } + fn keys(&self) -> KeyUse { + // A prose field leaves Tab to the focus order, so Tab can take the keyboard away from it. + if self.purpose == EditorPurpose::Code { KeyUse::CODE } else { KeyUse::of(craft_ui::contract::Input::Editor) } + } + fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS } fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { - cx.editor(EDITOR, rect, EditorPurpose::Code); + cx.editor(EDITOR, rect, self.purpose); } fn update(&mut self, cx: &mut Cx<'_, Self>) { - self.log.borrow_mut().extend(cx.editor_input()); + let inputs: Vec = cx.editor_input().collect(); + if let Some(doc) = self.doc { + doc.apply(cx, &inputs); + } + self.log.borrow_mut().extend(inputs); } fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { if !self.report { return; } - let positions: Vec = (0..TEXT.len()).map(|at| at as f32 * 8.0).collect(); - let widths = vec![8.0; TEXT.len()]; - let runs = [EditorRun::new(0..TEXT.len(), false, &positions, &widths)]; + let text = self.doc.map(|doc| doc.text.borrow()); + let shown = text.as_deref().map_or(TEXT, String::as_str); + let positions: Vec = (0..shown.len()).map(|at| at as f32 * 8.0).collect(); + let widths = vec![8.0; shown.len()]; + let runs = [EditorRun::new(0..shown.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(TEXT, line, line.bottom(), &runs)]; - let end = TextPos::new(0, TEXT.len()); - let caret = Rect::from_min_size(line.min + egui::vec2(TEXT.len() as f32 * 8.0, 0.0), egui::vec2(0.0, 16.0)); - cx.editor_state(EditorState::new(caret, &lines, end)); + let lines = [EditorLine::new(shown, line, line.bottom(), &runs)]; + let end = TextPos::new(0, shown.len()); + let caret = Rect::from_min_size(line.min + egui::vec2(shown.len() as f32 * 8.0, 0.0), egui::vec2(0.0, 16.0)); + let mut state = EditorState::new(caret, &lines, end); + let Some(doc) = self.doc else { + cx.editor_state(state); + return; + }; + state.composing = doc.composing.get(); + if let Some(epoch) = doc.epoch.get() { + state = state.surrounding(epoch, EditorSurrounding::Text { text: shown, cursor: shown.len(), anchor: shown.len() }); + } + match cx.editor_handle().filter(|_| doc.body.get()) { + Some(handle) => body(&handle, &cx.response.ctx, state), + None => cx.editor_state(state), + } } fn finish(self, cx: Cx<'_, Self>) -> Response { @@ -69,33 +106,172 @@ impl Component for Probe<'_> { } } +/// A body inside the probe that has the editor handle and the context but no `Cx`, as a canvas tool's body does. +fn body(handle: &EditorHandle, ctx: &egui::Context, state: EditorState<'_>) { + handle.report(ctx, state); +} + +/// The committed text of a probe that keeps one, and how the probe reports it. +#[derive(Default)] +struct Doc { + /// The committed text; IME commits and typing append to it. + text: RefCell, + /// The epoch of the input-method target the text is reported at; `None` reports no surrounding text. + epoch: Cell>, + /// The probe shows marked text: a preedit started it, a commit or a press in the text ends it. + composing: Cell, + /// The probe reports from a body through `EditorHandle::report` rather than through `Cx::editor_state`. + body: Cell, + /// The probe discards the next pass it runs, so its frame runs a second pass. + discard: Cell, + /// What each IME receipt the probe noted answered. + receipts: RefCell>, +} + +impl Doc { + fn new(text: &str, epoch: Option) -> Doc { + Doc { text: RefCell::new(text.to_owned()), epoch: Cell::new(epoch), ..Doc::default() } + } + + /// Applies the pass's inputs: text after an `ImeCommit` is the input method's and notes a receipt, any other text + /// is the application's. + fn apply(&self, cx: &Cx<'_, C>, inputs: &[EditorInput]) { + let mut by_ime = false; + for input in inputs { + match input { + EditorInput::Preedit { text, .. } => self.composing.set(!text.is_empty()), + EditorInput::ImeCommit => { + by_ime = true; + self.composing.set(false); + } + EditorInput::Text(typed) => { + let mut text = self.text.borrow_mut(); + let before = stamp(&text); + text.push_str(typed); + let after = stamp(&text); + if std::mem::take(&mut by_ime) { + self.receipts.borrow_mut().push(cx.ime_receipt(before, after)); + } else { + cx.ime_application_change(); + } + } + _ => {} + } + } + // A press in the text moves the caret, which ends the marked text the probe shows. + if cx.response.clicked() { + self.composing.set(false); + } + if self.discard.take() { + discard_pass(&cx.response.ctx, "trial"); + } + } +} + +/// The receipt stamp of `text` with the caret at its end, where the probe reports it. +fn stamp(text: &str) -> ImeStamp { + ImeStamp::from_committed(text, text.len(), text.len(), None) +} + +/// What one frame of the rig shows, borrowed from the rig apart from its frames. +#[derive(Clone, Copy)] +struct View<'r> { + log: &'r RefCell>, + id: &'r Cell, + read_only: bool, + purpose: EditorPurpose, + doc: Option<&'r Doc>, + next: Option<&'r RefCell>, +} + +impl View<'_> { + fn show(self, ui: &mut egui::Ui) { + let probe = Probe { purpose: self.purpose, doc: self.doc, ..Probe::new(self.log, true) }; + let response = probe.label("Source").read_only(self.read_only).id_salt("code").show_at(ui, AT); + self.id.set(response.id); + if let Some(seen) = self.next { + let _ = Button::new(seen).id_salt("next").show_at(ui, NEXT); + } + } +} + struct Rig { frames: Frames, log: RefCell>, id: Cell, read_only: bool, + purpose: EditorPurpose, + doc: Option, + /// The control after the probe that Tab takes the keyboard to, when the rig shows one. + next: Option>, } impl Rig { fn new() -> Rig { - let mut rig = Rig { frames: Frames::new(), log: RefCell::new(Vec::new()), id: Cell::new(Id::NULL), read_only: false }; + Rig::with(EditorPurpose::Code, None, false) + } + + /// A rig whose probe edits `purpose`, keeps `doc` and, with `next`, has a control after it. + fn with(purpose: EditorPurpose, doc: Option, next: bool) -> Rig { + let mut rig = Rig { + frames: Frames::new(), + log: RefCell::new(Vec::new()), + id: Cell::new(Id::NULL), + read_only: false, + purpose, + doc, + next: next.then(|| RefCell::new(Seen::default())), + }; for _ in 0..3 { rig.frame(Vec::new()); } rig } - fn frame(&mut self, events: Vec) { - let (log, id, read_only) = (&self.log, &self.id, self.read_only); - self.frames.frame(events, |ui| show(ui, log, id, read_only)); + /// A frame with `events`; returns the passes it ran. + fn frame(&mut self, events: Vec) -> usize { + let view = View { + log: &self.log, + id: &self.id, + read_only: self.read_only, + purpose: self.purpose, + doc: self.doc.as_ref(), + next: self.next.as_ref(), + }; + self.frames.frame(events, |ui| view.show(ui)) } fn focus(&mut self) { - let (log, id, read_only) = (&self.log, &self.id, self.read_only); - click(&mut self.frames, AT.center(), &mut |ui| show(ui, log, id, read_only)); + let view = View { + log: &self.log, + id: &self.id, + read_only: self.read_only, + purpose: self.purpose, + doc: self.doc.as_ref(), + next: self.next.as_ref(), + }; + click(&mut self.frames, AT.center(), &mut |ui| view.show(ui)); self.log.borrow_mut().clear(); } + fn doc(&self) -> &Doc { + self.doc.as_ref().expect("the rig's probe keeps a text") + } + + /// The IME output of the last frame, which a focused probe always writes. + fn ime(&self) -> ImeSeen { + self.frames.ime().cloned().expect("the focused editor writes the IME output") + } + + /// Whether the last frame reset the input method as egui-winit counts it: the IME coming back on, or an + /// interrupt while it is on. `on` is whether it was on, and becomes whether it is. + fn resets_ime(&self, on: &mut bool) -> bool { + let ime = self.frames.ime(); + let reset = ime.is_some_and(|ime| !*on || ime.interrupt); + *on = ime.is_some(); + reset + } + fn take(&self) -> Vec { self.log.take() } @@ -112,11 +288,6 @@ impl Rig { } } -fn show(ui: &mut egui::Ui, log: &RefCell>, id: &Cell, read_only: bool) { - let response = Probe { common: Common::new(), log, report: true }.label("Source").read_only(read_only).id_salt("code").show_at(ui, AT); - id.set(response.id); -} - /// Text, Backspace, Tab and Enter reach an editor as one input stream in the order they were typed; a read-only /// editor still receives moves but none of the inputs that change text. #[trial] @@ -188,8 +359,8 @@ fn a_reset_the_integration_retires_is_asked_again() { let (first, second) = (RefCell::new(Vec::new()), RefCell::new(Vec::new())); let report = Cell::new(true); let mut ui = |ui: &mut egui::Ui| { - Probe { common: Common::new(), log: &first, report: true }.label("First").id_salt("first").show_at(ui, AT); - Probe { common: Common::new(), log: &second, report: report.get() }.label("Second").id_salt("second").show_at(ui, OTHER); + Probe::new(&first, true).label("First").id_salt("first").show_at(ui, AT); + Probe::new(&second, report.get()).label("Second").id_salt("second").show_at(ui, OTHER); }; let mut frames = Frames::new(); click(&mut frames, AT.center(), &mut ui); @@ -223,3 +394,153 @@ fn a_reset_the_integration_retires_is_asked_again() { "the new request's completion gives the new editor its IME: {inputs:?}" ); } + +fn commit(text: &str) -> Event { + Event::Ime(ImeEvent::Commit(text.to_owned())) +} + +/// The surrounding text of an IME output with its cursor and anchor; `None` when it is unavailable. +fn window(seen: &ImeSeen) -> Option<(String, usize, usize)> { + seen.surrounding.available().map(|payload| (payload.text.clone(), payload.cursor, payload.anchor)) +} + +/// The editor that owns the IME publishes its committed text around the caret with the cursor and anchor offsets. A +/// commit the editor applies with a receipt is the input method's change, also in a frame that runs a second pass, +/// which gets no input and notes no receipt; typing is the application's. Edits keep the context, a new epoch starts +/// a new one, and an owner that reports no surrounding text publishes none. +#[trial] +fn an_editors_surrounding_text_and_receipts_reach_the_ime_output() { + let mut rig = Rig::with(EditorPurpose::Code, Some(Doc::new(TEXT, Some(1))), false); + rig.focus(); + rig.frame(Vec::new()); + let seen = rig.ime(); + assert_eq!(window(&seen), Some((TEXT.to_owned(), 7, 7)), "the owner's text and caret reach the output"); + let generation = seen.generation; + + rig.doc().discard.set(true); + assert_eq!(rig.frame(vec![commit("(")]), 2, "the commit's frame runs a second pass"); + assert_eq!(*rig.doc().receipts.borrow(), [true], "the first pass's receipt continues the observed text; the second notes none"); + let seen = rig.ime(); + assert_eq!(window(&seen), Some(("fn main(".to_owned(), 8, 8))); + assert_eq!(seen.cause, ImeChangeCause::InputMethod, "the receipt proves the input method's change"); + assert_eq!(seen.generation, generation, "an edit keeps the context"); + + rig.frame(vec![Event::Text(")".into())]); + let seen = rig.ime(); + assert_eq!(window(&seen), Some(("fn main()".to_owned(), 9, 9))); + assert_eq!(seen.cause, ImeChangeCause::Other, "typing is the application's change"); + assert_eq!(seen.generation, generation, "typing keeps the context"); + + rig.doc().epoch.set(Some(2)); + rig.frame(Vec::new()); + let seen = rig.ime(); + assert_ne!(seen.generation, generation, "a new epoch starts a new context"); + assert_eq!(window(&seen), Some(("fn main()".to_owned(), 9, 9))); + + let second = seen.generation; + rig.doc().epoch.set(None); + rig.frame(Vec::new()); + let seen = rig.ime(); + assert_eq!(seen.surrounding, IMESurroundingText::Unavailable, "an owner that reports nothing publishes no text"); + assert_eq!(seen.generation, second, "a pass with no report keeps the target's epoch, so the context stays"); +} + +/// While the editor composes, and for one guard frame after a commit, Enter, Space, Backspace, Escape and Delete +/// never become editor inputs and do not interrupt: the composition goes on. A press in the editor's text does +/// interrupt it: the press moves the caret, the editor ends the marked text it showed, and the engine asks for one +/// reset and fences the composition's late events. +#[trial] +fn keys_that_end_a_composition_do_not_reach_the_editor_while_it_composes() { + let mut rig = Rig::with(EditorPurpose::Code, Some(Doc::new(TEXT, None)), false); + rig.focus(); + rig.frame(vec![preedit("k")]); + assert!(matches!(rig.take().as_slice(), [EditorInput::Preedit { .. }]), "the editor composes"); + for key in [Key::Enter, Key::Space, Key::Backspace, Key::Escape, Key::Delete] { + assert_eq!(rig.frame_reset(vec![key_press(key, Modifiers::NONE)]), None, "{key:?} interrupts the composition"); + let inputs = rig.take(); + assert!(inputs.is_empty(), "{key:?} pressed while composing reaches the editor: {inputs:?}"); + } + rig.frame(vec![preedit("ka")]); + let inputs = rig.take(); + assert!(matches!(inputs.as_slice(), [EditorInput::Preedit { text, .. }] if &**text == "ka"), "the composition goes on: {inputs:?}"); + + rig.frame(vec![commit("ka")]); + let inputs = rig.take(); + assert!(matches!(inputs.as_slice(), [EditorInput::ImeCommit, EditorInput::Text(text)] if &**text == "ka"), "the commit lands: {inputs:?}"); + rig.frame(vec![key_press(Key::Enter, Modifiers::NONE)]); + let inputs = rig.take(); + assert!(inputs.is_empty(), "the Enter that confirmed the commit, a frame late, is no newline: {inputs:?}"); + rig.frame(vec![key_press(Key::Enter, Modifiers::NONE)]); + let inputs = rig.take(); + assert!(matches!(inputs.as_slice(), [EditorInput::Newline]), "after the guard frame Enter is a newline: {inputs:?}"); + + rig.frame(vec![preedit("x")]); + assert!(matches!(rig.take().as_slice(), [EditorInput::Preedit { .. }]), "a new composition starts"); + let resets = rig.click_resets(AT.center()); + assert_eq!(resets.len(), 1, "a press in the text interrupts the composition with one reset: {resets:?}"); + rig.frame(vec![preedit("xy")]); + let inputs = rig.take(); + assert!(inputs.is_empty(), "the interrupted composition's late preedit is fenced: {inputs:?}"); +} + +/// A body that runs inside the component reports through `EditorHandle::report`: its caret reaches the IME output +/// and its lines reach AccessKit as the component's own `Cx::editor_state` report does. +#[trial] +fn a_report_through_the_editor_handle_reaches_the_ime_note_and_the_text_facts() { + let reported = |through_body: bool| { + let doc = Doc::new(TEXT, None); + doc.body.set(through_body); + let mut rig = Rig::with(EditorPurpose::Code, Some(doc), false); + rig.focus(); + rig.frame(Vec::new()); + let caret = rig.frames.ime().map(|ime| ime.caret); + (caret, rig.frames.tree().run_texts(rig.id.get())) + }; + let (own_caret, own_runs) = reported(false); + let (body_caret, body_runs) = reported(true); + assert!(own_caret.is_some_and(|caret| caret.is_finite()), "the component's own report notes the caret: {own_caret:?}"); + assert_eq!(own_runs, [TEXT.to_owned()], "the component's own report reaches AccessKit"); + assert_eq!(body_caret, own_caret, "the body's caret reaches the IME note"); + assert_eq!(body_runs, own_runs, "the body's text facts reach the pass's record and AccessKit"); +} + +/// #2986: a field that keeps the keyboard does not reset the input method every frame. Once it has focus no frame +/// interrupts and typing lands; when Tab takes the keyboard to the next control and Shift+Tab brings it back, the +/// input method is reset once, counted as egui-winit counts it, and not again in the frames after. +#[trial] +fn a_focused_text_field_does_not_interrupt_the_input_method_every_frame() { + let mut rig = Rig::with(EditorPurpose::Text, None, true); + let mut on = false; + let mut resets = 0; + for events in [vec![moved(AT.center())], vec![press(AT.center())], vec![release(AT.center())]] { + rig.frame(events); + resets += usize::from(rig.resets_ime(&mut on)); + } + assert!(on, "the focused field owns the input method"); + assert_eq!(resets, 1, "taking focus turns the input method on once"); + for frame in 0..6 { + rig.frame(Vec::new()); + let seen = rig.ime(); + assert!(!seen.interrupt && seen.reset.is_none(), "frame {frame} with focus interrupts the input method: {seen:?}"); + } + rig.take(); + rig.frame(vec![key_press(Key::A, Modifiers::NONE), Event::Text("a".into())]); + assert!(!rig.resets_ime(&mut on), "typing resets the input method"); + let inputs = rig.take(); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Text(text) if &**text == "a")), "typing lands: {inputs:?}"); + + let (mut left, mut round) = (false, 0); + for events in [vec![key_press(Key::Tab, Modifiers::NONE)], Vec::new(), vec![key_press(Key::Tab, Modifiers::SHIFT)], Vec::new()] { + rig.frame(events); + round += usize::from(rig.resets_ime(&mut on)); + left |= !on; + } + assert!(left, "Tab takes the keyboard to the next control"); + assert!(on, "Shift+Tab gives the field the input method back"); + assert_eq!(round, 1, "Tab and back reset the input method once"); + for frame in 0..4 { + rig.frame(Vec::new()); + assert!(!rig.resets_ime(&mut on), "frame {frame} after the round trip resets the input method"); + } +} +