mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 10:13:09 -06:00
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)
This commit is contained in:
@@ -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<CommandSpec> {
|
||||
// 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<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// 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<usize>,
|
||||
text: &str,
|
||||
kind: crate::TextReplaceKind,
|
||||
) -> Result<crate::TextReplaceResult> {
|
||||
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<Pos> {
|
||||
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<usize> {
|
||||
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<Value> {
|
||||
let result = editing::edit(s, p)?;
|
||||
s.begin_text_edit_session()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn exit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 {
|
||||
|
||||
@@ -99,8 +99,8 @@ pub(super) fn delete_surrounding(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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"))?;
|
||||
|
||||
@@ -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<RunProps>) -> Result<Value> {
|
||||
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<RunProps>)
|
||||
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<RunProps>) -> Result<Pos> {
|
||||
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<RunProps>)
|
||||
}
|
||||
}
|
||||
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
|
||||
|
||||
@@ -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<String> {
|
||||
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<ImeSurrounding> {
|
||||
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<Value> {
|
||||
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<usize>, 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");
|
||||
|
||||
@@ -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<deckcraft_color::Rgba> {
|
||||
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<Pos> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
Some((a.first()?.as_u64()? as usize, a.get(1)?.as_u64()? as usize))
|
||||
|
||||
+103
-90
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<egui::ime_context::ImeTarget> {
|
||||
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<egui::ime_context::ImeMutationStamp> {
|
||||
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<ImeDestination> {
|
||||
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<ImeTerminalStamp> {
|
||||
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::<bool>(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<ImeDescriptorKey>) {
|
||||
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<egui::Id>) -> 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<Value> {
|
||||
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<egui::Id>, 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<ImeDescriptorKey> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<bool>(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));
|
||||
}
|
||||
+108
-1905
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user