From 14e27ecbbd4d15cc82c6c105d537122ca4690fe2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 14:51:29 +0000 Subject: [PATCH] shell-w9: net change of 3 commits - shell-w9: written from its sheet - shell-w9: review fixes (review-1) - shell-w9: review fixes (review-1) --- crates/engine/src/cmd/text.rs | 131 +- crates/engine/src/cmd/text/caret.rs | 4 +- crates/engine/src/cmd/text/editing.rs | 21 +- crates/engine/src/cmd/text/ime.rs | 224 +-- crates/engine/src/cmd/text/layout.rs | 20 +- crates/engine/src/tests.rs | 193 +-- crates/ui-egui/src/app/ime.rs | 706 --------- crates/ui-egui/src/gpu_lock.rs | 37 - crates/ui-egui/src/ime_hooks.rs | 39 - crates/ui-egui/src/ime_tests.rs | 2013 ++----------------------- 10 files changed, 398 insertions(+), 2990 deletions(-) delete mode 100644 crates/ui-egui/src/app/ime.rs delete mode 100644 crates/ui-egui/src/ime_hooks.rs diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bc79dccfc..52a8593cb 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -26,15 +26,14 @@ use autocorrect::autocorrect_options; pub use autocorrect::{AUTOCORRECT, AutoList, correct_word}; pub(crate) use caret::{apply_leading_tabs, delete_dir}; use caret::{delete, delete_surrounding, get, insert, move_caret, select, select_all, select_para, select_word, set}; -use editing::{edit, exit}; pub(crate) use editing::{insert_field, insert_text, paste_body}; pub use formatting::format_range; use formatting::{fonts_used, replace_font}; pub(crate) use formatting::{format_body, format_para, format_run, format_run_levels, link_text}; -pub use ime::{IME_SURROUNDING_MAX_BYTES, ImeSurrounding, cell_range_underlines, composition_underlines, ime_surrounding, range_underlines}; +pub use ime::{cell_range_underlines, range_underlines}; use ime::{commit, compose}; pub(crate) use layout::ctx_for; -pub use layout::{caret_color, caret_line, fit_text_box, layout_for, text_frame, text_pos_at}; +pub use layout::{caret_line, fit_text_box, layout_for, text_frame, text_pos_at}; /// Catalogue text-editing, selection, autocorrect, font, IME, and surrounding-deletion commands /// with their parameter docs and enabled predicates. @@ -95,8 +94,8 @@ pub fn specs() -> Vec { // An input method asks for text around the caret to be removed (macOS press-and-hold, // dictation, Wayland text-input). Internal: the keyboard and control protocol keep the // existing text.delete spelling. `bytes` says the counts are UTF-8 bytes (winit's - // `Ime::DeleteSurrounding`), otherwise characters, both in the logical text - // `ime_surrounding` publishes: a paragraph mark or soft line break is one `\n` byte, so a + // `Ime::DeleteSurrounding`), otherwise characters, both in the logical coordinates + // the editor publishes: a paragraph mark or soft line break is one `\n` byte, so a // range may cross paragraphs. The selection and pre-edit are kept; byte ranges round // inward to whole scalars. A deletion while composing stays in the composition's single // undo step. @@ -134,6 +133,128 @@ pub fn specs() -> Vec { ] } +/// Applies one replacement inside the session's guarded, rollback-capable transaction. +/// The handler records per-insert history; live preedits retain their original undo snapshot. +pub(crate) fn replace_text_range( + s: &mut Session, + range: std::ops::Range, + text: &str, + kind: crate::TextReplaceKind, +) -> Result { + use crate::TextReplaceKind; + + let st = s.doc()?; + let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?; + if !selection.notes && st.shape(selection.shape).is_none_or(|shape| shape.locked) { + return Err(bad("text.replaceRange", "the text being edited is unavailable or locked")); + } + let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let invalid = || bad("text.replaceRange", "the range is not in the text"); + if range.start > range.end { + return Err(invalid()); + } + let from = flat_pos(body, range.start).ok_or_else(invalid)?; + let to = flat_pos(body, range.end).ok_or_else(invalid)?; + let old_text = (kind == TextReplaceKind::Typed).then(|| body.text()); + let composing = st.composition.is_some(); + if range.is_empty() && text.is_empty() && !composing { + return Ok(crate::TextReplaceResult { range, selection }); + } + s.begin_text_edit_session()?; + if !matches!(kind, TextReplaceKind::Composing | TextReplaceKind::Committed | TextReplaceKind::Deleted) { + s.settle_composition(); + } + let st = s.doc()?; + let (before, before_selection) = (st.doc.clone(), st.selection.clone()); + let vertex_kind = s.tool.vertex_kind.clone(); + match kind { + TextReplaceKind::Composing | TextReplaceKind::Committed => ime::replace_marked(s, from, to, text, kind == TextReplaceKind::Committed)?, + TextReplaceKind::Deleted if composing => ime::delete_range(s, range.clone(), text)?, + TextReplaceKind::Typed | TextReplaceKind::Pasted | TextReplaceKind::Deleted => { + if let Some(t) = s.doc_mut()?.selection.text.as_mut() { + // Setting the replacement endpoints is part of this edit, not a selection command + // that could settle composition or seal the session's cancellation boundary. + t.anchor = from; + t.caret = to; + t.line_end = None; + } + if kind == TextReplaceKind::Typed { + insert_text(s, text, None)?; + } else if from != to || !text.is_empty() { + editing::replace_selection(s, text, None)?; + } + let st = s.doc_mut()?; + if !Arc::ptr_eq(&before, &st.doc) { + let command = match kind { + TextReplaceKind::Pasted => "edit.paste", + TextReplaceKind::Deleted => "text.delete", + _ => "text.insert", + }; + let label = super::find_command(command).ok_or_else(|| bad("text.replaceRange", "the edit command is not registered"))?.label; + push_undo(st, HistoryEntry { label: label.into(), doc: before, selection: before_selection, vertex_kind }); + } + } + } + let st = s.doc()?; + let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?; + let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let caret = flat_offset(body, selection.caret).ok_or_else(invalid)?; + let inserted = if kind == TextReplaceKind::Composing && !text.is_empty() { + let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "the composition was refused"))?; + let start = flat_offset(body, c.start).ok_or_else(invalid)?; + start..start + c.len + } else if kind == TextReplaceKind::Deleted { + range.start..range.start + } else if text.is_empty() { + caret..caret + } else if let Some(old_text) = old_text { + // AutoCorrect can replace text preceding the requested insertion, such as (c) plus Space. + let after = body.text(); + let unchanged = old_text.chars().zip(after.chars()).take_while(|(a, b)| a == b).count(); + range.start.min(unchanged).min(caret)..caret + } else { + range.start.min(caret)..caret + }; + Ok(crate::TextReplaceResult { range: inserted, selection }) +} + +/// Character offsets count each paragraph separator once, including empty paragraphs. +fn flat_pos(body: &TextBody, mut offset: usize) -> Option { + if body.paragraphs.is_empty() { + return (offset == 0).then_some((0, 0)); + } + for (pi, para) in body.paragraphs.iter().enumerate() { + let len = para.char_len(); + if offset <= len { + return Some((pi, offset)); + } + offset = offset.checked_sub(len.checked_add(1)?)?; + } + None +} + +fn flat_offset(body: &TextBody, pos: Pos) -> Option { + if body.paragraphs.is_empty() { + return (pos == (0, 0)).then_some(0); + } + let para = body.paragraphs.get(pos.0)?; + if pos.1 > para.char_len() { + return None; + } + body.paragraphs.iter().take(pos.0).try_fold(pos.1, |offset, para| offset.checked_add(para.char_len())?.checked_add(1)) +} + +fn edit(s: &mut Session, p: &Value) -> Result { + let result = editing::edit(s, p)?; + s.begin_text_edit_session()?; + Ok(result) +} + +fn exit(s: &mut Session, p: &Value) -> Result { + s.finish_text_edit_session(false)?; + editing::exit(s, p) +} + /// The text body a text selection edits. pub fn body_of<'a>(st: &'a DocState, t: &TextSel) -> Option<&'a TextBody> { if t.notes { diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rs index db7cfd48e..df36eed4c 100644 --- a/crates/engine/src/cmd/text/caret.rs +++ b/crates/engine/src/cmd/text/caret.rs @@ -99,8 +99,8 @@ pub(super) fn delete_surrounding(s: &mut Session, p: &Value) -> Result { let t = st.selection.text.clone().ok_or_else(|| bad("text.deleteSurrounding", "not editing text"))?; let body = body_of(st, &t).ok_or_else(|| bad("text.deleteSurrounding", "the text being edited is gone"))?; let comp = composition_range(body, st.composition.as_ref()); - // The ranges are in the same logical coordinates `ime_surrounding` publishes: one byte for a - // paragraph separator and for a soft line break. A range may therefore cross paragraphs. + // The ranges use the logical coordinates the editor publishes: one byte for a paragraph + // separator and for a soft line break. A range may therefore cross paragraphs. let ordered = { let a = model_pos(body, t.anchor).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?; let b = model_pos(body, t.caret).ok_or_else(|| bad("text.deleteSurrounding", "the selection is not in the text"))?; diff --git a/crates/engine/src/cmd/text/editing.rs b/crates/engine/src/cmd/text/editing.rs index 7e2c37cb4..377dc39ab 100644 --- a/crates/engine/src/cmd/text/editing.rs +++ b/crates/engine/src/cmd/text/editing.rs @@ -73,7 +73,6 @@ fn typed(s: &Session, body: &TextBody, at: Pos, text: &str) -> String { } pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) -> Result { - let inherited = inherited_aligns_for_edit(s); let text = { let st = s.doc()?; match &st.selection.text { @@ -84,11 +83,21 @@ pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) None => text.to_string(), } }; - let pos = edit_text(s, |body, t| { + let pos = replace_selection(s, &text, props)?; + autocorrect(s, text.chars().count() == 1)?; + // AutoCorrect can move the caret: a replaced word, or a list lead it removed. + let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret); + Ok(json!({"caret": [pos.0, pos.1]})) +} + +/// Shares insertion styling and paragraph direction rules across typing, pasting and deletion. +pub(super) fn replace_selection(s: &mut Session, text: &str, props: Option) -> Result { + let inherited = inherited_aligns_for_edit(s); + edit_text(s, |body, t| { let (a, b) = t.ordered(); let at = ed::delete(body, a, b); let props = props.clone().or_else(|| if a != b { Some(ed::props_at(body, at)) } else { unlinked_at_link_end(body, at) }); - let c = ed::insert(body, at, &text, props); + let c = ed::insert(body, at, text, props); t.anchor = c; t.caret = c; let last = body.paragraphs.len().saturating_sub(1); @@ -98,11 +107,7 @@ pub(crate) fn insert_text(s: &mut Session, text: &str, props: Option) } } c - })?; - autocorrect(s, text.chars().count() == 1)?; - // AutoCorrect can move the caret: a replaced word, or a list lead it removed. - let pos = s.doc()?.selection.text.as_ref().map_or(pos, |t| t.caret); - Ok(json!({"caret": [pos.0, pos.1]})) + }) } /// Per outline level (0..=8), whether shape `id` on the current slide already resolves an diff --git a/crates/engine/src/cmd/text/ime.rs b/crates/engine/src/cmd/text/ime.rs index 274995467..16622b490 100644 --- a/crates/engine/src/cmd/text/ime.rs +++ b/crates/engine/src/cmd/text/ime.rs @@ -1,24 +1,7 @@ -use super::caret::cell_on_slide; use super::editing::unlinked_at_link_end; use super::layout::{ctx_for, layout_for}; use super::{DocState, Paragraph, Result, Session, TextBody, TextSel, Value, bad, body_of, ed, edit_text, json, str_param, xfrm_of}; -/// Maximum number of UTF-8 bytes in an outgoing IME surrounding-text query. -/// -/// This matches `egui::output::MAX_IME_SURROUNDING_TEXT_BYTES`; keeping the bound here lets the -/// engine answer without copying a whole body or document. -pub const IME_SURROUNDING_MAX_BYTES: usize = 4000; - -/// Bounded committed text around an IME selection, in logical (not visual) order and with UTF-8 -/// byte offsets. The current input-method composition (pre-edit) is removed from both the text -/// and the offsets. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ImeSurrounding { - pub text: String, - pub cursor: usize, - pub anchor: usize, -} - /// How a soft line break reads in the IME view: a newline, like a paragraph break. /// /// The model stores it as `\u{b}` ([`RunKind::Break`]); publishing that control character would @@ -166,77 +149,6 @@ pub(super) fn walk_backward( } } -/// The committed logical text between two model positions (excluding `end`). `None` when it is -/// longer than `cap` bytes: every caller only needs a bounded answer. -fn logical_between(body: &TextBody, comp: Option<(usize, usize, usize)>, start: (usize, usize), end: (usize, usize), cap: usize) -> Option { - let (a, b) = if start <= end { (start, end) } else { (end, start) }; - let mut out = String::new(); - for pi in a.0..=b.0 { - let Some(para) = body.paragraphs.get(pi) else { return Some(out) }; - let from = if pi == a.0 { a.1 } else { 0 }; - let to = if pi == b.0 { b.1 } else { usize::MAX }; - for (i, ch) in committed_chars(para, comp_in(comp, pi)) { - if i < from || i >= to { - continue; - } - out.push(ch); - if out.len() > cap { - return None; - } - } - if pi < b.0 { - out.push('\n'); - if out.len() > cap { - return None; - } - } - } - Some(out) -} - -/// Committed surrounding text for the text being edited. -/// -/// Returns `None` when the body or selection is invalid, or when the selection alone is wider -/// than [`IME_SURROUNDING_MAX_BYTES`]. An empty body is `Some` with empty text, which is distinct -/// from an unavailable context. `cursor > anchor` is preserved for a reversed selection. -/// -/// Only a bounded window is measured and copied: the query walks at most the budget out from the -/// selection on each side and does not copy the rest of the body. Finding the selection's -/// character offsets inside one paragraph still scans that paragraph's prefix, so the time is not -/// bounded independently of the paragraph length. -pub fn ime_surrounding(st: &DocState, t: &TextSel) -> Option { - let body = body_of(st, t)?; - let comp = composition_range(body, st.composition.as_ref()); - let caret = model_pos(body, t.caret)?; - let anchor = model_pos(body, t.anchor)?; - let (start, end) = if caret <= anchor { (caret, anchor) } else { (anchor, caret) }; - let selected = logical_between(body, comp, start, end, IME_SURROUNDING_MAX_BYTES)?; - let selection_len = selected.len(); - let budget = IME_SURROUNDING_MAX_BYTES.saturating_sub(selection_len); - let (_, _, before_available) = walk_backward(body, comp, start, budget, true); - let (_, _, after_available) = walk_forward(body, comp, end, budget, true); - let mut before = (budget / 2).min(before_available); - let mut after = (budget - before).min(after_available); - before = (budget - after).min(before_available); - after = (budget - before).min(after_available); - let (window_start, _, _) = walk_backward(body, comp, start, before, true); - let (window_end, _, _) = walk_forward(body, comp, end, after, true); - let before_text = logical_between(body, comp, window_start, start, budget)?; - let after_text = logical_between(body, comp, end, window_end, budget)?; - let before_len = before_text.len(); - let mut text = before_text; - text.push_str(&selected); - text.push_str(&after_text); - // The budget arithmetic above already bounds this; refuse rather than publish more. - if text.len() > IME_SURROUNDING_MAX_BYTES { - return None; - } - // The caret and anchor are the selection's own endpoints, so their offsets inside the - // window are the window's start plus either end of the selected text. - let (cursor, anchor) = if caret >= anchor { (before_len + selection_len, before_len) } else { (before_len, before_len + selection_len) }; - Some(ImeSurrounding { text, cursor, anchor }) -} - /// Text an input method sends: no paragraph or line breaks (Enter is a key of its own). fn ime_text(s: &str) -> String { s.chars().filter(|c| !c.is_control()).collect() @@ -273,6 +185,7 @@ pub(super) fn compose(s: &mut Session, p: &Value) -> Result { match current { None if text.is_empty() => Ok(json!({"composing": false})), None => { + s.begin_text_edit_session()?; let st = s.doc()?; let (before, before_selection) = (st.doc.clone(), st.selection.clone()); let (start, props) = edit_text(s, |body, t| { @@ -376,43 +289,52 @@ pub fn cell_range_underlines( out } -/// Underlines under an input method's composition (#101), in slide coordinates: `(from, to, -/// thick)` per line, thick under the part being converted. Empty without a composition, or for -/// notes (an egui text field draws its own composition). -pub fn composition_underlines(st: &DocState) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> { - let (Some(c), Some(t)) = (&st.composition, &st.selection.text) else { return vec![] }; - if t.notes { - return vec![]; +/// Replaces the marked text without a selection command that would settle it first. +pub(super) fn replace_marked(s: &mut Session, from: super::Pos, to: super::Pos, text: &str, committed: bool) -> Result<()> { + let st = s.doc()?; + let original_selection = st.selection.clone(); + let had_composition = st.composition.is_some(); + if let Some(c) = &st.composition { + if from != c.start || to != (c.start.0, c.start.1.saturating_add(c.len)) { + return Err(bad("text.replaceRange", "the range does not match the composition")); + } + } else if let Some(t) = s.doc_mut()?.selection.text.as_mut() { + t.anchor = from; + t.caret = to; + t.line_end = None; } - if let Some((row, col)) = t.cell { - let Some(placed) = cell_on_slide(st, t.shape, row, col) else { return vec![] }; - return underline_segments(&placed.layout, placed.to_slide, c); + let params = json!({"text": text}); + if committed && had_composition { + commit(s, ¶ms)?; + } else { + compose(s, ¶ms)?; + if !had_composition && let Some(c) = s.doc_mut()?.composition.as_mut() { + c.before_selection = original_selection; + } + if committed { + s.end_composition(); + } } - let Some(sh) = st.shape(t.shape) else { return vec![] }; - let Some(l) = layout_for(st, t) else { return vec![] }; - let x = xfrm_of(&st.doc, &st.selection, sh); - let tr = deckcraft_render::shape_geometry(sh, x.w, x.h).text_rect; - let m = deckcraft_render::text_transform(x.affine(), tr, l.rotation); - underline_segments(&l, m, c) + Ok(()) } -fn underline_segments( - layout: &deckcraft_text::TextLayout, - to_slide: deckcraft_geom::Affine, - c: &crate::Composition, -) -> Vec<(deckcraft_geom::Point, deckcraft_geom::Point, bool)> { - let pos = |ch: usize| deckcraft_text::Pos { para: c.start.0, ch: c.start.1 + ch }; - let mut out = vec![]; - let mut add = |a: usize, b: usize, thick: bool| { - for (x0, x1, y) in layout.composition_underlines(pos(a), pos(b)) { - out.push((to_slide * deckcraft_geom::Point::new(x0, y), to_slide * deckcraft_geom::Point::new(x1, y), thick)); - } +/// Removes an already normalized character range beside the live composition. +pub(super) fn delete_range(s: &mut Session, range: std::ops::Range, text: &str) -> Result<()> { + let st = s.doc()?; + let t = st.selection.text.as_ref().ok_or_else(|| bad("text.replaceRange", "not editing text"))?; + let body = body_of(st, t).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?; + let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "not composing"))?; + let start = super::flat_offset(body, c.start).ok_or_else(|| bad("text.replaceRange", "the composition is not in the text"))?; + let end = start.saturating_add(c.len); + let (before, after) = if text.is_empty() && range.end == start { + (range.len(), 0) + } else if text.is_empty() && range.start == end { + (0, range.len()) + } else { + return Err(bad("text.replaceRange", "the deletion must be beside the composition")); }; - add(0, c.len, false); - if let Some((a, b)) = c.active { - add(a, b.min(c.len), true); - } - out + super::caret::delete_surrounding(s, &json!({"before": before, "after": after}))?; + Ok(()) } #[cfg(test)] @@ -484,65 +406,14 @@ mod ime_surrounding_tests { assert_eq!(text(&s, id), "aéb", "four bytes contain the whole emoji"); } - /// The committed query is logical text with UTF-8 byte offsets; it keeps a reversed - /// selection, removes the model-stored pre-edit, and treats an empty body as available. - #[test] - fn surrounding_text_is_committed_logical_and_bounded() { - use super::{IME_SURROUNDING_MAX_BYTES, ime_surrounding}; - - let mut s = Session::with_new(); - let id = edit(&mut s); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("aé😀b", 8, 8)); - - s.execute("text.select", &json!({"anchor": [0, 3], "caret": [0, 1]})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.cursor, q.anchor), (1, 7), "reversed selection keeps caret before anchor"); - assert_eq!(q.text, "aé😀b"); - - s.execute("text.set", &json!({"id": id, "text": "ab"})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - s.compose_text("日本", None).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab", 2, 2), "pre-edit is not committed text"); - - s.execute("text.set", &json!({"id": id, "text": ""})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("", 0, 0), "empty body is available"); - - let long = "a".repeat(IME_SURROUNDING_MAX_BYTES + 1500); - s.execute("text.set", &json!({"id": id, "text": long})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - let st = s.doc().unwrap(); - let t = st.selection.text.clone().unwrap(); - let q = ime_surrounding(st, &t).unwrap(); - assert!(q.text.len() <= IME_SURROUNDING_MAX_BYTES, "{}", q.text.len()); - assert_eq!(q.cursor, q.text.len(), "caret stays at the end of the bounded window"); - } - - /// Paragraph marks are part of the logical text the platform sees (`\n`), so a deletion may - /// remove one and merge the paragraphs, exactly as the published offsets say. + /// A paragraph mark occupies one logical byte; deleting it merges its paragraphs. #[test] fn paragraph_marks_are_deletable_logical_text() { - use super::ime_surrounding; - let mut s = Session::with_new(); let id = edit(&mut s); s.execute("text.set", &json!({"id": id, "text": "ab\ncd"})).unwrap(); // The caret at the start of the second paragraph: after "ab" and its paragraph mark. s.execute("text.select", &json!({"anchor": [1, 0], "caret": [1, 0]})).unwrap(); - let st = s.doc().unwrap(); - let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("ab\ncd", 3, 3)); - // One byte before the caret is that paragraph mark. s.delete_surrounding(1, 0, true).unwrap(); assert_eq!(text(&s, id), "abcd", "the mark goes and the paragraphs merge"); @@ -563,12 +434,9 @@ mod ime_surrounding_tests { assert_eq!(text(&s, id), "abcd"); } - /// A soft line break (Shift+Enter) is published as a newline, like a paragraph break: the - /// platform must never see the model's `\u{b}`, which its own text filter would reject. + /// A soft line break occupies one logical byte even inside a single paragraph. #[test] fn soft_line_breaks_read_as_newlines() { - use super::ime_surrounding; - let mut s = Session::with_new(); let id = edit(&mut s); s.execute("text.autocorrect", &json!({"on": false})).unwrap(); // isolate logical line-break coordinates @@ -577,10 +445,6 @@ mod ime_surrounding_tests { s.execute("text.select", &json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); s.execute("text.insert", &json!({"text": "\u{b}"})).unwrap(); assert_eq!(text(&s, id), "a\u{b}b", "a line break inside one paragraph"); - let st = s.doc().unwrap(); - let q = ime_surrounding(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((q.text.as_str(), q.cursor, q.anchor), ("a\nb", 2, 2)); - // The break is one logical byte, so removing it removes one character. s.delete_surrounding(1, 0, true).unwrap(); assert_eq!(text(&s, id), "ab"); diff --git a/crates/engine/src/cmd/text/layout.rs b/crates/engine/src/cmd/text/layout.rs index 866eb7363..ba8de6e81 100644 --- a/crates/engine/src/cmd/text/layout.rs +++ b/crates/engine/src/cmd/text/layout.rs @@ -1,7 +1,7 @@ use super::caret::cell_on_slide; use super::{ - Affine, Arc, AutoFit, Ctx, DocState, Paragraph, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody, - TextSel, Value, ed, resolve, xfrm_of, + Affine, Arc, AutoFit, Ctx, DocState, Point, Pos, Presentation, Rect, Result, Selection, Session, Shape, ShapeId, Target, TextBody, TextSel, + Value, resolve, xfrm_of, }; /// Refit a shape after its text changed: remember the shrink-on-overflow scale the layout @@ -179,22 +179,6 @@ pub fn caret_line(st: &DocState, t: &TextSel) -> Option<(deckcraft_geom::Point, Some((m * deckcraft_geom::Point::new(cx, top), m * deckcraft_geom::Point::new(cx, bot))) } -/// The colour of text typed at the caret. The canvas draws the caret in it, so the caret shows -/// wherever the text does: light on a dark slide, dark on a light one. `None` when that text -/// has no fill to take a colour from. -pub fn caret_color(st: &DocState, t: &TextSel) -> Option { - if t.notes || t.cell.is_some() { - return None; - } - let sh = st.shape(t.shape)?; - let body = sh.text.as_ref()?; - let ctx = ctx_for(&st.doc, &st.selection)?; - let blank = Paragraph::default(); - let para = body.paragraphs.get(t.caret.0).unwrap_or(&blank); - let props = resolve::run(&ctx, sh, para, &ed::props_at(body, t.caret)); - Some(resolve::text_color(&ctx, &props)).filter(|c| c.a > 0) -} - pub(super) fn pos_param(p: &Value, key: &str) -> Option { let a = p.get(key)?.as_array()?; Some((a.first()?.as_u64()? as usize, a.get(1)?.as_u64()? as usize)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 52006b7a7..7cf9447cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2505,65 +2505,6 @@ fn ime_on_a_selected_shape_replaces_its_text() { assert_eq!(s.commit_text("x").unwrap()["handled"], false); } -/// #101: the composition is underlined in place, under the composed characters, with a thicker -/// line under the part being converted. -#[test] -fn ime_composition_underlines_follow_the_text() { - let mut s = session(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - s.compose_text("にほんご", Some((2, 4))).unwrap(); - let u = cmd::text::composition_underlines(s.doc().unwrap()); - let thin: Vec<_> = u.iter().filter(|x| !x.2).collect(); - let thick: Vec<_> = u.iter().filter(|x| x.2).collect(); - assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}"); - let sh = s.doc().unwrap().current_slide().unwrap().shapes[0].clone(); - let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh); - for (a, b, _) in &u { - assert!(b.x > a.x && (a.y - b.y).abs() < 1e-9, "a horizontal line: {a:?} {b:?}"); - assert!(a.x >= x.x - 1.0 && b.x <= x.x + x.w + 1.0 && a.y > x.y && a.y < x.y + x.h, "inside the title box"); - } - assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end"); - s.commit_text("日本語").unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); -} - -/// #101: a composition in a table cell is underlined inside that cell, the same way slide text is. -#[test] -fn ime_composition_in_a_table_cell_is_underlined() { - let mut s = session(); - let id = s.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [80.0, 90.0, 400.0, 120.0]})).unwrap()["id"].as_u64().unwrap(); - s.execute("text.edit", &json!({"id": id, "cell": [0, 0]})).unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - let ts = s.doc().unwrap().selection.text.clone().unwrap(); - assert!(cmd::text::caret_line(s.doc().unwrap(), &ts).is_some(), "the caret is in the cell"); - s.compose_text("にほんご", Some((2, 4))).unwrap(); - let u = cmd::text::composition_underlines(s.doc().unwrap()); - let thin: Vec<_> = u.iter().filter(|x| !x.2).collect(); - let thick: Vec<_> = u.iter().filter(|x| x.2).collect(); - assert_eq!((thin.len(), thick.len()), (1, 1), "{u:?}"); - let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone(); - let x = cmd::xfrm_of(&s.doc().unwrap().doc, &s.doc().unwrap().selection, &sh); - let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") }; - let col = tb.cols[0]; - let row = cmd::table_drawn_heights(&s.doc().unwrap().doc, &s.doc().unwrap().selection, tb)[0]; - for (a, b, _) in &u { - assert!(b.x > a.x && (a.y - b.y).abs() < 1e-6, "a horizontal line: {a:?} {b:?}"); - assert!(a.x >= x.x - 1.0 && b.x <= x.x + col + 1.0, "inside the first column"); - assert!(a.y > x.y && a.y < x.y + row + 1.0, "inside the first row"); - } - assert!(thick[0].0.x > thin[0].0.x && (thick[0].1.x - thin[0].1.x).abs() < 1e-6, "the converted part is the end"); - let ts = s.doc().unwrap().selection.text.clone().unwrap(); - let (top, bot) = cmd::text::caret_line(s.doc().unwrap(), &ts).unwrap(); - assert!(top.x >= x.x && top.x <= x.x + col && top.y >= x.y && bot.y <= x.y + row + 1.0, "caret in the cell"); - s.commit_text("日本語").unwrap(); - assert!(cmd::text::composition_underlines(s.doc().unwrap()).is_empty()); - let sh = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().clone(); - let deckcraft_model::ShapeKind::Table(tb) = &sh.kind else { panic!("not a table") }; - assert_eq!(tb.cell(0, 0).map(|c| c.text.text()), Some("日本語".into())); -} - /// File › Info (#76): the active presentation's name, location, counts and properties. #[test] fn file_info_reports_the_presentation() { @@ -3213,6 +3154,11 @@ fn shape_effects_props_adjust_shadow_glow_and_reflection() { let g = fx(&s).glow.unwrap(); assert_eq!(g.radius, 12.0); assert!((g.color.alpha() - 0.5).abs() < 1e-6); + s.execute("shape.effects", &json!({"glowProps": {"radius": 18}})).unwrap(); + let grown = fx(&s).glow.unwrap(); + assert_eq!(grown.radius, 18.0); + assert_eq!(grown.color, g.color); + assert!((grown.color.alpha() - 0.5).abs() < 1e-6); s.execute("shape.effects", &json!({"glowProps": {"radius": 0}})).unwrap(); assert!(fx(&s).glow.is_none()); // Reflection: transparency, size, distance, blur; hostile values are clamped or ignored. @@ -5572,37 +5518,6 @@ fn language_all_marks_every_text_in_the_deck_with_nothing_selected() { assert!(s.execute("format.languageAll", &json!({"lang": "en US!"})).is_err()); } -#[test] -fn the_caret_takes_the_colour_of_the_text() { - let caret = |theme: &str| { - let mut s = session(); - s.execute("design.theme", &json!({"name": theme})).unwrap(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - let st = s.doc().unwrap(); - let empty = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap(); - s.execute("text.insert", &json!({"text": "Typed"})).unwrap(); - let st = s.doc().unwrap(); - assert_eq!(cmd::text::caret_color(st, &st.selection.text.clone().unwrap()), Some(empty)); - empty - }; - // Dark text on the light theme, light text on the dark one: never black on a dark slide. - let (light, dark) = (caret("DeckCraft"), caret("Nocturne")); - assert!(light.r < 0x60 && light.g < 0x60 && light.b < 0x60, "{light:?}"); - assert!(dark.r > 0xC0 && dark.g > 0xC0 && dark.b > 0xC0, "{dark:?}"); - // Text set to red gets a red caret. - let mut s = session(); - let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; - s.execute("text.edit", &json!({"id": title})).unwrap(); - s.execute("text.insert", &json!({"text": "Red"})).unwrap(); - s.execute("text.selectAll", &json!({})).unwrap(); - s.execute("format.color", &json!({"color": "#FF0000"})).unwrap(); - s.execute("text.move", &json!({"to": "end"})).unwrap(); - let st = s.doc().unwrap(); - let red = cmd::text::caret_color(st, &st.selection.text.clone().unwrap()).unwrap(); - assert_eq!((red.r, red.g, red.b), (0xFF, 0, 0)); -} - /// Smooth Corners (#286): a rounded rectangle becomes a squircle outline that survives PPTX. #[test] fn smooth_corners_makes_a_squircle_outline() { @@ -7624,3 +7539,101 @@ fn shape_adjust_and_quick_style_reject_invalid_index() { assert_eq!(s.doc().unwrap().shape(id).unwrap().style, before.style); s.execute("shape.adjust", &json!({"value": 0.4})).unwrap(); } + +#[test] +fn active_document_transitions_invalidate_captures_without_edits() { + let mut s = Session::new(); + let empty = s.active_generation(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.active_index().unwrap(); + let a_uid = s.doc().unwrap().uid; + let a_revision = s.doc().unwrap().revision; + let first = s.active_generation(); + assert_ne!(first, empty); + s.execute("file.new", &json!({})).unwrap(); + let b = s.active_index().unwrap(); + let b_uid = s.doc().unwrap().uid; + let second = s.active_generation(); + assert_ne!(second, first); + for index in [a, b, a] { + let before = s.active_generation(); + s.set_active(index); + assert_ne!(s.active_generation(), before); + } + assert_eq!(s.doc().unwrap().uid, a_uid); + assert_eq!(s.doc().unwrap().revision, a_revision); + let same = s.active_generation(); + s.set_active(a); + s.set_active(usize::MAX); + s.close_document(usize::MAX); + assert_eq!(s.active_generation(), same); + s.close_document(a); + assert_ne!(s.active_generation(), same); + assert_eq!(s.doc().unwrap().uid, b_uid); + let remaining = s.active_generation(); + s.close_document(s.active_index().unwrap()); + assert!(s.active().is_none()); + assert_ne!(s.active_generation(), remaining); + let closed = s.active_generation(); + s.execute("file.new", &json!({})).unwrap(); + assert_ne!(s.active_generation(), closed); + assert_ne!(s.doc().unwrap().uid, a_uid); + assert_ne!(s.doc().unwrap().uid, b_uid); +} + +#[test] +fn partial_alt_text_updates_preserve_mixed_descriptions_and_decorative_values() { + let (mut s, a, b) = two_shapes(); + for (id, text, decorative) in [(a, "A diagram", false), (b, "A caption", true)] { + s.execute("shape.altText", &json!({"ids": [id.0], "text": text, "decorative": decorative})).unwrap(); + } + let descriptions = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().descr.clone()); + let flags = |s: &Session| [a, b].map(|id| s.doc().unwrap().shape(id).unwrap().decorative); + let original = descriptions(&s); + assert_ne!(original[0], original[1]); + s.execute("shape.altText", &json!({"ids": [a.0, b.0], "decorative": true})).unwrap(); + assert_eq!(descriptions(&s), original); + assert!(flags(&s).into_iter().all(|decorative| decorative)); + s.execute("shape.altText", &json!({"ids": [a.0], "decorative": false})).unwrap(); + assert_eq!(descriptions(&s), original); + let mixed = flags(&s); + assert_ne!(mixed[0], mixed[1]); + s.execute("shape.altText", &json!({"ids": [a.0, b.0], "text": ""})).unwrap(); + assert!(descriptions(&s).iter().all(String::is_empty)); + assert_eq!(flags(&s), mixed); +} + +#[test] +fn editor_replacements_report_autocorrection_and_cancel_only_the_open_session() { + let mut s = session(); + let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; + let original = "(c)"; + s.execute("text.set", &json!({"id": title, "text": original})).unwrap(); + s.execute("text.edit", &json!({"id": title})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let at = original.chars().count(); + let corrected = cmd::text::correct_word(&s.prefs, original, true, true).unwrap(); + let expected = format!("{corrected} "); + let written = s.replace_text_range(at..at, " ", crate::TextReplaceKind::Typed).unwrap(); + assert_eq!(title_text(&s), expected); + assert_eq!(written.range, 0..expected.chars().count()); + assert_eq!(written.selection.caret, (0, expected.chars().count())); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let before = s.doc().unwrap().clone(); + assert!(s.replace_text_range(0..usize::MAX, "x", crate::TextReplaceKind::Typed).is_err()); + let after = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc)); + assert_eq!(after.selection, before.selection); + assert_eq!(after.history.undo.len(), before.history.undo.len()); + s.finish_text_edit_session(true).unwrap(); + assert_eq!(title_text(&s), original); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + let restored = s.doc().unwrap().doc.clone(); + s.finish_text_edit_session(true).unwrap(); + assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc)); + s.execute("text.exit", &json!({})).unwrap(); + s.execute("text.edit", &json!({"id": title})).unwrap(); + s.finish_text_edit_session(true).unwrap(); + assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs deleted file mode 100644 index 3632b368f..000000000 --- a/crates/ui-egui/src/app/ime.rs +++ /dev/null @@ -1,706 +0,0 @@ -use super::{ - ImeCancelled, ImeComposition, ImeDescriptorKey, ImeDestination, ImeResetPhase, ImeTerminalPending, ImeTerminalStamp, SlideApp, Target, Value, - ViewMode, ime_in_ui_pass_key, -}; - -impl SlideApp { - /// Borrow faces for interface text in scripts the interface fonts lack (#101): the open - /// presentations' names and text, recent files, and what is typed or composed this frame. - pub(super) fn note_ui_text(&mut self, ctx: &egui::Context) { - let typed: String = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Text(t) | egui::Event::Paste(t) => Some(t.as_str()), - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. } | egui::ImeEvent::Commit(text)) => Some(text.as_str()), - _ => None, - }) - .collect() - }); - self.ui_fonts.note(ctx, &typed); - for d in self.session.documents() { - self.ui_fonts.note(ctx, &d.title()); - } - for r in &self.ui.recent { - self.ui_fonts.note(ctx, r); - } - if let Some(st) = self.session.active() { - self.ui_fonts.note_doc(ctx, st); - } - self.ui_fonts.apply(ctx); - } - - /// Stable IME owner for the canvas text target: document, view, shape and table cell. - /// - /// The caret, selection, text, revision and geometry are deliberately absent, so ordinary - /// edits and caret movement keep the same owner. A new document, shape or cell is a new - /// owner; [`egui::ime_context::ImeTarget::replacement_epoch`] stays zero because that key - /// itself changes on replacement. `file.revert` keeps the ids, so a composition it settles is - /// covered by the settle interrupt and by [`Self::ime_event`]'s staleness check instead. - pub(crate) fn ime_target(&self) -> Option { - let st = self.session.active()?; - let (shape, cell, notes) = match &st.selection.text { - Some(t) => (t.shape, t.cell, t.notes), - None => (*st.selection.shapes.first()?, None, false), - }; - if st.selection.text.is_none() && st.selection.shapes.len() != 1 { - return None; - } - let target = match st.selection.target { - Target::Slides => (0u8, 0usize, 0usize), - Target::Master { master } => (1, master, 0), - Target::Layout { master, layout } => (2, master, layout), - Target::Handout => (3, 0, 0), - Target::NotesMaster => (4, 0, 0), - }; - let owner = egui::Id::unique(("deckcraft-ime", st.uid, target, shape.0, cell, notes)); - Some(egui::ime_context::ImeTarget::new(owner, 0)) - } - - /// The committed surrounding snapshot for the current edit target, or `Unavailable` when - /// there is an owner but no committed text to describe. - /// - /// An unavailable stamp carries the document revision. The tracker requires a strictly - /// increasing revision on both sides of a receipt that involves `Unavailable`; without it, a - /// wide selection or a commit that starts from a selected shape would poison the whole frame. - fn ime_receipt_stamp(&self) -> Option { - let st = self.session.active()?; - self.ime_target()?; - Some(st.selection.text.as_ref().and_then(|t| deckcraft_engine::cmd::text::ime_surrounding(st, t)).map_or_else( - || egui::ime_context::ImeMutationStamp::unavailable_at_revision(st.revision), - |s| egui::ime_context::ImeMutationStamp::from_committed(&s.text, s.cursor, s.anchor, None), - )) - } - - /// Report an application-origin edit in this frame. The tracker lets `Other` dominate any - /// earlier or later IME receipt in the same frame. - pub(super) fn note_application_edit(&mut self, ctx: &egui::Context) { - let Some(viewport) = self.ime_frame_viewport else { return }; - if let Some(target) = self.ime_target() { - let frame = ctx.cumulative_frame_nr_for(viewport); - self.ime_tracker.note_application_change(viewport, frame, target); - } - } - - /// Record the expected selection after an accepted IME event. Its own deletion may move - /// the caret/revision; that is not an application interruption of the following commit. - fn refresh_ime_terminal_selection(&mut self) { - let state = self.session.active().and_then(|st| st.selection.text.as_ref().map(|t| (st.revision, t.anchor, t.caret))); - if let (Some(pending), Some((revision, anchor, caret))) = (&mut self.ime_terminal_pending, state) { - pending.revision = revision; - pending.anchor = anchor; - pending.caret = caret; - } - } - - /// The current live destination for an IME reset fence. - fn ime_destination(&self) -> Option { - let st = self.session.active()?; - let target = self.ime_target()?; - let (anchor, caret) = st.selection.text.as_ref().map_or((None, None), |t| (Some(t.anchor), Some(t.caret))); - Some(ImeDestination { owner: target.owner, revision: st.revision, anchor, caret }) - } - - /// Use the recorded IME viewport only while it matches the current context viewport. - pub(super) fn ime_viewport_or(&self, ctx: &egui::Context) -> egui::ViewportId { - self.ime_frame_viewport.filter(|v| *v == ctx.viewport_id()).unwrap_or_else(|| ctx.viewport_id()) - } - - /// The reset guard belonging to exactly this viewport. There is deliberately no fallback to - /// another viewport's phase. - pub(crate) fn ime_reset_for(&self, viewport: egui::ViewportId) -> ImeResetPhase { - self.ime_reset.get(&viewport).copied().unwrap_or(ImeResetPhase::Clear) - } - - /// Store a non-clear reset phase for one viewport, or remove the entry when the phase is `Clear`. - pub(crate) fn set_ime_reset(&mut self, viewport: egui::ViewportId, phase: ImeResetPhase) { - if matches!(phase, ImeResetPhase::Clear) { - let _ = self.ime_reset.remove(&viewport); - } else { - self.ime_reset.insert(viewport, phase); - } - } - - /// The live stamp used to compare against the origin/interrupted terminal destination. - fn ime_terminal_stamp(&self) -> Option { - let st = self.session.active()?; - let (anchor, caret) = st.selection.text.as_ref().map_or((None, None), |t| (Some(t.anchor), Some(t.caret))); - Some(ImeTerminalStamp { owner: self.ime_target().map(|t| t.owner), revision: st.revision, anchor, caret }) - } - - /// Positive route predicate for the canvas IME producer: this pass must be one that can - /// actually paint `canvas::show` for the active document, with no modal, stock field or - /// overlay owning input. - /// - /// Sorter and Notes Page are editor views without a canvas producer, so they are named here - /// even though the retained selection still yields an `ime_target`. A hidden, unfocused or - /// closing window, a missing document/target, a focused stock field, modal dialog, palette, - /// Backstage, slide show and opening overlay lose admission too. The finalizer remains the - /// authority for this pass's actual descriptor; keeping this predicate positive means a view - /// added later is not admitted by omission simply because it does not call `canvas::show`. - pub(crate) fn ime_custom_canvas_route(&self, ctx: &egui::Context) -> bool { - matches!(self.ui.view, ViewMode::Normal | ViewMode::Outline | ViewMode::Reading) - && self.session.active().is_some() - && self.ime_target().is_some() - && ctx.input(|i| i.viewport().focused.unwrap_or(true)) - && ctx.input(|i| i.viewport().visible() != Some(false)) - && !ctx.input(|i| i.viewport().close_requested()) - && ctx.memory(|m| m.focused().is_none()) - && self.dialog.as_ref().is_none_or(|d| !d.modal()) - && self.palette.is_none() - && self.backstage.is_none() - && self.show.is_none() - && self.opening.is_none() - } - - /// The singleton app's session, composition tracker and terminal guard belong to its owning - /// viewport. View › New Window and Presenter View render through their own immediate - /// viewports and never call `logic`/`ui`; admitting such a callback would let a render-only - /// viewport mutate root composition state while only the reset map is per-viewport. Reject it - /// before any state changes instead of pretending to support multi-view editing. - pub(super) fn root_viewport_admitted(ctx: &egui::Context) -> bool { - ctx.viewport_id() == egui::ViewportId::ROOT - } - - /// Report whether the current pass is a full UI pass for the IME-owning viewport rather than - /// standalone logic. - pub(super) fn ime_in_ui_pass(&self, ctx: &egui::Context) -> bool { - let key = ime_in_ui_pass_key(self.ime_viewport_or(ctx)); - ctx.data(|d| d.get_temp::(key).unwrap_or(false)) - } - - /// A new application-origin interruption supersedes any previous pending fence. - /// - /// This runs from the logic half of a full pass and from raw input handling, before the - /// finalizer has seen this pass's actual custom descriptor. No request is allocated here: - /// putting a token into egui `Memory` now would let egui attach it to a later stock - /// descriptor, or to a canvas this route does not paint. Retire the superseded id - /// immediately and store an unbound `Suspended { request: None }`; only the finalizer may - /// allocate its one replacement after confirming an eligible custom output. - pub(crate) fn note_ime_interruption(&mut self, ctx: &egui::Context, fresh: bool) { - let viewport = self.ime_viewport_or(ctx); - if !fresh - && matches!( - self.ime_reset_for(viewport), - ImeResetPhase::Awaiting { viewport: guard_viewport, .. } - | ImeResetPhase::Suspended { viewport: guard_viewport, .. } - if guard_viewport == viewport - ) - { - // This viewport already has a live or suspended guard. The finalizer replaces it - // once if the actual destination changed; do not churn a request per event. - return; - } - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - - /// Custom admission was lost on this route. Retire the old id without inventing an - /// acknowledgement and block until a later eligible pass can request a replacement. - pub(super) fn suspend_ime_reset(&mut self, viewport: egui::ViewportId) { - if self.ime_reset_for(viewport).blocks_custom_input() { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - - /// An ordered completion for the exact newest request. Wrong/foreign/obsolete markers are - /// inert; this never mutates text, caret or undo history. - pub(super) fn ime_reset_completed(&mut self, request_id: egui::ImeResetId, ctx: &egui::Context) { - let viewport = self.ime_viewport_or(ctx); - if request_id.viewport_id() != viewport { - return; - } - if let ImeResetPhase::Awaiting { id, viewport: waiting_viewport, .. } = self.ime_reset_for(viewport) - && id == request_id - && waiting_viewport == viewport - { - self.set_ime_reset(viewport, ImeResetPhase::Clear); - // The exact ordered completion is the platform-reset boundary. It also releases a - // cleared-preedit terminal guard: the app no longer has to wait for the old - // Commit/Enabled/Disabled before a fresh composition may start. Events ordered - // before this marker remain rejected; a late old terminal after the reset has the - // same documented residual as any other event crossing a platform reset. - if self.ime_terminal_pending.as_ref().is_some_and(|p| p.cancelled) { - self.ime_terminal_pending = None; - } - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - } - - /// Controls-only routing for a route where the custom editor cannot mutate. Markers are - /// visited in raw order; stock text/key events stay untouched for the stock widgets. - pub(super) fn route_ime_controls_only(&mut self, ctx: &egui::Context, events: &[egui::Event]) { - for e in events { - if let egui::Event::ImeResetCompleted { request_id } = e { - self.ime_reset_completed(*request_id, ctx); - } - } - } - - /// Bind a suspended reset to the actual custom descriptor, or retire it on loss. - pub(crate) fn finalize_ime_reset(&mut self, ctx: &egui::Context, custom: Option) { - let viewport = self.ime_viewport_or(ctx); - let phase = self.ime_reset_for(viewport); - let actual = ctx.output(|o| o.ime.as_ref().map(|i| ImeDescriptorKey::new(i.owner, i.context_generation, i.purpose))); - let destination = self.ime_destination(); - // The finalizer is the allocation authority, so it rechecks the positive canvas route - // and that this pass is not already known to be discarded. Sorter/Notes Page, a modal, - // palette, Backstage, show, opening overlay, hidden window, stock focus, font/layout - // discard or a missing target must suspend without putting a token into egui Memory. - let eligible = self.ime_custom_canvas_route(ctx) && !ctx.will_discard(); - let custom_output = match (eligible, custom, actual, destination) { - (true, Some(custom), Some(actual), Some(destination)) if custom == actual => Some((custom, destination)), - _ => None, - }; - let Some((output_context, destination)) = custom_output else { - match phase { - ImeResetPhase::Clear => {} - ImeResetPhase::Awaiting { .. } => { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - ImeResetPhase::Suspended { viewport: guard_viewport, request, .. } => { - // A request that was not bound to the actual custom output in this pass is - // retired locally; a later eligible activation obtains a fresh one. A guard - // stamped for another viewport (or a request issued for one) is never reused. - if guard_viewport != viewport || request.is_some() { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - ImeResetPhase::AllocationFailed { .. } => { - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - return; - }; - match phase { - ImeResetPhase::Clear => {} - ImeResetPhase::Awaiting { viewport: old_viewport, destination: old_destination, output_context: old_context, .. } => { - if old_viewport != viewport || old_destination != destination || old_context != output_context { - self.request_ime_rearm(ctx, viewport, destination, output_context); - } - } - ImeResetPhase::Suspended { viewport: guard_viewport, request, needs_rearm } => { - let request = if needs_rearm && guard_viewport == viewport { - // Only a request issued for this exact viewport may be bound here. - request.filter(|id| id.viewport_id() == viewport) - } else { - None - }; - match request.or_else(|| ctx.request_ime_reset(viewport)) { - Some(id) => { - self.set_ime_reset(viewport, ImeResetPhase::Awaiting { id, viewport, destination, output_context }); - } - None => { - self.set_ime_reset(viewport, ImeResetPhase::AllocationFailed { viewport, destination, output_context }); - } - } - } - ImeResetPhase::AllocationFailed { viewport: old_viewport, destination: old_destination, output_context: old_context } => { - // Repeated idle output for the same destination does not retry allocation. - if old_viewport != viewport || old_destination != destination || old_context != output_context { - self.request_ime_rearm(ctx, viewport, destination, output_context); - } - } - } - } - - /// Request one replacement IME reset token and record `Awaiting` on success or - /// `AllocationFailed` when no token can be allocated. - fn request_ime_rearm(&mut self, ctx: &egui::Context, viewport: egui::ViewportId, destination: ImeDestination, output_context: ImeDescriptorKey) { - match ctx.request_ime_reset(viewport) { - Some(id) => self.set_ime_reset(viewport, ImeResetPhase::Awaiting { id, viewport, destination, output_context }), - None => self.set_ime_reset(viewport, ImeResetPhase::AllocationFailed { viewport, destination, output_context }), - } - } - - /// A standalone run_logic tick paints no custom geometry. Suspend once, without replaying - /// stale input; the next full UI pass can rearm from its actual descriptor. - pub(super) fn finalize_ime_logic(&mut self, ctx: &egui::Context) { - let viewport = self.ime_viewport_or(ctx); - if self.ime_reset_for(viewport).blocks_custom_input() { - // Only this viewport's guard is touched. A root/child logic tick must not suspend or - // rebind another viewport's independent reset lifetime. - self.set_ime_reset(viewport, ImeResetPhase::Suspended { viewport, needs_rearm: true, request: None }); - } - } - - /// Note compositions the application settled since the last check (a click, a key, another - /// command). Those are announced to the platform as an interrupt in [`Self::observe_ime`], - /// and a platform event for them is stale from that moment on, even in the same pass. - pub(crate) fn note_settled_composition(&mut self, ctx: &egui::Context) { - let settles = self.session.composition_settles(); - let current_stamp = self.ime_terminal_stamp(); - // `file.close` then `file.new` can replace the active uid before any pass observes the - // empty document. That is not a safe boundary for the old terminal: the platform may - // still deliver its suffix. Keep the guard bound to its retired owner and treat the new - // destination as a fresh interruption; only exact reset completion or an observed - // teardown may clear the terminal metadata. - let pending_interrupted = self.ime_terminal_pending.as_ref().is_some_and(|p| { - let reference = if p.interrupted { - p.interrupted_at - } else { - Some(ImeTerminalStamp { owner: Some(p.owner), revision: p.revision, anchor: Some(p.anchor), caret: Some(p.caret) }) - }; - reference != current_stamp - }); - if settles == self.ime_settles_seen && !pending_interrupted { - return; - } - let fresh = settles != self.ime_settles_seen; - self.ime_settles_seen = settles; - if let Some(pending) = &mut self.ime_terminal_pending { - pending.cancelled = true; - pending.interrupted = true; - // Compare later passes against the destination where interruption actually happened, - // not forever against the retired composition's origin. The destination may be absent - // (the interruption closed its target); `interrupted` keeps that distinct from "not - // interrupted yet". - pending.interrupted_at = current_stamp; - } - self.ime_interrupt_pending = true; - self.note_ime_interruption(ctx, fresh); - let cancelled = self.ime_composition.as_mut().map(|c| { - c.settled = true; - (c.owner, c.generation) - }); - if let Some((owner, generation)) = cancelled { - // Retain a tombstone beyond the first stale event: clearing the composition must - // not let the rest of this input batch commit into the next target. `observe_ime` - // retires it in the pass that publishes the matching interrupt. - self.ime_cancelled = Some(ImeCancelled { owner, generation }); - } - } - - /// An input method's event for the slide's text (#101): the preedit is shown in the text and - /// replaced on each update; the commit replaces it as one undo step. - /// - /// An event only ever changes the target its composition began in. The application settles a - /// composition itself on a click, a key, a command or a target change, and the platform may - /// still hold it: pre-edits and commits queued for that generation in the settling input batch - /// are dropped (with [`egui::Memory::interrupt_ime`]) instead of being typed into whatever is - /// selected now. After the interrupt has been published the platform is reset, so the next - /// batch is treated as new input; egui's event payload has no generation, so an OS-queued - /// event that crosses that reset cannot be distinguished from a legitimate one. - /// - /// A receipt is captured immediately before and after a successful commit or - /// delete-surrounding mutation. Preedit, rejected/failed events and no-ops never earn - /// [`egui::output::ImeChangeCause::InputMethod`]. - pub(crate) fn ime_event(&mut self, ctx: &egui::Context, e: &egui::ImeEvent) { - self.note_settled_composition(ctx); - let viewport = self.ime_frame_viewport.unwrap_or_else(|| ctx.viewport_id()); - let frame = ctx.cumulative_frame_nr_for(viewport); - let target = self.ime_target(); - let owner = target.map(|t| t.owner); - let accepted = - matches!(e, egui::ImeEvent::Commit(_) | egui::ImeEvent::DeleteSurrounding { .. } | egui::ImeEvent::DeleteSurroundingBytes { .. }); - if self.reject_stale_ime_event(ctx, e, owner) { - return; - } - // Until the exact newest reset request completes at its ordered stream position, custom - // mutations stay blocked. Platform enable/disable signals are not acknowledgements and do - // not release this guard; they still settle the old composition below. - #[allow(deprecated)] - if self.ime_reset_for(viewport).blocks_custom_input() && !matches!(e, egui::ImeEvent::Disabled | egui::ImeEvent::Enabled) { - return; - } - let before = if accepted { self.ime_receipt_stamp() } else { None }; - let r = self.apply_ime_event(e); - self.settle_ime_event_state(e, owner, r.is_ok()); - if r.is_ok() && accepted { - self.refresh_ime_terminal_selection(); - } - if let Err(e) = &r { - self.set_status(e.to_string()); - } else if accepted - && let (Some(target), Some(before), Some(after)) = (target, before, self.ime_receipt_stamp()) - && before != after - && r.as_ref().is_ok_and(|v| !v.is_null() && v.get("handled").and_then(Value::as_bool) != Some(false)) - { - // A no-op receipt (an empty commit, a zero-length delete, same text reinserted) is - // not a mutation and must not poison the frame for a real commit later in the batch. - self.ime_tracker.note_input_method_apply(viewport, frame, target, before, after); - } - } - - /// Drop an event that belongs to a composition the application already settled, or to another - /// owner; returns `true` when the event must not be applied. - /// - /// A commit or deletion belongs to the composition that began the pre-edit: another owner - /// (the user clicked elsewhere) or a composition the app already settled makes it stale. - /// While the reset is still pending, the tombstone rejects pre-edits too (the platform has - /// not yet been told to cancel its copy). `observe_ime` retires the tombstone in the pass - /// that publishes the interrupt (or in an accepted no-descriptor pass, which resets the - /// backend just the same), so a later commit-only is not lost forever: it is a - /// legitimate direct commit or a new platform composition. egui's events carry no - /// generation, so an event queued by the OS across that reset is indistinguishable from - /// one the user just typed; only events in the same input batch as the settle are rejected - /// deterministically. A cleared-preedit terminal is a distinct case: its pending owner - /// remains guarded across that output boundary until its actual commit/enable/disable - /// arrives. Publishing a reset is not evidence that the separately queued terminal was - /// delivered. With no incoming event epoch, the first ambiguous new composition after an - /// unobserved reset may be rejected; no timer guesses that it became safe. - /// The tombstone is not filtered by the *current* target: a click can change the owner in - /// the settling pass, and every remaining event of that batch still belongs to the - /// pre-reset composition. Filtering would let the event after the first dropped pre-edit - /// start composing in the new target before the platform is reset. - fn reject_stale_ime_event(&mut self, ctx: &egui::Context, e: &egui::ImeEvent, owner: Option) -> bool { - let cancelled = self.ime_cancelled; - let pending_cancelled = self.ime_terminal_pending.as_ref().is_some_and(|p| p.cancelled); - #[allow(deprecated)] - let stale = !matches!(e, egui::ImeEvent::Disabled | egui::ImeEvent::Enabled) - && (self.ime_composition.is_some_and(|c| c.settled || Some(c.owner) != owner) || cancelled.is_some() || pending_cancelled); - if !stale { - return false; - } - if pending_cancelled && matches!(e, egui::ImeEvent::Commit(_)) { - // The old terminal finally arrived: reject it and release its pending owner now, - // so a new preedit later in this same raw batch can belong to the current target. - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - return true; - } - if pending_cancelled { - // note_settled_composition already queued the reset. Do not also latch the - // frame's memory interrupt: a terminal later in this batch can consume it and - // permit a fresh preedit without resetting that new composition at pass end. - self.ime_composition = None; - return true; - } - if let Some(c) = cancelled { - log::debug!("IGNORING IME event for settled composition owner {:?} generation {}", c.owner, c.generation); - } - self.ime_composition = None; - // Ask the backend to drop its copy, so this is one stale event and not a stream. - ctx.memory_mut(|m| m.interrupt_ime()); - true - } - - /// Apply the document mutation an IME event asks for, before any receipt or tracker state. - fn apply_ime_event(&mut self, e: &egui::ImeEvent) -> deckcraft_engine::Result { - match e { - egui::ImeEvent::Preedit { text, active_range_chars } => { - self.session.compose_text(text, active_range_chars.as_ref().map(|r| (r.start, r.end))) - } - // A commit only replaces text that is being edited. It must never start editing a - // merely selected shape: without a tracked pre-edit, a stale platform commit would - // replace that shape's whole text. - egui::ImeEvent::Commit(text) => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.commit_text(text) - } else { - Ok(Value::Null) - } - } - egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.delete_surrounding(*before_chars, *after_chars, false) - } else { - Ok(Value::Null) - } - } - egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { - if self.session.active().is_some_and(|d| d.selection.text.is_some()) { - self.session.delete_surrounding(*before_bytes, *after_bytes, true) - } else { - Ok(Value::Null) - } - } - #[allow(deprecated)] - egui::ImeEvent::Disabled | egui::ImeEvent::Enabled => { - // The platform ended (or is about to restart) its composition itself. - self.session.end_composition(); - Ok(Value::Null) - } - } - } - - /// Update the tracked composition after `e` has been applied; `applied` says whether the - /// document mutation succeeded. - fn settle_ime_event_state(&mut self, e: &egui::ImeEvent, owner: Option, applied: bool) { - match e { - // The platform ends its composition on a commit (and on Disabled/Enabled): nothing is - // left to interrupt. A pre-edit keeps (or starts) the tracked composition. - egui::ImeEvent::Commit(_) => { - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - #[allow(deprecated)] - egui::ImeEvent::Disabled | egui::ImeEvent::Enabled => { - // A platform-side disable/enable already reset the composition. Do not carry an - // older app-settled interrupt into the next (possibly new) composition. - self.ime_terminal_pending = None; - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_interrupt_pending = false; - } - egui::ImeEvent::Preedit { text, .. } => { - match (owner, applied, self.session.active().is_some_and(|d| d.composition.is_some())) { - (Some(owner), true, true) => { - // Updating the same composition keeps its generation. After a settle (or - // a first pre-edit) this is a new generation and clears the tombstone. - let generation = match self.ime_composition { - Some(c) if c.owner == owner && !c.settled => c.generation, - _ => { - self.ime_generation = self.ime_generation.wrapping_add(1).max(1); - self.ime_generation - } - }; - self.ime_composition = Some(ImeComposition { owner, generation, settled: false }); - self.ime_terminal_pending = None; - self.ime_cancelled = None; - } - (Some(owner), true, false) if text.is_empty() && self.ime_composition.is_some_and(|c| !c.settled && c.owner == owner) => { - // The model restored committed text, but no terminal was delivered. Keep - // this owner across passes; a later pointer/key/target change must reject - // its separately queued old delete/commit, even after an outgoing reset. - if let Some(st) = self.session.active() - && let Some(t) = &st.selection.text - { - self.ime_terminal_pending = Some(ImeTerminalPending { - owner, - revision: st.revision, - anchor: t.anchor, - caret: t.caret, - cancelled: false, - interrupted: false, - interrupted_at: None, - }); - } - } - _ => { - self.ime_composition = None; - self.ime_terminal_pending = None; - } - } - } - _ => {} - } - } - - /// Observe the canvas IME owner once per pass and publish its descriptor. - /// - /// No canvas target, a Sorter/Notes Page view, a focused egui field, a modal, the palette, - /// the Backstage view, a slide show, an opening overlay, or an unfocused/hidden window means - /// the custom owner is hidden: the tracker is told so and the next focus starts a new - /// generation. The descriptor is rebuilt from the current committed text every pass. - /// - /// A composition the application settled itself is announced once as - /// `should_interrupt_composition`, so the backend cancels the platform's copy of it. That - /// settled pass is also the active-composition tombstone's lifecycle end. A cleared-preedit - /// terminal retains its separate pending owner until the incoming terminal is observed. - pub(crate) fn observe_ime(&mut self, ctx: &egui::Context) -> Option { - let viewport = self.ime_frame_viewport.unwrap_or_else(|| ctx.viewport_id()); - self.note_settled_composition(ctx); - // The editing window going away really ends the viewport's context; a merely hidden - // owner (modal, palette, unfocused field) stays observed as unfocused instead. - if self.session.active().is_none() || ctx.input(|i| i.viewport().close_requested()) { - self.ime_interrupt_pending = false; - if let Some(old) = self.ime_viewport.take() { - self.ime_tracker.end_viewport(old); - // Explicit viewport destruction removes only that viewport's guard. - let _ = self.ime_reset.remove(&old); - } - let _ = self.ime_reset.remove(&viewport); - self.ime_composition = None; - self.ime_cancelled = None; - self.ime_terminal_pending = None; - return None; - } - if !ctx.input(|i| i.viewport().focused.unwrap_or(true)) { - // The native window itself lost focus: no custom editor is eligible this pass, even - // if the model still has a text selection and a last-pass geometry rect. - self.ime_tracker.observe(viewport, None); - return None; - } - let Some(rect) = self.ime_pending.take() else { - // No canvas editor was painted in this pass. A discarded font/layout pass publishes - // nothing the platform sees, so keep the interrupt and tombstone for a later pass. - // An accepted pass is a backend reset only when it publishes *no* IME descriptor at - // all: a focused stock `TextEdit` (notes pane, dialog, palette field) publishes its - // own `o.ime` while `ime_pending` is `None`, and that descriptor is not a reset. Gate - // retirement on the actual committed output, not on the absence of the canvas rect; - // otherwise the next legitimate commit in the focused field would be rejected. - let no_descriptor = ctx.output(|o| o.ime.is_none()); - if !ctx.will_discard() && no_descriptor { - self.ime_interrupt_pending = false; - self.ime_cancelled = None; - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - } - self.ime_tracker.observe(viewport, None); - return None; - }; - if !self.ime_custom_canvas_route(ctx) { - // The canvas can still paint behind an opening overlay or a Sorter/Notes Page - // reroute, and a forced hidden paint can run after the window lost focus or - // visibility. The positive route and the UI wrapper both reject those, so a pending - // rect must not republish the custom owner. - self.ime_tracker.observe(viewport, None); - return None; - } - let Some(st) = self.session.active() else { - self.ime_interrupt_pending = false; - self.ime_tracker.observe(viewport, None); - return None; - }; - let Some(target) = self.ime_target() else { - self.ime_interrupt_pending = false; - self.ime_cancelled = None; - self.ime_tracker.observe(viewport, None); - return None; - }; - if self.ime_viewport != Some(viewport) - && let Some(old) = self.ime_viewport.replace(viewport) - { - self.ime_tracker.end_viewport(old); - let _ = self.ime_reset.remove(&old); - } - let committed = st.selection.text.as_ref().and_then(|t| deckcraft_engine::cmd::text::ime_surrounding(st, t)); - let mut observation = - egui::ime_context::ImeObservation::new(ctx.cumulative_frame_nr_for(viewport), ctx.cumulative_pass_nr_for(viewport), target) - .purpose(egui::IMEPurpose::Normal) - .committed(committed.as_ref().map(|s| egui::ime_context::CommittedText::new(&s.text, s.cursor, s.anchor))); - if committed.is_none() { - observation = observation.unavailable_revision(st.revision); - } - let update = self.ime_tracker.observe(viewport, Some(observation))?; - // Clear the interrupt only once it is part of a settled pass's output descriptor. A - // discarded font/layout pass publishes nothing the platform sees, so keep it pending; - // that pass is not the boundary at which stale pre-edits become a new generation. - let interrupt = if ctx.will_discard() { false } else { std::mem::take(&mut self.ime_interrupt_pending) }; - if interrupt { - // This pass's output carries the backend reset. The tombstone did its job for the - // events already processed in this batch; from the next batch on every pre-edit or - // commit is a new platform generation. A late event the OS queued across the reset - // has no generation in its payload, so it cannot be rejected without also dropping - // legitimate direct commits (documented residual in `ime_event`). - self.ime_cancelled = None; - if self.ime_composition.is_some_and(|c| c.settled) { - self.ime_composition = None; - } - } - let key = ImeDescriptorKey::new(update.owner, update.context_generation, update.purpose); - ctx.output_mut(|o| { - o.ime = Some(egui::output::IMEOutput { - owner: update.owner, - context_generation: update.context_generation, - purpose: update.purpose, - rect, - cursor_rect: rect, - should_interrupt_composition: interrupt, - reset_request: None, - change_cause: update.change_cause, - surrounding_text: update.surrounding_text, - }); - }); - Some(key) - } -} diff --git a/crates/ui-egui/src/gpu_lock.rs b/crates/ui-egui/src/gpu_lock.rs index 49e98a778..2d9844511 100644 --- a/crates/ui-egui/src/gpu_lock.rs +++ b/crates/ui-egui/src/gpu_lock.rs @@ -17,40 +17,3 @@ static GPU_LOCK: Mutex<()> = Mutex::new(()); pub(crate) fn gpu_lock() -> MutexGuard<'static, ()> { GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_panicked_holder_does_not_block_the_next_test() { - let _ = std::thread::spawn(|| { - let _gpu = gpu_lock(); - panic!("a GPU test failed"); - }) - .join(); - drop(gpu_lock()); - } - - #[test] - fn holders_take_turns() { - use std::sync::atomic::{AtomicUsize, Ordering}; - static INSIDE: AtomicUsize = AtomicUsize::new(0); - static MAX: AtomicUsize = AtomicUsize::new(0); - let threads: Vec<_> = (0..8) - .map(|_| { - std::thread::spawn(|| { - let _gpu = gpu_lock(); - let now = INSIDE.fetch_add(1, Ordering::SeqCst) + 1; - MAX.fetch_max(now, Ordering::SeqCst); - std::thread::sleep(std::time::Duration::from_millis(2)); - INSIDE.fetch_sub(1, Ordering::SeqCst); - }) - }) - .collect(); - for t in threads { - assert!(t.join().is_ok()); - } - assert_eq!(MAX.load(Ordering::SeqCst), 1); - } -} diff --git a/crates/ui-egui/src/ime_hooks.rs b/crates/ui-egui/src/ime_hooks.rs deleted file mode 100644 index 93f3f8513..000000000 --- a/crates/ui-egui/src/ime_hooks.rs +++ /dev/null @@ -1,39 +0,0 @@ -/// Temp key holding whether the current viewport is inside an egui UI pass. -pub(crate) fn ime_in_ui_pass_key(viewport: egui::ViewportId) -> egui::Id { - egui::Id::unique(("deckcraft-ime-in-ui-pass", viewport)) -} - -/// Stable key marking that the IME pass hooks are installed. -fn ime_pass_hooks_key() -> egui::Id { - egui::Id::unique(("deckcraft-ime-pass-hooks", "installed")) -} - -/// Install the per-viewport UI-pass mode hooks exactly once for this [`egui::Context`]. -/// -/// Call this before the context's first `run_ui` (desktop/web shells and the test harness). -/// The callbacks receive `&mut Ui`; they obtain the context through `ui.ctx()` and capture no -/// context or app reference, so they cannot form a reference cycle. The flag distinguishes a -/// full `run_ui` pass (where `App::logic` runs before the UI that owns the final output) from a -/// standalone `run_logic` callback. It is only a mode marker, not an IME publication receipt. -pub fn install_ime_pass_hooks(ctx: &egui::Context) { - if ctx.data(|d| d.get_temp::(ime_pass_hooks_key()).is_some_and(|v| v)) { - return; - } - ctx.on_begin_pass( - "deckcraft-ime-ui-pass-begin", - std::sync::Arc::new(|ui: &mut egui::Ui| { - let ctx = ui.ctx(); - let key = ime_in_ui_pass_key(ctx.viewport_id()); - ctx.data_mut(|d| d.insert_temp(key, true)); - }), - ); - ctx.on_end_pass( - "deckcraft-ime-ui-pass-end", - std::sync::Arc::new(|ui: &mut egui::Ui| { - let ctx = ui.ctx(); - let key = ime_in_ui_pass_key(ctx.viewport_id()); - ctx.data_mut(|d| d.insert_temp(key, false)); - }), - ); - ctx.data_mut(|d| d.insert_temp(ime_pass_hooks_key(), true)); -} diff --git a/crates/ui-egui/src/ime_tests.rs b/crates/ui-egui/src/ime_tests.rs index 494431ce1..025b539de 100644 --- a/crates/ui-egui/src/ime_tests.rs +++ b/crates/ui-egui/src/ime_tests.rs @@ -1,26 +1,15 @@ -//! #101: Korean, Japanese and Chinese in the interface: input method composition on the slide and -//! in the notes pane (egui `Ime` events, as egui-winit sends them), and interface text drawn with -//! real glyphs rather than boxes. +//! Canvas input reaches the framework editor and preserves the engine's composition history. #![allow(clippy::unwrap_used, clippy::expect_used)] -use egui::{Event, FontId, ImeEvent}; +use egui::{Event, ImeEvent}; use serde_json::json; use crate::{Services, SlideApp}; use deckcraft_engine::Session; -/// Build the standard 1280×800 UI harness around a supplied session and run three frames. fn harness(session: Session) -> egui_kittest::Harness<'static, SlideApp> { - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - // P3(shell-w9): sh.A2 - SlideApp::new_base(session, Services::default()), - ); - crate::install_ime_pass_hooks(&h.ctx); - // The app keeps requesting repaints, so step frames instead of run(). + let builder = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)); + let mut h = crate::test_harness::harness_with(session, Services::default(), builder, |_| {}); h.run_steps(3); h } @@ -38,1945 +27,159 @@ fn undo_len(app: &SlideApp) -> usize { app.session.active().unwrap().history.undo.len() } -/// Typing 한글 with the Korean input method in the title: each preedit replaces the last in the -/// text box (not ㅎ ㅏ ㄴ …), is underlined, and the commit is one undo step. The input method -/// is on while the slide's text is edited, with its window at the insertion point. #[test] fn korean_composes_in_a_slide_text_box() { let mut h = harness(Session::with_new()); - assert!(h.output().platform_output.ime.is_none(), "nothing to type into: the input method stays off"); + assert!(h.output().platform_output.ime.is_none()); let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; + let original = title_text(h.state()); h.state_mut().run("text.edit", json!({"id": title})).unwrap(); h.run_steps(2); - let ime = h.output().platform_output.ime.as_ref().expect("the input method is on while editing"); - let slide = h.state().slide_rect.unwrap(); - assert!(slide.contains(ime.rect.center()), "candidate window at the insertion point {:?}, on the slide {slide:?}", ime.rect); - assert!(ime.rect.width() < 8.0 && ime.rect.height() > 4.0, "a caret, not the box: {:?}", ime.rect); - let caret0 = ime.rect; - - let undo0 = undo_len(h.state()); - for pre in ["ㅎ", "하", "한", "한ㄱ", "한그", "한글"] { - h.event(preedit(pre)); + let caret = h.output().platform_output.ime.as_ref().unwrap().cursor_rect; + let slide = h.state().slide_rect().unwrap(); + assert!(slide.contains(caret.center())); + assert!(caret.height() > caret.width()); + let undo = undo_len(h.state()); + let word = "한글"; + for text in ["ㅎ", "하", "한", "한ㄱ", "한그", word] { + // Only the input pass receives this preedit; a layout replay must not apply it again. + h.ctx.request_discard("exercise composition across layout passes"); + h.input_mut().events.push(preedit(text)); h.run_steps(1); - assert_eq!(title_text(h.state()), pre, "the preedit is shown in place, replacing the last"); - assert_eq!(undo_len(h.state()), undo0, "no undo step while composing"); - let st = h.state().session.active().unwrap(); - assert!(!deckcraft_engine::cmd::text::composition_underlines(st).is_empty(), "underlined while composing"); + assert_eq!(title_text(h.state()), text); + assert_eq!(undo_len(h.state()), undo); } + let advanced = h.output().platform_output.ime.as_ref().unwrap().cursor_rect; + assert!(advanced.center().x > caret.center().x); + h.ctx.request_discard("exercise commit across layout passes"); + h.input_mut().events.push(Event::Ime(ImeEvent::Commit(word.into()))); h.run_steps(1); - let ime = h.output().platform_output.ime.as_ref().unwrap(); - assert!(ime.rect.center().x > caret0.center().x, "the candidate window follows the insertion point"); - h.event(Event::Ime(ImeEvent::Commit("한글".into()))); - h.run_steps(2); - assert_eq!(title_text(h.state()), "한글"); + assert_eq!(title_text(h.state()), word); assert!(h.state().session.active().unwrap().composition.is_none()); - assert!(deckcraft_engine::cmd::text::composition_underlines(h.state().session.active().unwrap()).is_empty()); - assert_eq!(undo_len(h.state()), undo0 + 1, "the composition is one undo step"); - - // Escape cancels a composition: an empty preedit, and the text is as it was. - h.event(preedit("ㅁ")); - h.event(preedit("")); - h.run_steps(2); - assert_eq!(title_text(h.state()), "한글"); - assert_eq!(undo_len(h.state()), undo0 + 1); - + assert_eq!(undo_len(h.state()), undo + 1); h.state_mut().run("edit.undo", json!({})).unwrap(); - h.run_steps(1); - assert_eq!(title_text(h.state()), "", "one undo removes the whole word"); + assert_eq!(title_text(h.state()), original); } -/// Japanese conversion: the part being converted is drawn with a thicker line; a key settles a -/// composition the input method left open. #[test] fn japanese_conversion_shows_the_active_part() { let mut h = harness(Session::with_new()); let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.event(Event::Ime(ImeEvent::Preedit { text: "日本ご".into(), active_range_chars: Some(2..3) })); - h.run_steps(2); - let u = deckcraft_engine::cmd::text::composition_underlines(h.state().session.active().unwrap()); - assert_eq!(u.iter().filter(|x| x.2).count(), 1, "{u:?}"); - let undo0 = undo_len(h.state()); - // kittest runs one frame per queued event. Assert the key-down frame itself: the platform - // composition must be cancelled there, not one frame later after the key-up releases it. - h.key_down(egui::Key::End); h.run_steps(1); - let interrupted = h.output().platform_output.ime.clone().expect("still editing"); - assert!(interrupted.should_interrupt_composition, "the platform composition is interrupted"); - assert_eq!(title_text(h.state()), "日本ご"); - assert!(h.state().session.active().unwrap().composition.is_none()); - assert_eq!(undo_len(h.state()), undo0 + 1); - h.key_up(egui::Key::End); - h.run_steps(1); - // The published interrupt is the platform reset boundary; the tombstone for the settled - // generation ends there, so a later commit-only event is treated as a new platform - // generation rather than being dropped for the rest of the session. - assert!(h.state().ime_cancelled.is_none(), "the published interrupt retired the settled tombstone"); -} - -/// A composition the application settled (here an End key) drops the platform pre-edit and commit -/// already queued in the same input batch, so the conversion is typed once. The published -/// interrupt is the explicit boundary: after it the next pre-edit is a new generation. A commit -/// the platform queues after that reset is indistinguishable from a legitimate direct commit -/// (egui's events carry no generation), so the bounded tombstone does not pretend otherwise. -#[test] -fn settled_composition_drops_queued_preedit_and_same_batch_commit() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.event(preedit("日本")); - h.run_steps(1); - let undo0 = undo_len(h.state()); - - // One RawInput: the key settles the composition and the platform's queued pre-edit/commit - // arrive after it in the same pass. None of them may be applied. Force an extra discarded - // pass too: the interrupt may only be consumed by the settled pass the platform sees. - h.ctx.request_discard("ime interrupt through a discarded pass"); - h.input_mut().events.push(Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.input_mut().events.push(preedit("日本")); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("日本".into()))); - h.input_mut().events.push(Event::Key { key: egui::Key::End, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日本", "the stale pre-edit and commit do not restart the cancelled composition"); - assert!(h.state().session.active().unwrap().composition.is_none()); - assert_eq!(undo_len(h.state()), undo0 + 1, "the settled composition is one undo step"); - let interrupted = h.output().platform_output.ime.clone().expect("still editing"); - assert!(interrupted.should_interrupt_composition, "the settled platform composition is interrupted"); - assert!(h.state().ime_cancelled.is_none(), "the settled pass published the interrupt and retired the tombstone"); - let reset = interrupted.reset_request.expect("the settled pass carries the opaque reset request"); - - // A real new composition is admitted only by the exact ordered completion. - h.input_mut().events.extend([reset_completed(reset), preedit("新")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日本新", "a legitimate new pre-edit starts a new generation"); - assert!(h.state().session.active().unwrap().composition.is_some()); - h.event(Event::Ime(ImeEvent::Commit("新".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日本新"); -} - -/// A commit-only event in the settling batch is stale (it belongs to the composition the key -/// ended). After the published interrupt, a later commit-only event is a legitimate direct input -/// method commit and must not be swallowed by a permanent tombstone. -#[test] -fn stale_commit_in_the_settling_batch_is_rejected_and_a_later_direct_commit_is_accepted() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.event(preedit("日本")); - h.run_steps(1); - let undo0 = undo_len(h.state()); - - // One RawInput: the key settles the composition and the platform's queued commit follows. - h.input_mut().events.push(Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("日本".into()))); - h.input_mut().events.push(Event::Key { key: egui::Key::End, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日本", "the same-batch commit does not type the conversion twice"); - assert_eq!(undo_len(h.state()), undo0 + 1); - assert!(h.state().ime_cancelled.is_none(), "the published interrupt retired the tombstone"); - let reset = h.output().platform_output.ime.as_ref().and_then(|ime| ime.reset_request).expect("the settled pass carries the opaque reset request"); - - // A direct commit with no pre-edit (a real IME's punctuation/full-width character path) - // arrives after the exact ordered completion and is accepted. - h.input_mut().events.extend([reset_completed(reset), Event::Ime(ImeEvent::Commit("。".into()))]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日本。", "a later commit-only is not lost"); -} - -/// The interrupt is only a boundary when it reaches the platform. A discarded layout/font pass -/// keeps both the pending interrupt and the tombstone; the next settled pass retires the tombstone -/// and publishes the reset. Assert the per-pass state, not just the final output carrier. -#[test] -fn a_discarded_pass_keeps_the_tombstone_until_a_settled_pass_publishes_the_interrupt() { - use std::sync::{Arc, Mutex}; - let traces = Arc::new(Mutex::new(Vec::new())); - let seen = traces.clone(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state( - move |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - seen.lock().unwrap().push(( - app.ime_cancelled.is_some(), - app.ime_interrupt_pending, - app.ime_composition.is_none(), - ui.ctx().will_discard(), - )); - }, - // P3(shell-w9): sh.A2 - SlideApp::new_base(Session::with_new(), Services::default()), - ); - h.run_steps(3); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(2); - h.event(preedit("日本")); - h.run_steps(1); - traces.lock().unwrap().clear(); - - h.ctx.request_discard("discarded IME interrupt boundary"); - h.input_mut().events.push(Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.input_mut().events.push(preedit("日本")); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("日本".into()))); - h.run_steps(1); - - let t = traces.lock().unwrap().clone(); - assert_eq!(t.len(), 2, "one discarded pass followed by the settled pass: {t:?}"); - assert!(t[0].0, "the discarded pass keeps the settled tombstone"); - assert!(t[0].1, "the interrupt stays pending through the discarded pass"); - assert!(t[0].2, "the stale pre-edit/commit cleared the tracked composition"); - assert!(t[0].3, "the first pass is discarded"); - assert!(!t[1].0, "the settled pass publishes the interrupt and retires the tombstone"); - assert!(!t[1].1); - assert!(!t[1].3); - assert_eq!(title_text(h.state()), "日本"); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.should_interrupt_composition)); -} - -/// A settled composition whose descriptor was not painted leaves a tombstone. A *discarded* -/// pass keeps it (the platform has not been told to reset), but an accepted no-descriptor pass is -/// the backend's reset boundary: the tombstone must be retired there, or the first legitimate -/// commit into the next text target is lost. -#[test] -fn accepted_no_descriptor_pass_retires_the_settled_tombstone() { - use std::sync::{Arc, Mutex}; - - // P3(shell-w9): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - let ctx = egui::Context::default(); - let title = app.session.active().unwrap().doc.slides[0].shapes[0].id.0; - app.run("text.edit", json!({"id": title})).unwrap(); - let owner = app.ime_target().expect("the edited title is an IME target").owner; - let generation = 7; - app.ime_generation = generation; - app.ime_composition = Some(crate::ImeComposition { owner, generation, settled: true }); - app.ime_cancelled = Some(crate::ImeCancelled { owner, generation }); - app.ime_interrupt_pending = true; - app.ime_pending = None; - - let traces = Arc::new(Mutex::new(Vec::new())); - let seen = traces.clone(); - ctx.request_discard("no-descriptor IME boundary"); - ctx.run_ui(egui::RawInput::default(), |ui| { - let will_discard = ui.ctx().will_discard(); - app.ime_pending = None; - let _ = app.observe_ime(ui.ctx()); - seen.lock().unwrap().push((will_discard, app.ime_cancelled.is_some(), app.ime_interrupt_pending)); - }) - .drop_without_applying_deltas(); - - let t = traces.lock().unwrap().clone(); - assert_eq!(t.len(), 2, "one discarded pass then the accepted pass: {t:?}"); - assert!(t[0].0, "the first pass is discarded"); - assert!(t[0].1, "a discarded pass keeps the tombstone"); - assert!(t[0].2, "a discarded pass keeps the interrupt pending"); - assert!(!t[1].0, "the second pass is accepted"); - assert!(!t[1].1, "the accepted no-descriptor pass retires the tombstone"); - assert!(!t[1].2, "there is no descriptor to publish the interrupt in"); - assert!(app.ime_composition.is_none(), "the settled composition is retired with its tombstone"); - - // The next text target's first event is a legitimate direct commit, not the old generation. - app.ime_event(&ctx, &egui::ImeEvent::Commit("。".into())); - assert_eq!(title_text(&app), "。", "a first commit in the new target is not swallowed"); -} - -/// A focused stock `TextEdit` can publish its own `o.ime` while the canvas has no pending rect. -/// That descriptor is not a backend reset: the canvas tombstone and settled composition must -/// survive until an accepted pass really publishes no descriptor at all. -#[test] -fn focused_text_field_descriptor_keeps_the_settled_tombstone() { - let mut h = harness(Session::with_new()); - let notes = egui::Id::unique("notes_edit"); - h.ctx.memory_mut(|m| m.request_focus(notes)); - h.run_steps(2); - assert!(h.ctx.memory(|m| m.has_focus(notes)), "the notes TextEdit has focus"); - let owner = egui::Id::unique("old-canvas-ime"); - h.state_mut().ime_composition = Some(crate::ImeComposition { owner, generation: 7, settled: true }); - h.state_mut().ime_cancelled = Some(crate::ImeCancelled { owner, generation: 7 }); - h.state_mut().ime_interrupt_pending = true; - - h.run_steps(1); - assert!(h.output().platform_output.ime.is_some(), "the focused stock TextEdit publishes its own descriptor"); - assert!(h.state().ime_cancelled.is_some(), "a descriptor-publishing pass is not a reset"); - assert!(h.state().ime_interrupt_pending, "the canvas interrupt is still waiting for a reset pass"); - assert!(h.state().ime_composition.is_some_and(|c| c.settled), "the settled composition is not retired"); - - // With focus gone there is no canvas target and no TextEdit descriptor: this accepted pass - // is the backend reset boundary, so the tombstone and settled composition retire. - h.ctx.memory_mut(|m| m.surrender_focus(notes)); - h.run_steps(1); - assert!(h.output().platform_output.ime.is_none(), "nothing publishes an IME descriptor"); - assert!(h.state().ime_cancelled.is_none(), "the accepted no-descriptor pass retires the tombstone"); - assert!(!h.state().ime_interrupt_pending); - assert!(h.state().ime_composition.is_none(), "the settled composition retires with its tombstone"); -} - -/// Typing on a selected (not edited) shape with an input method replaces its text, as typing does; -/// the input method is on for it. -#[test] -fn composing_on_a_selected_shape_starts_editing_it() { - let mut h = harness(Session::with_new()); - let r = h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100, 100, 200, 100], "text": "Old"})).unwrap(); - let id = r["id"].as_u64().unwrap(); - h.state_mut().run("text.exit", json!({})).unwrap(); - h.run_steps(2); - assert!(h.state().session.active().unwrap().selection.text.is_none()); - assert!(h.output().platform_output.ime.is_some(), "a selected shape takes typing"); - h.event(preedit("新")); - h.event(Event::Ime(ImeEvent::Commit("新しい".into()))); - h.run_steps(2); - let v = h.state_mut().session.execute("text.get", &json!({"id": id})).unwrap(); - assert_eq!(v["text"], "新しい"); -} - -/// The notes pane is an egui text field: composition shows in it and replaces each preedit, the -/// candidate window is at its caret, and the notes are one undo step when it loses focus. -#[test] -fn korean_composes_in_the_notes_pane() { - let mut h = harness(Session::with_new()); - let id = egui::Id::unique("notes_edit"); - h.ctx.memory_mut(|m| m.request_focus(id)); - h.run_steps(2); - assert!(h.ctx.memory(|m| m.has_focus(id))); - let undo0 = undo_len(h.state()); - for pre in ["ㄴ", "노", "놑", "노트"] { - h.event(preedit(pre)); - h.run_steps(1); - assert_eq!(h.state().notes_buf.2.text, pre, "the preedit replaces the last one"); - } - let ime = h.output().platform_output.ime.as_ref().expect("the notes field turns the input method on"); - let slide = h.state().slide_rect.unwrap(); - assert!(ime.cursor_rect.min.y > slide.max.y, "candidate window at the notes caret, under the slide"); - h.event(Event::Ime(ImeEvent::Commit("노트".into()))); - h.run_steps(1); - assert_eq!(h.state().notes_buf.2.text, "노트"); - // Focus leaves the field (Escape): the notes are committed as one step. - h.key_press(egui::Key::Escape); - h.run_steps(2); - let notes = h.state().session.active().unwrap().doc.slides[0].notes_text(); - assert_eq!(notes, "노트"); - assert_eq!(undo_len(h.state()), undo0 + 1); - assert!(h.ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(13.0), "노트")) || !system_has("노트")); - - // Composing, then going to another slide: the notes stay with the slide they were typed for. - h.state_mut().run("slide.new", json!({})).unwrap(); - h.state_mut().run("slide.go", json!({"index": 0})).unwrap(); - h.run_steps(2); - h.ctx.memory_mut(|m| m.request_focus(id)); - h.run_steps(2); - h.event(Event::Key { key: egui::Key::End, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.event(preedit("ㅇ")); - h.event(Event::Ime(ImeEvent::Commit("요".into()))); - h.run_steps(1); - h.state_mut().run("slide.go", json!({"index": 1})).unwrap(); - h.run_steps(2); - let d = h.state().session.active().unwrap(); - assert_eq!(d.doc.slides[0].notes_text(), "노트요"); - assert_eq!(d.doc.slides[1].notes_text(), ""); -} - -/// Does some font on this machine (embedded or installed) draw every letter of `s`? Machines -/// without a Korean or Chinese font (a bare Linux runner) can't draw it in the interface either. -fn system_has(s: &str) -> bool { - s.chars().filter(|c| !c.is_whitespace()).all(|c| deckcraft_fonts::FontDb::global().fallback_for(c, u32::MAX).is_some_and(|f| !f.is_color())) -} - -/// Assert that both interface faces draw every non-space character of `text`; `painted` describes -/// the sample in a failure message. -fn assert_faces_draw(h: &egui_kittest::Harness<'_, SlideApp>, text: &str, painted: &str) { - for family in [FontId::proportional(13.0), crate::theme::bold(13.0)] { - let missing: String = text.chars().filter(|c| !c.is_whitespace() && !h.ctx.fonts_mut(|f| f.has_glyph(&family, *c))).collect(); - assert!(missing.is_empty(), "{family:?} draws {missing:?} of {painted} as boxes"); - } -} - -/// #101: a Korean file name, title, notes and comments, a Japanese slide and a Chinese section are -/// drawn with glyphs in the interface (title bar, outline, notes pane, comments), not boxes: faces -/// that draw them are borrowed from the font database. A Latin presentation borrows nothing. -#[test] -fn cjk_text_in_the_interface_is_drawn_with_real_glyphs() { - let h = harness(Session::with_new()); - assert!(h.state().ui_fonts.faces.is_empty(), "nothing to borrow for {:?}", h.state().session.active().unwrap().title()); - - let mut s = Session::with_new(); - let korean = "한국어 발표 자료"; - let japanese = "日本語のスライド"; - let chinese = "简体中文演示文稿"; - let notes = "발표자 노트입니다"; - let require_all = option_env!("CRAFT_FONTS_REQUIRED").is_some() || deckcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == "LXGW WenKai Lite"); - // The title slide's title and subtitle are painted by the initial Normal view, under - // kittest's strict missing-glyph policy. Pre-paint CJK only when this build is required to - // carry it or this machine can draw every initial sample; an optional build without those - // fonts must skip before that first paint instead of panicking and only then checking. - let initial_cjk = require_all || [chinese, japanese, korean].iter().all(|t| system_has(t)); - let slide = s.doc().unwrap().current_slide().unwrap(); - let title = slide.shapes[0].id.0; - let body = slide.shapes[1].id.0; - if initial_cjk { - s.execute("text.set", &json!({"id": title, "text": chinese})).unwrap(); - s.execute("text.set", &json!({"id": body, "text": japanese})).unwrap(); - s.execute("slide.notes", &json!({"text": notes})).unwrap(); - s.execute("section.add", &json!({"name": chinese})).unwrap(); - s.doc_mut().unwrap().path = Some(format!("{korean}.pptx")); - } - let mut h = harness(s); - if initial_cjk { - // `harness` already completed its first passes. Both initially painted samples must have - // real glyph coverage before any command (and the strict policy would have panicked - // otherwise). - let initial: Vec = h.state().session.active().unwrap().doc.slides[0] - .shapes - .iter() - .take(2) - .map(|sh| sh.text.as_ref().map(|t| t.paragraphs.iter().map(|p| p.text()).collect::>().join("\n")).unwrap_or_default()) - .collect(); - assert_eq!(initial, [chinese.to_owned(), japanese.to_owned()]); - for text in [chinese, japanese] { - assert_faces_draw(&h, text, &format!("initially painted {text:?}")); - } - } else { - eprintln!("optional font input: initial CJK paint skipped before layout (no complete local coverage)"); - // Each sample this machine can draw is still painted for real after the check; the - // strict policy then checks it. Unsupported samples stay out of the document entirely. - if system_has(chinese) { - h.state_mut().run("text.set", json!({"id": title, "text": chinese})).unwrap(); - h.state_mut().run("section.add", json!({"name": chinese})).unwrap(); - } - if system_has(japanese) { - h.state_mut().run("text.set", json!({"id": body, "text": japanese})).unwrap(); - } - if system_has(korean) { - h.state_mut().run("slide.notes", json!({"text": notes})).unwrap(); - h.state_mut().session.doc_mut().unwrap().path = Some(format!("{korean}.pptx")); - } - if system_has(chinese) || system_has(japanese) || system_has(korean) { - h.run_steps(3); - } - } - // Outline and file-name text is painted only after this command; the Chinese title above has - // already covered the initial-paint case. - h.state_mut().run("view.outline", json!({})).unwrap(); - h.run_steps(3); - assert!(!initial_cjk || h.state().session.active().unwrap().title().contains(korean)); - let mut checked = 0; - for text in [korean, japanese, chinese, notes] { - if !system_has(text) { - assert!(!require_all, "required font input does not draw {text:?}"); - eprintln!("skipped {text:?}: no font on this machine draws it"); - continue; - } - assert_faces_draw(&h, text, &format!("{text:?}")); - checked += 1; - } - if require_all || cfg!(windows) || cfg!(target_os = "macos") { - assert_eq!(checked, 4, "all CJK samples must be exercised with required/bundled fonts"); - } - // Text typed later (a dialog field, a new comment) is looked at too. Never type text this - // machine cannot draw: the strict missing-glyph policy would panic before the optional check. - let typed = "ไทย"; - if system_has(typed) { - h.event(Event::Text(typed.into())); - h.run_steps(2); - assert!(h.ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(13.0), typed))); - } else if require_all { - panic!("required font input does not draw {typed:?}"); - } else { - eprintln!("skipped {typed:?}: no font on this machine draws it"); - } -} - -/// An input method can ask for characters (stock `DeleteSurrounding`) or UTF-8 bytes (the fork's -/// `DeleteSurroundingBytes`) around the caret to be removed. The byte range never splits a -/// character, and a deletion made while composing stays in the composition's one undo step. -#[test] -fn ime_delete_surrounding_handles_chars_bytes_and_composition_undo() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "abc"})).unwrap(); - h.run_steps(2); - h.event(Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 2, after_chars: 0 })); - h.run_steps(1); - assert_eq!(title_text(h.state()), "a"); - let deleted = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(deleted.change_cause, egui::output::ImeChangeCause::InputMethod, "an accepted deletion is an IME mutation"); - h.state_mut().session.execute("edit.undo", &json!({})).unwrap(); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abc", "a non-composing deletion is one undo step"); - - // UTF-8 bytes: the four bytes of an emoji are one character and must delete whole. - h.state_mut().session.execute("text.set", &json!({"id": title, "text": "aé😀"})).unwrap(); - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.move", &json!({"to": "end"})).unwrap(); - h.run_steps(2); - h.event(Event::Ime(ImeEvent::DeleteSurroundingBytes { before_bytes: 4, after_bytes: 0 })); - h.run_steps(2); - assert_eq!(title_text(h.state()), "aé", "the emoji's bytes delete exactly one scalar"); - - // Deleting before a composition, then committing, is a single undo step. - h.state_mut().session.execute("text.set", &json!({"id": title, "text": "abc"})).unwrap(); - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(2); - let undo0 = undo_len(h.state()); - h.event(preedit("日本")); - h.run_steps(1); - h.event(Event::Ime(ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })); - h.run_steps(1); - assert_eq!(title_text(h.state()), "ab日本"); - h.event(Event::Ime(ImeEvent::Commit("日本".into()))); - h.run_steps(2); - assert_eq!(title_text(h.state()), "ab日本"); - assert_eq!(undo_len(h.state()), undo0 + 1, "delete + commit is one composition step"); - h.state_mut().session.execute("edit.undo", &json!({})).unwrap(); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abc"); -} - -/// The canvas producer publishes bounded logical committed text with UTF-8 byte offsets and a -/// stable owner/generation across ordinary typing, caret movement and reversed selection. -#[test] -fn ime_output_is_logical_bounded_and_owner_stable() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "aé😀b"})).unwrap(); - h.run_steps(2); - let first = h.output().platform_output.ime.clone().expect("editing text owns the input method"); - assert_eq!(first.purpose, egui::IMEPurpose::Normal); - assert_eq!(first.change_cause, egui::output::ImeChangeCause::Other); - let payload = first.surrounding_text.available().expect("model text is available"); - assert_eq!((payload.text.as_str(), payload.cursor, payload.anchor), ("aé😀b", 8, 8)); - let (owner, generation) = (first.owner, first.context_generation); - - // A caret move is not a new context and still reports logical UTF-8 offsets. - h.state_mut().session.execute("text.select", &json!({"anchor": [0, 2], "caret": [0, 2]})).unwrap(); - h.run_steps(1); - let moved = h.output().platform_output.ime.clone().unwrap(); - assert_eq!((moved.owner, moved.context_generation), (owner, generation)); - let payload = moved.surrounding_text.available().unwrap(); - assert_eq!((payload.cursor, payload.anchor), (3, 3)); - - // A reversed selection keeps caret < anchor in the outgoing bytes. - h.state_mut().session.execute("text.select", &json!({"anchor": [0, 3], "caret": [0, 1]})).unwrap(); - h.run_steps(1); - let reversed = h.output().platform_output.ime.clone().unwrap(); - assert_eq!((reversed.owner, reversed.context_generation), (owner, generation)); - let payload = reversed.surrounding_text.available().unwrap(); - assert_eq!((payload.cursor, payload.anchor), (1, 7), "caret and anchor keep their direction"); - - // A forced extra pass in the same frame keeps the same context. - h.ctx.request_discard("ime multipass regression"); - h.run_steps(1); - let multipass = h.output().platform_output.ime.clone().unwrap(); - assert_eq!((multipass.owner, multipass.context_generation), (owner, generation)); - - // The extra window renders the slide and owns no text: whether the backend draws it as its - // own native viewport or (as in kittest, which installs no immediate-viewport renderer) - // embedded in this pass, it must neither own nor disturb the editor's context. - h.state_mut().run("view.newWindow", json!({"on": true})).unwrap(); - h.run_steps(2); - let second_window = h.output().platform_output.ime.clone().unwrap(); - assert_eq!((second_window.owner, second_window.context_generation), (owner, generation)); - h.state_mut().run("view.newWindow", json!({"on": false})).unwrap(); -} - -/// A model-stored composition is pre-edit, not committed text. An accepted commit changes the -/// committed snapshot and is the only path that earns `InputMethod`. -#[test] -fn preedit_is_excluded_and_a_commit_is_input_method() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "ab"})).unwrap(); - h.run_steps(2); - h.event(preedit("日本")); - h.run_steps(1); - let composing = h.output().platform_output.ime.clone().unwrap(); - let payload = composing.surrounding_text.available().unwrap(); - assert_eq!((payload.text.as_str(), payload.cursor, payload.anchor), ("ab", 2, 2), "pre-edit is not committed text"); - assert_eq!(composing.change_cause, egui::output::ImeChangeCause::Other); - - h.event(Event::Ime(ImeEvent::Commit("日本".into()))); - h.run_steps(1); - let committed = h.output().platform_output.ime.clone().unwrap(); - let payload = committed.surrounding_text.available().unwrap(); - assert_eq!(payload.text, "ab日本"); - assert_eq!((payload.cursor, payload.anchor), (8, 8)); - assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod); - - // A pre-edit and its commit in one frame is still one accepted IME mutation. `Harness::event` - // queues one frame per event, so put both in a single RawInput. - h.state_mut().session.execute("text.insert", &json!({"text": "X"})).unwrap(); - h.run_steps(1); - h.input_mut().events.push(preedit("Y")); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - let same_frame = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(title_text(h.state()), "ab日本XY"); - assert_eq!(same_frame.change_cause, egui::output::ImeChangeCause::InputMethod); -} - -/// An application edit anywhere in the frame dominates an IME commit in that same frame. -#[test] -fn mixed_application_and_ime_edits_report_other() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "a"})).unwrap(); - h.run_steps(2); - // Both events belong to one pass. `Harness::event` queues one frame per event, so put them - // in a single RawInput instead. - h.input_mut().events.push(Event::Text("x".into())); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("y".into()))); - h.run_steps(1); - let ime = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(title_text(h.state()), "axy"); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::Other); - let payload = ime.surrounding_text.available().unwrap(); - assert_eq!(payload.text, "axy"); -} - -/// An empty commit is a no-op: it must not claim an IME mutation. An empty body is still an -/// available surrounding context, not `Unavailable`. -#[test] -fn no_op_commit_stays_other_and_empty_text_is_available() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - let empty = h.output().platform_output.ime.clone().unwrap(); - let payload = empty.surrounding_text.available().expect("an empty editable body is available"); - assert_eq!((payload.text.as_str(), payload.cursor, payload.anchor), ("", 0, 0)); - - h.event(Event::Ime(ImeEvent::Commit(String::new()))); - h.run_steps(1); - let no_op = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(no_op.change_cause, egui::output::ImeChangeCause::Other); - assert!(no_op.surrounding_text.available().is_some_and(|p| p.text.is_empty())); -} - -/// A no-op delete is not a mutation: a real commit in the same `RawInput` is still an accepted -/// IME edit, not `Other` caused by a poisoned frame. -#[test] -fn no_op_delete_does_not_poison_a_commit_in_the_same_frame() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "abc"})).unwrap(); - h.run_steps(2); - - h.input_mut().events.push(Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 0, after_chars: 0 })); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("X".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcX"); - let ime = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the no-op did not poison the real commit"); -} - -/// An empty commit is likewise a no-op; a real commit later in the same frame remains the -/// accepted input-method mutation. -#[test] -fn empty_commit_does_not_poison_a_commit_in_the_same_frame() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.insert", &json!({"text": "ab"})).unwrap(); - h.run_steps(2); - - h.input_mut().events.push(Event::Ime(ImeEvent::Commit(String::new()))); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abY"); - let ime = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the empty commit did not poison the real commit"); -} - -/// A selection wider than the surrounding-text budget is published as `Unavailable`. A real -/// deletion from that state must still be certified through the unavailable revision, including -/// when the selection stays unavailable afterwards. -#[test] -fn wide_selection_delete_is_certified_with_the_unavailable_revision() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.set", &json!({"id": title, "text": "a".repeat(4500)})).unwrap(); - h.state_mut().session.execute("text.select", &json!({"anchor": [0, 1], "caret": [0, 4500]})).unwrap(); - h.run_steps(2); - let before = h.output().platform_output.ime.clone().unwrap(); - assert!(before.surrounding_text.available().is_none(), "the wide selection is unavailable"); - - h.input_mut().events.push(Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 })); - h.run_steps(1); - assert_eq!(title_text(h.state()).len(), 4499, "one character before the selection was deleted"); - let after = h.output().platform_output.ime.clone().unwrap(); - assert!(after.surrounding_text.available().is_none(), "the selection is still wider than the budget"); - assert_eq!(after.change_cause, egui::output::ImeChangeCause::InputMethod, "the unavailable revision certifies the deletion"); -} - -/// A commit that replaces a wide (unavailable) selection produces available text; the mixed -/// unavailable -> available transition needs the before revision to be certified. -#[test] -fn wide_selection_commit_is_certified_with_the_unavailable_revision() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.state_mut().session.execute("text.set", &json!({"id": title, "text": "a".repeat(4500)})).unwrap(); - h.state_mut().session.execute("text.select", &json!({"anchor": [0, 1], "caret": [0, 4500]})).unwrap(); - h.run_steps(2); - assert!(h.output().platform_output.ime.as_ref().unwrap().surrounding_text.available().is_none()); - - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aY", "the selected tail is replaced"); - let ime = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(ime.surrounding_text.available().unwrap().text, "aY"); - assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the unavailable revision certifies the commit"); -} - -/// The surrounding window is bounded even in a large body, and switching the edited target -/// starts a new owner/generation once. -#[test] -fn surrounding_text_is_bounded_and_target_replacement_resets_generation() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - let long = "a".repeat(4500); - h.state_mut().session.execute("text.set", &json!({"id": title, "text": long})).unwrap(); - h.state_mut().session.execute("text.move", &json!({"to": "end"})).unwrap(); - h.run_steps(2); - let ime = h.output().platform_output.ime.clone().unwrap(); - let payload = ime.surrounding_text.available().unwrap(); - assert!(payload.text.len() <= 4000, "{}", payload.text.len()); - assert_eq!(payload.cursor, payload.text.len()); - let first = (ime.owner, ime.context_generation); - - // A selection wider than the protocol bound is explicitly unavailable, not truncated. - h.state_mut().session.execute("text.selectAll", &json!({})).unwrap(); - h.run_steps(1); - let wide = h.output().platform_output.ime.clone().unwrap(); - assert!(wide.surrounding_text.available().is_none(), "oversized selection is Unavailable"); - - h.state_mut().run("text.exit", json!({})).unwrap(); - let r = h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [20, 20, 200, 80], "text": "other"})).unwrap(); - let other = r["id"].as_u64().unwrap(); - h.state_mut().run("text.edit", json!({"id": other})).unwrap(); - h.run_steps(2); - let ime = h.output().platform_output.ime.clone().unwrap(); - assert_ne!((ime.owner, ime.context_generation), first, "a new target is a new context"); - let payload = ime.surrounding_text.available().unwrap(); - assert_eq!((payload.text.as_str(), payload.cursor, payload.anchor), ("other", 5, 5)); -} - -/// With no target, the custom owner is hidden: it observes `None` and publishes no descriptor. -#[test] -fn hidden_canvas_owner_observes_none() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - let first = h.output().platform_output.ime.clone().unwrap(); - h.state_mut().run("text.exit", json!({})).unwrap(); - h.state_mut().run("edit.select", json!({"ids": []})).unwrap(); - h.run_steps(1); - assert!(h.output().platform_output.ime.is_none(), "nothing to type into: no custom owner"); - - // Re-focusing the same shape starts one new generation after the hidden pass. - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - let again = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(again.owner, first.owner); - assert_ne!(again.context_generation, first.context_generation); -} - -/// A platform pre-edit or commit queued in the same pass as the application settling the -/// composition (a plain click on another shape) must not be typed into the new target: the -/// settled text stays in the body it was composed in, and the platform's copy is interrupted. -/// Once that interrupt is published, an event the OS still queues is indistinguishable from a -/// legitimate new composition (egui's event payload has no generation), so only the settling -/// batch can be rejected deterministically. -/// -/// The pre-edit is plain ASCII on purpose: borrowing a CJK face installs fonts and discards the -/// pass, which would hide the one pass the interruption is published in. -#[test] -fn a_settling_batch_cannot_land_an_ime_event_in_the_next_target() { - let mut h = harness(Session::with_new()); - let a = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - let r = h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [400, 400, 240, 120], "text": "Confidential draft"})).unwrap(); - let b = r["id"].as_u64().unwrap() as u32; - h.state_mut().run("text.exit", json!({})).unwrap(); - h.state_mut().session.execute("text.set", &json!({"id": a, "text": "Quarterly results"})).unwrap(); - h.state_mut().run("text.edit", json!({"id": a})).unwrap(); - h.run_steps(2); - - // An input-method pre-edit in A. - h.event(preedit("nihon")); - h.run_steps(2); - assert!(h.state().session.active().unwrap().composition.is_some()); - - // A plain press on B settles the composition (PowerPoint does the same) and selects B. Its - // queued pre-edit and commit travel in the same input batch as the settling pass. - let press = deckcraft_engine::tools::PointerEvent { kind: deckcraft_engine::tools::PointerKind::Down, x: 500.0, y: 450.0, ..Default::default() }; - h.state_mut().session.pointer(press).unwrap(); - h.input_mut().events.push(preedit("nihon")); - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("nihon".into()))); - h.run_steps(1); - let st = h.state().session.active().unwrap(); - assert!(st.composition.is_none(), "the click settles the composition"); - assert_eq!(st.selection.shapes, vec![deckcraft_model::ShapeId(b)], "B is the new target"); - assert!(st.selection.text.is_none(), "the queued IME events did not start editing B"); - assert_eq!(text_of(&h, a), "Quarterly resultsnihon", "the settled pre-edit stays in A"); - assert_eq!(text_of(&h, b), "Confidential draft", "B's whole text is not replaced"); - let ime = h.output().platform_output.ime.clone().expect("B is a typing target"); - assert!(ime.should_interrupt_composition, "the platform's copy is cancelled, not committed back"); - assert!(h.state().ime_cancelled.is_none(), "the settled pass published the interrupt boundary"); -} - -/// The extra document window is a rendered image, not a second text target: the canvas owner -/// stays in the editing viewport, and closing the last presentation really releases it. -#[test] -fn a_second_window_keeps_the_canvas_owner_and_closing_the_last_document_tears_it_down() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - let first = h.output().platform_output.ime.clone().unwrap(); - assert_eq!(h.state().ime_viewport, Some(egui::ViewportId::ROOT), "the canvas owner lives in the editing viewport"); - - h.state_mut().run("view.newWindow", json!({"on": true})).unwrap(); - h.run_steps(2); - let second = h.output().platform_output.ime.clone().expect("the canvas still owns the input method"); - assert_eq!( - (second.owner, second.context_generation), - (first.owner, first.context_generation), - "the render-only window neither owns nor disturbs the input method" - ); - assert_eq!(h.state().ime_viewport, Some(egui::ViewportId::ROOT)); - h.state_mut().run("view.newWindow", json!({"on": false})).unwrap(); - h.run_steps(1); - - h.state_mut().run("file.close", json!({})).unwrap(); - h.run_steps(1); - assert!(h.state().session.active().is_none(), "the last presentation closed"); - assert_eq!(h.state().ime_viewport, None, "its viewport's IME state is released"); - assert!(h.output().platform_output.ime.is_none()); -} - -/// The text of the shape `id` in the active presentation. -fn text_of(h: &egui_kittest::Harness<'static, SlideApp>, id: u32) -> String { - h.state() - .session - .active() - .and_then(|d| d.shape(deckcraft_model::ShapeId(id))) - .and_then(|sh| sh.text.as_ref()) - .map(deckcraft_model::text::TextBody::text) - .unwrap_or_default() -} - -/// Open the title editor on `abcd`, select the text, and return the caret point used for -/// pointer interruption. -fn pending_terminal_editor() -> (egui_kittest::Harness<'static, SlideApp>, egui::Pos2) { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.event(Event::Text("abcd".into())); - h.run_steps(1); - h.state_mut().run("text.select", json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); - h.run_steps(1); - let point = h.output().platform_output.ime.as_ref().expect("the actual canvas caret1").cursor_rect.center(); - assert!(h.state().canvas_rect.unwrap().contains(point)); - h.state_mut().run("text.select", json!({"anchor": [0, 4], "caret": [0, 4]})).unwrap(); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcd"); - (h, point) -} - -/// Clear a pending pre-edit and assert that the visible text and undo length are unchanged and -/// no platform interrupt was requested. -fn clear_pending_preedit(h: &mut egui_kittest::Harness<'_, SlideApp>) { let undo = undo_len(h.state()); - h.event(preedit("Q")); + let converted = "日本ご"; + h.event(Event::Ime(ImeEvent::Preedit { text: converted.into(), active_range_chars: Some(2..3) })); h.run_steps(1); + assert_eq!(title_text(h.state()), converted); assert!(h.state().session.active().unwrap().composition.is_some()); - h.event(preedit("")); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcd", "the visible preedit was restored, not committed"); - assert!(h.state().session.active().unwrap().composition.is_none()); assert_eq!(undo_len(h.state()), undo); - assert!(!h.output().platform_output.ime.as_ref().unwrap().should_interrupt_composition, "empty preedit is not a platform reset"); -} - -/// Build the terminal `DeleteSurrounding` event in character or byte units. -fn pending_terminal_delete(bytes: bool) -> Event { - Event::Ime(if bytes { - ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 } - } else { - ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 } - }) -} - -/// A pointer interruption after clearing pre-edit rejects both later `DeleteSurrounding` and -/// commit forms. -#[test] -fn cleared_preedit_pointer_interruption_rejects_later_delete_and_terminal_commit() { - for bytes in [false, true] { - for split_terminal in [false, true] { - let (mut h, point) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let undo = undo_len(h.state()); - let doc = h.state().session.active().unwrap().doc.clone(); - h.input_mut().events.extend([ - Event::PointerMoved(point), - Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, - ]); - h.run_steps(1); - let reset = published_reset(&h); - let t = h.state().session.active().unwrap().selection.text.as_ref().expect("the real pointer kept text editing"); - assert_eq!((t.anchor, t.caret), ((0, 1), (0, 1)), "the actual pointer moved the caret"); - h.input_mut().events.push(Event::PointerButton { - pos: point, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: Default::default(), - }); - h.run_steps(3); // Publishing an interrupt and idle passes do not deliver the terminal. - h.input_mut().events.push(pending_terminal_delete(bytes)); - if split_terminal { - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcd", "the separately delivered old deletion is refused"); - } - h.input_mut().events.extend([Event::Ime(ImeEvent::Commit("X".into())), reset_completed(reset), preedit("Y")]); - h.run_steps(1); - // Old terminal is refused, the exact completion admits the suffix in that same batch. - assert_eq!(title_text(h.state()), "aYbcd"); - assert!( - !h.output().platform_output.ime.as_ref().unwrap().should_interrupt_composition, - "the observed old terminal must not reset the new composition" - ); - assert_eq!(undo_len(h.state()), undo, "neither stale input nor new preedit creates undo"); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(title_text(h.state()), "abcd", "only the fresh commit needs undo"); - // Before the new preedit the stale terminal must not have changed the presentation; - // the fresh composition's own undo snapshot is exactly the original document. - assert!(std::sync::Arc::ptr_eq(&doc, &h.state().session.active().unwrap().doc)); - } - } -} - -/// A key interruption after clearing pre-edit rejects a terminal event delivered in a different -/// batch. -#[test] -fn cleared_preedit_key_interruption_rejects_a_terminal_in_a_later_batch() { - for bytes in [false, true] { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let undo = undo_len(h.state()); - h.key_down(egui::Key::ArrowLeft); - h.run_steps(1); - let reset = published_reset(&h); - h.key_up(egui::Key::ArrowLeft); - h.run_steps(2); - h.input_mut().events.extend([pending_terminal_delete(bytes), Event::Ime(ImeEvent::Commit("X".into()))]); - h.run_steps(1); - let t = h.state().session.active().unwrap().selection.text.as_ref().unwrap(); - assert_eq!((t.anchor, t.caret), ((0, 3), (0, 3))); - assert_eq!(title_text(h.state()), "abcd"); - assert_eq!(undo_len(h.state()), undo); - h.input_mut().events.extend([reset_completed(reset), Event::Ime(ImeEvent::Commit("Y".into()))]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcYd", "the exact completion admits the later direct commit"); - } -} - -/// Replacing the editing target rejects stale terminal mutations from the old composition. -#[test] -fn cleared_preedit_target_replacement_rejects_later_terminal_mutations() { - for bytes in [false, true] { - let (mut h, _) = pending_terminal_editor(); - let first = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - let second = h.state().session.active().unwrap().doc.slides[0].shapes[1].id.0; - h.state_mut().run("text.edit", json!({"id": second})).unwrap(); - h.event(Event::Text("WXYZ".into())); - h.run_steps(1); - h.state_mut().run("text.edit", json!({"id": first, "at": [0, 4]})).unwrap(); - h.run_steps(1); - clear_pending_preedit(&mut h); - let undo = undo_len(h.state()); - let doc = h.state().session.active().unwrap().doc.clone(); - // Actual production target-selection command, in a separate pass before the terminal. - h.state_mut().run("text.edit", json!({"id": second, "at": [0, 1]})).unwrap(); - h.run_steps(1); - let reset = published_reset(&h); - h.run_steps(2); - h.event(pending_terminal_delete(bytes)); - h.run_steps(1); - h.event(Event::Ime(ImeEvent::Commit("X".into()))); - h.run_steps(1); - assert!(std::sync::Arc::ptr_eq(&doc, &h.state().session.active().unwrap().doc), "neither old mutation can edit the replacement target"); - assert_eq!(title_text(h.state()), "abcd"); - assert_eq!(undo_len(h.state()), undo); - let t = h.state().session.active().unwrap().selection.text.as_ref().unwrap(); - assert_eq!((t.shape.0, t.anchor, t.caret), (second, (0, 1), (0, 1))); - h.input_mut().events.extend([reset_completed(reset), preedit("Y")]); - h.run_steps(1); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - let body = h.state().session.active().unwrap().doc.slides[0].shapes[1].text.as_ref().unwrap(); - assert_eq!(body.paragraphs[0].text(), "WYXYZ", "a fresh composition uses only the new target"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(h.state().session.active().unwrap().doc.slides[0].shapes[1].text.as_ref().unwrap().paragraphs[0].text(), "WXYZ"); - } -} - -/// Closing the last document clears pending terminal state, and a new document needs no -/// stale-composition fence. -#[test] -fn closing_the_last_document_clears_a_pending_preedit_terminal() { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - assert!(h.state().ime_terminal_pending.is_some()); - - h.state_mut().run("file.close", json!({})).unwrap(); - assert!(h.state().session.active().is_none(), "the last presentation closed"); - // An interruption observed after the document disappeared has no destination at all. It must - // stay distinct from "not interrupted yet", which would compare against the retired origin - // forever and request avoidable resets after a new document returns. - let ctx = h.ctx.clone(); - h.state_mut().note_settled_composition(&ctx); - let pending = h.state().ime_terminal_pending.as_ref().expect("the cleared-preedit terminal is still guarded"); - assert!(pending.cancelled && pending.interrupted); - assert!(pending.interrupted_at.is_none(), "the interruption has no active document destination"); - - h.run_steps(1); - assert!(h.state().ime_terminal_pending.is_none(), "document teardown releases the terminal guard"); - assert!(h.state().ime_composition.is_none()); - assert!(h.state().ime_cancelled.is_none()); - assert!(!h.state().ime_interrupt_pending); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); - - // Its dead-document terminal must not force a reset in a new presentation's editor. - h.state_mut().run("file.new", json!({})).unwrap(); - h.run_steps(1); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear), "the new document's first target needs no stale-composition fence"); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); -} - -/// After a plain clear, both character- and byte-count terminal deletes are accepted. -#[test] -fn cleared_preedit_without_interruption_accepts_both_terminal_delete_forms() { - for bytes in [false, true] { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - h.event(pending_terminal_delete(bytes)); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abc"); - h.event(Event::Ime(ImeEvent::Commit("X".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcX", "the accepted deletion's caret shift does not stale its commit"); - assert!(h.state().ime_terminal_pending.is_none()); - } -} - -/// A clear accepts its own commit, then permits a direct commit and a fresh composition without -/// stale state. -#[test] -fn cleared_preedit_accepts_its_commit_then_direct_and_fresh_compositions() { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - h.event(Event::Ime(ImeEvent::Commit("X".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcdX"); - assert!(h.state().ime_terminal_pending.is_none()); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcdXY", "a direct commit has no old owner"); - h.event(preedit("Z")); - h.run_steps(1); - h.event(Event::Ime(ImeEvent::Commit("Z".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abcdXYZ"); -} - -// --------------------------------------------------------------------------- -// Token-bound IME reset adoption (revision02): opaque id + ordered completion. -// --------------------------------------------------------------------------- - -/// Build the ordered reset-completion event for a request id. -fn reset_completed(id: egui::ImeResetId) -> Event { - Event::ImeResetCompleted { request_id: id } -} - -/// Return the custom descriptor's currently published reset id, asserting that a token-bound -/// request exists. -fn published_reset(h: &egui_kittest::Harness<'static, SlideApp>) -> egui::ImeResetId { - h.output().platform_output.ime.as_ref().and_then(|ime| ime.reset_request).expect("the custom descriptor carries a token-bound reset request") -} - -/// Read the reset phase recorded for the root viewport. -fn root_phase(h: &egui_kittest::Harness<'static, SlideApp>) -> crate::ImeResetPhase { - h.state().ime_reset_for(egui::ViewportId::ROOT) -} - -/// Match the backend contract: the active viewport must have an entry in RawInput. -fn viewport_input(viewport: egui::ViewportId) -> egui::RawInput { - let mut input = egui::RawInput { viewport_id: viewport, ..Default::default() }; - input.viewports.insert(viewport, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..Default::default() }); - input -} - -/// Read the reset phase for an arbitrary viewport, defaulting to `Clear` when none is stored. -fn phase_at(h: &egui_kittest::Harness<'static, SlideApp>, viewport: egui::ViewportId) -> crate::ImeResetPhase { - h.state().ime_reset_for(viewport) -} - -#[derive(Debug, PartialEq, Eq)] -struct ImeStateSnapshot { - composition: Option<(egui::Id, u64, bool)>, - terminal: Option<(egui::Id, u64, (usize, usize), (usize, usize), bool, bool, Option)>, - cancelled: Option<(egui::Id, u64)>, - generation: u64, - settles_seen: u64, - interrupt_pending: bool, - viewport: Option, - frame_viewport: Option, - reset_entries: usize, -} - -/// Every piece of the root composition lifetime that the per-viewport reset map does not own. -fn ime_state(h: &egui_kittest::Harness<'static, SlideApp>) -> ImeStateSnapshot { - let app = h.state(); - ImeStateSnapshot { - composition: app.ime_composition.map(|c| (c.owner, c.generation, c.settled)), - terminal: app.ime_terminal_pending.as_ref().map(|p| (p.owner, p.revision, p.anchor, p.caret, p.cancelled, p.interrupted, p.interrupted_at)), - cancelled: app.ime_cancelled.map(|c| (c.owner, c.generation)), - generation: app.ime_generation, - settles_seen: app.ime_settles_seen, - interrupt_pending: app.ime_interrupt_pending, - viewport: app.ime_viewport, - frame_viewport: app.ime_frame_viewport, - reset_entries: app.ime_reset.len(), - } -} - -/// Put the title editor into a settled composition and return the actual opaque request id. -fn settled_title_reset(h: &mut egui_kittest::Harness<'static, SlideApp>) -> egui::ImeResetId { - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - if h.state().session.active().unwrap().selection.text.is_none() { - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(2); - } - h.event(preedit("日")); - h.run_steps(1); h.key_down(egui::Key::End); h.run_steps(1); - let id = published_reset(h); + assert!(h.output().platform_output.ime.as_ref().unwrap().should_interrupt_composition); + assert!(h.state().session.active().unwrap().composition.is_none()); + assert_eq!(title_text(h.state()), converted); + assert_eq!(undo_len(h.state()), undo + 1); h.key_up(egui::Key::End); h.run_steps(1); - id -} - -/// Only the exact ordered completion releases the fence; a fresh suffix survives while a stale -/// prefix is discarded. -#[test] -fn ordered_reset_completion_is_exact_and_fresh_suffix_survives_stale_prefix() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - // Foreign completion and a fresh preedit in the same raw batch: inert, blocked. - let foreign = egui::Context::default().request_ime_reset(egui::ViewportId::ROOT).unwrap(); - h.input_mut().events.extend([reset_completed(foreign), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "foreign completion cannot release the guard"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - // A stale old commit is rejected while the fence is still Awaiting. - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("old".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "the stale prefix is rejected"); - - // The exact completion in one batch, then a fresh suffix in the NEXT batch. - h.input_mut().events.push(reset_completed(r1)); - h.run_steps(1); - h.input_mut().events.push(preedit("Y")); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y", "the exact completion admits the next-batch suffix"); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); - - // A second interruption gets a newer id; completion plus the suffix may share one batch. - h.event(preedit("Z")); - h.run_steps(1); - h.key_down(egui::Key::End); - h.run_steps(1); - let r2 = published_reset(&h); - h.key_up(egui::Key::End); - h.run_steps(1); - assert_ne!(r1, r2, "another interruption supersedes the previous fence"); - h.input_mut().events.extend([reset_completed(r2), preedit("W")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日YZW", "the exact new completion admits the same-batch suffix"); -} - -/// Waiting frames without the exact completion emit no replacement token and keep input blocked. -#[test] -fn no_completion_fails_closed_and_unchanged_waiting_frames_do_not_emit_new_requests() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - for _ in 0..3 { - h.input_mut().events.extend([Event::Ime(ImeEvent::Commit("X".into())), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "without a completion no IME mutation is admitted"); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); - } - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - h.input_mut().events.extend([reset_completed(r1), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y", "the exact completion is the only release"); -} - -/// A discarded final `None` suspends the guard; returning to the same editor publishes a new id. -#[test] -fn discarded_final_none_suspends_and_the_same_editor_rearms_with_a_new_id() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - h.state_mut().dialog = Some(crate::dialogs::Dialog::new("about")); - h.ctx.request_discard("final IME descriptor is absent on this discarded pass"); - h.run_steps(1); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), - "the discarded final-none pass retires R1 locally: {:?}", - root_phase(&h) - ); - assert!(h.output().platform_output.ime.is_none()); - - h.state_mut().dialog = None; - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2, "returning to the same caret publishes one replacement"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r2)); - - // A late completion for the retired request is inert. - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "the retired R1 cannot release R2"); - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); -} - -/// A real modal without a discarded pass suspends the guard and publishes no speculative token. -#[test] -fn actual_modal_without_discard_suspends_and_queues_no_token() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - - // A normal About pass, no request_discard: the modal is an explicitly ineligible route even - // though the canvas is painted behind it. - h.state_mut().dialog = Some(crate::dialogs::Dialog::new("about")); - h.run_steps(2); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), - "the modal retires R1 without allocating: {:?}", - root_phase(&h) - ); - assert!(h.output().platform_output.ime.is_none(), "the modal publishes no custom descriptor"); - - // Force a stock descriptor while the modal stays open. A token queued on the modal pass would - // be attached to this descriptor by egui; there must be none. - let notes = egui::Id::unique("notes_edit"); - h.ctx.memory_mut(|m| m.request_focus(notes)); - h.run_steps(1); - let stock = h.output().platform_output.ime.as_ref().expect("the notes field publishes its own descriptor"); - assert!(stock.reset_request.is_none(), "the modal pass did not queue a custom token for stock output"); - h.ctx.memory_mut(|m| m.surrender_focus(notes)); - - // Returning to the custom editor publishes exactly one replacement, and only its exact - // completion admits the suffix. - h.state_mut().dialog = None; - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2); - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "the retired modal-pass R1 stays inert"); - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); -} - -/// A modal-owned observe/finalizer pass rejects a matching custom descriptor before allocating a -/// token. -#[test] -fn modal_observe_and_finalizer_reject_a_matching_custom_descriptor_before_allocation() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - h.state_mut().dialog = Some(crate::dialogs::Dialog::new("about")); - h.state_mut().set_ime_reset( - egui::ViewportId::ROOT, - crate::ImeResetPhase::Suspended { viewport: egui::ViewportId::ROOT, needs_rearm: true, request: None }, - ); - - let rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(1.0, 18.0)); - h.state_mut().ime_pending = Some(rect); - let ctx = h.ctx.clone(); - ctx.output_mut(|o| o.ime = None); - assert!(h.state_mut().observe_ime(&ctx).is_none(), "a pending canvas rect is hidden by the modal"); - assert!(ctx.output(|o| o.ime.is_none()), "the hidden custom owner is not republished"); - - let owner = h.state().ime_target().expect("the title is still a custom target").owner; - let key = crate::ImeDescriptorKey::new(owner, 1, egui::IMEPurpose::Normal); - ctx.output_mut(|o| { - o.ime = Some(egui::output::IMEOutput { - owner, - context_generation: 1, - purpose: egui::IMEPurpose::Normal, - rect, - cursor_rect: rect, - should_interrupt_composition: false, - reset_request: None, - change_cause: egui::output::ImeChangeCause::Other, - surrounding_text: egui::output::IMESurroundingText::Unavailable, - }); - }); - h.state_mut().finalize_ime_reset(&ctx, Some(key)); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), - "the finalizer rejects a matching custom descriptor while the modal owns the route: {:?}", - root_phase(&h) - ); - assert!(ctx.output(|o| o.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())), "no token was added to the modal output"); -} - -/// Opening, Backstage, palette, and modal routes all report that the custom canvas cannot own -/// input. -#[test] -fn opening_backstage_palette_and_modal_routes_are_explicitly_ineligible() { - let mut h = harness(Session::with_new()); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - assert!(h.state().ime_custom_canvas_route(&h.ctx), "the plain canvas editor is eligible"); - - h.state_mut().opening = Some(crate::opening::Opening::for_test("deck.pptx")); - assert!(!h.state().ime_custom_canvas_route(&h.ctx), "the opening overlay hides the canvas"); - h.state_mut().opening = None; - - h.state_mut().open_backstage(crate::backstage::Page::Home); - assert!(!h.state().ime_custom_canvas_route(&h.ctx), "Backstage hides the canvas"); - h.state_mut().close_backstage(); - - h.state_mut().palette = Some((String::new(), 0)); - assert!(!h.state().ime_custom_canvas_route(&h.ctx), "the palette owns input"); - h.state_mut().palette = None; - - h.state_mut().dialog = Some(crate::dialogs::Dialog::new("about")); - assert!(!h.state().ime_custom_canvas_route(&h.ctx), "a modal owns input"); -} - -/// Stock focused controls keep their own descriptor; Backstage/no-editor routes suspend and then -/// re-arm once on return. -#[test] -fn stock_focus_backstage_and_no_editor_routes_preserve_stock_output_and_rearm() { - // A focused stock TextEdit keeps its own descriptor; the custom fence is suspended. - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - let custom_owner = h.state().ime_target().unwrap().owner; - let notes = egui::Id::unique("notes_edit"); - h.ctx.memory_mut(|m| m.request_focus(notes)); - h.run_steps(2); - let stock = h.output().platform_output.ime.as_ref().expect("the notes field publishes its own IME descriptor"); - assert_ne!(stock.owner, custom_owner, "the stock field's descriptor was not overwritten"); - assert!(stock.reset_request.is_none(), "the finalizer did not attach a custom token to stock output"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { .. })); - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "late R1 is inert after stock focus"); - - h.ctx.memory_mut(|m| m.surrender_focus(notes)); - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2); - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y", "returning to the custom editor re-arms once"); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - - // Backstage hides the canvas and must not edit the hidden slide. - let r3 = settled_title_reset(&mut h); - h.state_mut().open_backstage(crate::backstage::Page::Home); - h.run_steps(1); - assert!(h.output().platform_output.ime.is_none(), "Backstage publishes no canvas descriptor"); - assert_eq!(title_text(h.state()), "日Y日", "hidden slide is untouched"); - h.input_mut().events.extend([reset_completed(r3), preedit("Z")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y日", "Backstage leaves the old fence suspended"); - h.state_mut().close_backstage(); - h.run_steps(1); - let r4 = published_reset(&h); - assert_ne!(r3, r4); - h.input_mut().events.extend([reset_completed(r4), preedit("Z")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y日Z", "returning from Backstage re-arms the same editor"); - h.event(Event::Ime(ImeEvent::Commit("Z".into()))); - h.run_steps(1); - - // A no-editor/multi-selection route also suspends and returns with one fresh request. - let r5 = settled_title_reset(&mut h); - h.state_mut().run("text.exit", json!({})).unwrap(); - h.state_mut().session.active_mut().unwrap().selection.shapes.clear(); - h.run_steps(1); - assert!(h.output().platform_output.ime.is_none(), "no editor means no custom descriptor"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { .. })); - let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title, "at": [0, 5]})).unwrap(); - h.run_steps(1); - let r6 = published_reset(&h); - assert_ne!(r5, r6); - h.input_mut().events.extend([reset_completed(r6), preedit("K")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y日Z日K"); -} - -/// Full logic+UI passes do not re-arm, while standalone logic suspends exactly once without -/// replaying input. -#[test] -fn full_logic_ui_passes_do_not_rearm_while_standalone_logic_suspends_once() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - - // The full pass runs App::logic before the UI. The mode hook must prevent the logic half - // from treating the not-yet-painted UI as absence. - h.run_steps(2); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); - - let ctx = h.ctx.clone(); - // A child viewport frame supplies the actual viewport stack for its logic callback. - let other = egui::ViewportId::from_hash_of("deckcraft test other viewport"); - ctx.run_ui(viewport_input(other), |ui| h.state_mut().logic(ui.ctx())).drop_without_applying_deltas(); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - // Standalone root logic paints no geometry: suspend exactly once, without replaying input. - let _ = ctx.run_logic(&egui::RawInput::default(), |ctx| h.state_mut().logic(ctx)); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - let _ = ctx.run_logic(&egui::RawInput::default(), |ctx| h.state_mut().logic(ctx)); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - - // The next full UI pass reacts to the actual custom descriptor and publishes one replacement. - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r2)); - h.run_steps(1); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); -} - -/// A terminal change observed only in standalone logic never queues a token for a later stock -/// route. -#[test] -fn standalone_logic_changed_terminal_never_queues_a_token_for_the_next_stock_route() { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let before = title_text(h.state()); - h.state_mut().run("text.select", json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); - - // A changed pending terminal reaches the interruption branch in a standalone run_logic tick. - // Logic paints no geometry, so it must suspend locally instead of putting a request into - // egui Memory; otherwise the next stock descriptor consumes the abandoned token. - let ctx = h.ctx.clone(); - let _ = ctx.run_logic(&egui::RawInput::default(), |ctx| h.state_mut().logic(ctx)); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), "standalone logic allocates no token"); - assert!(h.state().ime_terminal_pending.as_ref().is_some_and(|p| p.cancelled), "the interruption is still recorded locally"); - assert!(h.state().ime_interrupt_pending, "the settled composition still needs its platform interrupt"); - - h.state_mut().palette = Some((String::new(), 0)); - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - assert!(h.output().platform_output.ime.as_ref().is_none_or(|ime| ime.reset_request.is_none())); - // TextEdit requests focus after painting; its stock descriptor is on the next frame. - h.run_steps(1); - let stock = h.output().platform_output.ime.as_ref().expect("the palette field publishes its own descriptor"); - assert!(stock.reset_request.is_none(), "the abandoned logic tick did not attach a token to stock output"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - h.input_mut().events.push(preedit("X")); - h.run_steps(1); - assert_eq!(title_text(h.state()), before, "stock input cannot edit the hidden slide"); - - // Returning to the custom editor publishes exactly one replacement for the real new caret. - h.state_mut().palette = None; - if let Some(id) = h.ctx.memory(|m| m.focused()) { - h.ctx.memory_mut(|m| m.surrender_focus(id)); - } - h.run_steps(1); - let r = published_reset(&h); - h.input_mut().events.extend([reset_completed(r), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd", "the exact replacement admits the fresh suffix at the real caret"); -} - -/// The exact completion admits a fresh suffix without admitting the old terminal commit. -#[test] -fn cleared_preedit_exact_completion_admits_fresh_suffix_without_the_old_terminal_commit() { - // Same batch: the exact completion is the platform-reset boundary; no old Commit, - // Enabled/Disabled or idle pass is needed before a new composition may start. The caret is - // the real one the fixture selected, so the oracle is `aYbcd` (not the review's illustrative - // `abcdY`, which assumed a different caret). - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let undo = undo_len(h.state()); - h.state_mut().run("text.select", json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); - h.run_steps(1); - let r1 = published_reset(&h); - let pending = h.state().ime_terminal_pending.as_ref().expect("the retired cleared-preedit terminal is guarded"); - assert!(pending.cancelled); - assert!(pending.interrupted_at.is_some(), "the interruption destination is stored separately from the origin"); - - h.input_mut().events.extend([reset_completed(r1), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd", "the exact completion admits the same-batch suffix"); - let t = h.state().session.active().unwrap().selection.text.as_ref().unwrap(); - assert_eq!((t.anchor, t.caret), ((0, 2), (0, 2)), "the fresh preedit advances the real caret"); - assert_eq!(undo_len(h.state()), undo, "a preedit creates no undo step"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); - assert!(h.state().ime_terminal_pending.is_none(), "the exact fence completion released the old terminal guard"); - for _ in 0..3 { - h.run_steps(1); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear), "unchanged idle passes do not request R churn"); - } - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd", "the committed suffix replaces its preedit"); - assert_eq!(undo_len(h.state()), undo + 1, "the fresh composition is exactly one undo step"); - - // Next batch: completion alone releases, then the fresh suffix arrives in a later raw batch. - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let undo = undo_len(h.state()); - h.state_mut().run("text.select", json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); - h.run_steps(1); - let r1 = published_reset(&h); - h.input_mut().events.push(reset_completed(r1)); - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); - assert!(h.state().ime_terminal_pending.is_none()); - for _ in 0..3 { - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear), "an idle pass after the exact completion keeps it clear"); - assert!(h.output().platform_output.ime.as_ref().is_some_and(|ime| ime.reset_request.is_none())); - } - h.input_mut().events.push(preedit("Y")); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd", "the next-batch suffix is admitted"); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "aYbcd"); assert_eq!(undo_len(h.state()), undo + 1); } -/// Repeating the exact completion after `Clear` changes no composition or undo state. #[test] -fn duplicate_exact_completion_after_clear_is_inert() { +fn composing_on_a_selected_shape_starts_editing_it() { let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - let undo = undo_len(h.state()); - - h.input_mut().events.push(reset_completed(r1)); - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); - - // A duplicate after Clear does nothing, and the same batch may carry a fresh preedit. - h.input_mut().events.extend([reset_completed(r1), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); - assert_eq!(undo_len(h.state()), undo); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); - - // A duplicate old completion never clears the latest replacement either. - h.event(preedit("Z")); - h.run_steps(1); - h.key_down(egui::Key::End); - h.run_steps(1); - let r2 = published_reset(&h); - h.key_up(egui::Key::End); - h.run_steps(1); - assert_ne!(r1, r2); - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日YZ", "the duplicate old completion cannot release R2"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r2)); - h.input_mut().events.extend([reset_completed(r2), preedit("W")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日YZW"); -} - -/// The font-install early return suspends without a token, and returning to the editor re-arms -/// once. -#[test] -fn font_install_early_return_suspends_without_a_speculative_token_and_rearms_once() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - let before = title_text(h.state()); - - // Force the real ui_setup font-install early return. The outer all-exit wrapper must still - // observe the absent custom descriptor and retire R1. - h.state_mut().styled = false; - // A discarded pass is invisible to `run_ui`: it retries immediately, up to `max_passes`. - // Drive exactly one root UI pass here so the discarded pass itself can be observed, while - // keeping the normal two-pass budget so `Context::will_discard` is genuinely true - // (`num_completed_passes + 1 < max_passes`; with `max_passes == 1` it would be false and the - // finalizer would take the accepted-pass branch). This calls only `SlideApp::ui`, not - // `run_ui` or its plugin pass hooks, and not `SlideApp::logic`; the font-install early return - // under test does not depend on them. - let input = h.input_mut().take(); - let ctx = h.ctx.clone(); - ctx.begin_pass(input); - ctx.root_ui(|ui| h.state_mut().ui(ui)); - assert!(ctx.will_discard(), "the font-install pass is a discarded pass under the normal budget"); - let pass = ctx.end_pass(); - let published = pass.platform_output.ime.clone(); - pass.drop_without_applying_deltas(); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - assert!(published.is_none(), "the discarded font pass publishes no custom descriptor"); - - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2, "the late R1 is inert; returning custom paints one replacement"); - assert_eq!(title_text(h.state()), before, "the late preedit stays blocked"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r2)); - - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}Y")); -} - -/// The palette route retires the guard without a token; returning to the canvas publishes one -/// replacement. -#[test] -fn palette_route_retires_the_guard_without_a_speculative_token_and_rearms_once() { - let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - let before = title_text(h.state()); - - h.state_mut().palette = Some((String::new(), 0)); + let original = "Old"; + let id = h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100, 100, 200, 100], "text": original})).unwrap()["id"].clone(); + h.state_mut().run("text.exit", json!({})).unwrap(); h.run_steps(2); - let output = h.output().platform_output.ime.as_ref(); - assert!(output.is_none_or(|output| output.reset_request.is_none()), "the finalizer never attaches a custom token to stock output"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); + assert!(h.state().session.active().unwrap().selection.text.is_none()); + assert!(h.output().platform_output.ime.is_some()); + let undo = undo_len(h.state()); + let marked = "新"; + h.ctx.request_discard("adopt the canvas composition in the editor's next pass"); + h.input_mut().events.push(preedit(marked)); h.run_steps(1); - assert_eq!(title_text(h.state()), before, "the palette leaves the hidden slide untouched"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { .. })); - - h.state_mut().palette = None; - if let Some(id) = h.ctx.memory(|m| m.focused()) { - h.ctx.memory_mut(|m| m.surrender_focus(id)); - } + assert!(h.state().session.active().unwrap().selection.text.is_some()); + let text = h.state_mut().session.execute("text.get", &json!({"id": id})).unwrap(); + assert_eq!(text["text"], marked); + assert_eq!(undo_len(h.state()), undo); + let committed = "新しい"; + h.event(Event::Ime(ImeEvent::Commit(committed.into()))); h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2); - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}Y")); + let text = h.state_mut().session.execute("text.get", &json!({"id": id})).unwrap(); + assert_eq!(text["text"], committed); + assert_eq!(undo_len(h.state()), undo + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + let text = h.state_mut().session.execute("text.get", &json!({"id": id})).unwrap(); + assert_eq!(text["text"], original); } -/// A render-only viewport cannot mutate the root composition or bind the root reset guard. #[test] -fn render_only_viewports_cannot_mutate_root_composition_or_bind_the_root_guard() { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - h.state_mut().run("text.select", json!({"anchor": [0, 1], "caret": [0, 1]})).unwrap(); - h.run_steps(1); - let r1 = published_reset(&h); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - // Move the live selection without a root pass. A second window/presenter viewport renders - // through its own immediate viewport and never calls `SlideApp::logic`/`ui`; admitting such a - // callback would mutate root composition state while only the reset map is per-viewport. - h.state_mut().run("text.select", json!({"anchor": [0, 2], "caret": [0, 2]})).unwrap(); - let before = ime_state(&h); - // `run_ui` for a child viewport runs that viewport's whole pass and returns its output; the - // harness keeps the last ROOT output. Publish nothing for the render-only viewport and leave - // the root's already-published token untouched. - let root_ime_before = h.output().platform_output.ime.clone(); - assert_eq!( - root_ime_before.as_ref().and_then(|ime| ime.reset_request), - Some(r1), - "the root descriptor legitimately still carries the published R1" - ); - let child = egui::ViewportId::from_hash_of("deckcraft test child viewport"); - let ctx = h.ctx.clone(); - let child_logic = ctx.run_ui(viewport_input(child), |ui| h.state_mut().logic(ui.ctx())); - assert!(child_logic.platform_output.ime.is_none(), "rejected child logic publishes no IME descriptor"); - child_logic.drop_without_applying_deltas(); - assert_eq!(ime_state(&h), before, "rejected child logic left every root composition field unchanged"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1), "root R1 survives the child tick"); - assert!(matches!(phase_at(&h, child), crate::ImeResetPhase::Clear), "no child guard was admitted"); - assert_eq!(h.output().platform_output.ime, root_ime_before, "the child tick does not clear or rebind the root's published token"); - - let child_ui = ctx.run_ui(viewport_input(child), |ui| h.state_mut().ui(ui)); - assert!(child_ui.platform_output.ime.is_none(), "rejected child UI publishes no IME descriptor"); - child_ui.drop_without_applying_deltas(); - assert_eq!(ime_state(&h), before, "rejected child UI left every root composition field unchanged"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - assert_eq!(h.output().platform_output.ime, root_ime_before, "the child UI does not clear or rebind the root's published token"); - - // The root guard, not a child request, is what admits the real next-batch input. - h.input_mut().events.extend([reset_completed(r1), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "abYcd", "the moved real caret receives the fresh suffix"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); -} - -/// A suspended guard or request stamped for another viewport is never rebound to root. -#[test] -fn a_suspended_guard_or_request_stamped_for_another_viewport_is_never_rebound() { - let mut h = harness(Session::with_new()); - let _ = settled_title_reset(&mut h); - let child = egui::ViewportId::from_hash_of("deckcraft foreign suspended viewport"); - let child_request = h.ctx.request_ime_reset(child).expect("a real child request token"); - h.state_mut() - .ime_reset - .insert(egui::ViewportId::ROOT, crate::ImeResetPhase::Suspended { viewport: child, needs_rearm: true, request: Some(child_request) }); - h.run_steps(1); - let root_request = published_reset(&h); - assert_ne!(root_request, child_request, "a request issued for the child viewport is not rebound to root"); - assert_eq!(root_request.viewport_id(), egui::ViewportId::ROOT); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, viewport, .. } if id == root_request && viewport == egui::ViewportId::ROOT) - ); - - // A child completion delivered on the root stream is foreign and inert. - h.input_mut().events.extend([reset_completed(child_request), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "the foreign request completion cannot clear the root fence"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == root_request)); - h.input_mut().events.extend([reset_completed(root_request), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); -} - -/// Sorter and Notes Page stock routes allocate no custom reset token when a composition settles. -#[test] -fn sorter_and_notes_page_settles_never_allocate_for_a_stock_route() { - for (view, command) in [(crate::ViewMode::Sorter, "view.sorter"), (crate::ViewMode::NotesPage, "view.notesPage")] { +fn ime_delete_surrounding_handles_chars_bytes_and_composition_undo() { + for bytes in [false, true] { let mut h = harness(Session::with_new()); let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; - h.state_mut().run("text.edit", json!({"id": title})).unwrap(); + let (before, after, tail) = ("a", "🙂", "b"); + let original = format!("{before}{after}{tail}"); + h.state_mut().run("text.set", json!({"id": title, "text": original})).unwrap(); + h.state_mut().run("text.edit", json!({"id": title, "at": [0, before.chars().count()]})).unwrap(); h.run_steps(2); - assert!(h.state().ime_custom_canvas_route(&h.ctx), "the plain canvas editor is eligible"); - h.event(preedit("日")); + let undo = undo_len(h.state()); + let marked = "한"; + h.event(preedit(marked)); h.run_steps(1); - let before = title_text(h.state()); - - // Switch to a production view that paints no canvas producer. The retained text - // selection still yields an IME owner, so a negative-only admission check would let the - // settle below allocate a token for a route that never publishes a custom descriptor. - h.state_mut().run(command, json!({})).unwrap(); - assert_eq!(h.state().ui.view, view); - assert!(h.state().ime_target().is_some(), "the retained text selection still yields an owner"); - assert!(!h.state().ime_custom_canvas_route(&h.ctx), "{command} does not call canvas::show"); - - h.key_down(egui::Key::End); + assert_eq!(title_text(h.state()), format!("{before}{marked}{after}{tail}")); + // In a한🙂b the trailing 2..3 goes before 0..1, leaving the mark at 0..1. + let deletion = if bytes { + ImeEvent::DeleteSurroundingBytes { before_bytes: before.len(), after_bytes: after.len() } + } else { + ImeEvent::DeleteSurrounding { before_chars: before.chars().count(), after_chars: after.chars().count() } + }; + h.ctx.request_discard("exercise surrounding deletion across layout passes"); + h.input_mut().events.push(Event::Ime(deletion)); h.run_steps(1); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), - "the settle retires the old guard before the finalizer; no request is allocated in input: {:?}", - root_phase(&h) - ); - h.key_up(egui::Key::End); + assert_eq!(title_text(h.state()), format!("{marked}{tail}")); + assert_eq!(undo_len(h.state()), undo); + let committed = "한글"; + h.event(Event::Ime(ImeEvent::Commit(committed.into()))); h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - - // The palette's focused TextEdit is a stock descriptor. A token allocated on the sorter - // settle would be attached here by egui. - h.state_mut().palette = Some((String::new(), 0)); - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - assert!(h.output().platform_output.ime.as_ref().is_none_or(|ime| ime.reset_request.is_none())); - // TextEdit requests focus after painting; its stock descriptor is on the next frame. - h.run_steps(1); - let stock = h.output().platform_output.ime.as_ref().expect("the palette TextEdit publishes its own descriptor"); - assert!(stock.reset_request.is_none(), "{command} did not attach a speculative token to stock output"); - h.input_mut().events.push(preedit("X")); - h.run_steps(1); - assert_eq!(title_text(h.state()), before, "stock input cannot edit the hidden canvas"); - - // Returning to the custom canvas publishes exactly one replacement, and only its exact - // completion admits the fresh suffix. - h.state_mut().palette = None; - if let Some(id) = h.ctx.memory(|m| m.focused()) { - h.ctx.memory_mut(|m| m.surrender_focus(id)); - } - h.state_mut().run("view.normal", json!({})).unwrap(); - h.run_steps(1); - let reset = published_reset(&h); - h.input_mut().events.extend([reset_completed(reset), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}Y"), "returning to the canvas re-arms once"); - h.event(Event::Ime(ImeEvent::Commit("Y".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}Y")); + assert_eq!(title_text(h.state()), format!("{committed}{tail}")); + assert_eq!(undo_len(h.state()), undo + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(title_text(h.state()), original); } } -/// A same-pass switch from custom canvas to stock palette retires the guard without publishing a -/// token. #[test] -fn same_pass_custom_to_stock_palette_retires_the_guard_without_a_new_token() { +fn opening_backstage_palette_and_modal_routes_are_explicitly_ineligible() { + use craft::ui::runtime::env::WindowKey; + use craft::ui::shell::WindowDialogs; + let mut h = harness(Session::with_new()); - let r1 = settled_title_reset(&mut h); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == r1)); - - let rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(1.0, 18.0)); - let ctx = h.ctx.clone(); - let mut custom = None; - let output = ctx.run_ui(egui::RawInput::default(), |ui| { - let ctx = ui.ctx(); - h.state_mut().ime_frame_viewport = Some(egui::ViewportId::ROOT); - // A pre-UI interruption in a full pass must retire the guard locally, not allocate. - // The old implementation allocated here because the canvas route looked available. - h.state_mut().note_ime_interruption(ctx, true); - assert!(matches!(h.state().ime_reset_for(egui::ViewportId::ROOT), crate::ImeResetPhase::Suspended { request: None, .. })); - - h.state_mut().ime_pending = Some(rect); - // The canvas producer ran first and published a matching custom descriptor this pass. - custom = h.state_mut().observe_ime(ctx); - assert!(custom.is_some(), "the canvas's descriptor is eligible"); - - // Later in the same pass the command palette opens and its TextEdit owns IME output. - // Replace the pass output with that stock descriptor before the finalizer runs. - h.state_mut().palette = Some((String::new(), 0)); - let stock_owner = egui::Id::unique("same-pass-stock-palette"); - ctx.output_mut(|o| { - o.ime = Some(egui::output::IMEOutput { - owner: stock_owner, - context_generation: 1, - purpose: egui::IMEPurpose::Normal, - rect, - cursor_rect: rect, - should_interrupt_composition: false, - reset_request: None, - change_cause: egui::output::ImeChangeCause::Other, - surrounding_text: egui::output::IMESurroundingText::Unavailable, - }); - }); - h.state_mut().finalize_ime_reset(ctx, custom); - }); - // Read after `end_pass`: this is where egui would attach a request left in Memory to the - // pass's stock descriptor. It must be absent. - let stock_reset = output.platform_output.ime.as_ref().and_then(|ime| ime.reset_request); - output.drop_without_applying_deltas(); - assert!(stock_reset.is_none(), "the pre-UI interruption did not leave a token for the stock descriptor"); - assert!( - matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. }), - "the custom->stock pass retires R1 without allocating: {:?}", - root_phase(&h) - ); - - // A full palette pass must not publish R1 or any replacement into the stock field. - h.run_steps(1); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Suspended { request: None, .. })); - assert!(h.output().platform_output.ime.as_ref().is_none_or(|ime| ime.reset_request.is_none())); - // TextEdit requests focus after painting; its stock descriptor is on the next frame. - h.run_steps(1); - let stock = h.output().platform_output.ime.as_ref().expect("the palette TextEdit publishes its own descriptor"); - assert!(stock.reset_request.is_none()); - assert!(!h.state().ime_custom_canvas_route(&h.ctx)); - - h.state_mut().palette = None; - if let Some(id) = h.ctx.memory(|m| m.focused()) { - h.ctx.memory_mut(|m| m.surrender_focus(id)); - } - h.run_steps(1); - let r2 = published_reset(&h); - assert_ne!(r1, r2, "returning to the canvas requests one replacement"); - h.input_mut().events.extend([reset_completed(r1), preedit("X")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日", "the retired custom R1 stays inert"); - h.input_mut().events.extend([reset_completed(r2), preedit("Y")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), "日Y"); -} - -/// Closing and creating a deck before a pass keeps the old terminal fence until its exact reset -/// completion. -#[test] -fn close_new_then_edit_before_a_pass_keeps_the_old_terminal_fence_until_exact_reset() { - let (mut h, _) = pending_terminal_editor(); - clear_pending_preedit(&mut h); - let old_owner = h.state().ime_target().unwrap().owner; - let old_uid = h.state().session.active().unwrap().uid; - let pending = h.state().ime_terminal_pending.as_ref().expect("the cleared-preedit terminal is guarded"); - assert_eq!(pending.owner, old_owner); - assert!(!pending.cancelled); - - // Replace the active document and enter its first editor without an intervening pass - // observing `None`. Blindly clearing on the uid change would let the old platform suffix - // land in the new document, so the old terminal must stay bound to its old owner. - h.state_mut().run("file.close", json!({})).unwrap(); - h.state_mut().run("file.new", json!({})).unwrap(); - let new_uid = h.state().session.active().unwrap().uid; - assert_ne!(old_uid, new_uid); let title = h.state().session.active().unwrap().doc.slides[0].shapes[0].id.0; h.state_mut().run("text.edit", json!({"id": title})).unwrap(); - h.run_steps(1); - - let pending = h.state().ime_terminal_pending.as_ref().expect("the old terminal survives the document replacement"); - assert_eq!(pending.owner, old_owner, "the terminal is still bound to the retired composition's owner"); - assert!(pending.cancelled && pending.interrupted); - let reset = published_reset(&h); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == reset)); - let before = title_text(h.state()); - let undo = undo_len(h.state()); - - // The old composition's suffix arrives before its terminal commit: no preedit may enter the - // new document's editor, and the old terminal guard must still be live. - h.input_mut().events.push(preedit("F")); - h.run_steps(1); - assert_eq!(title_text(h.state()), before, "a stale old preedit is rejected"); - assert_eq!(undo_len(h.state()), undo); - assert!(h.state().ime_terminal_pending.as_ref().is_some_and(|p| p.owner == old_owner && p.cancelled)); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == reset)); - - // The old terminal commit is rejected and consumed as a terminal event. The new document's - // reset fence remains Awaiting: terminal delivery is not the platform-reset boundary. - h.input_mut().events.push(Event::Ime(ImeEvent::Commit("F".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), before, "the old terminal commit is rejected"); - assert_eq!(undo_len(h.state()), undo); - assert!(h.state().ime_terminal_pending.is_none(), "the delivered old terminal no longer needs a guard"); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Awaiting { id, .. } if id == reset)); - - // Another stale suffix still cannot cross the new document's reset fence. - h.input_mut().events.push(preedit("F")); - h.run_steps(1); - assert_eq!(title_text(h.state()), before, "the reset fence, not just the terminal, blocks the old suffix"); - - // Only the exact completion of the new document's fence releases custom input. The latest - // new composition then gets its own preedit and commit. - h.input_mut().events.extend([reset_completed(reset), preedit("F")]); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}F"), "the fresh new-document composition is admitted"); - assert!(h.state().ime_terminal_pending.is_none()); - assert!(matches!(root_phase(&h), crate::ImeResetPhase::Clear)); - h.event(Event::Ime(ImeEvent::Commit("F".into()))); - h.run_steps(1); - assert_eq!(title_text(h.state()), format!("{before}F")); - assert_eq!(undo_len(h.state()), undo + 1, "only the latest new composition is one undo step"); + h.run_steps(2); + let owner = h.output().platform_output.ime.as_ref().unwrap().owner; + for route in 0..4 { + match route { + 0 => h.state_mut().opening = Some(crate::opening::Opening::for_test("deck.pptx")), + 1 => h.state_mut().open_backstage(crate::backstage::Page::Home), + 2 => h.state_mut().palette_open = true, + _ => h.state_mut().open_dialog("about", json!({})), + } + h.run_steps(2); + assert!(h.output().platform_output.ime.as_ref().is_none_or(|ime| ime.owner != owner), "route {route} hides the canvas owner"); + match route { + 0 => h.state_mut().opening = None, + 1 => h.state_mut().close_backstage(), + 2 => h.state_mut().palette_open = false, + _ => { + assert!(crate::dialogs::open_keys(&h.ctx).iter().any(|key| key == "about")); + let id = crate::dialogs::top_dialog(&h.ctx).unwrap(); + assert!(WindowDialogs::of(&h.ctx, &WindowKey::main()).with(|host| host.cancel_by_id(&h.ctx, id))); + } + } + h.run_steps(2); + assert_eq!(h.output().platform_output.ime.as_ref().map(|ime| ime.owner), Some(owner), "closing route {route} restores the canvas editor"); + } }