mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 22:14:30 +00:00
IME engine: an editor's own end of composition interrupts the OS composition; resets end only with their own completion
EditorState.composing replaces EditorState.revision (and TextEditorHost::revision): an editor that reported composing and now does not ended the composition itself (a press in its text, a selection, an app edit over the marked text), and the engine interrupts the OS composition and drops its late events. TextEditor and the sheet grid report their marked text; editors that show none report false throughout. The reset fence ends only with the completion of the engine's latest request (ImeResetId); an earlier request's completion is stale. A request the integration can no longer answer (a pass with no IME output, an unfocused window) is retired and asked again when an owner returns. Trials: preedit and a click during composition for a canvas TextEditor, with one press per pass holding the late commit for the next pass (craft-text); reset requests and stale completions (craft-ui-contract).
This commit is contained in:
@@ -27,7 +27,6 @@ pub(super) struct Draft {
|
||||
caret: usize,
|
||||
anchor: Option<usize>,
|
||||
preedit: Option<String>,
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
fn previous(text: &str, at: usize) -> usize {
|
||||
@@ -61,11 +60,11 @@ impl Draft {
|
||||
self.caret = self.text.len();
|
||||
self.anchor = None;
|
||||
self.preedit = None;
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub(super) fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
/// The draft shows marked text of an input method.
|
||||
pub(super) fn composing(&self) -> bool {
|
||||
self.preedit.is_some()
|
||||
}
|
||||
|
||||
pub(super) fn caret(&self) -> usize {
|
||||
@@ -101,7 +100,6 @@ impl Draft {
|
||||
self.anchor = None;
|
||||
self.text.insert_str(self.caret, &text);
|
||||
self.caret += text.len();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
fn delete(&mut self, forward: bool, by: Granularity) {
|
||||
@@ -109,7 +107,6 @@ impl Draft {
|
||||
self.text.replace_range(range.clone(), "");
|
||||
self.caret = range.start;
|
||||
self.anchor = None;
|
||||
self.revision += 1;
|
||||
return;
|
||||
}
|
||||
let (from, to) = match (forward, by) {
|
||||
@@ -124,7 +121,6 @@ impl Draft {
|
||||
if from < to {
|
||||
self.text.replace_range(from..to, "");
|
||||
self.caret = from;
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +182,6 @@ impl Draft {
|
||||
self.text.push_str(reference);
|
||||
self.caret = self.text.len();
|
||||
self.anchor = None;
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -373,7 +373,7 @@ impl CellGrid<'_> {
|
||||
Some(cell) if open => self.paint_editor(&draw, cx, &editing, geometry.mirror_rect(geometry.cell_rect(cell))),
|
||||
_ => {
|
||||
let lead = selection.active().map_or(Rect::NOTHING, |cell| geometry.mirror_rect(geometry.cell_rect(*cell)));
|
||||
cx.editor_state(EditorState::new(Rect::from_min_size(lead.min, Vec2::new(0.0, lead.height())), &[], TextPos::new(0, 0), 0));
|
||||
cx.editor_state(EditorState::new(Rect::from_min_size(lead.min, Vec2::new(0.0, lead.height())), &[], TextPos::new(0, 0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -504,8 +504,9 @@ impl CellGrid<'_> {
|
||||
draw.stroke(&PaintShape::Path(vec![top, top + Vec2::new(0.0, line.height())]), StrokeWidth::Medium, style.edit_edge);
|
||||
}
|
||||
let lines = [EditorLine::new(&text, line, line.top() + layout.first_baseline, &runs)];
|
||||
let mut state = EditorState::new(Rect::from_min_size(top, Vec2::new(0.0, line.height())), &lines, at, editing.draft.revision());
|
||||
let mut state = EditorState::new(Rect::from_min_size(top, Vec2::new(0.0, line.height())), &lines, at);
|
||||
state.selection = editing.draft.selection();
|
||||
state.composing = editing.draft.composing();
|
||||
cx.editor_state(state);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,9 @@
|
||||
//! The marked (preedit) text of an input method is written into the host's text with [`EditKind::Composing`] and
|
||||
//! replaced by every update, so it lays out, wraps and takes the character style exactly as typed text does. The
|
||||
//! editor remembers its range and underlines it, the converted segment thicker. A commit replaces the range with
|
||||
//! the result; a click keeps the marked text as typed. The host's [`revision`](TextEditorHost::revision) bumps on
|
||||
//! every change, so a change that follows no delivered edit resets the composition.
|
||||
//! the result; a click keeps the marked text as typed. Whenever the editor ends the composition itself (a press, a
|
||||
//! selection, an app edit over the marked text), it reports that it no longer composes and the input method's
|
||||
//! composition is interrupted.
|
||||
|
||||
mod commands;
|
||||
mod edits;
|
||||
@@ -208,9 +209,6 @@ pub trait TextEditorHost {
|
||||
/// The whole text, including the marked text while composing.
|
||||
fn text(&self) -> &str;
|
||||
|
||||
/// Bumped on every change to the text, the editor's own and outside ones alike.
|
||||
fn revision(&self) -> u64;
|
||||
|
||||
/// Replace the chars `range` with `text`. The host applies its insertion style (the style the Character panel
|
||||
/// set at the caret), records history (one step per editing session) and lays the text out again. `false` when
|
||||
/// it refused (a locked layer): the editor leaves its selection as it was.
|
||||
@@ -663,7 +661,8 @@ impl Component for TextEditor<'_> {
|
||||
EditorLine::new(&line.text, rect, rect.top() + (line.baseline - line.rect.top()) * zoom, runs)
|
||||
})
|
||||
.collect();
|
||||
let mut state = EditorState::new(caret_rect, &lines, text_pos(&host_lines, caret_at), self.host.revision());
|
||||
let mut state = EditorState::new(caret_rect, &lines, text_pos(&host_lines, caret_at));
|
||||
state.composing = session.preedit.is_some();
|
||||
state.selection = (!range.is_empty()).then(|| (text_pos(&host_lines, selection.anchor.min(chars)), text_pos(&host_lines, caret_at)));
|
||||
cx.editor_state(state);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ const TEXT_SIZE: f32 = 16.0;
|
||||
/// wrap after the last space that fits `columns` cells; a wrapped row keeps the spaces it ends with.
|
||||
struct MonoHost {
|
||||
text: String,
|
||||
revision: u64,
|
||||
columns: usize,
|
||||
}
|
||||
|
||||
@@ -100,15 +99,10 @@ impl TextEditorHost for MonoHost {
|
||||
&self.text
|
||||
}
|
||||
|
||||
fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
fn replace(&mut self, range: Range<usize>, text: &str, _: EditKind) -> bool {
|
||||
let byte = |chars: usize| self.text.char_indices().nth(chars).map_or(self.text.len(), |(at, _)| at);
|
||||
let (from, to) = (byte(range.start), byte(range.end));
|
||||
self.text.replace_range(from..to, text);
|
||||
self.revision += 1;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -249,7 +243,7 @@ const SAMPLE: &str = "The quick brown fox\njumps over the lazy dog";
|
||||
/// width, whose view puts document (0, 0) at its top left. The host's edits (typed, pasted and composed text) are
|
||||
/// written back to `text`, which the story keeps between passes.
|
||||
fn over_canvas(ui: &mut Ui, text: &mut String, mut bind: Bind<'_, TextSelection>) -> StoryOutput {
|
||||
let mut host = MonoHost { text: std::mem::take(text), revision: 0, columns: 1 };
|
||||
let mut host = MonoHost { text: std::mem::take(text), columns: 1 };
|
||||
let room = stage_fitting(ui, |width| {
|
||||
// One cell stays free at the end of a row for the caret after its last char.
|
||||
host.columns = ((f64::from(width) / CELL).floor() as usize).saturating_sub(1);
|
||||
|
||||
@@ -459,7 +459,7 @@ impl Component for NotesEditor<'_> {
|
||||
let text = editor_lines.get(line).map_or("", |l| l.0.as_str());
|
||||
TextPos::new(line, text.char_indices().nth(column).map_or(text.len(), |(b, _)| b))
|
||||
};
|
||||
let mut state = EditorState::new(caret_rect, &lines, position(cursor.caret), revision(&plain));
|
||||
let mut state = EditorState::new(caret_rect, &lines, position(cursor.caret));
|
||||
state.selection = (!selected.is_empty()).then(|| (position(cursor.anchor), position(cursor.caret)));
|
||||
cx.editor_state(state);
|
||||
}
|
||||
@@ -535,14 +535,6 @@ fn paragraph_runs<'a>(paragraph: &'a NotesParagraph, font: &FontRef, size: f32,
|
||||
if runs.is_empty() { vec![DocRun::new("", font.clone(), size, ink)] } else { runs }
|
||||
}
|
||||
|
||||
/// A number that changes with the notes' text, for the input method's revision.
|
||||
fn revision(plain: &str) -> u64 {
|
||||
use std::hash::{Hash as _, Hasher as _};
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
plain.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// The selection of the chars `from..to` of a laid-out paragraph as one band per galley row it touches, in the
|
||||
/// galley's coordinates.
|
||||
fn selection_bands(galley: &egui::Galley, from: usize, to: usize) -> Vec<Rect> {
|
||||
|
||||
@@ -16,7 +16,6 @@ use egui::{Event, ImeEvent, Key, Modifiers, Rect, pos2, vec2};
|
||||
#[derive(Default)]
|
||||
struct Host {
|
||||
text: String,
|
||||
revision: u64,
|
||||
vertical: bool,
|
||||
/// The host applies formatting keys.
|
||||
formats: bool,
|
||||
@@ -32,10 +31,6 @@ impl TextEditorHost for Host {
|
||||
&self.text
|
||||
}
|
||||
|
||||
fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
fn vertical(&self) -> bool {
|
||||
self.vertical
|
||||
}
|
||||
@@ -44,7 +39,6 @@ impl TextEditorHost for Host {
|
||||
let byte = |chars: usize| self.text.char_indices().nth(chars).map_or(self.text.len(), |(at, _)| at);
|
||||
let (from, to) = (byte(range.start), byte(range.end));
|
||||
self.text.replace_range(from..to, text);
|
||||
self.revision += 1;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -171,6 +165,49 @@ fn a_primary_press_on_the_canvas_background_commits_the_session_with_its_marked_
|
||||
assert_eq!(editor.text(), "abcdkzk", "the marked text stays as typed");
|
||||
}
|
||||
|
||||
fn preedit(text: &str) -> Event {
|
||||
Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None })
|
||||
}
|
||||
|
||||
/// Composing on a canvas: the marked text is written at the caret, the IME opens at the editor's caret, and
|
||||
/// Command+Enter while composing commits nothing. A click in the text that arrives with its release and a late commit
|
||||
/// in one raw frame keeps the marked text as typed and interrupts the composition once: one press per pass holds the
|
||||
/// release and the commit for the next pass, where the commit is stale. Later events of the interrupted composition
|
||||
/// are dropped until the OS completes the reset; then a new composition starts at the clicked caret.
|
||||
#[trial]
|
||||
fn a_click_during_composition_keeps_the_marked_text_and_interrupts_the_composition_once() {
|
||||
let mut editor = session("abc", None);
|
||||
editor.focus();
|
||||
editor.fixture.frame(vec![preedit("kzk")]).settle();
|
||||
assert_eq!(editor.text(), "abckzk", "the marked text is written at the caret");
|
||||
let ime = editor.fixture.ime().cloned().expect("the editor owns the IME");
|
||||
assert!(!ime.interrupt);
|
||||
assert!(
|
||||
Rect::from_min_size(pos2(0.0, 0.0), vec2(200.0, 20.0)).expand(1.0).contains_rect(ime.caret),
|
||||
"the IME opens at the caret: {:?}",
|
||||
ime.caret
|
||||
);
|
||||
editor.fixture.key(Key::Enter, Modifiers::COMMAND).settle();
|
||||
assert_eq!(editor.commits.get(), 0, "Enter while composing belongs to the input method");
|
||||
|
||||
let at = pos2(1.0, 10.0);
|
||||
editor.fixture.frame(vec![pointer::moved(at)]);
|
||||
editor.fixture.frame(vec![pointer::press(at), pointer::release(at), Event::Ime(ImeEvent::Commit("kzk".to_owned()))]);
|
||||
let pressed = editor.fixture.ime().cloned().expect("the editor keeps the IME");
|
||||
let reset = pressed.reset.filter(|_| pressed.interrupt).expect("the press pass interrupts the composition and asks for a reset");
|
||||
for _ in 0..3 {
|
||||
editor.fixture.frame(Vec::new());
|
||||
assert!(!editor.fixture.ime().is_some_and(|ime| ime.interrupt), "the composition is interrupted once");
|
||||
}
|
||||
assert_eq!(editor.text(), "abckzk", "the marked text stays as typed and the late commit is dropped");
|
||||
assert_eq!(*editor.selection.borrow(), TextSelection::caret_at(1), "the press placed the caret");
|
||||
editor.fixture.frame(vec![preedit("q")]).settle();
|
||||
assert_eq!(editor.text(), "abckzk", "a preedit before the reset completes belongs to the interrupted composition");
|
||||
editor.fixture.frame(vec![Event::ImeResetCompleted { request_id: reset }, preedit("q")]).settle();
|
||||
assert_eq!(editor.text(), "aqbckzk", "after the reset a new composition starts at the caret");
|
||||
assert_eq!(editor.commits.get(), 0, "a press in the text keeps the session open");
|
||||
}
|
||||
|
||||
/// In vertical text Alt+Down follows the flow and loosens the tracking; a host that applies no formatting leaves
|
||||
/// Alt+Up to move the caret a line up.
|
||||
#[trial]
|
||||
|
||||
@@ -26,8 +26,6 @@ pub(crate) struct EditorInfo {
|
||||
pub purpose: EditorPurpose,
|
||||
pub focused: bool,
|
||||
pub read_only: bool,
|
||||
/// An input that changes text was delivered this pass.
|
||||
pub edited: bool,
|
||||
}
|
||||
|
||||
impl<C: Component> PartsCx<'_, C> {
|
||||
@@ -84,8 +82,7 @@ pub(crate) fn run<C: Component>(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe
|
||||
can
|
||||
});
|
||||
}
|
||||
let edited = inputs.iter().any(|input| !input.is_read_only_safe());
|
||||
cx.core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only, edited });
|
||||
cx.core.editor = Some(EditorInfo { widget, rect: decl.rect, purpose: decl.purpose, focused, read_only });
|
||||
cx.core.editor_inputs = inputs;
|
||||
}
|
||||
|
||||
@@ -107,7 +104,7 @@ impl<C: Component> Cx<'_, C> {
|
||||
if info.focused {
|
||||
ime::note_caret(ctx, info.widget, info.rect, state.caret, masked);
|
||||
}
|
||||
ime::note_editor(ctx, info.widget, state.revision, info.edited, (state.can_undo, state.can_redo));
|
||||
ime::note_editor(ctx, info.widget, state.composing, (state.can_undo, state.can_redo));
|
||||
if !text_access::exposed(ctx, info.widget) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -254,8 +254,10 @@ pub struct EditorState<'a> {
|
||||
pub caret_at: TextPos,
|
||||
/// The selection.
|
||||
pub selection: Option<(TextPos, TextPos)>,
|
||||
/// Bumped on every document change; a change that follows no delivered edit resets the composition context.
|
||||
pub revision: u64,
|
||||
/// The editor shows marked text of an input method. An editor that ends the composition itself (a press in its
|
||||
/// text, a selection, an app edit over the marked text) reports `false` and the OS composition is interrupted;
|
||||
/// an editor that shows no marked text reports `false` throughout.
|
||||
pub composing: bool,
|
||||
/// Whether undo and redo have something to do; false sends them to the app command (11.3).
|
||||
pub can_undo: bool,
|
||||
/// Whether redo has something to do.
|
||||
@@ -263,9 +265,9 @@ pub struct EditorState<'a> {
|
||||
}
|
||||
|
||||
impl<'a> EditorState<'a> {
|
||||
/// A state with no selection and nothing to undo.
|
||||
pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos, revision: u64) -> Self {
|
||||
EditorState { caret, lines, caret_at, selection: None, revision, can_undo: false, can_redo: false }
|
||||
/// A state with no selection, no marked text and nothing to undo.
|
||||
pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos) -> Self {
|
||||
EditorState { caret, lines, caret_at, selection: None, composing: false, can_undo: false, can_redo: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,8 @@ pub struct ImeSeen {
|
||||
pub owner: egui::Id,
|
||||
/// The OS composition is to be interrupted.
|
||||
pub interrupt: bool,
|
||||
/// The reset the frame asked for; a trial answers it with `Event::ImeResetCompleted`.
|
||||
pub reset: Option<egui::ImeResetId>,
|
||||
/// Where the candidate window opens.
|
||||
pub caret: Rect,
|
||||
}
|
||||
@@ -230,6 +232,7 @@ pub(crate) fn run_frame(
|
||||
ime: output.platform_output.ime.as_ref().map(|ime| ImeSeen {
|
||||
owner: ime.owner,
|
||||
interrupt: ime.should_interrupt_composition,
|
||||
reset: ime.reset_request,
|
||||
caret: ime.cursor_rect,
|
||||
}),
|
||||
textures: std::mem::take(&mut output.textures_delta),
|
||||
|
||||
@@ -10,8 +10,8 @@ pub(crate) enum Raw {
|
||||
cursor_chars: Option<std::ops::Range<usize>>,
|
||||
},
|
||||
Commit(String),
|
||||
/// The OS finished the reset the engine asked for.
|
||||
ResetCompleted,
|
||||
/// The OS finished the reset with this request id.
|
||||
ResetCompleted(egui::ImeResetId),
|
||||
}
|
||||
|
||||
/// Removes the IME events from `events` and returns them in order.
|
||||
@@ -28,8 +28,8 @@ pub(crate) fn take_events(events: &mut Vec<Event>) -> Vec<Raw> {
|
||||
}
|
||||
false
|
||||
}
|
||||
Event::ImeResetCompleted { .. } => {
|
||||
taken.push(Raw::ResetCompleted);
|
||||
Event::ImeResetCompleted { request_id } => {
|
||||
taken.push(Raw::ResetCompleted(*request_id));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
@@ -49,8 +49,9 @@ pub(crate) struct Output {
|
||||
pub password: bool,
|
||||
}
|
||||
|
||||
/// Writes the pass's IME output; egui reads it only when it is `Some` at the end of the pass.
|
||||
pub(crate) fn write(ctx: &Context, viewport: ViewportId, out: Output) {
|
||||
/// Writes the pass's IME output; egui reads it only when it is `Some` at the end of the pass. Returns the reset
|
||||
/// request an interrupt published: its completion is the one that matches (`None` when the ids ran out).
|
||||
pub(crate) fn write(ctx: &Context, viewport: ViewportId, out: Output) -> Option<egui::ImeResetId> {
|
||||
let reset = out.interrupt.then(|| ctx.request_ime_reset(viewport)).flatten();
|
||||
ctx.output_mut(|output| {
|
||||
let mut ime = egui::output::IMEOutput::new(
|
||||
@@ -64,6 +65,7 @@ pub(crate) fn write(ctx: &Context, viewport: ViewportId, out: Output) {
|
||||
ime.reset_request = reset;
|
||||
output.ime = Some(ime);
|
||||
});
|
||||
reset
|
||||
}
|
||||
|
||||
/// Drops what `TextEdit` wrote in a pass whose IME output the engine writes.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! the one writer of `PlatformOutput.ime`; otherwise both stay with egui and the app's own widgets.
|
||||
|
||||
use crate::runtime::egui::ime as os;
|
||||
use crate::runtime::egui::pass;
|
||||
use crate::runtime::egui::{pass, viewports};
|
||||
use crate::runtime::frame::{PerViewport, Stored};
|
||||
use craft_behavior::EditorInput;
|
||||
use egui::{Context, Event, Id, Key, Rect, ViewportId};
|
||||
@@ -19,8 +19,12 @@ struct Engine {
|
||||
generation: u64,
|
||||
composing: bool,
|
||||
guard: u8,
|
||||
/// A reset was asked for; events of the old composition are dropped until the OS answers or the IME disables.
|
||||
/// A reset was asked for; events of the old composition are dropped until its completion arrives.
|
||||
stale: bool,
|
||||
/// The reset request `stale` waits for, as the pass that published it got it back. `None` before it is published,
|
||||
/// and once the integration can no longer answer it: a pass with no IME output disallows the IME and an unfocused
|
||||
/// window drops the pending reset, so the next pass with an owner asks again.
|
||||
reset: Option<egui::ImeResetId>,
|
||||
/// Edits for `owner`, in arrival order, until its run of this pass takes them.
|
||||
edits: Vec<EditorInput>,
|
||||
/// `owner` took its edits this pass; an owner not shown for a pass never does, and its edits are dropped.
|
||||
@@ -39,11 +43,22 @@ impl Stored for Engine {}
|
||||
#[derive(Clone, Copy)]
|
||||
struct EditorFacts {
|
||||
owner: Id,
|
||||
revision: u64,
|
||||
composing: bool,
|
||||
can_undo: bool,
|
||||
can_redo: bool,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
/// 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) {
|
||||
self.composing = false;
|
||||
self.preedit.clear();
|
||||
self.stale = true;
|
||||
self.interrupt = Some(owner);
|
||||
}
|
||||
}
|
||||
|
||||
fn with<R>(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut Engine) -> R) -> R {
|
||||
PerViewport::<Engine>::with(ctx, viewport, f)
|
||||
}
|
||||
@@ -57,7 +72,7 @@ fn current<R>(ctx: &Context, f: impl FnOnce(&mut Engine) -> R) -> R {
|
||||
/// the keys that would end the composition.
|
||||
pub(crate) fn input_hook(ctx: &Context, events: &mut Vec<Event>, viewport: ViewportId) {
|
||||
with(ctx, viewport, |engine| {
|
||||
if engine.owner.is_some() || engine.stale {
|
||||
if engine.owner.is_some() || engine.reset.is_some() {
|
||||
engine.queue.extend(os::take_events(events));
|
||||
}
|
||||
let guarded = engine.composing || engine.guard > 0;
|
||||
@@ -78,8 +93,7 @@ pub(crate) fn begin(ctx: &Context, owner: Option<Id>) {
|
||||
&& let Some(old) = engine.owner
|
||||
{
|
||||
engine.leaving = Some((old, std::mem::take(&mut engine.preedit)));
|
||||
engine.interrupt = Some(old);
|
||||
engine.stale = true;
|
||||
engine.interrupt(old);
|
||||
}
|
||||
engine.composing = false;
|
||||
engine.edits.clear();
|
||||
@@ -88,7 +102,13 @@ pub(crate) fn begin(ctx: &Context, owner: Option<Id>) {
|
||||
}
|
||||
for raw in std::mem::take(&mut engine.queue) {
|
||||
match raw {
|
||||
os::Raw::ResetCompleted => engine.stale = false,
|
||||
// A completion of an earlier request is stale: the latest request still fences.
|
||||
os::Raw::ResetCompleted(id) => {
|
||||
if engine.reset == Some(id) {
|
||||
engine.stale = false;
|
||||
engine.reset = None;
|
||||
}
|
||||
}
|
||||
_ if engine.stale || engine.owner.is_none() => {}
|
||||
os::Raw::Preedit { text, cursor_chars } => {
|
||||
engine.composing = !text.is_empty();
|
||||
@@ -122,9 +142,7 @@ pub(crate) fn take(ctx: &Context, owner: Id, read_only: bool) -> Vec<EditorInput
|
||||
if read_only {
|
||||
engine.edits.clear();
|
||||
if engine.composing {
|
||||
engine.composing = false;
|
||||
engine.stale = true;
|
||||
engine.interrupt = Some(owner);
|
||||
engine.interrupt(owner);
|
||||
}
|
||||
engine.preedit.clear();
|
||||
return Vec::new();
|
||||
@@ -133,19 +151,17 @@ pub(crate) fn take(ctx: &Context, owner: Id, read_only: bool) -> Vec<EditorInput
|
||||
})
|
||||
}
|
||||
|
||||
/// What an editor that draws its own caret reports once per pass. A new `revision` that follows no edit the engine
|
||||
/// delivered (`edited`) is an app change: the composition context is stale, so the OS composition is interrupted
|
||||
/// and its late events are dropped.
|
||||
pub(crate) fn note_editor(ctx: &Context, owner: Id, revision: u64, edited: bool, history: (bool, bool)) {
|
||||
/// What an editor that draws its own caret reports once per pass. An editor that reported composing and now does
|
||||
/// not ended the composition itself (a press in its text, a selection, an app edit over the marked text): the OS
|
||||
/// composition is interrupted and its late events are dropped. An editor that shows no marked text reports `false`
|
||||
/// throughout and the OS composes for it until the commit.
|
||||
pub(crate) fn note_editor(ctx: &Context, owner: Id, composing: bool, history: (bool, bool)) {
|
||||
current(ctx, |engine| {
|
||||
let changed = engine.editor.is_some_and(|last| last.owner == owner && last.revision != revision);
|
||||
if changed && !edited && engine.owner == Some(owner) && engine.composing {
|
||||
engine.composing = false;
|
||||
engine.preedit.clear();
|
||||
engine.stale = true;
|
||||
engine.interrupt = Some(owner);
|
||||
let ended = !composing && engine.editor.is_some_and(|last| last.owner == owner && last.composing);
|
||||
if ended && engine.owner == Some(owner) && engine.composing {
|
||||
engine.interrupt(owner);
|
||||
}
|
||||
engine.editor = Some(EditorFacts { owner, revision, can_undo: history.0, can_redo: history.1 });
|
||||
engine.editor = Some(EditorFacts { owner, composing, can_undo: history.0, can_redo: history.1 });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -176,26 +192,45 @@ pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, pas
|
||||
/// 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 focused = viewports::current(ctx).focused;
|
||||
let (owner, interrupt, caret, generation) = with(ctx, viewport, |engine| {
|
||||
if !std::mem::take(&mut engine.ran) {
|
||||
engine.edits.clear();
|
||||
}
|
||||
if !focused {
|
||||
engine.reset = None;
|
||||
}
|
||||
// The fence has no request the integration can answer: the owner's output asks again.
|
||||
if engine.stale
|
||||
&& engine.reset.is_none()
|
||||
&& focused
|
||||
&& let Some(owner) = engine.owner
|
||||
{
|
||||
engine.interrupt.get_or_insert(owner);
|
||||
}
|
||||
(engine.owner, engine.interrupt.take(), engine.caret.take(), engine.generation)
|
||||
});
|
||||
if owner.is_none() && interrupt.is_none() {
|
||||
return;
|
||||
}
|
||||
os::clear(ctx);
|
||||
match (caret, interrupt, owner) {
|
||||
(Some((id, field, caret, password)), interrupt, _) if Some(id) == owner => {
|
||||
os::write(ctx, viewport, os::Output { owner: id, field, caret, interrupt: interrupt.is_some(), generation, password });
|
||||
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 }))
|
||||
}
|
||||
// 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,
|
||||
}
|
||||
// The old owner still gets an output in the pass it lost focus, or the OS never interrupts.
|
||||
(_, Some(old), _) => os::write(
|
||||
ctx,
|
||||
viewport,
|
||||
os::Output { owner: old, field: Rect::NOTHING, caret: Rect::NOTHING, interrupt: true, generation, password: false },
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
with(ctx, viewport, |engine| match written {
|
||||
Some(published) if interrupt.is_some() => engine.reset = published,
|
||||
Some(_) => {}
|
||||
// No IME output disallows the IME, and the integration drops the pending reset with it.
|
||||
None => engine.reset = None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,10 +7,10 @@ use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState};
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::click;
|
||||
use craft_ui::testing::pointer::{click, moved, press, release};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::{Event, Id, Key, Modifiers, Pos2, Rect, Response};
|
||||
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) };
|
||||
@@ -56,7 +56,7 @@ impl Component for Probe<'_> {
|
||||
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, 0));
|
||||
cx.editor_state(EditorState::new(caret, &lines, end));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
@@ -94,6 +94,17 @@ impl Rig {
|
||||
fn take(&self) -> Vec<EditorInput> {
|
||||
self.log.take()
|
||||
}
|
||||
|
||||
/// A frame with `events`, and the reset request its IME output carries.
|
||||
fn frame_reset(&mut self, events: Vec<Event>) -> Option<egui::ImeResetId> {
|
||||
self.frame(events);
|
||||
self.frames.ime().and_then(|ime| ime.reset)
|
||||
}
|
||||
|
||||
/// Hover, press, release and an idle frame at `at`, and the reset requests they carry.
|
||||
fn click_resets(&mut self, at: Pos2) -> Vec<egui::ImeResetId> {
|
||||
[vec![moved(at)], vec![press(at)], vec![release(at)], Vec::new()].into_iter().filter_map(|events| self.frame_reset(events)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn show(ui: &mut egui::Ui, log: &RefCell<Vec<EditorInput>>, id: &Cell<Id>, read_only: bool) {
|
||||
@@ -126,3 +137,38 @@ fn editor_input_reaches_an_editor_part_and_read_only_filtering_drops_edits() {
|
||||
let moves = rig.take();
|
||||
assert!(matches!(moves.as_slice(), [EditorInput::Move(..)]), "moves still arrive: {moves:?}");
|
||||
}
|
||||
|
||||
fn preedit(text: &str) -> Event {
|
||||
Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None })
|
||||
}
|
||||
|
||||
/// A reset fences the interrupted composition until its own request completes. Focus leaving an editor while it
|
||||
/// composes asks for a reset; a pass with no IME output retires the request (the integration drops it with the
|
||||
/// IME), so focus coming back asks again. The retired request's completion is stale and lets nothing through; the
|
||||
/// new request's completion lets the composition that follows it in.
|
||||
#[trial]
|
||||
fn a_reset_ends_only_with_the_completion_of_its_own_request() {
|
||||
let mut rig = Rig::new();
|
||||
rig.focus();
|
||||
rig.frame(vec![preedit("k")]);
|
||||
assert!(matches!(rig.take().as_slice(), [EditorInput::Preedit { .. }]), "the editor composes");
|
||||
|
||||
let left = rig.click_resets(Pos2::new(400.0, 300.0));
|
||||
let [first] = left.as_slice() else { panic!("focus leaving a composition asks for one reset: {left:?}") };
|
||||
for _ in 0..2 {
|
||||
assert_eq!(rig.frame_reset(Vec::new()), None, "no editor owns the IME, so no reset is asked for");
|
||||
}
|
||||
let back = rig.click_resets(AT.center());
|
||||
let [second] = back.as_slice() else { panic!("focus coming back while the reset is pending asks again: {back:?}") };
|
||||
assert_ne!(first, second);
|
||||
rig.take();
|
||||
|
||||
rig.frame(vec![Event::ImeResetCompleted { request_id: *first }, preedit("x")]);
|
||||
assert!(rig.take().is_empty(), "the retired request's completion is stale: the composition stays fenced");
|
||||
rig.frame(vec![Event::ImeResetCompleted { request_id: *second }, preedit("y")]);
|
||||
let inputs = rig.take();
|
||||
assert!(
|
||||
matches!(inputs.as_slice(), [EditorInput::Preedit { text, .. }] if &**text == "y"),
|
||||
"the completion of the latest request ends the fence in its place in the stream: {inputs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2656,8 +2656,8 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
|
||||
- `craft_ui::primitives::EditorPurpose`: `pub enum EditorPurpose { Text, Code, Number, Password }`. What an editor part edits.
|
||||
- `craft_ui::primitives::EditorRun`: `pub struct EditorRun<'a> { pub bytes: Range<usize>, pub rtl: bool, pub positions: &'a [f32], pub widths: &'a [f32] }`. One bidi run of a line: its bytes, direction, each character's start offset and advance.
|
||||
- `pub const fn new(bytes: Range<usize>, rtl: bool, positions: &'a [f32], widths: &'a [f32]) -> Self`. A run over `bytes`.
|
||||
- `craft_ui::primitives::EditorState`: `pub struct EditorState<'a> { pub caret: Rect, pub lines: &'a [EditorLine<'a>], pub caret_at: TextPos, pub selection: Option<(TextPos, TextPos)>, pub revision: u64, pub can_undo: bool, pub can_redo: bool }`. What an own-caret editor reports once per frame for the IME and AccessKit.
|
||||
- `pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos, revision: u64) -> Self`. A state with no selection and nothing to undo.
|
||||
- `craft_ui::primitives::EditorState`: `pub struct EditorState<'a> { pub caret: Rect, pub lines: &'a [EditorLine<'a>], pub caret_at: TextPos, pub selection: Option<(TextPos, TextPos)>, pub composing: bool, pub can_undo: bool, pub can_redo: bool }`. What an own-caret editor reports once per frame for the IME and AccessKit.
|
||||
- `pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos) -> Self`. A state with no selection, no marked text and nothing to undo.
|
||||
- `craft_ui::primitives::FacesCx`: `pub trait FacesCx`. Where a document face is asked for: a component's context, its measure or a content painter.
|
||||
- `fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState`. The face registered under `key` as a family of its own. `load` runs only for a new key within the frame's
|
||||
- `craft_ui::primitives::FakeThumbSource`: `pub struct FakeThumbSource<K>`. A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets,
|
||||
|
||||
Reference in New Issue
Block a user