Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

egui-037: reconcile shared window integration with main

skylar taylor-barrickbd4b9dd1d258
diff --cc Cargo.lock
index 19899a2f7,1b8a1240a..bebf138cc
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -1003,14 -868,17 +1003,25 @@@ dependencies =
"serde",
]
+ [[package]]
+ name = "craft-window"
+ version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=ea4c823abb46fa9d21361604ed1c6d21c54e9ca8#ea4c823abb46fa9d21361604ed1c6d21c54e9ca8"
++source = "git+https://github.com/storytold/craft-libs?rev=42e30cd5b3f4b114270dd053fccbc33bedc47f68#42e30cd5b3f4b114270dd053fccbc33bedc47f68"
+ dependencies = [
+ "egui",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
+ "wayland-client",
+ ]
+
+[[package]]
+name = "craft-winprint-gdi"
+version = "0.1.0"
+source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.2"
diff --cc Cargo.toml
index 4819a9b9e,e61b0f932..ad1542e9f
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -86,13 -86,13 +86,15 @@@ craft-cms = { version = "0.1.0", git =
# ui
# Shared frontend components; keep this dependency above the engine boundary.
-craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
-# The application bar as the window's title bar (craft-libs).
-craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ea4c823abb46fa9d21361604ed1c6d21c54e9ca8", features = ["egui"] }
-egui = "0.36"
-egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
-eframe = { version = "0.36", default-features = false }
-egui_kittest = "0.36"
+craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }
++# The application bar as the window's title bar (craft-libs); its egui 0.37 port.
++craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "42e30cd5b3f4b114270dd053fccbc33bedc47f68", features = ["egui"] }
+egui = "0.37"
+egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
+eframe = { version = "0.37", default-features = false }
+egui_kittest = "0.37"
+# Monotonic clock on native and web (`Instant`); screenshot settlement must not use wall time.
+web-time = "1"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
diff --cc apps/designcraft/src/main.rs
index da84db264,1f2c0ff32..965fa601d
--- a/apps/designcraft/src/main.rs
+++ b/apps/designcraft/src/main.rs
@@@ -37,7 -35,7 +35,7 @@@ struct App
/// Documents and quit requests from Finder, the Dock and Open With.
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
-- /// The window's `movable` flag as last set; see `mac_window`.
++ /// The window's `movable` flag as last set; see `craft_window::title_bar`.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Frames begun so far.
diff --cc crates/engine/src/cmd/text.rs
index 469cc7579,a353cd1f5..f8e5177da
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@@ -9,6 -9,6 +9,7 @@@ use serde_json::{Value, json}
use super::{CommandSpec, bad, bool_or, cmd, has_doc, has_text, has_text_or_frames, id_param, ok, point_param, str_param};
use crate::{Result, Session};
++/// Build the text command registry: caret/selection movement, insertion/deletion, release, text and paragraph formatting, story queries, ruby and OpenType commands, with their parameters and enabled predicates.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "text.placeCaret", "Place Caret", [], None, "{frame, point: [x,y] (spread coords)} — converts empty frames to text frames", has_doc, |s, p| place(s, p, false)),
diff --cc crates/engine/src/lib.rs
index c7e4f9275,545c3fac3..03e0e9946
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -144,6 -141,6 +144,7 @@@ fn next_revision() -> u64
}
impl DocState {
++ /// Initialize saved/live document identity, revision, epoch, active default layer, empty history with limit 1,000 and the initial path.
pub fn new(doc: Document, path: Option<String>) -> Self {
let active_layer = doc.default_layer();
let doc = Arc::new(doc);
diff --cc crates/engine/src/math.rs
index c22755799,16ef7e234..96bb228e2
--- a/crates/engine/src/math.rs
+++ b/crates/engine/src/math.rs
@@@ -79,51 -79,6 +79,54 @@@ enum Node
Fenced(String, Box<Node>, String),
}
+// Empty a node before field drop glue can follow its children recursively. This also covers
+// replaced scripts and partially built parser continuations during unwinding.
+impl Node {
++ /// Move every child link into `pending`, draining `Group` children and replacing boxed children with empty groups, so field drop glue never walks a deep subtree.
+ fn detach_children(&mut self, pending: &mut Vec<Node>) {
++ /// Detach one child into `pending`, leaving an empty group in its slot.
+ fn detach(child: &mut Node, pending: &mut Vec<Node>) {
+ pending.push(std::mem::replace(child, Node::Group(Vec::new())));
+ }
+ match self {
+ Self::Group(nodes) => pending.append(nodes),
+ Self::Frac(a, b) => {
+ detach(a, pending);
+ detach(b, pending);
+ }
+ Self::Sqrt(index, body) => {
+ if let Some(index) = index {
+ detach(index, pending);
+ }
+ detach(body, pending);
+ }
+ Self::Scripts { base, sup, sub } => {
+ detach(base, pending);
+ if let Some(sup) = sup {
+ detach(sup, pending);
+ }
+ if let Some(sub) = sub {
+ detach(sub, pending);
+ }
+ }
+ Self::Fenced(_, body, _) => detach(body, pending),
+ Self::Sym(_, _) | Self::Text(_) | Self::Space(_) | Self::Big(_) => {}
+ }
+ }
+}
+
+impl Drop for Node {
++ /// Drain an explicit worklist, emptying each node before normal drop glue, so deep or replaced ASTs drop without stack overflow.
+ fn drop(&mut self) {
+ let mut pending = Vec::new();
+ self.detach_children(&mut pending);
+ while let Some(mut node) = pending.pop() {
+ node.detach_children(&mut pending);
+ // Its own Drop and boxed field glue now see only empty leaves, never this subtree.
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq)]
enum Class {
Ident,
@@@ -293,279 -265,166 +296,297 @@@ impl Parser<'_>
None => String::new(),
}
}
- fn atom(&mut self) -> Option<Node> {
+}
+
+/// Continuations carry parser state on the heap instead of in native call frames.
+enum ParseWork<'a> {
+ List { end: Option<char>, depth: usize },
+ Sequence { kind: SequenceKind, depth: usize, out: Vec<Node> },
+ Append { kind: SequenceKind, depth: usize, out: Vec<Node>, group: bool },
+ Arg { depth: usize },
+ Atom { depth: usize },
+ Script { kind: SequenceKind, depth: usize, out: Vec<Node>, up: bool },
+ FractionNumerator { depth: usize },
+ FractionDenominator { numerator: Node },
+ SqrtIndex { outer: Parser<'a>, depth: usize },
+ SqrtArgument { index: Option<Box<Node>> },
+ Fence { open: String },
+ UntilRight { depth: usize },
+ One { depth: usize },
+ OneAtom { depth: usize },
+}
+
+#[derive(Clone, Copy)]
+enum SequenceKind {
+ List(Option<char>),
+ Fence,
+ One,
+}
+
+/// Repeated scripts replace only their own slot, preserving the base and the opposite slot.
+fn attach_script(mut base: Node, argument: Node, up: bool) -> Node {
+ if let Node::Scripts { sup, sub, .. } = &mut base {
+ let slot = if up { sup } else { sub };
+ *slot = Some(Box::new(argument));
+ base
+ } else if up {
+ Node::Scripts { base: Box::new(base), sup: Some(Box::new(argument)), sub: None }
+ } else {
+ Node::Scripts { base: Box::new(base), sup: None, sub: Some(Box::new(argument)) }
+ }
+}
+
+impl<'a> Parser<'a> {
++ /// Run the parser as a heap worklist from a root `List`, so input nesting does not consume native stack.
+ fn parse(&mut self, depth: usize) -> Node {
+ let mut work = vec![ParseWork::List { end: None, depth }];
+ let mut value = Node::Group(Vec::new());
+ while let Some(next) = work.pop() {
+ match next {
+ ParseWork::List { end, depth } => Self::step_list(&mut work, &mut value, end, depth),
+ ParseWork::Sequence { kind, depth, out } => self.step_sequence(&mut work, &mut value, kind, depth, out),
+ ParseWork::Append { kind, depth, out, group } => Self::step_append(&mut work, &mut value, kind, depth, out, group),
+ ParseWork::Arg { depth } => self.step_arg(&mut work, &mut value, depth),
+ ParseWork::Atom { depth } => self.step_atom(&mut work, &mut value, depth),
+ ParseWork::Script { kind, depth, out, up } => Self::step_script(&mut work, &mut value, kind, depth, out, up),
+ ParseWork::FractionNumerator { depth } => Self::step_fraction_numerator(&mut work, &mut value, depth),
+ ParseWork::FractionDenominator { numerator } => Self::step_fraction_denominator(&mut value, numerator),
+ ParseWork::SqrtIndex { outer, depth } => self.step_sqrt_index(&mut work, &mut value, outer, depth),
+ ParseWork::SqrtArgument { index } => Self::step_sqrt_argument(&mut value, index),
+ ParseWork::Fence { open } => self.step_fence(&mut value, open),
+ ParseWork::UntilRight { depth } => Self::step_until_right(&mut work, &mut value, depth),
+ ParseWork::One { depth } => Self::step_one(&mut work, depth),
+ ParseWork::OneAtom { depth } => Self::step_one_atom(&mut work, &mut value, depth),
+ }
+ }
+ value
+ }
+
++ /// Start a list sequence, or yield an empty group when `depth` has reached `MAX_NESTING`.
+ fn step_list(work: &mut Vec<ParseWork<'a>>, value: &mut Node, end: Option<char>, depth: usize) {
+ if depth >= MAX_NESTING {
+ *value = Node::Group(Vec::new());
+ } else {
+ work.push(ParseWork::Sequence { kind: SequenceKind::List(end), depth: depth + 1, out: Vec::new() });
+ }
+ }
+
++ /// Consume list/fence terminators, route `^`/`_` to script attachment, append the next atom for list and fence sequences, or finish a `One` sequence after its single atom; fence sequences stop only at a real `\right`.
+ fn step_sequence(&mut self, work: &mut Vec<ParseWork<'a>>, value: &mut Node, kind: SequenceKind, depth: usize, mut out: Vec<Node>) {
self.skip_ws();
- let c = self.peek()?;
- self.i += 1;
- Some(match c {
- '{' => Node::Group(self.list(Some('}'))),
- '\\' => {
- let name = self.command();
- match name.as_str() {
- "frac" | "dfrac" | "tfrac" => {
- let a = self.arg();
- let b = self.arg();
- Node::Frac(Box::new(a), Box::new(b))
- }
- "sqrt" => {
- self.skip_ws();
- let idx = (self.peek() == Some('[')).then(|| {
- self.i += 1;
- let mut s = String::new();
- while let Some(c) = self.peek() {
- self.i += 1;
- if c == ']' {
- break;
- }
- s.push(c);
- }
- Box::new(parse_at(&s, self.depth + 1))
- });
- let a = self.arg();
- Node::Sqrt(idx, Box::new(a))
- }
- "text" | "mathrm" | "textrm" | "operatorname" => Node::Text(self.raw_group()),
- "sin" | "cos" | "tan" | "log" | "ln" | "exp" | "lim" | "max" | "min" => Node::Text(name),
- "," => Node::Space(3.0 / 18.0),
- ":" | ">" => Node::Space(4.0 / 18.0),
- ";" => Node::Space(5.0 / 18.0),
- "quad" => Node::Space(1.0),
- "qquad" => Node::Space(2.0),
- "!" => Node::Space(-3.0 / 18.0),
- " " => Node::Space(0.25),
- "left" => {
- let open = self.delimiter();
- let body = self.list_until_right();
- let close = self.delimiter();
- Node::Fenced(open, Box::new(Node::Group(body)), close)
- }
- "{" => Node::Sym("{".into(), Class::Punct),
- "}" => Node::Sym("}".into(), Class::Punct),
- "%" | "$" | "#" | "&" | "_" => Node::Sym(name, Class::Plain),
- n => match (big_op(n), symbol(n)) {
- (Some(op), _) => Node::Big(op.into()),
- (None, Some((s, cl))) => Node::Sym(s.into(), cl),
- _ => Node::Text(format!("\\{n}")),
- },
- }
+ let Some(c) = self.peek() else {
+ *value = Node::Group(out);
+ return;
+ };
+ if let SequenceKind::List(Some(end)) = kind
+ && c == end
+ {
+ self.i += 1;
+ *value = Node::Group(out);
+ return;
+ }
+ if matches!(kind, SequenceKind::Fence)
+ && self.s.get(self.i..).is_some_and(|s| s.starts_with(&['\\', 'r', 'i', 'g', 'h', 't']))
+ && !self.s.get(self.i + 6).is_some_and(char::is_ascii_alphabetic)
+ {
+ self.i += 6;
+ *value = Node::Group(out);
+ return;
+ }
+ if (c == '^' || c == '_') && !matches!(kind, SequenceKind::Fence) {
+ self.i += 1;
+ work.push(ParseWork::Script { kind, depth, out, up: c == '^' });
+ work.push(ParseWork::Arg { depth });
+ } else if matches!(kind, SequenceKind::One) {
+ *value = Node::Group(out);
+ } else {
+ let group = matches!(kind, SequenceKind::Fence);
+ work.push(ParseWork::Append { kind, depth, out: std::mem::take(&mut out), group });
+ work.push(if group { ParseWork::One { depth: depth + 1 } } else { ParseWork::Atom { depth } });
+ }
+ }
+
++ /// Commit the completed atom or fence group into the pending sequence and resume it.
+ fn step_append(work: &mut Vec<ParseWork<'a>>, value: &mut Node, kind: SequenceKind, depth: usize, mut out: Vec<Node>, group: bool) {
+ if group {
+ if let Node::Group(nodes) = &mut *value {
+ out.append(nodes);
}
+ } else {
+ out.push(std::mem::replace(value, Node::Group(Vec::new())));
+ }
+ work.push(ParseWork::Sequence { kind, depth, out });
+ }
+
++ /// Parse a braced list or one atom at `depth + 1`; a capped argument becomes an empty group.
+ fn step_arg(&mut self, work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ if depth >= MAX_NESTING {
+ *value = Node::Group(Vec::new());
+ return;
+ }
+ self.skip_ws();
+ if self.peek() == Some('{') {
+ self.i += 1;
+ work.push(ParseWork::List { end: Some('}'), depth: depth + 1 });
+ } else {
+ work.push(ParseWork::Atom { depth: depth + 1 });
+ }
+ }
+
++ /// Attach the completed argument as superscript or subscript, preserving the opposite slot of an existing script node.
+ fn step_script(work: &mut Vec<ParseWork<'a>>, value: &mut Node, kind: SequenceKind, depth: usize, mut out: Vec<Node>, up: bool) {
+ let argument = std::mem::replace(value, Node::Group(Vec::new()));
+ let base = out.pop().unwrap_or(Node::Group(Vec::new()));
+ out.push(attach_script(base, argument, up));
+ work.push(ParseWork::Sequence { kind, depth, out });
+ }
+
++ /// Save the parsed numerator and queue the denominator argument.
+ fn step_fraction_numerator(work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ let numerator = std::mem::replace(value, Node::Group(Vec::new()));
+ work.push(ParseWork::FractionDenominator { numerator });
+ work.push(ParseWork::Arg { depth });
+ }
+
++ /// Build `Frac` from the saved numerator and the completed denominator.
+ fn step_fraction_denominator(value: &mut Node, numerator: Node) {
+ *value = Node::Frac(Box::new(numerator), Box::new(std::mem::replace(value, Node::Group(Vec::new()))));
+ }
+
++ /// Restore the outer parser after the root-index subparse and queue the radicand argument.
+ fn step_sqrt_index(&mut self, work: &mut Vec<ParseWork<'a>>, value: &mut Node, outer: Parser<'a>, depth: usize) {
+ *self = outer;
+ let index = Some(Box::new(std::mem::replace(value, Node::Group(Vec::new()))));
+ work.push(ParseWork::SqrtArgument { index });
+ work.push(ParseWork::Arg { depth });
+ }
+
++ /// Build `Sqrt`, retaining the optional root index.
+ fn step_sqrt_argument(value: &mut Node, index: Option<Box<Node>>) {
+ *value = Node::Sqrt(index, Box::new(std::mem::replace(value, Node::Group(Vec::new()))));
+ }
+
++ /// Wrap the completed body in `Fenced` with the opening and resolved closing delimiter.
+ fn step_fence(&mut self, value: &mut Node, open: String) {
+ let close = self.delimiter();
+ *value = Node::Fenced(open, Box::new(std::mem::replace(value, Node::Group(Vec::new()))), close);
+ }
+
++ /// Start a fence-body sequence that stops at a real `\right`, or an empty group at the nesting cap.
+ fn step_until_right(work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ if depth >= MAX_NESTING {
+ *value = Node::Group(Vec::new());
+ } else {
+ work.push(ParseWork::Sequence { kind: SequenceKind::Fence, depth, out: Vec::new() });
+ }
+ }
+
++ /// Queue one atom and its one-item sequence collector.
+ fn step_one(work: &mut Vec<ParseWork<'a>>, depth: usize) {
+ work.push(ParseWork::OneAtom { depth });
+ work.push(ParseWork::Atom { depth });
+ }
+
++ /// Wrap the completed atom in a `Group` and continue the `One` sequence.
+ fn step_one_atom(work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ let out = vec![std::mem::replace(value, Node::Group(Vec::new()))];
+ work.push(ParseWork::Sequence { kind: SequenceKind::One, depth, out });
+ }
+
++ /// Parse a number, identifier, operator, punctuation mark or symbol with its spacing class, dispatching braces and commands.
+ fn step_atom(&mut self, work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ self.skip_ws();
+ let Some(c) = self.peek() else {
+ *value = Node::Group(Vec::new());
+ return;
+ };
+ self.i += 1;
+ match c {
+ '{' => work.push(ParseWork::List { end: Some('}'), depth }),
+ '\\' => self.step_command(work, value, depth),
c if c.is_ascii_digit() || c == '.' => {
let mut s = c.to_string();
while let Some(d) = self.peek().filter(|d| d.is_ascii_digit() || *d == '.') {
s.push(d);
self.i += 1;
}
- Node::Sym(s, Class::Number)
- }
- c if c.is_alphabetic() => Node::Sym(c.to_string(), Class::Ident),
- '+' => Node::Sym("+".into(), Class::Bin),
- '-' => Node::Sym("−".into(), Class::Bin),
- '*' => Node::Sym("∗".into(), Class::Bin),
- '<'..='>' => Node::Sym(c.to_string(), Class::Rel),
- ',' | ';' => Node::Sym(c.to_string(), Class::Punct),
- '\'' => Node::Sym("′".into(), Class::Plain),
- c => Node::Sym(c.to_string(), Class::Plain),
- })
- }
- fn list(&mut self, end: Option<char>) -> Vec<Node> {
- if self.depth >= MAX_NESTING {
- return Vec::new();
- }
- self.depth += 1;
- let mut out: Vec<Node> = Vec::new();
- loop {
- self.skip_ws();
- match self.peek() {
- None => break,
- Some(c) if Some(c) == end => {
- self.i += 1;
- break;
- }
- Some('^') | Some('_') => {
- let up = self.peek() == Some('^');
- self.i += 1;
- let a = self.arg();
- let base = out.pop().unwrap_or(Node::Group(vec![]));
- let node = match base {
- Node::Scripts { base, sup, sub } => {
- if up {
- Node::Scripts { base, sup: Some(Box::new(a)), sub }
- } else {
- Node::Scripts { base, sup, sub: Some(Box::new(a)) }
- }
- }
- b => Node::Scripts { base: Box::new(b), sup: up.then(|| Box::new(a.clone())), sub: (!up).then(|| Box::new(a)) },
- };
- out.push(node);
- }
- Some(_) => {
- if let Some(a) = self.atom() {
- out.push(a);
- }
- }
+ *value = Node::Sym(s, Class::Number);
}
+ c if c.is_alphabetic() => *value = Node::Sym(c.to_string(), Class::Ident),
+ '+' => *value = Node::Sym("+".into(), Class::Bin),
+ '-' => *value = Node::Sym("−".into(), Class::Bin),
+ '*' => *value = Node::Sym("∗".into(), Class::Bin),
+ '<'..='>' => *value = Node::Sym(c.to_string(), Class::Rel),
+ ',' | ';' => *value = Node::Sym(c.to_string(), Class::Punct),
+ '\'' => *value = Node::Sym("′".into(), Class::Plain),
+ c => *value = Node::Sym(c.to_string(), Class::Plain),
}
- self.depth -= 1;
- out
}
- fn list_until_right(&mut self) -> Vec<Node> {
- if self.depth >= MAX_NESTING {
- return Vec::new();
- }
- let mut out = Vec::new();
- loop {
- self.skip_ws();
- if self.peek().is_none() {
- break;
+
++ /// Dispatch fractions, roots, fences, raw-text commands and named symbols/operators.
+ fn step_command(&mut self, work: &mut Vec<ParseWork<'a>>, value: &mut Node, depth: usize) {
+ let name = self.command();
+ match name.as_str() {
+ "frac" | "dfrac" | "tfrac" => {
+ work.push(ParseWork::FractionNumerator { depth });
+ work.push(ParseWork::Arg { depth });
}
- if self.s[self.i..].starts_with(&['\\', 'r', 'i', 'g', 'h', 't']) && !self.s.get(self.i + 6).is_some_and(char::is_ascii_alphabetic) {
- self.i += 6;
- break;
+ "sqrt" => self.push_sqrt(work, depth),
+ "left" => {
+ let open = self.delimiter();
+ work.push(ParseWork::Fence { open });
+ work.push(ParseWork::UntilRight { depth });
}
- let mut p = Parser { s: self.s, i: self.i, depth: self.depth + 1 };
- let one = p.list_one();
- self.i = p.i;
- out.extend(one);
+ "text" | "mathrm" | "textrm" | "operatorname" => *value = Node::Text(self.raw_group()),
+ n => *value = command_atom(n),
}
- out
}
- /// One atom plus any scripts on it.
- fn list_one(&mut self) -> Vec<Node> {
- let mut out = Vec::new();
- if let Some(a) = self.atom() {
- out.push(a);
- }
- loop {
- self.skip_ws();
- match self.peek() {
- Some('^') | Some('_') => {
- let up = self.peek() == Some('^');
- self.i += 1;
- let a = self.arg();
- let base = out.pop().unwrap_or(Node::Group(vec![]));
- out.push(match base {
- Node::Scripts { base, sub, .. } if up => Node::Scripts { base, sup: Some(Box::new(a)), sub },
- Node::Scripts { base, sup, .. } => Node::Scripts { base, sup, sub: Some(Box::new(a)) },
- b => Node::Scripts { base: Box::new(b), sup: up.then(|| Box::new(a.clone())), sub: (!up).then(|| Box::new(a)) },
- });
+
++ /// Parse an optional bracketed root index with the existing first-`]` grammar, otherwise queue a braced or atomic radicand.
+ fn push_sqrt(&mut self, work: &mut Vec<ParseWork<'a>>, depth: usize) {
+ self.skip_ws();
+ if self.peek() == Some('[') {
+ self.i += 1;
+ let start = self.i;
+ let mut end = start;
+ // Keep the existing first-']' index grammar, including EOF.
+ while let Some(c) = self.peek() {
+ self.i += 1;
+ if c == ']' {
+ break;
}
- _ => break,
+ end = self.i;
}
+ let inner = self.s.get(start..end).unwrap_or_default();
+ let outer = std::mem::replace(self, Parser { s: inner, i: 0 });
+ work.push(ParseWork::SqrtIndex { outer, depth });
+ work.push(ParseWork::List { end: None, depth: depth + 1 });
+ } else {
+ work.push(ParseWork::SqrtArgument { index: None });
+ work.push(ParseWork::Arg { depth });
}
- out
+ }
+}
+
++/// Map function names, spacing commands, escaped punctuation, big operators and symbols; an unknown command becomes literal `\name` text.
+fn command_atom(name: &str) -> Node {
+ match name {
+ "sin" | "cos" | "tan" | "log" | "ln" | "exp" | "lim" | "max" | "min" => Node::Text(name.to_owned()),
+ "," => Node::Space(3.0 / 18.0),
+ ":" | ">" => Node::Space(4.0 / 18.0),
+ ";" => Node::Space(5.0 / 18.0),
+ "quad" => Node::Space(1.0),
+ "qquad" => Node::Space(2.0),
+ "!" => Node::Space(-3.0 / 18.0),
+ " " => Node::Space(0.25),
+ "{" => Node::Sym("{".into(), Class::Punct),
+ "}" => Node::Sym("}".into(), Class::Punct),
+ "%" | "$" | "#" | "&" | "_" => Node::Sym(name.to_owned(), Class::Plain),
+ n => match (big_op(n), symbol(n)) {
+ (Some(op), _) => Node::Big(op.into()),
+ (None, Some((s, cl))) => Node::Sym(s.into(), cl),
+ _ => Node::Text(format!("\\{n}")),
+ },
}
}
@@@ -573,9 -432,10 +594,10 @@@ fn parse(src: &str) -> Node
parse_at(src, 0)
}
++/// Collect the input into chars and start parsing at the supplied depth.
fn parse_at(src: &str, depth: usize) -> Node {
let chars: Vec<char> = src.chars().collect();
- let mut p = Parser { s: &chars, i: 0, depth };
- Node::Group(p.list(None))
+ Parser { s: &chars, i: 0 }.parse(depth)
}
/// Typesetting fonts and metrics.
@@@ -624,251 -484,174 +646,254 @@@ fn hbox(parts: Vec<(MBox, f64)>) -> MBo
out
}
+struct GroupLayout<'a> {
+ items: std::iter::Enumerate<std::slice::Iter<'a, Node>>,
+ parts: Vec<(MBox, f64)>,
+ prev: Option<Class>,
+ size: f64,
+}
+
+struct ScriptLayout {
+ out: MBox,
+ bw: f64,
+ basc: f64,
+ bdesc: f64,
+ big: bool,
+ size: f64,
+}
+
+impl ScriptLayout {
++ /// Seed script layout with the base box width and metrics, the big-operator flag and the size.
+ fn new(base: MBox, big: bool, size: f64) -> Self {
+ Self { bw: base.w, basc: base.asc, bdesc: base.desc, out: base, big, size }
+ }
++ /// Place a superscript, subscript or big-operator limit and expand the aggregate width, ascent and descent.
+ fn add(&mut self, script: MBox, up: bool) {
+ let Self { out, bw, basc, bdesc, big, size } = self;
+ let y = if *big {
+ if up { -*basc - *size * 0.1 - script.desc } else { *bdesc + *size * 0.1 + script.asc }
+ } else if up {
+ -(*size * 0.42).max(*basc - script.asc * 0.6)
+ } else {
+ (*size * 0.2).max(*bdesc * 0.8)
+ };
+ out.w = out.w.max(if *big { script.w } else { *bw + script.w + *size * 0.05 });
+ let (sa, sd) = (script.asc, script.desc);
+ let x = if *big { (*bw - script.w) / 2.0 } else { *bw + *size * 0.05 };
+ out.els.extend(script.shifted(x, y));
+ if up {
+ out.asc = out.asc.max(-y + sa);
+ } else {
+ out.desc = out.desc.max(y + sd);
+ }
+ }
++ /// For big operators, recentre the operator over the widest limit.
+ fn finish(mut self) -> MBox {
+ if self.big {
+ let dx = (self.out.w - self.bw) / 2.0;
+ let els = std::mem::take(&mut self.out.els);
+ self.out.els = MBox { els, ..Default::default() }.shifted(dx, 0.0);
+ }
+ self.out
+ }
+}
+
+enum LayoutWork<'a> {
+ Visit(&'a Node, f64),
+ GroupNext(GroupLayout<'a>),
+ GroupAppend(GroupLayout<'a>, f64),
+ FractionNumerator(&'a Node, f64),
+ FractionDenominator(MBox, f64),
+ SqrtBody(Option<&'a Node>, f64),
+ SqrtIndex(MBox, f64),
+ ScriptBase { sup: Option<&'a Node>, sub: Option<&'a Node>, big: bool, size: f64 },
+ ScriptSup { state: ScriptLayout, sub: Option<&'a Node> },
+ ScriptSub(ScriptLayout),
+ Fence(&'a str, &'a str, f64),
+}
+
+/// Postorder evaluation moves each child's box into its parent before visiting the next child.
+/// No ancestor retains a second flattened copy, and native stack use is independent of nesting.
fn layout(f: &Fonts, n: &Node, size: f64) -> MBox {
- let axis = size * 0.25;
- match n {
- Node::Sym(s, cl) => text_box(f, s, size, *cl == Class::Ident),
- Node::Text(s) => text_box(f, s, size, false),
- Node::Space(em) => MBox { w: em * size, ..Default::default() },
- Node::Group(list) => {
- let mut parts = Vec::new();
- let mut prev: Option<Class> = None;
- for (k, item) in list.iter().enumerate() {
- let cl = match item {
- Node::Sym(_, c) => Some(*c),
- Node::Scripts { base, .. } => match &**base {
+ let mut work = vec![LayoutWork::Visit(n, size)];
+ let mut value = MBox::default();
+ while let Some(next) = work.pop() {
+ match next {
+ LayoutWork::Visit(node, size) => match node {
+ Node::Sym(s, cl) => value = text_box(f, s, size, *cl == Class::Ident),
+ Node::Text(s) => value = text_box(f, s, size, false),
+ Node::Space(em) => value = MBox { w: em * size, ..Default::default() },
+ Node::Group(list) => {
+ work.push(LayoutWork::GroupNext(GroupLayout { items: list.iter().enumerate(), parts: Vec::new(), prev: None, size }))
+ }
+ Node::Frac(a, b) => {
+ work.push(LayoutWork::FractionNumerator(b, size));
+ work.push(LayoutWork::Visit(a, size * 0.85));
+ }
+ Node::Sqrt(index, body) => {
+ work.push(LayoutWork::SqrtBody(index.as_deref(), size));
+ work.push(LayoutWork::Visit(body, size));
+ }
+ Node::Scripts { base, sup, sub } => {
+ work.push(LayoutWork::ScriptBase { sup: sup.as_deref(), sub: sub.as_deref(), big: matches!(&**base, Node::Big(_)), size });
+ work.push(LayoutWork::Visit(base, size));
+ }
+ Node::Big(op) => {
+ let mut b = text_box(f, op, size * 1.5, false);
+ b.asc = size * 1.05;
+ b.desc = size * 0.35;
+ for e in &mut b.els {
+ if let Elem::Text { y, .. } = e {
+ *y = size * 0.32;
+ }
+ }
+ value = b;
+ }
+ Node::Fenced(open, body, close) => {
+ work.push(LayoutWork::Fence(open, close, size));
+ work.push(LayoutWork::Visit(body, size));
+ }
+ },
+ LayoutWork::GroupNext(mut group) => {
+ if let Some((k, item)) = group.items.next() {
+ let cl = match item {
Node::Sym(_, c) => Some(*c),
+ Node::Scripts { base, .. } => match &**base {
+ Node::Sym(_, c) => Some(*c),
+ _ => None,
+ },
_ => None,
- },
- _ => None,
- };
- // A leading + or − (or after another operator) is a sign, not a binary operator.
- let cl = if cl == Some(Class::Bin) && (k == 0 || matches!(prev, Some(Class::Bin | Class::Rel | Class::Punct))) {
- Some(Class::Plain)
+ };
+ let cl = if cl == Some(Class::Bin) && (k == 0 || matches!(group.prev, Some(Class::Bin | Class::Rel | Class::Punct))) {
+ Some(Class::Plain)
+ } else {
+ cl
+ };
+ let gap = |c: Option<Class>| match c {
+ Some(Class::Bin) => group.size * 4.0 / 18.0,
+ Some(Class::Rel) => group.size * 5.0 / 18.0,
+ _ => 0.0,
+ };
+ let mut before = gap(cl).max(gap(group.prev));
+ if k == 0 {
+ before = 0.0;
+ }
+ if group.prev == Some(Class::Punct) {
+ before = before.max(group.size * 3.0 / 18.0);
+ }
+ group.prev = cl;
+ let size = group.size;
+ work.push(LayoutWork::GroupAppend(group, before));
+ work.push(LayoutWork::Visit(item, size));
} else {
- cl
- };
- let gap = |c: Option<Class>| match c {
- Some(Class::Bin) => size * 4.0 / 18.0,
- Some(Class::Rel) => size * 5.0 / 18.0,
- _ => 0.0,
- };
- let mut before = gap(cl).max(gap(prev));
- if k == 0 {
- before = 0.0;
+ value = hbox(group.parts);
}
- if prev == Some(Class::Punct) {
- before = before.max(size * 3.0 / 18.0);
+ }
+ LayoutWork::GroupAppend(mut group, before) => {
+ group.parts.push((std::mem::take(&mut value), before));
+ work.push(LayoutWork::GroupNext(group));
+ }
+ LayoutWork::FractionNumerator(denominator, size) => {
+ work.push(LayoutWork::FractionDenominator(std::mem::take(&mut value), size));
+ work.push(LayoutWork::Visit(denominator, size * 0.85));
+ }
+ LayoutWork::FractionDenominator(na, size) => {
+ let nb = std::mem::take(&mut value);
+ let axis = size * 0.25;
+ let w = na.w.max(nb.w) + size * 0.2;
+ let t = (size * 0.06).max(0.4);
+ let gap = size * 0.15;
+ let num_base = -(axis + t / 2.0 + gap + na.desc);
+ let den_base = -axis + t / 2.0 + gap + nb.asc;
+ let mut out = MBox { w, asc: -num_base + na.asc, desc: den_base + nb.desc, els: Vec::new() };
+ out.els.push(Elem::Rule { x: 0.0, y: -axis - t / 2.0, w, h: t });
+ let (wa, wb) = (na.w, nb.w);
+ out.els.extend(na.shifted((w - wa) / 2.0, num_base));
+ out.els.extend(nb.shifted((w - wb) / 2.0, den_base));
+ value = out;
+ }
+ LayoutWork::SqrtBody(index, size) => {
+ let inner = std::mem::take(&mut value);
+ let axis = size * 0.25;
+ let t = (size * 0.05).max(0.4);
+ let gap = size * 0.12;
+ let top = inner.asc + gap + t;
+ let bottom = inner.desc;
+ let hook = size * 0.55;
+ let mut out = MBox { w: hook + inner.w + size * 0.1, asc: top, desc: bottom, els: Vec::new() };
+ out.els.push(Elem::Line {
+ pts: vec![(0.0, -axis * 0.6), (hook * 0.25, -axis), (hook * 0.55, bottom), (hook, -top + t / 2.0), (out.w, -top + t / 2.0)],
+ w: t,
+ });
+ out.els.extend(inner.shifted(hook, 0.0));
+ if let Some(index) = index {
+ work.push(LayoutWork::SqrtIndex(out, size));
+ work.push(LayoutWork::Visit(index, size * 0.55));
+ } else {
+ value = out;
}
- parts.push((layout(f, item, size), before));
- prev = cl;
- }
- hbox(parts)
- }
- Node::Frac(a, b) => {
- let s2 = size * 0.85;
- let (na, nb) = (layout(f, a, s2), layout(f, b, s2));
- let w = na.w.max(nb.w) + size * 0.2;
- let t = (size * 0.06).max(0.4);
- let gap = size * 0.15;
- let num_base = -(axis + t / 2.0 + gap + na.desc);
- let den_base = -axis + t / 2.0 + gap + nb.asc;
- let mut out = MBox { w, asc: -num_base + na.asc, desc: den_base + nb.desc, els: Vec::new() };
- out.els.push(Elem::Rule { x: 0.0, y: -axis - t / 2.0, w, h: t });
- let (wa, wb) = (na.w, nb.w);
- out.els.extend(na.shifted((w - wa) / 2.0, num_base));
- out.els.extend(nb.shifted((w - wb) / 2.0, den_base));
- out
- }
- Node::Sqrt(idx, a) => {
- let inner = layout(f, a, size);
- let t = (size * 0.05).max(0.4);
- let gap = size * 0.12;
- let top = inner.asc + gap + t;
- let bottom = inner.desc;
- let hook = size * 0.55;
- let mut out = MBox { w: hook + inner.w + size * 0.1, asc: top, desc: bottom, els: Vec::new() };
- // The radical: a short rise, the long stroke down, then up to the bar.
- out.els.push(Elem::Line {
- pts: vec![(0.0, -axis * 0.6), (hook * 0.25, -axis), (hook * 0.55, bottom), (hook, -top + t / 2.0), (out.w, -top + t / 2.0)],
- w: t,
- });
- let iw = inner.w;
- let _ = iw;
- out.els.extend(inner.shifted(hook, 0.0));
- if let Some(i) = idx {
- let ib = layout(f, i, size * 0.55);
- let (ia, iw2) = (ib.asc, ib.w);
- out.els.extend(ib.shifted((hook * 0.3 - iw2).max(0.0) - 0.0, -axis - size * 0.1));
+ }
+ LayoutWork::SqrtIndex(mut out, size) => {
+ let ib = std::mem::take(&mut value);
+ let (ia, iw) = (ib.asc, ib.w);
+ let axis = size * 0.25;
+ let hook = size * 0.55;
+ out.els.extend(ib.shifted((hook * 0.3 - iw).max(0.0) - 0.0, -axis - size * 0.1));
out.asc = out.asc.max(axis + size * 0.1 + ia);
+ value = out;
}
- out
- }
- Node::Big(op) => {
- let mut b = text_box(f, op, size * 1.5, false);
- b.asc = size * 1.05;
- b.desc = size * 0.35;
- for e in &mut b.els {
- if let Elem::Text { y, .. } = e {
- // Centre the glyph on the math axis.
- *y = size * 0.32;
+ LayoutWork::ScriptBase { sup, sub, big, size } => {
+ let state = ScriptLayout::new(std::mem::take(&mut value), big, size);
+ if let Some(sup) = sup {
+ work.push(LayoutWork::ScriptSup { state, sub });
+ work.push(LayoutWork::Visit(sup, size * 0.7));
+ } else if let Some(sub) = sub {
+ work.push(LayoutWork::ScriptSub(state));
+ work.push(LayoutWork::Visit(sub, size * 0.7));
+ } else {
+ value = state.finish();
}
}
- b
- }
- Node::Scripts { base, sup, sub } => {
- let big = matches!(&**base, Node::Big(_));
- let b = layout(f, base, size);
- let s2 = size * 0.7;
- let (bw, basc, bdesc) = (b.w, b.asc, b.desc);
- let mut out = MBox { w: bw, asc: basc, desc: bdesc, els: b.els };
- if big {
- // Limits above and below.
- let mut w = bw;
- if let Some(sp) = sup {
- let sb = layout(f, sp, s2);
- let y = -basc - size * 0.1 - sb.desc;
- w = w.max(sb.w);
- let (sw, sa) = (sb.w, sb.asc);
- out.els.extend(sb.shifted((bw - sw) / 2.0, y));
- out.asc = out.asc.max(-y + sa);
- }
- if let Some(sbn) = sub {
- let sb = layout(f, sbn, s2);
- let y = bdesc + size * 0.1 + sb.asc;
- w = w.max(sb.w);
- let (sw, sd) = (sb.w, sb.desc);
- out.els.extend(sb.shifted((bw - sw) / 2.0, y));
- out.desc = out.desc.max(y + sd);
+ LayoutWork::ScriptSup { mut state, sub } => {
+ state.add(std::mem::take(&mut value), true);
+ if let Some(sub) = sub {
+ let size = state.size;
+ work.push(LayoutWork::ScriptSub(state));
+ work.push(LayoutWork::Visit(sub, size * 0.7));
+ } else {
+ value = state.finish();
}
- // Centre the operator over the widest limit.
- let dx = (w - bw) / 2.0;
- let els = std::mem::take(&mut out.els);
- out = MBox { w, asc: out.asc, desc: out.desc, els: MBox { els, ..Default::default() }.shifted(dx, 0.0) };
- return out;
- }
- let mut w = bw;
- if let Some(sp) = sup {
- let sb = layout(f, sp, s2);
- let y = -(size * 0.42).max(basc - sb.asc * 0.6);
- w = w.max(bw + sb.w + size * 0.05);
- let sa = sb.asc;
- out.els.extend(sb.shifted(bw + size * 0.05, y));
- out.asc = out.asc.max(-y + sa);
}
- if let Some(sbn) = sub {
- let sb = layout(f, sbn, s2);
- let y = (size * 0.2).max(bdesc * 0.8);
- w = w.max(bw + sb.w + size * 0.05);
- let sd = sb.desc;
- out.els.extend(sb.shifted(bw + size * 0.05, y));
- out.desc = out.desc.max(y + sd);
+ LayoutWork::ScriptSub(mut state) => {
+ state.add(std::mem::take(&mut value), false);
+ value = state.finish();
}
- out.w = w;
- out
- }
- Node::Fenced(open, body, close) => {
- let inner = layout(f, body, size);
- let h = (inner.asc + inner.desc).max(size);
- let k = h / size;
- let ds = size * k.max(1.0);
- let mk = |s: &str| -> MBox {
- if s.is_empty() {
- return MBox::default();
- }
- let mut b = text_box(f, s, ds, false);
- // Scaled delimiters centred on the content.
- let mid = (inner.desc - inner.asc) / 2.0;
- for e in &mut b.els {
- if let Elem::Text { y, .. } = e {
- *y = mid + ds * 0.25;
+ LayoutWork::Fence(open, close, size) => {
+ let inner = std::mem::take(&mut value);
+ let h = (inner.asc + inner.desc).max(size);
+ let k = h / size;
+ let ds = size * k.max(1.0);
+ let mk = |s: &str| -> MBox {
+ if s.is_empty() {
+ return MBox::default();
}
- }
- b.asc = inner.asc.max(size * 0.72);
- b.desc = inner.desc.max(size * 0.22);
- b
- };
- let (l, r) = (mk(open), mk(close));
- hbox(vec![(l, 0.0), (inner, size * 0.05), (r, size * 0.05)])
+ let mut b = text_box(f, s, ds, false);
+ let mid = (inner.desc - inner.asc) / 2.0;
+ for e in &mut b.els {
+ if let Elem::Text { y, .. } = e {
+ *y = mid + ds * 0.25;
+ }
+ }
+ b.asc = inner.asc.max(size * 0.72);
+ b.desc = inner.desc.max(size * 0.22);
+ b
+ };
+ let (l, r) = (mk(open), mk(close));
+ value = hbox(vec![(l, 0.0), (inner, size * 0.05), (r, size * 0.05)]);
+ }
}
}
+ value
}
/// Typeset `latex` at `size` points: SVG bytes and the size in points.
@@@ -923,189 -706,6 +948,197 @@@ pub fn to_svg(latex: &str, size: f64) -
mod tests {
use super::*;
+ // Frozen pre-repair arithmetic; called only for shallow fixtures, never deep input.
++ /// Frozen recursive layout oracle for shallow test fixtures only, never deep input.
+ fn recursive_layout_reference(f: &Fonts, n: &Node, size: f64) -> MBox {
+ match n {
+ Node::Sym(s, cl) => text_box(f, s, size, *cl == Class::Ident),
+ Node::Text(s) => text_box(f, s, size, false),
+ Node::Space(em) => MBox { w: em * size, ..Default::default() },
+ Node::Group(list) => recursive_group_reference(f, list, size),
+ Node::Frac(a, b) => recursive_fraction_reference(f, a, b, size),
+ Node::Sqrt(idx, a) => recursive_sqrt_reference(f, idx, a, size),
+ Node::Big(op) => recursive_big_reference(f, op, size),
+ Node::Scripts { base, sup, sub } => recursive_scripts_reference(f, base, sup, sub, size),
+ Node::Fenced(open, body, close) => recursive_fenced_reference(f, open, body, close, size),
+ }
+ }
+
++ /// Oracle for operator spacing, leading-sign treatment and punctuation gaps.
+ fn recursive_group_reference(f: &Fonts, list: &[Node], size: f64) -> MBox {
+ let mut parts = Vec::new();
+ let mut prev: Option<Class> = None;
+ for (k, item) in list.iter().enumerate() {
+ let cl = match item {
+ Node::Sym(_, c) => Some(*c),
+ Node::Scripts { base, .. } => match &**base {
+ Node::Sym(_, c) => Some(*c),
+ _ => None,
+ },
+ _ => None,
+ };
+ // A leading + or − (or after another operator) is a sign, not a binary operator.
+ let cl = if cl == Some(Class::Bin) && (k == 0 || matches!(prev, Some(Class::Bin | Class::Rel | Class::Punct))) {
+ Some(Class::Plain)
+ } else {
+ cl
+ };
+ let gap = |c: Option<Class>| match c {
+ Some(Class::Bin) => size * 4.0 / 18.0,
+ Some(Class::Rel) => size * 5.0 / 18.0,
+ _ => 0.0,
+ };
+ let mut before = gap(cl).max(gap(prev));
+ if k == 0 {
+ before = 0.0;
+ }
+ if prev == Some(Class::Punct) {
+ before = before.max(size * 3.0 / 18.0);
+ }
+ parts.push((recursive_layout_reference(f, item, size), before));
+ prev = cl;
+ }
+ hbox(parts)
+ }
+
++ /// Oracle for fraction rule, child scale, math axis, gaps and bounds.
+ fn recursive_fraction_reference(f: &Fonts, a: &Node, b: &Node, size: f64) -> MBox {
+ let axis = size * 0.25;
+ let s2 = size * 0.85;
+ let (na, nb) = (recursive_layout_reference(f, a, s2), recursive_layout_reference(f, b, s2));
+ let w = na.w.max(nb.w) + size * 0.2;
+ let t = (size * 0.06).max(0.4);
+ let gap = size * 0.15;
+ let num_base = -(axis + t / 2.0 + gap + na.desc);
+ let den_base = -axis + t / 2.0 + gap + nb.asc;
+ let mut out = MBox { w, asc: -num_base + na.asc, desc: den_base + nb.desc, els: Vec::new() };
+ out.els.push(Elem::Rule { x: 0.0, y: -axis - t / 2.0, w, h: t });
+ let (wa, wb) = (na.w, nb.w);
+ out.els.extend(na.shifted((w - wa) / 2.0, num_base));
+ out.els.extend(nb.shifted((w - wb) / 2.0, den_base));
+ out
+ }
+
++ /// Oracle for radical geometry, body offset and optional root index.
+ fn recursive_sqrt_reference(f: &Fonts, idx: &Option<Box<Node>>, a: &Node, size: f64) -> MBox {
+ let axis = size * 0.25;
+ let inner = recursive_layout_reference(f, a, size);
+ let t = (size * 0.05).max(0.4);
+ let gap = size * 0.12;
+ let top = inner.asc + gap + t;
+ let bottom = inner.desc;
+ let hook = size * 0.55;
+ let mut out = MBox { w: hook + inner.w + size * 0.1, asc: top, desc: bottom, els: Vec::new() };
+ // The radical: a short rise, the long stroke down, then up to the bar.
+ out.els.push(Elem::Line {
+ pts: vec![(0.0, -axis * 0.6), (hook * 0.25, -axis), (hook * 0.55, bottom), (hook, -top + t / 2.0), (out.w, -top + t / 2.0)],
+ w: t,
+ });
+ let iw = inner.w;
+ let _ = iw;
+ out.els.extend(inner.shifted(hook, 0.0));
+ if let Some(i) = idx {
+ let ib = recursive_layout_reference(f, i, size * 0.55);
+ let (ia, iw2) = (ib.asc, ib.w);
+ out.els.extend(ib.shifted((hook * 0.3 - iw2).max(0.0) - 0.0, -axis - size * 0.1));
+ out.asc = out.asc.max(axis + size * 0.1 + ia);
+ }
+ out
+ }
+
++ /// Oracle for enlarged, math-axis-centred big operators.
+ fn recursive_big_reference(f: &Fonts, op: &str, size: f64) -> MBox {
+ let mut b = text_box(f, op, size * 1.5, false);
+ b.asc = size * 1.05;
+ b.desc = size * 0.35;
+ for e in &mut b.els {
+ if let Elem::Text { y, .. } = e {
+ // Centre the glyph on the math axis.
+ *y = size * 0.32;
+ }
+ }
+ b
+ }
+
++ /// Oracle for ordinary sup/sub placement and big-operator limits above and below.
+ fn recursive_scripts_reference(f: &Fonts, base: &Node, sup: &Option<Box<Node>>, sub: &Option<Box<Node>>, size: f64) -> MBox {
+ let big = matches!(base, Node::Big(_));
+ let b = recursive_layout_reference(f, base, size);
+ let s2 = size * 0.7;
+ let (bw, basc, bdesc) = (b.w, b.asc, b.desc);
+ let mut out = MBox { w: bw, asc: basc, desc: bdesc, els: b.els };
+ if big {
+ // Limits above and below.
+ let mut w = bw;
+ if let Some(sp) = sup {
+ let sb = recursive_layout_reference(f, sp, s2);
+ let y = -basc - size * 0.1 - sb.desc;
+ w = w.max(sb.w);
+ let (sw, sa) = (sb.w, sb.asc);
+ out.els.extend(sb.shifted((bw - sw) / 2.0, y));
+ out.asc = out.asc.max(-y + sa);
+ }
+ if let Some(sbn) = sub {
+ let sb = recursive_layout_reference(f, sbn, s2);
+ let y = bdesc + size * 0.1 + sb.asc;
+ w = w.max(sb.w);
+ let (sw, sd) = (sb.w, sb.desc);
+ out.els.extend(sb.shifted((bw - sw) / 2.0, y));
+ out.desc = out.desc.max(y + sd);
+ }
+ // Centre the operator over the widest limit.
+ let dx = (w - bw) / 2.0;
+ let els = std::mem::take(&mut out.els);
+ return MBox { w, asc: out.asc, desc: out.desc, els: MBox { els, ..Default::default() }.shifted(dx, 0.0) };
+ }
+ let mut w = bw;
+ if let Some(sp) = sup {
+ let sb = recursive_layout_reference(f, sp, s2);
+ let y = -(size * 0.42).max(basc - sb.asc * 0.6);
+ w = w.max(bw + sb.w + size * 0.05);
+ let sa = sb.asc;
+ out.els.extend(sb.shifted(bw + size * 0.05, y));
+ out.asc = out.asc.max(-y + sa);
+ }
+ if let Some(sbn) = sub {
+ let sb = recursive_layout_reference(f, sbn, s2);
+ let y = (size * 0.2).max(bdesc * 0.8);
+ w = w.max(bw + sb.w + size * 0.05);
+ let sd = sb.desc;
+ out.els.extend(sb.shifted(bw + size * 0.05, y));
+ out.desc = out.desc.max(y + sd);
+ }
+ out.w = w;
+ out
+ }
+
++ /// Oracle for content-scaled, centred delimiters.
+ fn recursive_fenced_reference(f: &Fonts, open: &str, body: &Node, close: &str, size: f64) -> MBox {
+ let inner = recursive_layout_reference(f, body, size);
+ let h = (inner.asc + inner.desc).max(size);
+ let k = h / size;
+ let ds = size * k.max(1.0);
+ let mk = |s: &str| -> MBox {
+ if s.is_empty() {
+ return MBox::default();
+ }
+ let mut b = text_box(f, s, ds, false);
+ // Scaled delimiters centred on the content.
+ let mid = (inner.desc - inner.asc) / 2.0;
+ for e in &mut b.els {
+ if let Elem::Text { y, .. } = e {
+ *y = mid + ds * 0.25;
+ }
+ }
+ b.asc = inner.asc.max(size * 0.72);
+ b.desc = inner.desc.max(size * 0.22);
+ b
+ };
+ let (l, r) = (mk(open), mk(close));
+ hbox(vec![(l, 0.0), (inner, size * 0.05), (r, size * 0.05)])
+ }
+
++ /// Asserts fraction/nested-root, big scripts, relation, symbol, fence and raw `\text` parse shapes.
#[test]
fn parses_the_common_constructs() {
let n = parse(r"\frac{a^2+b}{\sqrt[3]{x}}");
@@@ -1167,223 -767,9 +1200,229 @@@
format!("{}x{}", "{".repeat(100_000), "}".repeat(100_000)),
format!("{}x", r"\frac".repeat(100_000)),
format!("{}x", r"\left(".repeat(100_000)),
+ format!("{}z{}", r"\sqrt{".repeat(1_024), "}".repeat(1_024)),
+ format!("{}z{}", "x^{".repeat(1_024), "}".repeat(1_024)),
] {
- let (svg, _) = to_svg(&latex, 12.0);
+ let (svg, (w, h)) = to_svg(&latex, 12.0);
assert!(!svg.is_empty());
+ assert!(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0, "{w} {h}");
+ }
+ }
+ /// Count actual tree shape without recursively comparing or formatting a deep AST.
+ fn shape(root: &Node) -> ([usize; 6], usize) {
+ let mut counts = [0; 6]; // groups, fractions, roots, fences, scripts, sentinel z
+ let mut deepest = 0;
+ let mut work = vec![(root, 1)];
+ while let Some((node, depth)) = work.pop() {
+ deepest = deepest.max(depth);
+ match node {
+ Node::Group(nodes) => {
+ counts[0] += 1;
+ work.extend(nodes.iter().map(|node| (node, depth + 1)));
+ }
+ Node::Frac(a, b) => {
+ counts[1] += 1;
+ work.extend([(a.as_ref(), depth + 1), (b.as_ref(), depth + 1)]);
+ }
+ Node::Sqrt(index, body) => {
+ counts[2] += 1;
+ work.push((body, depth + 1));
+ if let Some(index) = index {
+ work.push((index, depth + 1));
+ }
+ }
+ Node::Fenced(_, body, _) => {
+ counts[3] += 1;
+ work.push((body, depth + 1));
+ }
+ Node::Scripts { base, sup, sub } => {
+ counts[4] += 1;
+ work.push((base, depth + 1));
+ if let Some(sup) = sup {
+ work.push((sup, depth + 1));
+ }
+ if let Some(sub) = sub {
+ work.push((sub, depth + 1));
+ }
+ }
+ Node::Sym(s, _) if s == "z" => counts[5] += 1,
+ _ => {}
+ }
+ }
+ (counts, deepest)
+ }
+
++ /// With `MAX_NESTING == 256`, all supported 255-level constructs stay nested and still render their sentinel.
+ #[test]
+ fn the_full_256_budget_keeps_deep_valid_formulas_intact() {
+ assert_eq!(MAX_NESTING, 256, "preserve the existing expression capability");
+ let groups = MAX_NESTING - 1;
+ let arguments = (MAX_NESTING - 1) / 2;
+ let index_groups = MAX_NESTING - 3;
+ let cases = [
+ (format!("{}z{}", "{".repeat(groups), "}".repeat(groups)), [groups + 1, 0, 0, 0, 0, 1], groups + 2),
+ (format!("{}z{}", r"\left(".repeat(groups), r"\right)".repeat(groups)), [groups + 1, 0, 0, groups, 0, 1], groups * 2 + 2),
+ (format!("{}z{}", r"\frac{".repeat(arguments), "}{y}".repeat(arguments)), [arguments * 2 + 1, arguments, 0, 0, 0, 1], arguments * 2 + 2),
+ (format!("{}z{}", r"\sqrt{".repeat(arguments), "}".repeat(arguments)), [arguments + 1, 0, arguments, 0, 0, 1], arguments * 2 + 2),
+ (format!("{}z{}", "x^{".repeat(arguments), "}".repeat(arguments)), [arguments + 1, 0, 0, 0, arguments, 1], arguments * 2 + 2),
+ (format!("{}z{}", "x_{".repeat(arguments), "}".repeat(arguments)), [arguments + 1, 0, 0, 0, arguments, 1], arguments * 2 + 2),
+ (format!(r"\sqrt[{}z{}]{{y}}", "{".repeat(index_groups), "}".repeat(index_groups)), [index_groups + 3, 0, 1, 0, 0, 1], index_groups + 4),
+ ];
+ for (latex, counts, depth) in cases {
+ assert_eq!(shape(&parse(&latex)), (counts, depth), "all constructs must remain nested, not flatten into siblings");
+ let (svg, (w, h)) = to_svg(&latex, 12.0);
+ assert!(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0, "{w} {h}");
+ assert!(String::from_utf8(svg).unwrap().contains(">z<"), "the innermost content must render");
+ }
+ }
+
++ /// A capped list consumes nothing; capped root-index/body cursor behavior and the permissive first-`]` grammar remain unchanged.
+ #[test]
+ fn cap_and_index_returns_preserve_their_exact_cursor_semantics() {
+ let chars: Vec<_> = "x".chars().collect();
+ let mut p = Parser { s: &chars, i: 0 };
+ assert_eq!(p.parse(MAX_NESTING - 1), Node::Group(vec![Node::Sym("x".into(), Class::Ident)]));
+ assert_eq!(p.i, 1);
+ let mut p = Parser { s: &chars, i: 0 };
+ assert_eq!(p.parse(MAX_NESTING), Node::Group(vec![]));
+ assert_eq!(p.i, 0, "a capped List does not consume its input");
+ // Both the index subparse and radicand still have their entire old depth allowance.
+ let source = r"\sqrt[x]{y}z";
+ assert_eq!(
+ parse_at(source, MAX_NESTING - 4),
+ Node::Group(vec![
+ Node::Sqrt(
+ Some(Box::new(Node::Group(vec![Node::Sym("x".into(), Class::Ident)]))),
+ Box::new(Node::Group(vec![Node::Sym("y".into(), Class::Ident)]))
+ ),
+ Node::Sym("z".into(), Class::Ident),
+ ])
+ );
+ // At this starting depth the index and braced body are capped. The outer cursor is
+ // restored after ']', then the old non-consuming body cap leaves y/}/z as siblings.
+ let chars: Vec<_> = source.chars().collect();
+ let mut p = Parser { s: &chars, i: 0 };
+ assert_eq!(
+ p.parse(MAX_NESTING - 2),
+ Node::Group(vec![
+ Node::Sqrt(Some(Box::new(Node::Group(vec![]))), Box::new(Node::Group(vec![]))),
+ Node::Sym("y".into(), Class::Ident),
+ Node::Sym("}".into(), Class::Plain),
+ Node::Sym("z".into(), Class::Ident),
+ ])
+ );
+ assert_eq!(p.i, chars.len());
+ // Do not change the permissive first-']' index grammar into balanced bracket parsing.
+ assert_eq!(
+ parse(r"\sqrt[x[y]z]q"),
+ Node::Group(vec![
+ Node::Sqrt(
+ Some(Box::new(Node::Group(vec![
+ Node::Sym("x".into(), Class::Ident),
+ Node::Sym("[".into(), Class::Plain),
+ Node::Sym("y".into(), Class::Ident)
+ ]))),
+ Box::new(Node::Sym("z".into(), Class::Ident))
+ ),
+ Node::Sym("]".into(), Class::Plain),
+ Node::Sym("q".into(), Class::Ident),
+ ])
+ );
+ }
+
++ /// Repeated scripts replace slots; a fence `^` stays literal; incomplete fractions, escaped braces and unknown commands retain the prior grammar.
+ #[test]
+ fn heap_continuations_preserve_small_grammar_and_script_precedence() {
+ let sym = |s: &str| Node::Sym(s.into(), Class::Ident);
+ assert_eq!(
+ parse("x^{a}_{b}^{c}_{d}"),
+ Node::Group(vec![Node::Scripts {
+ base: Box::new(sym("x")),
+ sup: Some(Box::new(Node::Group(vec![sym("c")]))),
+ sub: Some(Box::new(Node::Group(vec![sym("d")]))),
+ }])
+ );
+ assert_eq!(
+ parse(r"\left( ^x \right)"),
+ Node::Group(vec![Node::Fenced("(".into(), Box::new(Node::Group(vec![Node::Sym("^".into(), Class::Plain), sym("x")])), ")".into())])
+ );
+ assert_eq!(parse(r"\frac{x"), Node::Group(vec![Node::Frac(Box::new(Node::Group(vec![sym("x")])), Box::new(Node::Group(vec![])))]));
+ assert_eq!(
+ parse(r"\text{a{b}}\{\}\_\unknown"),
+ Node::Group(vec![
+ Node::Text("a{b}".into()),
+ Node::Sym("{".into(), Class::Punct),
+ Node::Sym("}".into(), Class::Punct),
+ Node::Sym("_".into(), Class::Plain),
+ Node::Text(r"\unknown".into())
+ ])
+ );
+ }
+
++ /// Iterative layout equals the frozen recursive oracle for representative formulas, including malformed inputs.
+ #[test]
+ fn heap_layout_preserves_the_existing_element_order_and_geometry() {
+ let db = FontDb::global();
+ let f = Fonts { upright: db.face(FAMILY, "Regular"), italic: db.face(FAMILY, "Italic"), fallback: db.face(FALLBACK, "Regular") };
+ for latex in [
+ "E = mc^2",
+ "x^{a}_{b}^{c}_{d}",
+ r"\frac{a^2+b}{\sqrt[3]{x}}",
+ r"\sum_{i=0}^{n} i^2",
+ r"\int_a^b x",
+ r"\left( x \rightarrow y \right) + \text{if } x",
+ r"\left. x \right]",
+ r"-x,+y;\quad z",
+ r"\sqrt[x[y]z]q",
+ r"\frac{x",
+ r"\left( ^x \right)",
+ ] {
+ let tree = parse(latex);
+ let actual = layout(&f, &tree, 12.0);
+ let expected = recursive_layout_reference(&f, &tree, 12.0);
+ assert_eq!((actual.w, actual.asc, actual.desc, actual.els), (expected.w, expected.asc, expected.desc, expected.els), "{latex}");
+ }
+ }
+
++ /// Build a deep five-way alternating AST for destructor stress tests.
+ fn mixed_chain(depth: usize) -> Node {
+ let mut node = Node::Sym("z".into(), Class::Ident);
+ for i in 0..depth {
+ node = match i % 5 {
+ 0 => Node::Group(vec![node]),
+ 1 => Node::Frac(Box::new(node), Box::new(Node::Text("d".into()))),
+ 2 => Node::Sqrt(Some(Box::new(Node::Text("3".into()))), Box::new(node)),
+ 3 => Node::Scripts { base: Box::new(node), sup: Some(Box::new(Node::Text("p".into()))), sub: Some(Box::new(Node::Text("q".into()))) },
+ _ => Node::Fenced("(".into(), Box::new(node), ")".into()),
+ };
+ }
+ node
+ }
+
++ /// Drops 50k-node chains, replaces one script slot, and unwinds parser continuations while preserving the retained slot.
+ #[test]
+ fn deep_nodes_drop_when_replaced_or_owned_by_unwinding_continuations() {
+ // Far beyond the parser budget: this directly proves the private destructor's traversal.
+ drop(mixed_chain(50_000));
+ for up in [false, true] {
+ let old = Box::new(mixed_chain(50_000));
+ let other = Box::new(Node::Text("other".into()));
+ let (sup, sub) = if up { (Some(old), Some(other)) } else { (Some(other), Some(old)) };
+ let root = attach_script(Node::Scripts { base: Box::new(Node::Big("∑".into())), sup, sub }, Node::Text("new".into()), up);
+ let Node::Scripts { base, sup, sub } = &root else { panic!("script wrapper") };
+ assert!(matches!(&**base, Node::Big(s) if s == "∑"));
+ let (replaced, retained) = if up { (sup, sub) } else { (sub, sup) };
+ assert!(matches!(replaced.as_deref(), Some(Node::Text(s)) if s == "new"));
+ assert!(matches!(retained.as_deref(), Some(Node::Text(s)) if s == "other"));
}
+ let result = std::panic::catch_unwind(|| {
+ // Actual continuation variants own completed children while awaiting later input.
+ let _partial = [
+ ParseWork::FractionDenominator { numerator: mixed_chain(25_000) },
+ ParseWork::SqrtArgument { index: Some(Box::new(mixed_chain(25_000))) },
+ ];
+ panic!("exercise partial-parser-state unwinding");
+ });
+ assert!(result.is_err(), "the intentional panic must actually unwind the owned frames");
}
}
diff --cc crates/engine/src/tests_ime.rs
index 73100c428,266470914..792a6a407
--- a/crates/engine/src/tests_ime.rs
+++ b/crates/engine/src/tests_ime.rs
@@@ -30,47 -30,6 +30,49 @@@ fn steps(s: &Session) -> usize
s.doc().unwrap().history.undo.len()
}
++/// Byte counts round inward to whole characters, cap at the text bounds, and scan from the requested count rather than the story start.
+#[test]
+fn ime_byte_deletion_rounds_inward_from_the_requested_count() {
+ // a: 0..1, é: 1..3, 😀: 3..7, b: 7..8.
+ let text = "aé😀b";
+ assert_eq!(ime_delete_ranges(text, 7, 7, 4, 0, true), Some((3..7, 7..7)), "the whole emoji");
+ assert_eq!(ime_delete_ranges(text, 7, 7, 6, 0, true), Some((1..7, 7..7)), "é and the emoji");
+ assert_eq!(ime_delete_ranges(text, 7, 7, 3, 0, true), Some((7..7, 7..7)), "a count starting inside the emoji leaves it");
+ assert_eq!(ime_delete_ranges(text, 7, 7, 100, 0, true), Some((0..7, 7..7)), "more bytes than the text takes it all");
+ // The scan starts at the requested count, not at the start of the story.
+ let long = format!("{}é", "x".repeat(20_000));
+ let end = long.len();
+ assert_eq!(ime_delete_ranges(&long, end, end, 3, 0, true), Some((end - 3..end, end..end)), "x and é");
+ assert_eq!(ime_delete_ranges(&long, end, end, 2, 0, true), Some((end - 2..end, end..end)), "the whole é");
+ assert_eq!(ime_delete_ranges(&long, end, end, 1, 0, true), Some((end..end, end..end)), "one byte inside é leaves it");
+}
+
++/// Reports exact before/after byte ranges, preserves and remaps the selection direction; no-op deletes report `None`.
+#[test]
+fn ime_delete_reports_the_ranges_it_applied() {
+ let mut s = session();
+ let sid = typing_into(&mut s, "aé😀b");
+ s.execute("text.select", &json!({"story": sid, "anchor": 1, "focus": 3})).unwrap();
+ let m = s.ime_delete_surrounding(2, 4, true).unwrap().expect("the delete changed the text");
+ assert_eq!(m.deleted_before, 0..1, "the byte before the selection");
+ assert_eq!(m.deleted_after, 3..7, "the emoji after it");
+ assert_eq!((m.anchor_before, m.focus_before), (1, 3));
+ assert_eq!((m.anchor_after, m.focus_after), (0, 2), "the selection stays selected, shifted left");
+ assert_eq!((m.text_len_before, m.text_len_after), (8, 3));
+ assert!(m.inserted.is_empty());
+ assert_eq!(text(&mut s, sid), "éb");
+ // A request that removes nothing is reported as no mutation at all.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ assert!(s.ime_delete_surrounding(0, 0, false).unwrap().is_none());
+ // A commit reports the text it typed and replaces the selection.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 2})).unwrap();
+ let m = s.ime_commit("日", ViewInfo::default()).unwrap().expect("the commit changed the text");
+ assert_eq!(m.inserted, "日");
+ assert!(m.deleted_before.is_empty() && m.deleted_after.is_empty());
+ assert_eq!((m.anchor_after, m.focus_after), (3, 3));
+ assert_eq!(text(&mut s, sid), "日b");
+}
+
#[test]
fn ime_composition_shows_in_place_and_commits_as_one_step() {
// Romaji → kana → conversion → commit, as the macOS Japanese IME sends it.
diff --cc crates/engine/src/tooling.rs
index f26e50714,65d069bac..c982cade7
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@@ -348,304 -346,3 +348,307 @@@ impl Session
}
}
}
+
+/// The committed text around the Type tool's IME caret.
+///
+/// While an IME composition is active the marked text is only an interaction preview, so this
+/// borrows the interaction's committed snapshot and selection instead of the previewed document.
+/// `anchor` and `focus` are UTF-8 byte offsets into `text`; `focus` is the primary caret end.
+#[derive(Clone, Copy, Debug)]
+pub struct ImeTextContext<'a> {
+ /// Stable document identity (a new document gets a new value).
+ pub document_uid: u64,
+ /// Document-state identity: changes when the state is recreated even if `document_uid` is
+ /// preserved (File › Revert).
+ pub document_epoch: u64,
+ /// Story being edited, or the story that owns the edited table cell.
+ pub story: StoryId,
+ /// Edited table cell, when the caret is in one.
+ pub cell: Option<CellAddr>,
+ /// Committed logical story text, without the current IME pre-edit.
+ pub text: &'a str,
+ /// Selection anchor (the end that stays put under Shift-arrow selection).
+ pub anchor: usize,
+ /// Primary selection end (the caret).
+ pub focus: usize,
+}
+
+/// What an accepted IME mutation applied to the committed story text.
+///
+/// The engine reports this from the whole story, not from the bounded outgoing IME window, so a
+/// successful mutation can be described exactly even when the deleted text lies outside that
+/// window. `deleted_before` and `deleted_after` are byte ranges of the text before the mutation;
+/// `inserted` is the text the mutation typed at the selection. Invalid or unreportable mutations
+/// return `None` rather than a guessed description.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ImeMutation {
+ /// Stable document identity of the mutation.
+ pub document_uid: u64,
+ /// Document-state identity (see [`ImeTextContext::document_epoch`]).
+ pub document_epoch: u64,
+ /// Story (or the story owning the edited cell) that changed.
+ pub story: StoryId,
+ /// Edited table cell, when the caret was in one.
+ pub cell: Option<CellAddr>,
+ /// Committed selection before and after the mutation (UTF-8 byte offsets).
+ pub anchor_before: usize,
+ pub focus_before: usize,
+ pub anchor_after: usize,
+ pub focus_after: usize,
+ /// Committed story text length before and after the mutation.
+ pub text_len_before: usize,
+ pub text_len_after: usize,
+ /// Text removed before and after the selection (empty when nothing was removed).
+ pub deleted_before: Range<usize>,
+ pub deleted_after: Range<usize>,
+ /// Text typed at the selection, after the commit normalization.
+ pub inserted: String,
+}
+
+/// The identity, committed selection and text length at the IME caret.
+#[derive(Clone, Copy, Debug)]
+struct ImeState {
+ document_uid: u64,
+ document_epoch: u64,
+ story: StoryId,
+ cell: Option<CellAddr>,
+ anchor: usize,
+ focus: usize,
+ text_len: usize,
+}
+
+/// The ranges a successful `text.deleteSurrounding` reports it removed.
+fn ime_ranges_from_command(r: &Value) -> Option<(Range<usize>, Range<usize>)> {
+ let range = |key: &str| {
+ let arr = r.get(key)?.as_array()?;
+ let start = usize::try_from(arr.first()?.as_u64()?).ok()?;
+ let end = usize::try_from(arr.get(1)?.as_u64()?).ok()?;
+ (start <= end).then_some(start..end)
+ };
+ Some((range("deletedBefore")?, range("deletedAfter")?))
+}
+
+/// The byte ranges an IME delete-surrounding request removes around a selection.
+///
+/// The returned pair is `(before_selection, after_selection)`. Counts exclude the selection
+/// itself and the current pre-edit. Character counts are Unicode scalar values. Byte counts
+/// round inward: a count that ends inside a character leaves that whole character. Invalid or
+/// non-boundary selection offsets return `None` rather than guessed ranges.
+pub fn ime_delete_ranges(text: &str, anchor: usize, focus: usize, before: usize, after: usize, bytes: bool) -> Option<(Range<usize>, Range<usize>)> {
+ let (min, max) = ime_selection_bounds(text, anchor, focus)?;
+ Some(if bytes { ime_byte_delete_ranges(text, min, max, before, after) } else { ime_character_delete_ranges(text, min, max, before, after) })
+}
+
+/// Validate the committed selection and return its lower and upper UTF-8 byte offsets.
+fn ime_selection_bounds(text: &str, anchor: usize, focus: usize) -> Option<(usize, usize)> {
+ if anchor > text.len() || focus > text.len() || !text.is_char_boundary(anchor) || !text.is_char_boundary(focus) {
+ return None;
+ }
+ Some((anchor.min(focus), anchor.max(focus)))
+}
+
+/// Byte-counted ranges around the selection, rounded inward to character boundaries.
+fn ime_byte_delete_ranges(text: &str, min: usize, max: usize, before: usize, after: usize) -> (Range<usize>, Range<usize>) {
+ // Start at the requested byte offset and step at most three bytes to the next character
+ // boundary: the scan is bounded by the count, not by the caret's offset in the story.
+ let from = min.saturating_sub(before).min(min);
+ let mut before_start = from;
+ while before_start < min && !text.is_char_boundary(before_start) {
+ before_start += 1;
+ }
+ let target = max.saturating_add(after).min(text.len());
+ let mut after_end = max;
+ for (i, c) in text[max..].char_indices() {
+ let end = max + i + c.len_utf8();
+ if end <= target {
+ after_end = end;
+ } else {
+ break;
+ }
+ }
+ (before_start..min, max..after_end)
+}
+
+/// Character-counted ranges around the selection, using Unicode scalar values.
+fn ime_character_delete_ranges(text: &str, min: usize, max: usize, before: usize, after: usize) -> (Range<usize>, Range<usize>) {
+ let before_start = if before == 0 {
+ min
+ } else {
+ let mut seen = 0usize;
+ let mut start = 0usize;
+ for (i, _) in text[..min].char_indices().rev() {
+ seen += 1;
+ start = i;
+ if seen == before {
+ break;
+ }
+ }
+ if seen < before { 0 } else { start }
+ };
+ let mut after_end = max;
+ if after > 0 {
+ let mut seen = 0usize;
+ for (i, c) in text[max..].char_indices() {
+ seen += 1;
+ after_end = max + i + c.len_utf8();
+ if seen == after {
+ break;
+ }
+ }
+ }
+ (before_start..min, max..after_end)
+}
+
+impl Session {
+ /// The committed text and selection at the Type tool's IME caret.
+ ///
+ /// Returns `None` without an insertion point, without a committed story, or while a
+ /// composition has no interaction snapshot to describe its committed text. The query never
+ /// copies the story.
+ pub fn ime_text_context(&self) -> Option<ImeTextContext<'_>> {
+ let st = self.active()?;
+ let (doc, ts) = if self.tool.composing() {
+ let it = st.interaction.as_ref()?;
+ (it.doc.as_ref(), it.selection.text?)
+ } else {
+ (st.doc.as_ref(), st.selection.text?)
+ };
+ let story = doc.text_story(ts.story, ts.cell)?;
+ if ts.anchor > story.text.len()
+ || ts.focus > story.text.len()
+ || !story.text.is_char_boundary(ts.anchor)
+ || !story.text.is_char_boundary(ts.focus)
+ {
+ // A stale or corrupt insertion point: report unavailable rather than inventing offsets.
+ return None;
+ }
+ Some(ImeTextContext {
+ document_uid: st.uid,
+ document_epoch: st.identity_epoch,
+ story: ts.story,
+ cell: ts.cell,
+ text: &story.text,
+ anchor: ts.anchor,
+ focus: ts.focus,
+ })
+ }
+
+ /// Delete the text an IME asked to remove around the selection, as one undo step.
+ ///
+ /// The mutation goes through the `text.deleteSurrounding` command, so it restores a Data Merge
+ /// preview, records undo, auto-sizes, journals and is panic-guarded like any other edit.
+ /// The selection itself and any current pre-edit are excluded. Character counts are scalar
+ /// values; byte counts round inward to whole characters. A selection keeps its direction and
+ /// is remapped past the deleted text.
+ pub fn ime_delete_surrounding(&mut self, before: usize, after: usize, bytes: bool) -> Result<Option<ImeMutation>> {
+ if !self.ime_deletion_changes_text(before, after, bytes)? {
+ return Ok(None);
+ }
+ let Some(pre) = self.ime_state() else { return Ok(None) };
+ self.end_preedit_without_typing()?;
+ let r = self.execute("text.deleteSurrounding", &json!({"before": before, "after": after, "bytes": bytes}))?;
+ Ok(self.ime_mutation_from_command(pre, &r, String::new()))
+ }
+
+ /// The IME committed `text`: one `text.insert`, reported as the mutation it applied.
+ pub fn ime_commit(&mut self, text: &str, view: ViewInfo) -> Result<Option<ImeMutation>> {
+ let Some(pre) = self.ime_state() else { return self.tool_ime_commit(text, view).map(|()| None) };
+ self.tool_ime_commit(text, view)?;
+ let inserted = designcraft_tools::ime_commit_text(text);
+ // A commit replaces the selection: the removed ranges are empty at its two ends.
+ let (start, end) = (pre.anchor.min(pre.focus), pre.anchor.max(pre.focus));
+ Ok(self.ime_mutation_from_states(pre, start..start, end..end, inserted))
+ }
+
+ /// Delete surrounding text and insert the IME commit in one undo step.
+ ///
+ /// This is the normal delete-surrounding-then-commit batch: both mutations are one
+ /// `text.deleteSurrounding` command, so one Undo restores the state before the batch.
+ pub fn ime_commit_after_delete(&mut self, text: &str, view: ViewInfo, before: usize, after: usize, bytes: bool) -> Result<Option<ImeMutation>> {
+ if !self.ime_deletion_changes_text(before, after, bytes)? {
+ return self.ime_commit(text, view);
+ }
+ let Some(pre) = self.ime_state() else { return Ok(None) };
+ self.end_preedit_without_typing()?;
+ let inserted = designcraft_tools::ime_commit_text(text);
+ let r = self.execute("text.deleteSurrounding", &json!({"before": before, "after": after, "bytes": bytes, "commit": inserted.clone()}))?;
+ Ok(self.ime_mutation_from_command(pre, &r, inserted))
+ }
+
+ /// The identity, committed selection and text length of the IME caret's story.
+ fn ime_state(&self) -> Option<ImeState> {
+ let context = self.ime_text_context()?;
+ Some(ImeState {
+ document_uid: context.document_uid,
+ document_epoch: context.document_epoch,
+ story: context.story,
+ cell: context.cell,
+ anchor: context.anchor,
+ focus: context.focus,
+ text_len: context.text.len(),
+ })
+ }
+
+ /// Report the mutation the delete command applied, from its ranges and the states around it.
+ fn ime_mutation_from_command(&self, before: ImeState, r: &Value, inserted: String) -> Option<ImeMutation> {
+ let (deleted_before, deleted_after) = ime_ranges_from_command(r)?;
+ self.ime_mutation_from_states(before, deleted_before, deleted_after, inserted)
+ }
+
++ /// Return a mutation only when the document uid/epoch, story and cell still match; otherwise report no mutation.
+ fn ime_mutation_from_states(
+ &self,
+ before: ImeState,
+ deleted_before: Range<usize>,
+ deleted_after: Range<usize>,
+ inserted: String,
+ ) -> Option<ImeMutation> {
+ let after = self.ime_state()?;
+ // The mutation must have stayed in the story it began in.
+ if after.document_uid != before.document_uid
+ || after.document_epoch != before.document_epoch
+ || after.story != before.story
+ || after.cell != before.cell
+ {
+ return None;
+ }
+ Some(ImeMutation {
+ document_uid: before.document_uid,
+ document_epoch: before.document_epoch,
+ story: before.story,
+ cell: before.cell,
+ anchor_before: before.anchor,
+ focus_before: before.focus,
+ anchor_after: after.anchor,
+ focus_after: after.focus,
+ text_len_before: before.text_len,
+ text_len_after: after.text_len,
+ deleted_before,
+ deleted_after,
+ inserted,
+ })
+ }
+
++ /// Clear an active pre-edit without inserting text; if no interaction snapshot exists, reset the tool.
+ fn end_preedit_without_typing(&mut self) -> Result<()> {
+ if !self.tool.composing() {
+ return Ok(());
+ }
+ match self.with_ctx(ViewInfo::default(), |s, cx| s.tool.ime_preedit(cx, "", None)) {
+ Some(actions) => self.run_actions(actions),
+ None => {
+ self.tool = designcraft_tools::create(self.tool.id());
+ Ok(())
+ }
+ }
+ }
+
++ /// Report false for no IME context or no-op ranges, and error when the selection is not on character boundaries.
+ fn ime_deletion_changes_text(&self, before: usize, after: usize, bytes: bool) -> Result<bool> {
+ let Some(context) = self.ime_text_context() else { return Ok(false) };
+ let Some((before_range, after_range)) = ime_delete_ranges(context.text, context.anchor, context.focus, before, after, bytes) else {
+ return Err(EngineError::Other("the IME text selection is not on character boundaries".into()));
+ };
+ Ok(!before_range.is_empty() || !after_range.is_empty())
+ }
+}
diff --cc crates/fonts/src/fontdb.rs
index 1aa4ec068,1c1e55bd1..2c973b057
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@@ -2208,71 -2200,6 +2208,72 @@@ mod tests_fallback
#[path = "tests_docfonts.rs"]
mod tests_docfonts;
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod native_gui_document_fonts_tests {
+ use super::*;
+
++ /// The production font scope contains the canonical bundled and Japanese faces in their existing order, including bundled Hebrew/Devanagari faces, without system or injected fonts.
+ #[test]
+ fn native_gui_canonical_document_faces_load_without_system_or_added_fonts() {
+ if crate::CRAFT_FONTS.is_empty() {
+ assert!(std::env::var_os("CRAFT_FONTS_REQUIRED").is_none(), "required canonical fonts were not embedded");
+ return; // Optional-input builds retain their supported Latin-only database.
+ }
+ let db = FontDb::with_font_dirs(Vec::new());
+ db.set_system_fallback(false);
+ let scope = db.scoped(0);
+ let japanese = crate::japanese_document_fonts();
+ let previous: Vec<_> = BUNDLED
+ .iter()
+ .copied()
+ .chain(japanese.iter().map(|f| f.bytes))
+ .flat_map(enumerate_faces)
+ .map(|(_, family, style, _)| (family, style))
+ .collect();
+ let loaded: Vec<_> = db.read_faces().iter().map(|f| (f.family.clone(), f.style.clone())).collect();
+ assert!(loaded.len() >= previous.len(), "existing bundled/Japanese faces disappeared");
+ assert_eq!(&loaded[..previous.len()], previous.as_slice(), "preserve all Latin and Japanese face ordering");
+ for family in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] {
+ let face = db.face(family, "Regular");
+ assert_eq!((face.family.as_str(), face.style.as_str(), &face.source), (family, "Regular", &FontSource::Bundled));
+ }
+ assert!(!japanese.is_empty(), "the required central manifest includes the existing Japanese faces");
+ assert!(japanese[0].family.contains("Mincho"));
+ assert_eq!(crate::japanese_ui_fonts(false)[0].family, "BIZ UDPGothic");
+ assert_eq!(crate::japanese_ui_fonts(true)[0].style, "Bold");
+ let latin = db.face(crate::DEFAULT_FAMILY, "Regular");
+ for language in [Some("ja"), None] {
+ assert!(db.fallback_for('語', latin.id(), language).unwrap().family.contains("Mincho"), "Japanese fallback changed: {language:?}");
+ }
+ let mut admitted = Vec::new();
+ for (family, text) in [("Noto Sans Hebrew", "שלום עולם"), ("Noto Sans Devanagari", "नमस्ते दुनिया")] {
+ let embedded: Vec<_> = crate::CRAFT_FONTS.iter().filter(|f| f.family == family && f.style == "Regular").collect();
+ assert_eq!(embedded.len(), 1, "exactly one canonical {family} Regular input");
+ assert!(scope.has_family(family), "production database did not register {family}");
+ assert!(scope.has_style(family, "Regular"), "{family} Regular");
+ assert!(!scope.has_style(family, "Unavailable Native GUI Style"));
+ assert!(db.families().iter().any(|f| f == family), "family catalog omits {family}");
+ assert!(scope.family_infos().iter().any(|f| f.family == family), "menu catalog omits {family}");
+ let face = scope.face(family, "Regular");
+ assert_eq!((face.family.as_str(), face.style.as_str(), &face.source), (family, "Regular", &FontSource::Bundled));
+ assert_eq!(face.data(), embedded[0].bytes, "neither OS discovery nor an injected face may satisfy this contract");
+ for c in text.chars().filter(|c| !c.is_whitespace()) {
+ assert_ne!(face.glyph_for(c), 0, "{family} lacks U+{:04X} ({c})", u32::from(c));
+ let fallback = db.fallback_for(c, latin.id(), None).unwrap();
+ assert_eq!((fallback.family.as_str(), fallback.style.as_str(), &fallback.source), (family, "Regular", &FontSource::Bundled));
+ assert_eq!(fallback.data(), embedded[0].bytes, "document fallback must use the canonical {family} face for {c}");
+ assert_ne!(fallback.glyph_for(c), 0);
+ }
+ let replacement = scope.face(family, "Unavailable Native GUI Style");
+ assert_eq!((replacement.family.as_str(), replacement.style.as_str()), (family, "Regular"), "nearest-style policy stays truthful");
+ admitted.push((family.to_string(), "Regular".to_string()));
+ }
+ assert_eq!(&loaded[previous.len()..], admitted.as_slice(), "only the two deliberate Regular tuples follow the existing document faces");
+ assert!(!scope.has_family("Unavailable Native GUI Family"));
+ assert_eq!(scope.face("Unavailable Native GUI Family", "Regular").family, FALLBACK_FAMILY);
+ }
+}
+
#[cfg(test)]
#[path = "tests_vertical.rs"]
mod tests_vertical;
diff --cc crates/images/src/lib.rs
index 8154f4bfe,3a8facf08..824346340
--- a/crates/images/src/lib.rs
+++ b/crates/images/src/lib.rs
@@@ -60,6 -60,6 +60,7 @@@ pub fn mime(bytes: &[u8]) -> &'static s
}
}
++/// Initialize the process-wide usvg database from the bundled and Japanese fonts, with case-aware family/PostScript resolution, fallback selection and preflighted SVG data URLs; file-backed image URLs are never read.
fn svg_options() -> &'static usvg::Options<'static> {
static OPTS: OnceLock<usvg::Options<'static>> = OnceLock::new();
OPTS.get_or_init(|| {
@@@ -222,69 -207,9 +223,71 @@@ fn add_face(db: &mut Arc<usvg::fontdb::
ids.into_iter().find(|id| db.face(*id).is_some_and(|f| f.index == index))
}
-/// The parsed SVG.
+/// Limits apply before usvg's recursive XML/SVG parsing, including SVGZ output.
+/// Ordinary SVG doctypes are accepted; internal DTD subsets are not, since entity
+/// expansion could introduce markup that the streaming depth check never sees.
+const MAX_SVG_BYTES: usize = 16 * 1024 * 1024;
+const MAX_SVG_EVENTS: usize = 100_000;
+const MAX_SVG_DEPTH: usize = 64;
+
++/// Enforce the encoded-size cap, gunzip SVGZ data with that bound, and return the decoded content within the cap as an owned or borrowed `Cow`.
+fn svg_data(bytes: &[u8]) -> Option<std::borrow::Cow<'_, [u8]>> {
+ use std::io::Read;
+
+ if bytes.len() > MAX_SVG_BYTES {
+ return None;
+ }
+ if bytes.starts_with(&[0x1f, 0x8b]) {
+ let mut xml = Vec::new();
+ flate2::read::GzDecoder::new(bytes).take(MAX_SVG_BYTES as u64 + 1).read_to_end(&mut xml).ok()?;
+ (xml.len() <= MAX_SVG_BYTES).then_some(std::borrow::Cow::Owned(xml))
+ } else {
+ Some(std::borrow::Cow::Borrowed(bytes))
+ }
+}
+
++/// Require UTF-8, bounded XML events, balanced tags and depth at most 64; reject internal DTD subsets while accepting ordinary external doctypes.
+fn svg_preflight(bytes: &[u8]) -> Option<()> {
+ use quick_xml::events::Event;
+
+ let text = std::str::from_utf8(bytes).ok()?;
+ let mut reader = quick_xml::Reader::from_str(text);
+ let mut depth = 0usize;
+ for _ in 0..MAX_SVG_EVENTS {
+ match reader.read_event().ok()? {
+ Event::Start(_) => {
+ depth += 1;
+ if depth > MAX_SVG_DEPTH {
+ return None;
+ }
+ }
+ Event::Empty(_) if depth >= MAX_SVG_DEPTH => return None,
+ Event::End(_) => depth = depth.checked_sub(1)?,
+ Event::DocType(doctype) => {
+ // A '[' inside a quoted external identifier is not an internal subset.
+ let mut quote = None;
+ for &byte in doctype.as_ref() {
+ match (quote, byte) {
+ (Some(q), b) if b == q => quote = None,
+ (None, b'\'' | b'"') => quote = Some(byte),
+ (None, b'[') => return None,
+ _ => {}
+ }
+ }
+ }
+ Event::Eof => return (depth == 0).then_some(()),
+ _ => {}
+ }
+ }
+ None
+}
+
+/// Parse an SVG with at most 16 MiB encoded/decoded data, 100,000 XML events and
+/// 64 nested elements. Reject internal DTD subsets before recursive conversion.
pub fn svg_tree(bytes: &[u8]) -> Option<usvg::Tree> {
- usvg::Tree::from_data(bytes, svg_options()).ok()
+ let xml = svg_data(bytes)?;
+ svg_preflight(&xml)?;
+ usvg::Tree::from_data(&xml, svg_options()).ok()
}
/// Natural size of a placed graphic in points: rasters at 72 ppi (one pixel per point), PSDs
@@@ -578,98 -503,6 +581,106 @@@ mod tests
<text x="110" y="60" font-size="20">Hi</text>
</svg>"##;
++ /// Build an SVG with the requested number of nested `g` wrappers around a leaf rect.
+ fn nested_svg(groups: usize) -> String {
+ format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{}<rect width="10" height="10"/>{}</svg>"#,
+ "<g opacity=\"0.99\">".repeat(groups),
+ "</g>".repeat(groups)
+ )
+ }
+
++ /// Fast-gzip helper for SVGZ tests.
+ fn gzip(bytes: &[u8]) -> Vec<u8> {
+ use std::io::Write;
+
+ let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
+ encoder.write_all(bytes).unwrap();
+ encoder.finish().unwrap()
+ }
+
++ /// A boundary-depth SVG parses into a tree; one level deeper and 2,000 levels are rejected by the tree, size and render APIs.
+ #[test]
+ fn svg_depth_is_checked_before_recursive_parsing() {
+ // Count the SVG root and leaf too; the boundary document still draws its path.
+ let accepted = nested_svg(MAX_SVG_DEPTH - 2);
+ let tree = svg_tree(accepted.as_bytes()).unwrap();
+ assert!(!tree.root().children().is_empty());
+ drop(tree);
+ for depth in [MAX_SVG_DEPTH - 1, 2000] {
+ let rejected = nested_svg(depth);
+ assert!(svg_tree(rejected.as_bytes()).is_none());
+ assert!(natural_size(rejected.as_bytes()).is_none());
+ assert!(render_svg(rejected.as_bytes(), 10).is_none());
+ }
+ }
+
++ /// Markup-looking text in comments, CDATA and attributes does not count as XML depth.
+ #[test]
+ fn svg_depth_ignores_markup_in_comments_cdata_and_attributes() {
+ let markup = "<g>".repeat(2000);
+ let svg = format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><!--{markup}--><desc><![CDATA[{markup}]]></desc><rect data-label="&lt;g>" width="10" height="10"/></svg>"#
+ );
+ assert!(svg_tree(svg.as_bytes()).is_some());
+ }
+
++ /// An external SVG doctype is accepted; an internal entity subset is rejected.
+ #[test]
+ fn svg_external_doctype_is_preserved_but_entity_markup_is_refused() {
+ let external =
+ format!(r#"<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">{}"#, nested_svg(2));
+ assert!(svg_tree(external.as_bytes()).is_some());
+ let internal = r#"<!DOCTYPE svg [<!ENTITY shape "<rect width='10' height='10'/>">]><svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">&shape;</svg>"#;
+ assert!(svg_tree(internal.as_bytes()).is_none());
+ }
+
++ /// The exact 16 MiB document and 100,000-event boundaries are accepted, each one-over case rejected.
+ #[test]
+ fn svg_byte_and_event_limits_are_enforced() {
+ let mut bytes = nested_svg(0).into_bytes();
+ bytes.resize(MAX_SVG_BYTES, b' ');
+ assert!(svg_tree(&bytes).is_some());
+ bytes.push(b' ');
+ assert!(svg_tree(&bytes).is_none());
+
+ let document = |comments| {
+ format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">{}<rect width="10" height="10"/></svg>"#,
+ "<!-- -->".repeat(comments)
+ )
+ };
+ assert!(svg_tree(document(MAX_SVG_EVENTS - 4).as_bytes()).is_some());
+ assert!(svg_tree(document(MAX_SVG_EVENTS - 3).as_bytes()).is_none());
+ }
+
++ /// SVGZ depth, decoded size and malformed gzip follow the plain-SVG limits.
+ #[test]
+ fn svgz_has_the_same_depth_and_decoded_size_limits() {
+ assert!(svg_tree(&gzip(nested_svg(2).as_bytes())).is_some());
+ assert!(svg_tree(&gzip(nested_svg(2000).as_bytes())).is_none());
+ let mut bytes = nested_svg(0).into_bytes();
+ bytes.resize(MAX_SVG_BYTES + 1, b' ');
+ let compressed = gzip(&bytes);
+ assert!(compressed.len() < MAX_SVG_BYTES);
+ assert!(svg_tree(&compressed).is_none());
+ assert!(svg_tree(b"\x1f\x8bnot gzip").is_none());
+ }
+
++ /// Deeply nested SVG data images are omitted without bypassing the depth preflight.
+ #[test]
+ fn nested_svg_data_images_cannot_bypass_the_depth_limit() {
+ let nested = nested_svg(2000);
+ let encoded = nested.bytes().map(|b| format!("%{b:02X}")).collect::<String>();
+ for mime in ["image/svg+xml", "text/plain"] {
+ let svg = format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><image width="10" height="10" href="data:{mime},{encoded}"/></svg>"#
+ );
+ // As with other unreadable data images, the parent survives without the image.
+ assert!(svg_tree(svg.as_bytes()).unwrap().root().children().is_empty());
+ }
+ }
+
#[test]
fn svg_sniff_size_and_render() {
let b = SVG.as_bytes();
diff --cc crates/tools/src/text.rs
index daa68949c,f0503e912..b879760f0
--- a/crates/tools/src/text.rs
+++ b/crates/tools/src/text.rs
@@@ -449,8 -441,8 +449,9 @@@ impl Tool for TypeTool
out
}
++ /// Normalize commit text, cancel marked text, and emit one `text.insert` when text remains and a text selection is active.
fn ime_commit(&mut self, cx: &ToolContext, text: &str) -> Vec<Action> {
- let text: String = text.chars().map(|c| if c == '\r' { '\n' } else { c }).filter(|c| !c.is_control() || matches!(c, '\n' | '\t')).collect();
+ let text = ime_commit_text(text);
// The marked text goes; the result is typed in its place like any typing: one command,
// one undo step.
let mut out = if self.preedit.take().is_some() { vec![Action::Cancel] } else { vec![] };
diff --cc crates/ui-egui/src/canvas.rs
index 8d3e4af8b,75acc32a9..2cfedfaa3
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -476,8 -459,8 +476,9 @@@ fn navigation_space(app: &mut DesignApp
ctx.input(|i| i.focused && i.key_down(egui::Key::Space)) && !app.session.wants_text() && !ctx.text_edit_focused()
}
++/// Allow temporary Zoom only for Cmd+Space with no pointer press and no busy tool.
fn spring_zoom_mode(app: &DesignApp, ctx: &egui::Context, space: bool) -> bool {
- let down = ctx.data(|d| d.get_temp::<bool>(egui::Id::new(("canvas_pointer_down", app.pane)))).unwrap_or(false);
+ let down = ctx.data(|d| d.get_temp::<bool>(egui::Id::unique(("canvas_pointer_down", app.pane)))).unwrap_or(false);
space && ctx.input(|i| i.modifiers.command) && !down && !app.session.tool_busy()
}
@@@ -533,6 -516,6 +534,7 @@@ fn spring_zoom_input(app: &mut DesignAp
true
}
++/// Lay out the canvas, scrollbars and rulers, presentation mode, fit/view state, input handling and painting.
pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let outer = ui.available_rect_before_wrap();
@@@ -2084,6 -2062,6 +2086,7 @@@ fn draw_liquid_pins(painter: &egui::Pai
}
}
++/// Paint ruler bands and ticks, the zero-point crosshair, guide previews, and ticks restarted at each page origin.
#[allow(clippy::too_many_arguments)]
fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) {
let painter = ui.painter_at(full);
@@@ -2496,6 -2474,6 +2499,7 @@@ fn scrollbars(app: &mut DesignApp, ui:
}
}
++/// Give an open menu priority, then handle wheel/zoom/pan, spring Zoom, guide drags and primary pointer routing.
fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect) {
// While a context menu is open (in either pane), the click that closes it and the keys go to the menu.
let menu_open = context_menu_open(ui.ctx());
@@@ -2864,245 -2778,15 +2868,249 @@@ fn ime_event(app: &mut DesignApp, ctx:
app.after_engine();
}
-/// Delete `before` characters before the caret and `after` after it (sizes come from the browser:
-/// a correction never deletes more than a word's worth).
-fn delete_surrounding(app: &mut DesignApp, before: usize, after: usize) -> Result<(), String> {
- for (n, forward) in [(before, false), (after, true)] {
- for _ in 0..n.min(64) {
- app.run("text.delete", json!({"forward": forward}))?;
+/// The bounded committed snapshot and stable target just before an IME mutation.
+struct ImeBefore {
+ target: ImeTarget,
+ stamp: ImeMutationStamp,
+ snapshot: IMESurroundingText,
+ document_uid: u64,
+ document_epoch: u64,
+ story: designcraft_doc::StoryId,
+ cell: Option<designcraft_doc::CellAddr>,
+ anchor: usize,
+ focus: usize,
+}
+
++/// Build a stable owner from the document uid, story and cell identity, plus the document epoch.
+fn ime_target(context: &ImeTextContext<'_>) -> ImeTarget {
+ let owner = egui::Id::unique(("designcraft-ime", context.document_uid, context.story.0, context.cell.map(|c| (c.table, c.row, c.col))));
+ ImeTarget::new(owner, context.document_epoch)
+}
+
++/// Capture the bounded committed surrounding text, mutation stamp, target and selection identity before an IME edit.
+fn capture_ime_before(app: &DesignApp) -> Option<ImeBefore> {
+ let context = app.session.ime_text_context()?;
+ let snapshot = IMESurroundingText::from_text(context.text, context.focus, context.anchor, None);
+ let stamp = ImeMutationStamp::from_surrounding_text(snapshot.clone());
+ Some(ImeBefore {
+ target: ime_target(&context),
+ stamp,
+ snapshot,
+ document_uid: context.document_uid,
+ document_epoch: context.document_epoch,
+ story: context.story,
+ cell: context.cell,
+ anchor: context.anchor,
+ focus: context.focus,
+ })
+}
+
++/// Fold a pending delete-surrounding plus commit into one engine operation, clear marked/target state and record the change.
+fn ime_commit(app: &mut DesignApp, ctx: &egui::Context, text: &str, vi: designcraft_engine::ViewInfo) -> Result<(), String> {
+ let pending = app.pending_ime_delete.take();
+ let before = capture_ime_before(app);
+ let r = if let Some((before_bytes, after_bytes, bytes)) = pending {
+ app.session.ime_commit_after_delete(text, vi, before_bytes, after_bytes, bytes)
+ } else {
+ app.session.ime_commit(text, vi)
+ };
+ app.ime_marked = None;
+ app.ime_target = None;
+ let r = r.map_err(|e| e.to_string());
+ if let Ok(mutation) = &r {
+ note_ime_change(app, ctx, before, mutation.as_ref(), pending);
+ }
+ r.map(|_| ())
+}
+
++/// Apply a pending IME delete unless its composition ended or moved; record the mutation and drop stale marked text.
+fn finish_pending_ime_delete(app: &mut DesignApp, ctx: &egui::Context) {
+ let Some((before_bytes, after_bytes, bytes)) = app.pending_ime_delete.take() else { return };
+ if ime_composition_ended(app) || ime_composition_moved(app) {
+ // The composition ended earlier in this batch: its delete belongs to the copy the system
+ // IME still holds, not to the caret that is there now.
+ drop_stale_ime_events(app);
+ return;
+ }
+ let before = capture_ime_before(app);
+ match app.session.ime_delete_surrounding(before_bytes, after_bytes, bytes) {
+ Ok(mutation) => {
+ // The delete drops the composition (its marked text is not typed): the IME's copy goes.
+ if !app.session.tool_composing() && app.ime_marked.take().is_some() {
+ app.ime_discard = true;
+ }
+ if !app.session.tool_composing() {
+ app.ime_target = None;
+ }
+ note_ime_change(app, ctx, before, mutation.as_ref(), Some((before_bytes, after_bytes, bytes)));
}
+ Err(e) => app.status(e.to_string()),
}
- Ok(())
+ app.after_engine();
+}
+
+/// Record the origin of a successful IME mutation.
+///
+/// A receipt is earned only when the engine reported the exact mutation it applied and the bounded
+/// committed snapshot agrees with it. Smart quotes, autocorrect, tracked changes and any other
+/// application transformation therefore report `Other`, as do failed, stale and no-op mutations.
+fn note_ime_change(
+ app: &mut DesignApp,
+ ctx: &egui::Context,
+ before: Option<ImeBefore>,
+ mutation: Option<&ImeMutation>,
+ delete: Option<(usize, usize, bool)>,
+) {
+ let Some(before) = before else { return };
+ let Some(after) = app.session.ime_text_context() else {
+ let viewport = ctx.viewport_id();
+ app.ime_tracker.note_application_change(viewport, ctx.cumulative_frame_nr_for(viewport), before.target);
+ return;
+ };
+ if ime_target(&after) != before.target {
+ return;
+ }
+ let after_snapshot = IMESurroundingText::from_text(after.text, after.focus, after.anchor, None);
+ if &after_snapshot == before.stamp.surrounding_text() {
+ return;
+ }
+ let after_stamp = ImeMutationStamp::from_surrounding_text(after_snapshot.clone());
+ let viewport = ctx.viewport_id();
+ let frame_nr = ctx.cumulative_frame_nr_for(viewport);
+ if mutation.is_some_and(|m| ime_change_is_exact(&before, &after_snapshot, m, delete)) {
+ app.ime_tracker.note_input_method_apply(viewport, frame_nr, before.target, before.stamp, after_stamp);
+ } else {
+ app.ime_tracker.note_application_change(viewport, frame_nr, before.target);
+ }
+}
+
+/// Does the bounded post-mutation snapshot agree with the mutation the engine applied?
+///
+/// The expected result is built from the reported ranges and typed text — absolute byte offsets in
+/// the whole story, not the truncated outgoing window — so a delete that reaches past the window
+/// still matches. Every visible byte of the after window must agree with it, but a mutation the
+/// after window does not overlap at all (a delete longer than the window) rests on the engine's
+/// report alone, which is exact because the engine computed it from the whole story. A rewrite,
+/// tracked changes or a replaced story is not a receipt.
+fn ime_change_is_exact(before: &ImeBefore, after: &IMESurroundingText, m: &ImeMutation, delete: Option<(usize, usize, bool)>) -> bool {
+ // The same target, selection and text the receipt was captured around.
+ if m.document_uid != before.document_uid
+ || m.document_epoch != before.document_epoch
+ || m.story != before.story
+ || m.cell != before.cell
+ || m.anchor_before != before.anchor
+ || m.focus_before != before.focus
+ {
+ return false;
+ }
+ let (Some(before_payload), Some(after_payload)) = (before.snapshot.available(), after.available()) else { return false };
+ let before_text = before_payload.text.as_str();
+ let after_text = after_payload.text.as_str();
+ let selection = m.anchor_before.min(m.focus_before)..m.anchor_before.max(m.focus_before);
+ // The reported deletion adjoins the selection, is inside the text, and exists only for a
+ // delete-surrounding event. Its exact extent is the engine's: it computes the ranges from the
+ // whole story with the requested counts.
+ if m.deleted_before.end != selection.start
+ || m.deleted_after.start != selection.end
+ || m.deleted_before.start > selection.start
+ || m.deleted_after.end > m.text_len_before
+ {
+ return false;
+ }
+ if delete.is_none() && (!m.deleted_before.is_empty() || !m.deleted_after.is_empty()) {
+ return false;
+ }
+ // The story changed by exactly the removed bytes, the replaced selection and the typed text:
+ // tracked changes and an inserted paragraph return (a table anchor) break this identity.
+ let replaced = if m.inserted.is_empty() { 0 } else { selection.len() };
+ let expected_len = m
+ .text_len_before
+ .saturating_sub(m.deleted_before.len())
+ .saturating_sub(m.deleted_after.len())
+ .saturating_sub(replaced)
+ .saturating_add(m.inserted.len());
+ if m.text_len_after != expected_len {
+ return false;
+ }
+ // A commit collapses the caret after the typed text; a delete keeps the selection, shifted.
+ let (want_anchor, want_focus) = if m.inserted.is_empty() {
+ (m.anchor_before.saturating_sub(m.deleted_before.len()), m.focus_before.saturating_sub(m.deleted_before.len()))
+ } else {
+ let at = m.deleted_before.start + m.inserted.len();
+ (at, at)
+ };
+ if m.anchor_after != want_anchor || m.focus_after != want_focus {
+ return false;
+ }
+ // The text around the caret, rebuilt from the reported mutation. A snapshot's window starts
+ // before its selection's start by the selection's own offset in that window.
+ let before_win = selection.start.saturating_sub(before_payload.cursor.min(before_payload.anchor));
+ let after_selection = m.anchor_after.min(m.focus_after)..m.anchor_after.max(m.focus_after);
+ let after_win = after_selection.start.saturating_sub(after_payload.cursor.min(after_payload.anchor));
+ if after_win.saturating_add(after_payload.cursor) != m.focus_after || after_win.saturating_add(after_payload.anchor) != m.anchor_after {
+ return false;
+ }
+ let before_end = before_win.saturating_add(before_text.len());
+ let after_end = after_win.saturating_add(after_text.len());
+ if before_end > m.text_len_before || after_end > m.text_len_after {
+ return false;
+ }
+ let kept = if m.inserted.is_empty() { selection.len() } else { 0 };
+ let inserted_post = m.deleted_before.start + kept;
+ let tail_post = inserted_post + m.inserted.len();
+ let compared = (|| -> Option<usize> {
+ let mut n = 0usize;
+ n += ime_compare_kept(before_text, before_win..before_end, 0..m.deleted_before.start, 0, after_text, after_win..after_end)?;
+ if kept > 0 {
+ n += ime_compare_kept(before_text, before_win..before_end, selection.clone(), m.deleted_before.start, after_text, after_win..after_end)?;
+ }
+ n += ime_compare_window(after_text, after_win..after_end, &(inserted_post..tail_post), &m.inserted)?;
+ n += ime_compare_kept(
+ before_text,
+ before_win..before_end,
+ m.deleted_after.end..m.text_len_before,
+ tail_post,
+ after_text,
+ after_win..after_end,
+ )?;
+ Some(n)
+ })();
+ compared.is_some()
+}
+
+/// Compare one unchanged piece of the story: the pre-mutation bytes `pre` (absolute) appear at
+/// post-mutation offset `post_start`. Returns the number of bytes compared, or `None` on a
+/// mismatch. Bytes outside the bounded before window cannot be checked and are skipped.
+fn ime_compare_kept(
+ before_text: &str,
+ before_win: std::ops::Range<usize>,
+ pre: std::ops::Range<usize>,
+ post_start: usize,
+ after_text: &str,
+ after_win: std::ops::Range<usize>,
+) -> Option<usize> {
+ let from = pre.start.max(before_win.start);
+ let to = pre.end.min(before_win.end);
+ if from >= to {
+ return Some(0);
+ }
+ let expected = before_text.get(from - before_win.start..to - before_win.start)?;
+ let post = post_start + (from - pre.start)..post_start + (to - pre.start);
+ ime_compare_window(after_text, after_win, &post, expected)
+}
+
+/// Compare `expected`, which begins at absolute post-mutation offset `post.start`, with what the
+/// after window shows of it. Returns the number of bytes compared; `None` when they differ.
+fn ime_compare_window(after_text: &str, after_win: std::ops::Range<usize>, post: &std::ops::Range<usize>, expected: &str) -> Option<usize> {
+ let from = post.start.max(after_win.start);
+ let to = post.end.min(after_win.end);
+ if from >= to {
+ return Some(0);
+ }
+ let actual = after_text.get(from - after_win.start..to - after_win.start)?;
+ let skip = from - post.start;
+ let want = expected.get(skip..skip + (to - from))?;
+ (actual == want).then_some(to - from)
}
/// End a composition outside the IME (a click away, the canvas losing the keyboard): the marked
@@@ -4174,15 -3805,8 +4182,16 @@@ mod tests
}
}
++ /// Build the four-fps app harness used by canvas tests.
fn harness(app: DesignApp) -> Harness<'static, DesignApp> {
- let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
+ harness_with_step(app, 1.0 / 4.0)
+ }
+
+ /// A window whose frames last `step_dt` seconds. Wheel motion is tested at a realistic frame
+ /// rate: egui ends a scroll action after 150 ms without wheel events, so quarter-second
+ /// frames would split every motion into separate actions.
+ fn harness_with_step(app: DesignApp, step_dt: f32) -> Harness<'static, DesignApp> {
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(step_dt).build_ui_state(
|ui, app: &mut DesignApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
@@@ -4409,8 -4026,8 +4418,9 @@@
egui::Event::ModifiersChanged(modifiers)
}
++ /// Construct a point-unit vertical mouse-wheel event with an unknown source.
fn wheel(phase: egui::TouchPhase, up: f32, modifiers: egui::Modifiers) -> egui::Event {
- egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, up), phase, modifiers }
+ egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, up), phase, modifiers, source: egui::MouseWheelSource::Unknown }
}
// Plays `events` with the pointer at `at`, a frame each, and lets the motion settle.
@@@ -4492,6 -4109,6 +4502,7 @@@
app
}
++ /// Run one app frame with the supplied modifiers, install fonts, draw the canvas when ready and return the cursor icon.
fn canvas_frame(app: &mut DesignApp, ctx: &egui::Context, m: egui::Modifiers, mut events: Vec<egui::Event>) -> egui::CursorIcon {
events.insert(0, egui::Event::ModifiersChanged(m));
let mut output = ctx.run_ui(
@@@ -5968,428 -5585,6 +5979,441 @@@
egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) })
}
++ /// Extract `(surrounding text, cursor, anchor)` from an IME output.
+ fn ime_payload(ime: &egui::output::IMEOutput) -> Option<(&str, usize, usize)> {
+ ime.surrounding_text.available().map(|p| (p.text.as_str(), p.cursor, p.anchor))
+ }
+
++ /// Set an engine text selection for a test fixture.
+ fn text_selection(app: &mut DesignApp, sid: &Value, anchor: usize, focus: usize) {
+ app.session.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap();
+ }
+
+ struct NativeClickFixture {
+ app: DesignApp,
+ ctx: egui::Context,
+ target: Value,
+ old: Value,
+ at: Pos2,
+ focus: usize,
+ }
+
++ /// Build the old and target stories, measure an interior target caret, and leave the old story selected before the click.
+ fn native_gui_click_fixture() -> NativeClickFixture {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let old = typing_app(&mut app, &ctx, "Old story");
+ let frame = app.run("frame.create", json!({"rect": [36, 280, 300, 400], "content": "text", "text": "Target story"})).unwrap();
+ let target = frame["story"].clone();
+ // Measure an interior first-word caret through the engine, rather than guessing a
+ // font-dependent screen pixel or clicking the frame's resize border.
+ let (point, focus) = (50..180)
+ .find_map(|x| {
+ app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap();
+ let sel = app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(sel.story.0, target.as_u64().unwrap());
+ (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus))
+ })
+ .expect("an interior point in the target's first word");
+ text_selection(&mut app, &old, "Old story".len(), "Old story".len());
+ for _ in 0..4 {
+ ime_frame(&mut app, &ctx, vec![]);
+ }
+ let at = on_screen(&app, point);
+ assert!(app.canvas_rect.unwrap().contains(at));
+ ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
+ assert_eq!(app.session.doc().unwrap().selection.text.unwrap().story.0, old.as_u64().unwrap());
+ NativeClickFixture { app, ctx, target, old, at, focus }
+ }
+
++ /// Build a primary pointer press or release event at a position.
+ fn native_gui_button(pos: Pos2, pressed: bool) -> egui::Event {
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }
+ }
+
+ /// The 37-byte Devanagari line the native run had in the previous story.
+ const NATIVE_GUI_OLD_DEVANAGARI: &str = "नमस्ते दुनिया";
+
+ /// The click fixture with the non-empty selection in the previous story that the native
+ /// Windows run had (37-byte Devanagari, 0..37). A non-empty selection shows the contextual
+ /// task bar; keep it present but clear of the target click.
+ fn native_gui_selected_old_click_fixture() -> NativeClickFixture {
+ let mut f = native_gui_click_fixture();
+ text_selection(&mut f.app, &f.old, 0, "Old story".len());
+ f.app.run("text.insert", json!({"text": NATIVE_GUI_OLD_DEVANAGARI})).unwrap();
+ text_selection(&mut f.app, &f.old, 0, NATIVE_GUI_OLD_DEVANAGARI.len());
+ for _ in 0..4 {
+ ime_frame(&mut f.app, &f.ctx, vec![]);
+ }
+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((sel.story.0, sel.anchor, sel.focus), (f.old.as_u64().unwrap(), 0, NATIVE_GUI_OLD_DEVANAGARI.len()));
+ assert_eq!(NATIVE_GUI_OLD_DEVANAGARI.len(), 37, "the native fixture's Devanagari line was 37 UTF-8 bytes");
+ assert!(!sel.is_caret(), "the previous story's selection is non-empty");
+ assert!(!context_menu_open(&f.ctx), "no context menu owns this frame's keys");
+ assert!(f.app.ui.dialog.is_none() && f.app.ui.palette.is_none(), "no modal owns the keyboard");
+ assert!(!f.ctx.text_edit_focused(), "no text field owns the keyboard");
+ assert_eq!(f.app.pane, f.app.focus_pane, "the canvas pane takes the keyboard");
+ let task_bar = egui::Id::unique(("task_bar", f.ctx.viewport_id(), f.app.pane));
+ let bar = f.ctx.memory(|m| m.area_rect(task_bar)).expect("the old selection shows the floating task bar");
+ assert!(!bar.contains(f.at), "the floating task bar does not cover the target click at {bar:?}");
+ f
+ }
+
++ /// Run one raw event batch, optionally force a discarded pass, and return the pointer edges observed by each pass.
+ fn native_gui_input(f: &mut NativeClickFixture, events: Vec<egui::Event>, discard: bool) -> Vec<(bool, bool, bool)> {
+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };
+ let mut edges = Vec::new();
+ let mut out = f.ctx.run_ui(raw, |ui| {
+ edges.push(ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin().is_some())));
+ f.app.logic(ui.ctx());
+ f.app.ui(ui);
+ if discard && edges.len() == 1 {
+ ui.ctx().request_discard("native same-batch click exactly-once regression");
+ }
+ });
+ if discard {
+ assert_eq!(out.platform_output.num_completed_passes, 2, "the requested discarded pass actually ran");
+ }
+ out.textures_delta.clear();
+ edges
+ }
+
++ /// Assert that the primary button, canvas press state and tool gesture are all released.
+ fn native_gui_released(f: &NativeClickFixture) {
+ assert!(!f.ctx.input(|i| i.pointer.primary_down()), "the native primary button is up");
+ let down = f.ctx.data(|d| d.get_temp::<bool>(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap_or(false);
+ assert!(!down, "the canvas retained a released pointer");
+ assert!(!f.app.session.tool_busy(), "a released click must not leave a tool gesture");
+ }
+
++ /// Create an independently measured second-story caret farther apart than the double-click distance.
+ fn native_gui_second_click_target(f: &mut NativeClickFixture) -> (Value, Pos2, usize) {
+ let frame = f.app.run("frame.create", json!({"rect": [330, 280, 575, 400], "content": "text", "text": "Second story"})).unwrap();
+ let story = frame["story"].clone();
+ let (point, focus) = (345..465)
+ .find_map(|x| {
+ f.app.run("text.placeCaret", json!({"frame": frame["id"], "point": [x, 290]})).unwrap();
+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(sel.story.0, story.as_u64().unwrap());
+ (1..5).contains(&sel.focus).then_some((Point::new(f64::from(x), 290.0), sel.focus))
+ })
+ .expect("an independently measured interior caret in the second story");
+ text_selection(&mut f.app, &f.old, "Old story".len(), "Old story".len());
+ for _ in 0..4 {
+ ime_frame(&mut f.app, &f.ctx, vec![]);
+ }
+ let at = on_screen(&f.app, point);
+ assert!(f.app.canvas_rect.unwrap().contains(f.at));
+ assert!(f.app.canvas_rect.unwrap().contains(at));
+ let max_click_dist = f.ctx.options(|o| o.input_options.max_click_dist);
+ assert!((at - f.at).length() > max_click_dist, "the two target presses must not form a double click");
+ (story, at, focus)
+ }
+
++ /// Two completed clicks in one batch use the last press once, emit one caret/release pair, add no history, and type at the final caret.
+ #[test]
+ fn native_gui_two_completed_clicks_use_last_primary_press_once() {
+ for reverse in [false, true] {
+ for discard in [false, true] {
+ let mut f = native_gui_click_fixture();
+ let (second, second_at, second_focus) = native_gui_second_click_target(&mut f);
+ let (first_at, last_at, final_story, final_focus) =
+ if reverse { (second_at, f.at, f.target.clone(), f.focus) } else { (f.at, second_at, second.clone(), second_focus) };
+ let initial = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((initial.story.0, initial.anchor, initial.focus), (f.old.as_u64().unwrap(), "Old story".len(), "Old story".len()));
+ let undo = f.app.session.doc().unwrap().history.undo.len();
+ let journal = f.app.session.journal.len();
+ let edges = native_gui_input(
+ &mut f,
+ vec![
+ egui::Event::PointerMoved(first_at),
+ native_gui_button(first_at, true),
+ native_gui_button(first_at, false),
+ egui::Event::PointerMoved(last_at),
+ native_gui_button(last_at, true),
+ native_gui_button(last_at, false),
+ ],
+ discard,
+ );
+ assert_eq!(edges[0], (true, true, false), "both completed clicks leave no held origin");
+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay either press");
+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(
+ (sel.story.0, sel.anchor, sel.focus),
+ (final_story.as_u64().unwrap(), final_focus, final_focus),
+ "reverse={reverse}, discard={discard}"
+ );
+ let commands = &f.app.session.journal[journal..];
+ assert_eq!(
+ commands.iter().filter(|(id, _)| id == "text.placeCaret").count(),
+ 1,
+ "one aggregate canvas selection, reverse={reverse}, discard={discard}"
+ );
+ assert_eq!(
+ commands.iter().filter(|(id, _)| id == "text.release").count(),
+ 1,
+ "one corresponding release, reverse={reverse}, discard={discard}"
+ );
+ let clicks =
+ f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one recovered canvas press");
+ assert_eq!(clicks.n, 1, "separated clicks and discarded passes must not select a word");
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "pointer selection adds no document history");
+ native_gui_released(&f);
+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false);
+ let mut target_text = "Target story".to_owned();
+ let mut second_text = "Second story".to_owned();
+ if reverse {
+ target_text.insert(final_focus, '!');
+ } else {
+ second_text.insert(final_focus, '!');
+ }
+ assert_eq!(story_text(&mut f.app, &f.target), target_text);
+ assert_eq!(story_text(&mut f.app, &second), second_text);
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "typing at the final caret is one edit");
+ native_gui_released(&f);
+ }
+ }
+ }
+
++ /// A non-finite final press rejects the click instead of reviving an earlier valid press; later motion cannot drag.
+ #[test]
+ fn native_gui_nonfinite_final_press_cannot_reuse_an_earlier_click() {
+ for discard in [false, true] {
+ let mut f = native_gui_click_fixture();
+ let at = f.at;
+ let initial = f.app.session.doc().unwrap().selection.text;
+ let undo = f.app.session.doc().unwrap().history.undo.len();
+ let journal = f.app.session.journal.len();
+ let edges = native_gui_input(
+ &mut f,
+ vec![
+ egui::Event::PointerMoved(at),
+ native_gui_button(at, true),
+ native_gui_button(at, false),
+ native_gui_button(pos2(f32::NAN, at.y), true),
+ egui::Event::PointerMoved(at),
+ native_gui_button(at, false),
+ ],
+ discard,
+ );
+ assert_eq!(edges[0], (true, true, false));
+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "discard must not replay malformed input");
+ assert_eq!(
+ f.app.session.doc().unwrap().selection.text,
+ initial,
+ "discard={discard}: reject the last press instead of reviving an earlier valid one"
+ );
+ assert!(f.app.session.journal[journal..].iter().all(|(id, _)| id != "text.placeCaret" && id != "text.release"));
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo);
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ native_gui_released(&f);
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false);
+ assert_eq!(f.app.session.doc().unwrap().selection.text, initial, "motion after the invalid released press cannot drag");
+ native_gui_released(&f);
+ }
+ }
+
++ /// A same-batch click switches story exactly once; typing, undo and redo affect only the target story, including discarded-pass runs.
+ #[test]
+ fn native_gui_same_batch_click_switches_story_once_before_typing() {
+ for discard in [false, true] {
+ let mut f = native_gui_click_fixture();
+ let undo = f.app.session.doc().unwrap().history.undo.len();
+ let at = f.at;
+ let edges =
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], discard);
+ assert_eq!(edges[0], (true, true, false), "the real input consumed both edges and cleared the origin");
+ assert_eq!(edges.iter().filter(|e| e.0).count(), 1, "a discarded pass must not replay the press");
+ let selection = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((selection.story.0, selection.anchor, selection.focus), (f.target.as_u64().unwrap(), f.focus, f.focus), "discard={discard}");
+ let clicks = f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click");
+ assert_eq!(clicks.n, 1, "discard={discard}: replay must not turn a caret into word selection");
+ native_gui_released(&f);
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo, "a click is not a document edit");
+ let end = |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ native_gui_input(&mut f, vec![end(true), end(false)], false);
+ let caret = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((caret.story.0, caret.focus), (f.target.as_u64().unwrap(), "Target story".len()));
+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], false);
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story!");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "one typed edit, including discarded-pass control");
+ f.app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ f.app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story!");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ native_gui_released(&f);
+ }
+ }
+
+ /// The native Windows failure: with a non-empty selection in another story, a click that
+ /// switches stories followed by End in the same job left the new story's caret at the click
+ /// point. End in a later job worked. Drive the actual app UI and actual pointer/key events in
+ /// one batch, in split batches, and with End while the press is still held; discard a pass to
+ /// cover replay. The End press must reach the type tool once and win over the click, wherever
+ /// the pointer release falls, and typing must go there once.
+ #[test]
+ fn native_gui_click_then_end_in_one_batch_keeps_the_target_caret_at_the_story_end() {
+ let names = ["same batch, click events first", "click batch then End batch", "End while the press is held"];
+ for (layout, name) in names.into_iter().enumerate() {
+ for discard in [false, true] {
+ let mut f = native_gui_selected_old_click_fixture();
+ let (at, target, old) = (f.at, f.target.clone(), f.old.clone());
+ let undo = f.app.session.doc().unwrap().history.undo.len();
+ let journal = f.app.session.journal.len();
+ let moved = || egui::Event::PointerMoved(at);
+ let down = || native_gui_button(at, true);
+ let up = || native_gui_button(at, false);
+ let end =
+ |pressed| egui::Event::Key { key: egui::Key::End, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ let batches: Vec<Vec<egui::Event>> = match layout {
+ 0 => vec![vec![moved(), down(), up(), end(true), end(false)]],
+ 1 => vec![vec![moved(), down(), up()], vec![end(true), end(false)]],
+ _ => vec![vec![moved(), down()], vec![end(true)], vec![up(), end(false)]],
+ };
+ for events in batches {
+ native_gui_input(&mut f, events, discard);
+ }
+ let selection = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(
+ (selection.story.0, selection.anchor, selection.focus),
+ (target.as_u64().unwrap(), "Target story".len(), "Target story".len()),
+ "{name}, discard={discard}: End must win after the click, wherever the release falls"
+ );
+ let commands = &f.app.session.journal[journal..];
+ assert_eq!(
+ commands.iter().filter(|(id, _)| id == "text.move").count(),
+ 1,
+ "{name}, discard={discard}: the End press reached the type tool once"
+ );
+ let clicks = f.ctx.data(|d| d.get_temp::<Clicks>(egui::Id::unique(("canvas_clicks", f.app.pane)))).expect("one actual canvas click");
+ assert_eq!(clicks.n, 1, "{name}, discard={discard}: a discarded pass must not replay the press as a word selection");
+ native_gui_released(&f);
+ native_gui_input(&mut f, vec![egui::Event::Text("!".into())], discard);
+ assert_eq!(story_text(&mut f.app, &target), "Target story!", "{name}, discard={discard}: typing lands at the End caret once");
+ assert_eq!(story_text(&mut f.app, &old), NATIVE_GUI_OLD_DEVANAGARI);
+ assert_eq!(
+ f.app.session.journal[journal..].iter().filter(|(id, _)| id == "text.insert").count(),
+ 1,
+ "{name}, discard={discard}: the text event is not replayed"
+ );
+ assert_eq!(f.app.session.doc().unwrap().history.undo.len(), undo + 1, "{name}, discard={discard}: one edit");
+ }
+ }
+ }
+
++ /// Pointer ownership survives a split press/move/release; a real drag selects, release ends it, and later motion cannot continue it.
+ #[test]
+ fn native_gui_split_click_and_drag_release_keep_pointer_ownership() {
+ for drag in [false, true] {
+ let mut f = native_gui_click_fixture();
+ let at = f.at;
+ native_gui_input(&mut f, vec![native_gui_button(at, true)], false);
+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((sel.story.0, sel.focus), (f.target.as_u64().unwrap(), f.focus));
+ assert!(f.ctx.input(|i| i.pointer.primary_down()));
+ assert!(f.ctx.data(|d| d.get_temp::<bool>(egui::Id::unique(("canvas_pointer_down", f.app.pane)))).unwrap());
+ if drag {
+ let moved = at + vec2(60.0, 0.0);
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(moved)], false);
+ let sel = f.app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(sel.story.0, f.target.as_u64().unwrap());
+ assert!(!sel.is_caret(), "a real held drag selects text");
+ }
+ let release = if drag { pos2(-20.0, at.y) } else { at };
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(release), native_gui_button(release, false)], false);
+ native_gui_released(&f);
+ let selection = f.app.session.doc().unwrap().selection.text;
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at + vec2(90.0, 0.0))], false);
+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "motion after release cannot continue the old drag");
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ }
+ }
+
++ /// An unowned outside press, and a press that dismisses an open menu, cannot move the selection or edit either story.
+ #[test]
+ fn native_gui_outside_press_and_open_menu_do_not_click_through() {
+ for menu in [false, true] {
+ let mut f = native_gui_click_fixture();
+ let at = f.at;
+ let selection = f.app.session.doc().unwrap().selection.text;
+ if menu {
+ let blank = f.app.canvas_rect.unwrap().max - vec2(30.0, 30.0);
+ for pressed in [true, false] {
+ let event =
+ egui::Event::PointerButton { pos: blank, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() };
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(blank), event], false);
+ }
+ assert!(context_menu_open(&f.ctx), "the actual secondary click opened the canvas menu");
+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection);
+ native_gui_input(&mut f, vec![egui::Event::PointerMoved(at), native_gui_button(at, true), native_gui_button(at, false)], false);
+ } else {
+ let outside = pos2(-20.0, -20.0);
+ assert!(!f.app.canvas_rect.unwrap().contains(outside));
+ native_gui_input(
+ &mut f,
+ vec![
+ egui::Event::PointerMoved(outside),
+ native_gui_button(outside, true),
+ egui::Event::PointerMoved(at),
+ native_gui_button(at, false),
+ ],
+ false,
+ );
+ }
+ assert_eq!(f.app.session.doc().unwrap().selection.text, selection, "menu={menu}: an unowned press cannot move the old caret");
+ assert_eq!(story_text(&mut f.app, &f.target), "Target story");
+ assert_eq!(story_text(&mut f.app, &f.old), "Old story");
+ native_gui_released(&f);
+ }
+ }
+
++ /// Font inventory distinguishes exact bundled faces, missing styles and missing families without accepting installed or injected substitutes.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn native_gui_font_inventory_keeps_exact_regular_and_missing_style_diagnostics() {
+ if designcraft_fonts::CRAFT_FONTS.is_empty() {
+ assert!(std::env::var_os("CRAFT_FONTS_REQUIRED").is_none(), "required canonical fonts were not embedded");
+ return; // The supported optional-input build has no central document fonts.
+ }
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ for (family, text) in [("Noto Sans Hebrew", "שלום"), ("Noto Sans Devanagari", "नमस्ते")] {
+ assert!(designcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == family && f.style == "Regular"), "canonical {family} Regular absent");
+ for style in ["Regular", "Unavailable Native GUI Style"] {
+ let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap();
+ app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": text.len()})).unwrap();
+ app.run("type.char", json!({"fontFamily": family, "fontStyle": style})).unwrap();
+ }
+ }
+ let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Missing"})).unwrap();
+ app.run("text.select", json!({"story": frame["story"], "anchor": 0, "focus": 7})).unwrap();
+ app.run("type.char", json!({"fontFamily": "Unavailable Native GUI Family", "fontStyle": "Regular"})).unwrap();
+ let inventory = app.run("font.list", json!({})).unwrap();
+ let rows = inventory.as_array().unwrap();
+ assert_eq!(rows.len(), 5, "{inventory}");
+ for family in ["Noto Sans Hebrew", "Noto Sans Devanagari"] {
+ for style in ["Regular", "Unavailable Native GUI Style"] {
+ let row = rows.iter().find(|r| r["family"] == family && r["style"] == style).unwrap();
+ assert_eq!(row["missing"], false, "{row}");
+ assert_eq!(row["styleMissing"], style != "Regular", "{row}");
+ assert_eq!(row["matchStatus"], if style == "Regular" { "exact" } else { "styleSubstitute" }, "{row}");
+ assert_eq!(row["resolvedFamily"], family, "{row}");
+ assert_eq!(row["resolvedStyle"], "Regular", "{row}");
+ assert_eq!(row["source"], "bundled", "an installed or injected face cannot satisfy this production contract: {row}");
+ }
+ }
+ let missing = rows.iter().find(|r| r["family"] == "Unavailable Native GUI Family").unwrap();
+ assert_eq!(missing["missing"], true, "{missing}");
+ assert_eq!(missing["matchStatus"], "missing", "{missing}");
+ assert!(missing["source"].is_null(), "{missing}");
+ }
+
#[test]
#[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may.
fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() {
@@@ -6472,312 -5667,6 +6496,321 @@@
assert_eq!(story_text(&mut app, &sid), "abde日");
}
++ /// Surrounding text is committed text only, preserves reversed selection direction, and a commit keeps owner/generation while reporting `InputMethod`.
+ #[test]
+ fn ime_reports_the_committed_story_and_excludes_the_pre_edit() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "a😀b");
+ let len = "a😀b".len();
+ text_selection(&mut app, &sid, 0, len);
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)), "reversed selection keeps its direction");
+ let owner = (ime.owner, ime.context_generation);
+ // Marked text previews in the document but is not committed surrounding text.
+ let ime = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("a😀b", len, 0)));
+ assert_eq!(ime.owner, owner.0);
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("日", 3, 3)));
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);
+ assert_eq!(story_text(&mut app, &sid), "日");
+ assert_eq!(ime.owner, owner.0);
+ assert_eq!(ime.context_generation, owner.1, "a commit is not a new context");
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("日", 3, 3)), "a later pass reports the same committed text");
+ assert_eq!((ime.owner, ime.context_generation), owner, "an unchanged pass keeps the context");
+ }
+
++ /// An empty story provides `("",0,0)`; long text is bounded and an out-of-window selection is explicitly unavailable.
+ #[test]
+ fn ime_empty_story_is_available_and_wide_text_is_bounded() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ typing_app(&mut app, &ctx, "");
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("", 0, 0)), "an empty document is available, not unavailable");
+ assert!(!app.session.tool_composing());
+
+ let long = "a".repeat(5000);
+ let sid = typing_app(&mut app, &ctx, &long);
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ let (text, _, _) = ime_payload(&ime).expect("a long document still has surrounding text");
+ assert!(text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES, "{}", text.len());
+ text_selection(&mut app, &sid, 0, 5000);
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert!(ime.surrounding_text.available().is_none(), "a selection beyond the bound is explicitly unavailable");
+ }
+
++ /// Caret movement preserves owner; changing story or document changes owner and generation.
+ #[test]
+ fn ime_owner_follows_the_story_and_the_document() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ typing_app(&mut app, &ctx, "ab");
+ let first = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ app.session.execute("text.move", &json!({"dir": "left"})).unwrap();
+ let moved = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_eq!((moved.owner, moved.context_generation), (first.owner, first.context_generation), "a caret move keeps the context");
+
+ let other = app.run("frame.create", json!({"rect": [400, 36, 200, 100], "content": "text", "text": "xy"})).unwrap();
+ let other_sid = other["story"].clone();
+ text_selection(&mut app, &other_sid, 2, 2);
+ let second = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_ne!(second.owner, first.owner, "another story is another owner");
+ assert_ne!(second.context_generation, first.context_generation);
+
+ app.run("file.new", json!({})).unwrap();
+ let doc = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "z"})).unwrap();
+ text_selection(&mut app, &doc["story"], 1, 1);
+ let replaced = ime_frame(&mut app, &ctx, vec![]).expect("a text caret");
+ assert_ne!(replaced.owner, second.owner, "a new document is another owner");
+ assert_eq!(ime_payload(&replaced), Some(("z", 1, 1)));
+ }
+
++ /// Pure commits report `InputMethod`; typing before or after a commit in one pass makes the cause `Other`.
+ #[test]
+ fn ime_cause_distinguishes_commits_from_application_edits() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ typing_app(&mut app, &ctx, "a");
+ let committed = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]).expect("a text caret");
+ assert_eq!(committed.change_cause, egui::output::ImeChangeCause::InputMethod);
+ let typed = ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]).expect("a text caret");
+ assert_eq!(typed.change_cause, egui::output::ImeChangeCause::Other, "ordinary typing is an application edit");
+ assert_eq!(ime_payload(&typed), Some(("a日!", 5, 5)));
+
+ // An application edit before the commit in one pass breaks the receipt chain.
+ let mut before = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ typing_app(&mut before, &ctx, "a");
+ let mixed = ime_frame(&mut before, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("日".into()))])
+ .expect("a text caret");
+ assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other);
+ assert_eq!(ime_payload(&mixed), Some(("ax日", 5, 5)));
+
+ // An application edit after the commit in one pass also dominates.
+ let mut after = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ typing_app(&mut after, &ctx, "a");
+ let mixed = ime_frame(&mut after, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Text("!".into())])
+ .expect("a text caret");
+ assert_eq!(mixed.change_cause, egui::output::ImeChangeCause::Other);
+ assert_eq!(ime_payload(&mixed), Some(("a日!", 5, 5)));
+ }
+
++ /// The settled multipass result rebuilds the current surrounding text while retaining the accepted commit cause.
+ #[test]
+ fn ime_cause_and_context_survive_a_discarded_pass() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ typing_app(&mut app, &ctx, "a");
+ let raw = egui::RawInput {
+ screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))),
+ events: vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))],
+ ..Default::default()
+ };
+ let mut passes = 0;
+ let mut out = ctx.run_ui(raw, |ui| {
+ passes += 1;
+ if passes == 1 {
+ ui.ctx().request_discard("IME multipass regression");
+ }
+ app.logic(ui.ctx());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ assert_eq!(out.platform_output.num_completed_passes, 2, "the frame really was multipass");
+ let ime = out.platform_output.ime.expect("a text caret");
+ assert_eq!(ime_payload(&ime), Some(("a日", 4, 4)), "the second pass rebuilds the current text");
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod, "the discarded pass keeps the accepted commit's cause");
+ }
+
++ /// Autocorrected commit text is an application edit with cause `Other`.
+ #[test]
+ fn ime_autocorrect_is_not_an_input_method_cause() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ app.session.prefs.autocorrect = true;
+ let sid = typing_app(&mut app, &ctx, "teh");
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit(" ".into()))]).expect("a text caret");
+ assert_eq!(story_text(&mut app, &sid), "the ");
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::Other);
+ }
+
++ /// The selection stays selected and directed; byte partials leave whole characters; the deletion is one undo step.
+ #[test]
+ fn ime_delete_surrounding_excludes_the_selection_and_rounds_bytes_inward() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "aé😀b");
+ // Select é, which keeps its bytes and direction; 'a' before and 😀 after go.
+ text_selection(&mut app, &sid, 1, 3);
+ ime_frame(&mut app, &ctx, vec![]);
+ let steps = app.session.doc().unwrap().history.undo.len();
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })])
+ .expect("a text caret");
+ assert_eq!(story_text(&mut app, &sid), "éb");
+ let sel = app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((sel.anchor, sel.focus), (0, 2), "the selected text stays selected and directed");
+ assert_eq!(ime_payload(&ime), Some(("éb", 2, 0)));
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "one deletion is one undo step");
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(story_text(&mut app, &sid), "aé😀b");
+ ime_frame(&mut app, &ctx, vec![]);
+ // The same deletion with a reversed selection keeps anchor > focus.
+ text_selection(&mut app, &sid, 3, 1);
+ ime_frame(&mut app, &ctx, vec![]);
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 4 })])
+ .expect("a text caret");
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);
+ let sel = app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!(story_text(&mut app, &sid), "éb");
+ assert_eq!((sel.anchor, sel.focus), (2, 0), "reversed selection stays reversed");
+
+ // One byte of a two-byte character leaves the whole character.
+ let partial = typing_app(&mut app, &ctx, "aé");
+ text_selection(&mut app, &partial, 1, 1);
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 0, after_bytes: 1 })]);
+ assert_eq!(story_text(&mut app, &partial), "aé");
+ // A preceding count that lands inside the four-byte emoji leaves it whole too.
+ let partial = typing_app(&mut app, &ctx, "a😀");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 2, after_bytes: 0 })]);
+ assert_eq!(story_text(&mut app, &partial), "a😀");
+ }
+
++ /// A 200-character request deletes the whole 100-character story.
+ #[test]
+ fn ime_delete_surrounding_has_no_sixty_four_character_cap() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, &"x".repeat(100));
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 200, after_chars: 0 })]);
+ assert_eq!(story_text(&mut app, &sid), "");
+ }
+
++ /// Delete plus commit in one IME batch produces one undoable edit and reports the final surrounding text.
+ #[test]
+ fn ime_delete_and_commit_are_one_undo_step() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "ab");
+ text_selection(&mut app, &sid, 1, 2);
+ ime_frame(&mut app, &ctx, vec![]);
+ let steps = app.session.doc().unwrap().history.undo.len();
+ let ime = ime_frame(
+ &mut app,
+ &ctx,
+ vec![
+ egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 }),
+ egui::Event::Ime(egui::ImeEvent::Commit("X".into())),
+ ],
+ )
+ .expect("a text caret");
+ assert_eq!(story_text(&mut app, &sid), "X");
+ assert_eq!(ime_payload(&ime), Some(("X", 1, 1)));
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the IME batch is one undo step");
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(story_text(&mut app, &sid), "ab");
+ }
+
+ /// The input method's Commit for a composition a click ended earlier in the same event batch
+ /// must not type the marked text again at the clicked caret.
+ #[test]
+ fn a_commit_after_a_click_in_the_same_batch_is_not_typed_twice() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "ab");
+ ime_frame(&mut app, &ctx, vec![preedit("い", 1)]);
+ assert_eq!(story_text(&mut app, &sid), "abい");
+ let p = on_screen(&app, Point::new(150.0, 120.0));
+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
+ ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))])
+ .expect("still at a text caret");
+ let typed = story_text(&mut app, &sid);
+ assert_eq!(typed.matches('い').count(), 1, "the click typed the marked text once: {typed:?}");
+ assert!(typed.starts_with("ab"), "{typed:?}");
+ assert!(!app.session.tool_composing());
+ assert!(app.take_ime_discard(), "the system IME is told to drop its copy");
+ ime_frame(&mut app, &ctx, vec![press(false)]);
+ }
+
+ /// A delete-surrounding and its commit from the same ended composition must not edit the
+ /// clicked caret's text either.
+ #[test]
+ fn a_delete_and_commit_after_a_click_in_the_same_batch_are_dropped() {
+ for delete in [
+ egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 },
+ egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 },
+ ] {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "ab");
+ ime_frame(&mut app, &ctx, vec![preedit("い", 1)]);
+ let p = on_screen(&app, Point::new(150.0, 120.0));
+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
+ ime_frame(
+ &mut app,
+ &ctx,
+ vec![egui::Event::PointerMoved(p), press(true), egui::Event::Ime(delete), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))],
+ )
+ .expect("still at a text caret");
+ let typed = story_text(&mut app, &sid);
+ assert_eq!(typed.matches('い').count(), 1, "the late commit is dropped: {typed:?}");
+ assert!(typed.contains("ab"), "the click's text was not deleted: {typed:?}");
+ assert!(app.take_ime_discard());
+ ime_frame(&mut app, &ctx, vec![press(false)]);
+ }
+ }
+
+ /// A byte-count delete that reaches past the bounded IME window is still exactly the requested
+ /// input method mutation: the engine reports the ranges from the whole story.
+ #[test]
+ fn a_delete_beyond_the_surrounding_window_is_still_an_input_method_cause() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, &"x".repeat(5000));
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 4500, after_bytes: 0 })])
+ .expect("a text caret");
+ assert_eq!(story_text(&mut app, &sid).len(), 500);
+ assert_eq!(ime.change_cause, egui::output::ImeChangeCause::InputMethod);
+ assert_eq!(ime_payload(&ime).map(|(text, cursor, anchor)| (text.len(), cursor, anchor)), Some((500, 500, 500)));
+ }
+
+ /// The pass's IME observation comes after the later UI sections: a click into the Story
+ /// Editor's field takes the keyboard from the canvas in the same pass, so the composition
+ /// ends there and the canvas reports no IME.
+ #[test]
+ fn a_later_field_taking_the_keyboard_ends_the_composition_in_that_pass() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let f = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap();
+ let sid = f["story"].clone();
+ app.select_tool("type");
+ app.run("text.select", json!({"story": sid, "anchor": 2, "focus": 2})).unwrap();
+ app.run("app.storyEditor", json!({"story": sid})).unwrap();
+ let mut h = crate::test_window::open(app, egui::vec2(1440.0, 900.0));
+ h.event(preedit("い", 1));
+ h.run_steps(2);
+ assert!(h.state().app.session.tool_composing());
+ let canvas_owner = h.output().platform_output.ime.as_ref().expect("the canvas owns the composition").owner;
+ let field = h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().expect("the Story Editor's text field");
+ field.click();
+ h.run_steps(2);
+ assert!(!h.state().app.session.tool_composing(), "the composition ended where the field took the keyboard");
+ assert!(h.state_mut().app.take_ime_discard());
+ assert!(h.get_all_by_role(egui::accesskit::Role::MultilineTextInput).next().unwrap().is_focused(), "the field has the keyboard");
+ let ime = h.output().platform_output.ime.as_ref().expect("the focused Story Editor publishes its IME context");
+ assert_ne!(ime.owner, canvas_owner, "the field owns the IME, not the canvas");
+ let typed = story_text(&mut h.state_mut().app, &sid);
+ assert!(typed.contains('い'), "the marked text stays as typed: {typed:?}");
+ h.event(egui::Event::Ime(egui::ImeEvent::Commit("X".into())));
+ h.run_steps(2);
+ let edited = story_text(&mut h.state_mut().app, &sid);
+ assert_eq!(edited.matches('X').count(), 1, "the field's next commit is applied once: {edited:?}");
+ assert_eq!(edited.matches('い').count(), 1, "the old canvas composition is not replayed: {edited:?}");
+ }
+
#[test]
fn clicking_away_mid_composition_keeps_the_text_and_interrupts_the_ime() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
@@@ -6972,6 -5861,6 +7005,7 @@@ mod scrollbar_tests
h.run_steps(3);
}
++ /// Scrollbars sit immediately outside the view, have non-full-size thumbs and use a positive content scale.
#[test]
fn document_views_have_scrollbars_beside_the_view() {
let h = window();
@@@ -7019,6 -5908,6 +7053,7 @@@
assert!((next.y - paged.y - view).abs() < 0.01, "{next:?} → {paged:?}, want -{view}");
}
++ /// Wheel scrolling moves both thumbs and keeps the painted scrollbar rect in sync.
#[test]
fn scrolling_the_view_moves_the_thumbs() {
let mut h = window();
diff --cc crates/ui-egui/src/chrome.rs
index 34d6cfb5e,c6ba485c6..dd7ef2807
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@@ -180,6 -180,6 +180,7 @@@ fn tools_slot_width(available: f32, too
(available - 1.0).max(tools_w)
}
++/// Lay out the application bar, native/custom title handling, menu and tool scrolling, drag region, caption controls and search.
pub fn app_bar(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let mac = app.integrated_titlebar;
@@@ -660,6 -656,6 +661,7 @@@ fn control_text(app: &mut DesignApp, ui
}
}
++/// Draw the character-mode controls and issue their corresponding text commands.
fn control_character(
app: &mut DesignApp,
ui: &mut egui::Ui,
@@@ -1033,6 -1029,6 +1035,7 @@@ const DOC_TAB_MAX_W: f32 = 260.0
/// Close button and padding around a tab's title.
const DOC_TAB_PAD: f32 = 44.0;
++/// Draw bounded document tabs with active, dirty, preview and zoom state, plus activation and close actions.
pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
diff --cc crates/ui-egui/src/dialogs.rs
index 5b30a372d,23ab08b31..e93e64679
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -2161,6 -2242,6 +2253,7 @@@ fn check(ui: &mut egui::Ui, d: &mut Dia
}
}
++/// Draw the active localized dialog; open popups own Enter/Escape, and result handling drives confirm or cancel.
pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
let Some(mut d) = app.ui.dialog.clone() else { return };
// Enter and Escape belong to an open popup (a menu, a name field) rather than the dialog.
diff --cc crates/ui-egui/src/dialogs/options.rs
index 4f192cd7d,d8aba2bea..28005e7ac
--- a/crates/ui-egui/src/dialogs/options.rs
+++ b/crates/ui-egui/src/dialogs/options.rs
@@@ -94,6 -94,6 +94,7 @@@ fn caption(ui: &mut egui::Ui, lang: &st
crate::rtl::label(ui, tr(lang, s));
}
++/// Render a labelled, bounded colour-channel spinner, name it for accessibility and write changed values to dialog fields.
fn channel(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, max: f64, suffix: &str) {
ui.label(egui::RichText::new(label).monospace());
let mut v = d.n(key).unwrap_or(0.0);
diff --cc crates/ui-egui/src/lib.rs
index 0141e16a4,26ea71f59..055343fe8
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -776,6 -676,6 +775,7 @@@ struct QuitState
}
impl DesignApp {
++ /// Start the background font scan, establish the monotonic timing origin, and initialize document, view, input, screenshot, dialog and control state.
pub fn new(session: Session, services: Services) -> Self {
// The font menus and the first file opened need the installed fonts: catalog them now.
designcraft_fonts::FontDb::global().scan_in_background();
@@@ -1777,104 -1533,10 +1777,107 @@@
egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } => 1,
_ => events.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(events.len(), |i| i + 1),
};
- if let egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } = first {
- raw.events.push(egui::Event::PointerMoved(*p));
+ let batch: Vec<egui::Event> = events.drain(..n).collect();
+ self.injected_generation = self.input_generation();
+ self.injected_private = private;
+ self.injected_events = batch.clone();
+ self.injected_pending.store(true, std::sync::atomic::Ordering::Relaxed);
+ raw.events.extend(batch);
+ // Held until a settled UI pass runs with the fonts installed; a hidden logic tick, a
+ // discarded multipass first pass or a font-gated early return must not acknowledge it.
+ self.synthetic_injected = true;
+ }
+
+ /// Notify after enqueuing a native menu event, before waking the host. The returned callback
+ /// owns its state so the event handler never borrows the app.
+ pub fn native_action_notifier(&self, ctx: egui::Context) -> Box<dyn Fn() + Send + Sync> {
+ let pending = self.native_events_pending.clone();
+ Box::new(move || {
+ pending.store(true, std::sync::atomic::Ordering::Release);
+ ctx.request_repaint();
+ })
+ }
+
+ /// Poll from the first real UI pass, under the host's normal UI/watchdog guard. Resolve menu
+ /// choices before refreshing their IDs, then execute them once synthetic input has settled.
+ /// Event arrival already blocks logic deliveries, so a deferred action keeps its ordering
+ /// without executing native dialogs or menu commands from a hidden logic-only tick.
+ pub fn poll_native_actions(&mut self, ctx: &egui::Context, mut next: impl FnMut() -> Option<(String, Value)>) {
+ // Clear before draining: a notification arriving during the drain stays set for the
+ // next pass, even when its channel send races the final empty receive.
+ self.native_events_pending.swap(false, std::sync::atomic::Ordering::AcqRel);
+ while let Some((id, params)) = next() {
+ self.native_actions.push_back((id, params));
+ }
+ self.apply_native_actions(ctx);
+ }
+
++ /// True while an injected batch, control synthetic event or ordinary synthetic event remains queued.
+ fn synthetic_input_pending(&self) -> bool {
+ self.synthetic_injected || !self.control_synthetic.is_empty() || !self.synthetic.is_empty()
+ }
+
++ /// True when synthetic input, a queued native action or a pending native-event notification remains.
+ fn host_order_pending(&self) -> bool {
+ self.synthetic_input_pending() || !self.native_actions.is_empty() || self.native_events_pending.load(std::sync::atomic::Ordering::Acquire)
+ }
+
++ /// Execute queued native actions only after synthetic input settles, and request another repaint while host work remains.
+ fn apply_native_actions(&mut self, ctx: &egui::Context) {
+ while !self.synthetic_input_pending() {
+ let Some((id, params)) = self.native_actions.pop_front() else { break };
+ menus::activate_native(self, ctx, &id, &params);
+ }
+ if self.host_order_pending() {
+ ctx.request_repaint();
}
- raw.events.extend(events.drain(..n));
+ }
+
+ /// The current state an injected batch belongs to.
+ fn input_generation(&self) -> InputGeneration {
+ InputGeneration {
+ document: self.active_document_epoch(),
+ dialog: self.ui.dialog.as_ref().map(|dialog| egui::Id::unique(&dialog.id)),
+ focus: self.egui_ctx.as_ref().and_then(|ctx| ctx.memory(|memory| memory.focused())),
+ }
+ }
+
+ /// Drop a batch whose document, dialog or focus changed before a UI pass could take it.
+ /// The batch is still in the host's pending raw input; remove exactly the events we appended
+ /// (contiguously, in order) so a subsequent forced paint cannot replay stale input.
+ fn discard_stale_injected_batch(&mut self, raw: &mut egui::RawInput) {
+ if !self.synthetic_injected || self.input_generation() == self.injected_generation {
+ return;
+ }
+ let events = std::mem::take(&mut self.injected_events);
+ if !events.is_empty()
+ && let Some(start) = raw.events.windows(events.len()).rposition(|window| window == events.as_slice())
+ {
+ raw.events.drain(start..start + events.len());
+ }
+ self.synthetic_injected = false;
+ self.injected_pending.store(false, std::sync::atomic::Ordering::Relaxed);
+ self.injected_private = false;
+ self.control_input_frame.store(false, std::sync::atomic::Ordering::Relaxed);
+ }
+
+ /// A font-gated first pass saw the events before any widget did. Put the same batch back at
+ /// the front of its queue (with the original provenance) so a later UI pass consumes it.
+ fn requeue_injected_batch(&mut self) {
+ if !std::mem::take(&mut self.synthetic_injected) {
+ return;
+ }
+ let events = std::mem::take(&mut self.injected_events);
+ if !events.is_empty() {
+ if self.injected_private {
+ self.control_synthetic.splice(0..0, events);
+ } else {
+ self.synthetic.splice(0..0, events);
+ }
+ }
+ self.injected_pending.store(false, std::sync::atomic::Ordering::Relaxed);
+ self.injected_private = false;
+ self.control_input_frame.store(false, std::sync::atomic::Ordering::Relaxed);
}
/// Lay out the whole window.
@@@ -2073,16 -1685,9 +2076,17 @@@
self.perf.frame_ms = now_ms() - t0;
}
++ /// Defer control commands while host-order input is pending; otherwise handle replies and screenshot admission.
fn drain_control(&mut self, ctx: &egui::Context) {
+ // An injected batch may still be waiting in the host's pending raw input. Running another
+ // control command now could switch documents or dialogs under it, so keep the channel
+ // queued until a settled UI pass has taken the batch.
+ if self.host_order_pending() {
+ return;
+ }
let Some(rx) = self.control_rx.take() else { return };
- while let Ok(req) = rx.try_recv() {
+ while !self.host_order_pending() {
+ let Ok(req) = rx.try_recv() else { break };
let reply = req.reply.clone();
match control::handle(self, ctx, &req) {
control::Outcome::Done(v) => {
@@@ -3343,1119 -2733,6 +3347,1165 @@@ mod tests
app.run("text.select", json!({"story": story, "anchor": 2})).unwrap();
assert_eq!(app.run("edit.paste", json!({})).unwrap()["anchored"], 1);
}
+
+ // ---------------------------------------------------------------------------------------
+ // egui 0.37 lifecycle, hidden input and screenshot completion regressions.
+ // ---------------------------------------------------------------------------------------
+
+ /// One frame of the real callback order the native and web hosts use.
+ fn shot_frame(app: &mut DesignApp, ctx: &egui::Context, size: egui::Vec2) -> egui::FullOutput {
+ shot_frame_at(app, ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size), true)
+ }
+
+ /// One frame at a chosen window rect. `inner_rect = false` is the web/egui_kittest shape:
+ /// `screen_rect` is set but `ViewportInfo::inner_rect` is not.
+ fn shot_frame_at(app: &mut DesignApp, ctx: &egui::Context, rect: egui::Rect, inner_rect: bool) -> egui::FullOutput {
+ let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
+ raw.viewports.insert(
+ egui::ViewportId::ROOT,
+ egui::ViewportInfo {
+ inner_rect: inner_rect.then_some(rect),
+ native_pixels_per_point: Some(1.0),
+ minimized: Some(false),
+ occluded: Some(false),
+ ..Default::default()
+ },
+ );
+ let mut output = ctx.run_ui(raw, |ui| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ });
+ output.textures_delta.clear();
+ output
+ }
+
+ /// A hidden host iteration: the raw input is prepared and then only the logic callback runs.
+ fn hidden_tick(app: &mut DesignApp, ctx: &egui::Context, raw: &mut egui::RawInput) -> egui::LogicOutput {
+ app.raw_input_hook(ctx, raw);
+ ctx.run_logic(raw, |ctx| app.logic(ctx))
+ }
+
++ /// Build a 640x480 root viewport marked minimized and occluded.
+ fn hidden_raw() -> egui::RawInput {
+ let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0));
+ let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
+ raw.viewports.insert(
+ egui::ViewportId::ROOT,
+ egui::ViewportInfo {
+ inner_rect: Some(rect),
+ native_pixels_per_point: Some(1.0),
+ minimized: Some(true),
+ occluded: Some(true),
+ ..Default::default()
+ },
+ );
+ raw
+ }
+
++ /// Count root `RequestPaintWhileHidden` commands.
+ fn hidden_paints(output: &egui::LogicOutput) -> usize {
+ output
+ .viewport_commands
+ .get(&egui::ViewportId::ROOT)
+ .map_or(0, |commands| commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaintWhileHidden)).count())
+ }
+
++ /// Remove and return the root screenshot callback, replacing its command with `Focus`.
+ fn screenshot_callback(output: &mut egui::FullOutput) -> Option<egui::ScreenshotCallback> {
+ let viewport = output.viewport_output.get_mut(&egui::ViewportId::ROOT)?;
+ for command in &mut viewport.commands {
+ if matches!(command, egui::ViewportCommand::Screenshot(_)) {
+ let egui::ViewportCommand::Screenshot(callback) = std::mem::replace(command, egui::ViewportCommand::Focus) else {
+ return None;
+ };
+ return Some(callback);
+ }
+ }
+ None
+ }
+
++ /// Create a recording-write app with a new document and four settling frames.
+ fn screenshot_app() -> (DesignApp, egui::Context, std::sync::Arc<std::sync::Mutex<Vec<(String, usize)>>>) {
+ let writes: std::sync::Arc<std::sync::Mutex<Vec<(String, usize)>>> = Default::default();
+ let sink = writes.clone();
+ let mut app = DesignApp::new(
+ Session::new(),
+ Services {
+ write: Some(Box::new(move |path, bytes| {
+ sink.lock().unwrap().push((path.to_string(), bytes.len()));
+ Ok(())
+ })),
+ ..Default::default()
+ },
+ );
+ app.run("file.new", json!({"title": "shots"})).unwrap();
+ let ctx = egui::Context::default();
+ for _ in 0..4 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ output.textures_delta.clear();
+ }
+ (app, ctx, writes)
+ }
+
++ /// The callback only fills a slot; the next logic pass writes and replies once and releases admission.
+ #[test]
+ fn screenshot_callback_stays_weak_and_writes_only_from_logic() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let (reply, replies) = std::sync::mpsc::channel();
+ let path = std::env::temp_dir().join(format!("designcraft-shot-{}.png", std::process::id()));
+ app.admit_screenshot(Some(path.to_string_lossy().to_string()), reply).unwrap();
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ callback = Some(cb);
+ }
+ }
+ let callback = callback.expect("the settling frames issue one capture");
+ assert!(writes.lock().unwrap().is_empty());
+ // The callback only fills its slot; writing happens in the next logic pass.
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ assert!(writes.lock().unwrap().is_empty(), "the callback must not write files");
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ let written = writes.lock().unwrap().clone();
+ assert_eq!(written.len(), 1, "one file after the logic drain");
+ assert_eq!(written[0].0, path.to_string_lossy());
+ let reply = replies.recv().unwrap();
+ assert_eq!(reply["ok"], true, "{reply}");
+ assert_eq!(reply["result"]["width"], 640);
+ assert_eq!(reply["result"]["height"], 480);
+ assert!(app.pending_shots.is_empty(), "the reservation is released");
+ }
+
++ /// Admission enforces the request count, aggregate RGBA byte budget and per-image limit before capture.
+ #[test]
+ fn screenshot_admission_bounds_count_aggregate_and_image_bytes() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let admit = |app: &mut DesignApp, path: &str| {
+ let (reply, _replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(Some(path.into()), reply)
+ };
+ for i in 0..SCREENSHOT_MAX_REQUESTS {
+ assert!(admit(&mut app, &format!("shot-{i}.png")).is_ok(), "request {i}");
+ }
+ let error = admit(&mut app, "too-many.png").unwrap_err();
+ assert_eq!(error["ok"], false, "{error}");
+ // Drain the admitted requests without replying so the byte-budget check is exercised.
+ app.pending_shots.clear();
+ app.queued_shots.clear();
+ for _ in 0..2 {
+ shot_frame(&mut app, &ctx, egui::vec2(5120.0, 5120.0));
+ }
+ assert!(admit(&mut app, "hundred-a.png").is_ok());
+ assert!(admit(&mut app, "hundred-b.png").is_ok());
+ let error = admit(&mut app, "over-aggregate.png").unwrap_err();
+ assert!(error["error"].as_str().unwrap_or_default().contains("budget"), "{error}");
+ app.pending_shots.clear();
+ app.queued_shots.clear();
+ for _ in 0..2 {
+ shot_frame(&mut app, &ctx, egui::vec2(6000.0, 6000.0));
+ }
+ let error = admit(&mut app, "too-large.png").unwrap_err();
+ assert!(error["error"].as_str().unwrap_or_default().contains("image limit"), "{error}");
+ }
+
++ /// A resize invalidates in-flight pixels and retries within the deadline; a timeout errors and late callbacks are inert.
+ #[test]
+ fn screenshot_epoch_change_and_timeout_drop_stale_pixels() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let (reply, replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(Some("stale.png".into()), reply).unwrap();
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ callback = Some(cb);
+ }
+ }
+ let callback = callback.expect("issued");
+ // Resize away and back: the epoch advances even though the size ends up the same.
+ shot_frame(&mut app, &ctx, egui::vec2(800.0, 600.0));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ callback.clone().complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert!(replies.try_recv().is_err(), "stale pixels must not be replied");
+ assert!(!app.queued_shots.is_empty(), "the request is retried inside its deadline");
+ assert!(writes.lock().unwrap().is_empty());
+ // Let the deadline pass: the retry reports an error and a later callback is inert.
+ app.pending_shots[0].deadline = 0.0;
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ let reply = replies.try_recv().unwrap();
+ assert_eq!(reply["ok"], false, "{reply}");
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert!(replies.try_recv().is_err(), "no second reply from a late callback");
+ assert!(writes.lock().unwrap().is_empty());
+ assert!(app.pending_shots.is_empty());
+ }
+
++ /// A host without `inner_rect` uses `screen_rect` and can still admit and complete a capture.
+ #[test]
+ fn screenshot_geometry_uses_screen_rect_when_inner_rect_is_absent() {
+ let (mut app, ctx, writes) = screenshot_app();
+ app.screenshot_geometry = None;
+ app.screenshot_epoch = 0;
+ let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0));
+ // Web eframe and egui_kittest set screen_rect but not ViewportInfo::inner_rect.
+ for _ in 0..2 {
+ shot_frame_at(&mut app, &ctx, rect, false);
+ }
+ let geometry = app.screenshot_geometry.expect("the screen rect is the logical viewport");
+ assert_eq!((geometry.width, geometry.height), (640, 480), "the fallback is the same logical geometry");
+ let (reply, replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(Some("web-like.png".into()), reply).expect("an inner-rect-less host admits screenshots");
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ for _ in 0..3 {
+ if let Some(cb) = screenshot_callback(&mut shot_frame_at(&mut app, &ctx, rect, false)) {
+ callback = Some(cb);
+ }
+ }
+ callback.expect("the capture is issued").complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame_at(&mut app, &ctx, rect, false);
+ let reply = replies.recv().unwrap();
+ assert_eq!(reply["ok"], true, "{reply}");
+ assert_eq!(writes.lock().unwrap().len(), 1);
+ }
+
++ /// Apply native pixels-per-point and UI zoom exactly once.
+ #[test]
+ fn screenshot_geometry_applies_native_dpi_and_zoom_once() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ app.ui.ui_scale = 1.5;
+ let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 50.0));
+ let raw = {
+ let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
+ raw.viewports.insert(
+ egui::ViewportId::ROOT,
+ egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(2.0), minimized: Some(false), ..Default::default() },
+ );
+ raw
+ };
+ // The first pass applies the zoom; the next logic tick measures the new geometry.
+ for _ in 0..2 {
+ let mut raw = raw.clone();
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().inner_rect = Some(rect);
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ }
+ let geometry = app.screenshot_geometry.expect("geometry");
+ // 100 x 50 points at 2 physical pixels per point and 1.5 UI zoom: apply each exactly once.
+ assert_eq!((geometry.width, geometry.height), (300, 150));
+ }
+
++ /// Moving the window leaves the capture epoch unchanged; resizing and resizing back advance it.
+ #[test]
+ fn screenshot_epoch_ignores_window_position_but_tracks_size_changes() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let before = app.screenshot_epoch;
+ let moved = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0));
+ shot_frame_at(&mut app, &ctx, moved, true);
+ assert_eq!(app.screenshot_epoch, before, "moving the window is not a capture-surface change");
+ shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(800.0, 600.0)), true);
+ let resized = app.screenshot_epoch;
+ assert_ne!(resized, before, "a size change advances the epoch");
+ shot_frame_at(&mut app, &ctx, egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(640.0, 480.0)), true);
+ assert_ne!(app.screenshot_epoch, resized, "and resizing back advances it again");
+ }
+
++ /// `ui.screenshot` is admitted, waits for capture, then writes once and replies with the dimensions.
+ #[test]
+ fn control_screenshot_replies_with_the_saved_capture() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let (requests, receiver) = std::sync::mpsc::channel();
+ app = app.with_control(receiver);
+ let (reply, replies) = std::sync::mpsc::channel();
+ requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap();
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted, not issued from the queue");
+ assert!(replies.try_recv().is_err(), "the reply waits for the capture");
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ for _ in 0..3 {
+ if let Some(cb) = screenshot_callback(&mut shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0))) {
+ callback = Some(cb);
+ }
+ }
+ let callback = callback.expect("the settled frames issue one capture");
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ let reply = replies.recv().unwrap();
+ assert_eq!(reply["ok"], true, "{reply}");
+ assert_eq!(reply["result"]["width"], 640);
+ assert_eq!(reply["result"]["height"], 480);
+ let written = writes.lock().unwrap().clone();
+ assert_eq!(written.len(), 1);
+ assert_eq!(written[0].0, "control.png");
+ assert!(written[0].1 > 0);
+ assert!(app.pending_shots.is_empty(), "the reservation is released");
+ assert!(app.queued_shots.is_empty());
+ }
+
++ /// A timed-out capture replies with a no-frame error and writes no file.
+ #[test]
+ fn control_screenshot_times_out_without_writing_a_file() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let (requests, receiver) = std::sync::mpsc::channel();
+ app = app.with_control(receiver);
+ let (reply, replies) = std::sync::mpsc::channel();
+ requests.send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "control.png", "focus": false}), reply }).unwrap();
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert_eq!(app.pending_shots.len(), 1);
+ app.pending_shots[0].deadline = 0.0;
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ let reply = replies.recv().unwrap();
+ assert_eq!(reply["ok"], false, "{reply}");
+ assert!(reply["error"].as_str().unwrap_or_default().contains("no frame"), "{reply}");
+ assert!(writes.lock().unwrap().is_empty(), "a timed-out request writes no file");
+ assert!(app.pending_shots.is_empty());
+ }
+
++ /// A multipass frame ticks for every pass but runs once-per-frame work once.
+ #[test]
+ fn discarded_pass_runs_the_frame_stage_once_but_ticks_every_pass() {
+ let mut app = DesignApp::new(Session::new(), Services::default());
+ app.run("file.new", json!({"title": "multipass"})).unwrap();
+ let ctx = egui::Context::default();
+ let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 600.0));
+ let mut raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() };
+ raw.viewports
+ .insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), ..Default::default() });
+ let mut passes = 0;
+ let mut output = ctx.run_ui(raw, |ui| {
+ passes += 1;
+ if passes == 1 {
+ // Requested before `app.ui` so the first pass is a discarded one and must not
+ // acknowledge injected input.
+ ui.ctx().request_discard("forced multipass regression");
+ }
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ });
+ assert_eq!(output.platform_output.num_completed_passes, 2, "the frame really was multipass");
+ // 0.37's TexturesDelta panics if dropped unapplied; this test only inspects the passes.
+ output.textures_delta.clear();
+ assert_eq!(app.logic_tick_ticks, 2, "every pass ticks queues and deadlines");
+ assert_eq!(app.logic_frame_ticks, 1, "once-per-frame work runs once");
+ assert_eq!(app.input_ticks, 2);
+ }
+
++ /// Hidden logic requests one paint per tick, injects one queued step at a time, treats unknown visibility as hidden, and lets one visible pass consume the step.
+ #[test]
+ fn hidden_logic_requests_exactly_one_paint_per_tick_until_a_settled_ui_pass() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let mut raw = hidden_raw();
+ // Three pointer steps queued: one batch may be in the host's pending raw input at a time.
+ app.control_synthetic = vec![
+ egui::Event::PointerMoved(egui::pos2(10.0, 10.0)),
+ egui::Event::PointerMoved(egui::pos2(20.0, 20.0)),
+ egui::Event::PointerMoved(egui::pos2(30.0, 30.0)),
+ ];
+ app.raw_input_hook(&ctx, &mut raw);
+ let injected = raw.events.clone();
+ assert_eq!(app.injected_events.len(), 1, "one pointer event in the batch");
+ assert_eq!(app.control_synthetic.len(), 2, "the rest wait for later host iterations");
+ for tick in 0..3 {
+ let output = hidden_tick(&mut app, &ctx, &mut raw);
+ assert_eq!(hidden_paints(&output), 1, "tick {tick}: exactly one hidden paint request");
+ assert!(app.synthetic_injected, "the injected step is still unapplied");
+ assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "control provenance is retained while hidden");
+ assert_eq!(raw.events, injected, "tick {tick}: no second batch accumulated into the pending raw input");
+ assert_eq!(app.control_synthetic.len(), 2, "tick {tick}: the queue did not drain another step");
+ }
+ // A real visible UI pass takes exactly the one pending event (no duplicated PointerMoved).
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false);
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().occluded = Some(false);
+ let mut seen = Vec::new();
+ ctx.run_ui(raw, |ui| {
+ seen = ui.ctx().input(|i| i.events.clone());
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert_eq!(seen.iter().filter(|event| matches!(event, egui::Event::PointerMoved(_))).count(), 1);
+ assert!(!app.synthetic_injected, "a settled UI pass acknowledges delivery");
+ assert!(app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the pass's end guard still sees the provenance");
+ app.control_synthetic.clear();
+ app.raw_input_hook(&ctx, &mut egui::RawInput::default());
+ assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "the next host iteration clears it");
+ // Unknown visibility is treated like hidden, and the next queued step is injected.
+ let mut unknown = egui::RawInput::default();
+ unknown.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default());
+ app.control_synthetic.push(egui::Event::Text("x".into()));
+ app.raw_input_hook(&ctx, &mut unknown);
+ let output = ctx.run_logic(&unknown, |ctx| app.logic(ctx));
+ assert_eq!(hidden_paints(&output), 1, "visible() == None is treated like hidden");
+ }
+
++ /// A font-gated first pass requeues injected input instead of acknowledging it; a later settled pass consumes it.
+ #[test]
+ fn font_gated_first_pass_requeues_injected_input_instead_of_acknowledging_it() {
+ let mut app = DesignApp::new(Session::new(), Services::default());
+ app.run("file.new", json!({"title": "fonts"})).unwrap();
+ let ctx = egui::Context::default();
+ app.control_synthetic.push(egui::Event::Text("x".into()));
+ let mut raw = hidden_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(app.synthetic_injected);
+ // The first real pass installs fonts and returns before any widget consumes input.
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert!(!app.synthetic_injected, "a font-gated pass is not an acknowledgement");
+ assert_eq!(app.control_synthetic, vec![egui::Event::Text("x".into())], "the batch is back in its queue");
+ assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed));
+ // Once fonts are ready the same step is injected and a settled pass consumes it.
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert!(app.fonts_ready);
+ let mut raw = hidden_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(app.synthetic_injected);
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false);
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert!(!app.synthetic_injected);
+ assert!(app.control_synthetic.is_empty());
+ }
+
++ /// Injected input is acknowledged only by the settled multipass frame.
+ #[test]
+ fn discarded_pass_does_not_acknowledge_injected_input() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ app.control_synthetic.push(egui::Event::Text("d".into()));
+ let mut raw = hidden_raw();
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(app.synthetic_injected);
+ let mut passes = 0;
+ let output = ctx.run_ui(raw, |ui| {
+ passes += 1;
+ if passes == 1 {
+ ui.ctx().request_discard("injected input must survive a discarded pass");
+ }
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ });
+ assert_eq!(output.platform_output.num_completed_passes, 2);
+ assert!(!app.synthetic_injected, "the settled second pass acknowledges it");
+ assert!(app.control_synthetic.is_empty());
+ }
+
++ /// A document change drops the stale batch and removes its events from pending raw input.
+ #[test]
+ fn a_document_switch_before_the_ui_pass_drops_the_pending_batch() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let pos = egui::pos2(10.0, 10.0);
+ app.control_synthetic.push(egui::Event::PointerMoved(pos));
+ let mut raw = hidden_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(app.synthetic_injected);
+ let _ = hidden_tick(&mut app, &ctx, &mut raw);
+ // A menu/control action switched documents before the forced paint.
+ app.run("file.new", json!({"title": "handoff"})).unwrap();
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(!app.synthetic_injected, "the stale batch was discarded");
+ assert!(app.injected_events.is_empty());
+ assert!(
+ !raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)),
+ "the event was removed from pending input"
+ );
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(false);
+ let mut seen = Vec::new();
+ ctx.run_ui(raw, |ui| {
+ seen = ui.ctx().input(|i| i.events.clone());
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert!(!seen.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)), "the new document did not receive it");
+ }
+
++ /// Save a document, make an unsaved edit and return the temporary directory.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn prepare_revert(app: &mut DesignApp) -> tempfile::TempDir {
+ let dir = tempfile::tempdir().unwrap();
+ app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap();
+ app.run("frame.create", json!({"rect": [72, 72, 144, 144], "content": "text", "text": "unsaved"})).unwrap();
+ assert!(app.session.active().unwrap().is_dirty());
+ dir
+ }
+
++ /// Revert keeps the document uid, advances the identity epoch and clears dirty state.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn revert_preserving_uid(app: &mut DesignApp) {
+ let before = app.session.active().unwrap();
+ let (uid, epoch) = (before.uid, before.identity_epoch);
+ app.run("file.revert", json!({})).unwrap();
+ let after = app.session.active().unwrap();
+ assert_eq!(after.uid, uid, "Revert keeps the open document's stable identity");
+ assert_ne!(after.identity_epoch, epoch, "Revert replaces the document state");
+ assert!(!after.is_dirty());
+ }
+
++ /// Input captured before Revert is neither acknowledged nor delivered to the restored document.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_revert_discards_a_buffered_input_batch() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ let pos = egui::pos2(10.0, 10.0);
+ app.control_synthetic.push(egui::Event::PointerMoved(pos));
+ let mut raw = hidden_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(app.synthetic_injected);
+ revert_preserving_uid(&mut app);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(!app.synthetic_injected, "input captured before Revert must not reach the restored document");
+ assert!(app.injected_events.is_empty());
+ assert!(!raw.events.iter().any(|event| matches!(event, egui::Event::PointerMoved(p) if *p == pos)));
+ }
+
++ /// Return `hidden_raw` with the root viewport marked visible.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn visible_raw() -> egui::RawInput {
+ let mut raw = hidden_raw();
+ let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap();
+ viewport.minimized = Some(false);
+ viewport.occluded = Some(false);
+ raw
+ }
+
++ /// Build Cmd-key press and release events.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn command_key(key: egui::Key) -> Vec<egui::Event> {
+ let modifiers = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE };
+ [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec()
+ }
+
+ /// A different document with one selectable item, for an asynchronous open.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn document_with_a_frame() -> Vec<u8> {
+ let mut session = Session::new();
+ session.execute("file.new", &json!({"title": "Incoming"})).unwrap();
+ session.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap();
+ let serialized = session.execute("file.serialize", &json!({})).unwrap();
+ designcraft_engine::cmd::base64_decode(serialized["base64"].as_str().unwrap())
+ }
+
+ /// One host iteration in eframe's order: `raw_input_hook`, then `run_ui` calling
+ /// `App::logic` and `App::ui` (eframe native `update`).
+ #[cfg(not(target_arch = "wasm32"))]
+ fn run_host_frame(app: &mut DesignApp, ctx: &egui::Context, mut raw: egui::RawInput) {
+ app.raw_input_hook(ctx, &mut raw);
+ ctx.run_ui(raw, |ui| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ if ctx.current_pass_index() == 0 {
+ app.poll_native_actions(&ctx, || None);
+ }
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ }
+
++ /// A native Revert runs only after the injected press/release settles; pointer state and user clipboard provenance are preserved.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_native_revert_waits_for_the_control_gesture() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]);
+ for pressed in [true, false] {
+ app.control_synthetic.push(egui::Event::PointerButton {
+ pos: egui::pos2(320.0, 240.0),
+ button: egui::PointerButton::Primary,
+ pressed,
+ modifiers: egui::Modifiers::NONE,
+ });
+ }
+ for step in 0..3 {
+ let mut raw = visible_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ ctx.run_ui(raw, |ui| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ if ctx.current_pass_index() == 0 {
+ app.poll_native_actions(&ctx, || actions.pop_front());
+ }
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert_eq!(app.session.active().unwrap().is_dirty(), step < 2, "Revert runs only after the release");
+ assert_eq!(ctx.input(|input| input.pointer.primary_down()), step == 0, "pointer state is not reset by the boundary");
+ }
+ assert!(actions.is_empty());
+ assert!(app.session.active().unwrap().selection.is_empty());
+ assert!(!app.control_input_frame.load(std::sync::atomic::Ordering::Relaxed), "native actions keep user clipboard provenance");
+ }
+
++ /// Close is cancelled and deferred while old-document input is pending, then the request survives to the next frame.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_close_waits_for_input_and_keeps_the_request() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ let mut raw = visible_raw();
+ raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().events.push(egui::ViewportEvent::Close);
+ app.raw_input_hook(&ctx, &mut raw);
+ let mut out = ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ assert!(app.ui.dialog.is_none(), "the close dialog must not receive the old document's input");
+ app.ui(ui);
+ });
+ assert!(out.viewport_output[&egui::ViewportId::ROOT].commands.contains(&egui::ViewportCommand::CancelClose));
+ out.textures_delta.clear();
+ assert_eq!(app.session.documents().len(), 1);
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(dialog_uid(&app), Some(app.session.active().unwrap().uid), "the close request survives the deferred frame");
+ }
+
++ /// A later control command cannot overtake queued input and eventually completes.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_control_command_waits_for_the_preceding_input() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let (requests, receiver) = std::sync::mpsc::channel();
+ app = app.with_control(receiver);
+ let (movement, first_reply) = ControlRequest::new("ui.move", json!({"x": 10, "y": 10}));
+ let (command, second_reply) = ControlRequest::new("engine.execute", json!({"command": "frame.create", "params": {"rect": [72,72,144,144]}}));
+ requests.send(movement).unwrap();
+ requests.send(command).unwrap();
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(first_reply.try_recv().unwrap()["ok"], true);
+ assert!(second_reply.try_recv().is_err(), "later commands must not overtake queued input");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert!(second_reply.try_recv().is_err(), "the injected input must settle first");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(second_reply.try_recv().unwrap()["ok"], true, "the later command is eventually handled");
+ }
+
++ /// Revert targets the original document before deferred OS-open delivery resumes.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_native_revert_precedes_the_deferred_os_open() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let dir = prepare_revert(&mut app);
+ let original = app.session.active().unwrap().uid;
+ let path = dir.path().join("incoming.designcraft");
+ std::fs::write(&path, document_with_a_frame()).unwrap();
+ app.open_documents_later([path.to_string_lossy().to_string()]);
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]);
+ let mut raw = visible_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ if ui.ctx().current_pass_index() == 0 {
+ app.poll_native_actions(ui.ctx(), || actions.pop_front());
+ }
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(app.session.active().unwrap().is_dirty());
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.active().unwrap().uid, original);
+ assert!(!app.session.active().unwrap().is_dirty(), "Revert runs before delivery resumes");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2);
+ assert_ne!(app.session.active().unwrap().uid, original);
+ assert!(!app.session.documents().iter().find(|doc| doc.uid == original).unwrap().is_dirty(), "Revert targeted the original document");
+ }
+
++ /// Preview cleanup cannot replace the input batch's document and runs after the batch settles.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_stale_preview_waits_for_the_input_batch() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let original = app.session.active().unwrap().uid;
+ app.session.preview_new_document(&json!({"title": "Preview"})).unwrap();
+ let preview = app.session.new_document_preview();
+ assert!(preview.is_some());
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.new_document_preview(), preview, "preview cleanup cannot replace the input's document");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert!(app.session.new_document_preview().is_none());
+ assert_eq!(app.session.active().unwrap().uid, original);
+ }
+
++ /// Revert waits for Select All's forwarded text input to settle.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_native_choices_wait_for_forwarded_text_input() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ let mut text = String::from("native field");
+ ctx.run_ui(visible_raw(), |ui| {
+ ui.text_edit_singleline(&mut text).request_focus();
+ })
+ .textures_delta
+ .clear();
+ assert!(ctx.text_edit_focused(), "the native edit command must forward to an actual text field");
+ let mut actions = std::collections::VecDeque::from([("edit.selectAll".to_owned(), Value::Null), ("file.revert".to_owned(), json!({}))]);
+ app.poll_native_actions(&ctx, || actions.pop_front());
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert!(app.session.active().unwrap().is_dirty(), "Revert waits for Select All's forwarded input");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert!(!app.session.active().unwrap().is_dirty());
+ }
+
++ /// A queued native menu event precedes and blocks deferred OS-open delivery without synthetic input.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_arriving_native_event_blocks_an_os_open_without_synthetic_input() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let dir = prepare_revert(&mut app);
+ let original = app.session.active().unwrap().uid;
+ let path = dir.path().join("incoming.designcraft");
+ std::fs::write(&path, document_with_a_frame()).unwrap();
+ app.open_documents_later([path.to_string_lossy().to_string()]);
+ let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]);
+ app.native_action_notifier(ctx.clone())();
+ let mut raw = visible_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ assert_eq!(app.session.documents().len(), 1, "a menu event already queued by the host must precede the OS open");
+ if ui.ctx().current_pass_index() == 0 {
+ app.poll_native_actions(ui.ctx(), || actions.pop_front());
+ }
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert!(!app.session.active().unwrap().is_dirty(), "the menu action ran in the real UI callback");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2);
+ assert_ne!(app.session.active().unwrap().uid, original);
+ }
+
++ /// Hidden logic-only ticks cannot execute native menu actions; a real UI pass can.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_deferred_native_action_waits_for_a_real_ui_pass() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ let mut actions = std::collections::VecDeque::from([("file.revert".to_owned(), json!({}))]);
+ let mut raw = visible_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ ctx.run_ui(raw, |ui| {
+ app.logic(&ui.ctx().clone());
+ if ui.ctx().current_pass_index() == 0 {
+ app.poll_native_actions(ui.ctx(), || actions.pop_front());
+ }
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ assert!(app.session.active().unwrap().is_dirty());
+ let mut raw = hidden_raw();
+ app.raw_input_hook(&ctx, &mut raw);
+ let _ = ctx.run_logic(&raw, |ctx| app.logic(ctx));
+ assert!(app.session.active().unwrap().is_dirty(), "a hidden logic-only tick must not execute native menu actions");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert!(!app.session.active().unwrap().is_dirty(), "the deferred action runs when a UI callback resumes");
+ }
+
- /// An inbox delivery runs only after input sampled for the current document has settled.
++ /// An inbox delivery runs only after input sampled for the current document has settled, so
++ /// a pending Select All cannot select text in the opened document.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_inbox_open_must_not_receive_a_pending_shortcut() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ app.services.inbox = Some(Inbox::default());
+ let request = app.import_request("open");
+ let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() };
+ app.services.inbox.as_ref().unwrap().lock().unwrap().push(file);
+ app.control_synthetic.extend(command_key(egui::Key::A));
+ run_host_frame(&mut app, &ctx, visible_raw());
+ // A deferred delivery is handled by the next settled host iteration.
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2, "the inbox file is still opened");
+ assert!(
+ app.session.active().unwrap().selection.is_empty(),
+ "Select All sampled before the asynchronous open must not reach the opened document"
+ );
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_os_document_must_not_receive_a_pending_shortcut() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("incoming.designcraft");
+ std::fs::write(&path, document_with_a_frame()).unwrap();
+ app.open_documents_later([path.to_string_lossy().to_string()]);
+ app.control_synthetic.extend(command_key(egui::Key::A));
+ run_host_frame(&mut app, &ctx, visible_raw());
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2, "the OS document is still opened");
+ assert!(app.session.active().unwrap().selection.is_empty(), "Select All sampled before the OS open must not reach the opened document");
+ }
+
+ /// The intended boundary: an imported file waits while the batch that was sampled for the
+ /// current document is pending, and is handled once that batch has settled.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_inbox_delivery_waits_for_a_settled_batch_then_runs() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ app.services.inbox = Some(Inbox::default());
+ let request = app.import_request("open");
+ let file = ImportedFile { request, name: "incoming.designcraft".into(), bytes: document_with_a_frame() };
+ app.services.inbox.as_ref().unwrap().lock().unwrap().push(file);
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 1, "the delivery waited for the injected step");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2, "the deferred delivery is not lost");
+ }
+
++ /// Deferred OS open waits for injected input and is not lost.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_host_order_os_document_waits_for_a_settled_batch_then_runs() {
+ let (mut app, ctx, _writes) = screenshot_app();
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("incoming.designcraft");
+ std::fs::write(&path, document_with_a_frame()).unwrap();
+ app.open_documents_later([path.to_string_lossy().to_string()]);
+ app.control_synthetic.push(egui::Event::PointerMoved(egui::pos2(10.0, 10.0)));
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 1, "the OS open waited for the injected step");
+ run_host_frame(&mut app, &ctx, visible_raw());
+ assert_eq!(app.session.documents().len(), 2, "the deferred OS open is not lost");
+ }
+
++ /// Revert drops the buffered native drop so it cannot modify the restored document.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_revert_discards_a_buffered_native_drop() {
+ let (mut app, ctx) = drop_test_app();
+ let dir = prepare_revert(&mut app);
+ let path = dir.path().join("drop.png");
+ std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap();
+ let mut raw = visible_raw_with_drop(&[&path]);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert_eq!(app.pending_drops.len(), 1);
+ revert_preserving_uid(&mut app);
+ let assets_before = app.session.active().unwrap().doc.assets.len();
+ run_ui_pass(&mut app, &ctx, raw);
+ assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "a stale native drop must not modify the restored document");
+ assert!(app.pending_drops.is_empty());
+ }
+
++ /// Revert rejects pre-issue and in-flight screenshots with a document error, issues no retry and writes no pixels.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_revert_rejects_screenshots_before_issue_and_in_flight() {
+ for in_flight in [false, true] {
+ let (mut app, ctx, writes) = screenshot_app();
+ let _dir = prepare_revert(&mut app);
+ let (reply, replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(Some("revert-stale.png".into()), reply).unwrap();
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ if in_flight {
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ callback = Some(cb);
+ }
+ }
+ assert!(callback.is_some(), "the in-flight case must actually issue a capture");
+ }
+ revert_preserving_uid(&mut app);
+ if let Some(callback) = callback {
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ }
+ for _ in 0..4 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert!(screenshot_callback(&mut output).is_none(), "Revert must not issue or retry an old capture (in_flight={in_flight})");
+ }
+ let reply = replies.try_recv().expect("the replaced document's screenshot receives an error");
+ assert_eq!(reply["ok"], false, "in_flight={in_flight}: {reply}");
+ assert!(reply["error"].as_str().unwrap_or_default().contains("document"));
+ assert!(writes.lock().unwrap().is_empty(), "stale pixels must not be saved");
+ assert!(app.pending_shots.is_empty());
+ assert!(app.queued_shots.is_empty());
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // Document-generation regressions: reused screenshot slots and buffered native drops must
+ // not cross a document/dialog/focus change.
+ // ---------------------------------------------------------------------------------------
+
++ /// A document switch before issue errors the request and leaves no pending or queued capture.
+ #[test]
+ fn design_generation_screenshot_switch_before_issue_does_not_capture_the_new_document() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let document_a = app.session.active().unwrap().uid;
+ let (requests, receiver) = std::sync::mpsc::channel();
+ app = app.with_control(receiver);
+ let (reply, replies) = std::sync::mpsc::channel();
+ requests
+ .send(ControlRequest { method: "ui.screenshot".into(), params: json!({"path": "switch-before-issue.png", "focus": false}), reply })
+ .unwrap();
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ assert_eq!(app.pending_shots.len(), 1, "ui.screenshot is admitted");
+ assert_eq!(app.pending_shots[0].geometry.document, document_a);
+ // A menu/control action switches documents before the settling rule issues the capture.
+ app.run("file.new", json!({"title": "handoff-before-issue"})).unwrap();
+ let document_b = app.session.active().unwrap().uid;
+ assert_ne!(document_b, document_a);
+ if let Some(at) = app.queued_shots.first_mut() {
+ at.1 = 0.0;
+ }
+ let mut callback = None;
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ callback = Some(cb);
+ }
+ }
+ if let Some(callback) = callback {
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ }
+ assert!(writes.lock().unwrap().is_empty(), "the switched request must not write a file");
+ let reply = replies.try_recv().expect("the switched request must receive an error receipt");
+ assert_eq!(reply["ok"], false, "the old document's request must not succeed on the new one: {reply}");
+ assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}");
+ assert!(app.pending_shots.is_empty(), "the stale request released its admission");
+ assert!(app.queued_shots.is_empty(), "the stale request left no repaint token");
+ }
+
++ /// An in-flight old-document capture cannot complete or retry on the new document; the request and tokens are released.
+ #[test]
+ fn design_generation_screenshot_in_flight_after_switch_does_not_complete_on_the_new_document() {
+ let (mut app, ctx, writes) = screenshot_app();
+ let document_a = app.session.active().unwrap().uid;
+ let (reply, replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(Some("switch-in-flight.png".into()), reply).unwrap();
+ app.queued_shots[0].1 = 0.0;
+ let mut callback = None;
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ callback = Some(cb);
+ }
+ }
+ let callback = callback.expect("the request is issued on the first document");
+ assert_eq!(app.pending_shots[0].geometry.document, document_a);
+ // The capture is in flight on A when the app switches to B.
+ app.run("file.new", json!({"title": "handoff-in-flight"})).unwrap();
+ assert_ne!(app.session.active().unwrap().uid, document_a);
+ callback.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ // Old code retries the stale request on B; follow any retry through a completion so the
+ // regression proves that B never receives the old capture.
+ if let Some(at) = app.queued_shots.first_mut() {
+ at.1 = 0.0;
+ }
+ let mut retried = None;
+ for _ in 0..3 {
+ let mut output = shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ if let Some(cb) = screenshot_callback(&mut output) {
+ retried = Some(cb);
+ }
+ }
+ if let Some(retried) = retried {
+ retried.complete(std::sync::Arc::new(egui::ColorImage::filled([640, 480], egui::Color32::BLACK)));
+ shot_frame(&mut app, &ctx, egui::vec2(640.0, 480.0));
+ }
+ assert!(writes.lock().unwrap().is_empty(), "the in-flight request must not write a file after the switch");
+ let reply = replies.try_recv().expect("the in-flight request must receive an error receipt");
+ assert_eq!(reply["ok"], false, "the in-flight request must not succeed on the new document: {reply}");
+ assert!(reply["error"].as_str().unwrap_or_default().contains("document"), "the error must name the document change: {reply}");
+ assert!(app.pending_shots.is_empty(), "the stale request released its admission");
+ assert!(app.queued_shots.is_empty(), "the stale request left no repaint token");
+ }
+
++ /// Admission stamps the current session document, not cached geometry from the previous document.
+ #[test]
+ fn design_generation_screenshot_admission_uses_the_current_document_not_the_cached_geometry() {
+ let (mut app, _ctx, _writes) = screenshot_app();
+ let document_a = app.session.active().unwrap().uid;
+ // `screenshot_app` populated the geometry cache for A. Switch documents without a frame
+ // between the switch and admission, as two control requests in one logic tick would.
+ app.run("file.new", json!({"title": "admission-current-document"})).unwrap();
+ let document_b = app.session.active().unwrap().uid;
+ assert_ne!(document_b, document_a);
+ let (reply, replies) = std::sync::mpsc::channel();
+ app.admit_screenshot(None, reply).unwrap();
+ assert_eq!(
+ app.pending_shots[0].geometry.document, document_b,
+ "admission must use the current session document, not the last cached geometry"
+ );
+ assert!(replies.try_recv().is_err(), "admission alone replies only when it fails");
+ app.pending_shots.clear();
+ app.queued_shots.clear();
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[derive(Debug)]
+ struct TestDroppedFile(std::path::PathBuf);
+
+ #[cfg(not(target_arch = "wasm32"))]
+ impl egui::DroppedFile for TestDroppedFile {
+ fn path(&self) -> &std::path::Path {
+ &self.0
+ }
+
+ fn bytes(&self) -> Result<Vec<u8>, String> {
+ std::fs::read(&self.0).map_err(|error| error.to_string())
+ }
+ }
+
++ /// Wrap a path as an egui dropped-file handle backed by the test type.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn dropped_file(path: &std::path::Path) -> egui::DroppedFileHandle {
+ std::sync::Arc::new(TestDroppedFile(path.to_path_buf()))
+ }
+
++ /// Create a screenshot app with a fixed canvas rectangle and an initialized view for drop tests.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn drop_test_app() -> (DesignApp, egui::Context) {
+ let (mut app, ctx, _writes) = screenshot_app();
+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));
+ let _ = app.view_mut();
+ (app, ctx)
+ }
+
++ /// Write a tiny unique PNG for drop tests.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn temporary_png(name: &str) -> std::path::PathBuf {
+ let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}.png", std::process::id()));
+ std::fs::write(&path, designcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] }.to_png()).unwrap();
+ path
+ }
+
++ /// Build visible raw input with a pointer move and dropped-file handles.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn visible_raw_with_drop(paths: &[&std::path::Path]) -> egui::RawInput {
+ let mut raw = hidden_raw();
+ let viewport = raw.viewports.get_mut(&egui::ViewportId::ROOT).unwrap();
+ viewport.minimized = Some(false);
+ viewport.occluded = Some(false);
+ raw.events.push(egui::Event::PointerMoved(egui::pos2(100.0, 100.0)));
+ raw.dropped_files.extend(paths.iter().map(|path| dropped_file(path)));
+ raw
+ }
+
++ /// Run one logic-plus-UI frame and discard its texture deltas.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn run_ui_pass(app: &mut DesignApp, ctx: &egui::Context, raw: egui::RawInput) {
+ ctx.run_ui(raw, |ui| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ })
+ .textures_delta
+ .clear();
+ }
+
++ /// A drop buffered before a document switch cannot add assets to the switched document.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_generation_native_drop_is_discarded_when_the_document_changes_before_ui() {
+ let (mut app, ctx) = drop_test_app();
+ let path = temporary_png("drop-document-change");
+ let mut raw = visible_raw_with_drop(&[&path]);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert!(raw.dropped_files.is_empty(), "raw_input_hook captures the native drop");
+ assert_eq!(app.pending_drops.len(), 1, "the raw drop is buffered for the UI pass");
+ // A menu/control action switches documents before the settled UI pass consumes it.
+ app.run("file.new", json!({"title": "drop-target"})).unwrap();
+ let assets_before = app.session.active().unwrap().doc.assets.len();
+ run_ui_pass(&mut app, &ctx, raw);
+ assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land in the switched document");
+ assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer");
+ let _ = std::fs::remove_file(path);
+ }
+
++ /// A drop buffered before a dialog opens cannot land behind it.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_generation_native_drop_is_discarded_when_a_dialog_opens_before_ui() {
+ let (mut app, ctx) = drop_test_app();
+ let path = temporary_png("drop-dialog-change");
+ let mut raw = visible_raw_with_drop(&[&path]);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert_eq!(app.pending_drops.len(), 1);
+ app.run("app.preferences", json!({})).unwrap();
+ assert!(app.ui.dialog.is_some(), "a real dialog changed the generation");
+ let assets_before = app.session.active().unwrap().doc.assets.len();
+ run_ui_pass(&mut app, &ctx, raw);
+ assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land behind the dialog");
+ assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer");
+ let _ = std::fs::remove_file(path);
+ }
+
++ /// A keyboard-focus change invalidates a buffered drop.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_generation_native_drop_is_discarded_when_focus_changes_before_ui() {
+ let (mut app, ctx) = drop_test_app();
+ let path = temporary_png("drop-focus-change");
+ let mut raw = visible_raw_with_drop(&[&path]);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert_eq!(app.pending_drops.len(), 1);
+ let focus = egui::Id::unique("design-generation-drop-focus");
+ assert_ne!(app.input_generation().focus, Some(focus));
+ ctx.memory_mut(|memory| memory.request_focus(focus));
+ assert_eq!(app.input_generation().focus, Some(focus), "keyboard focus changed after the drop was buffered");
+ let assets_before = app.session.active().unwrap().doc.assets.len();
+ run_ui_pass(&mut app, &ctx, raw);
+ assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before, "the stale drop must not land after a focus change");
+ assert!(app.pending_drops.is_empty(), "the discarded drop released its buffer");
+ let _ = std::fs::remove_file(path);
+ }
+
++ /// With no generation change, every dropped file in a batch is placed.
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn design_generation_native_drop_batch_without_a_change_still_places_every_file() {
+ let (mut app, ctx) = drop_test_app();
+ let first = temporary_png("drop-batch-a");
+ let second = temporary_png("drop-batch-b");
+ let mut raw = visible_raw_with_drop(&[&first, &second]);
+ app.raw_input_hook(&ctx, &mut raw);
+ assert_eq!(app.pending_drops.len(), 2, "both files were captured from the raw input");
+ let assets_before = app.session.active().unwrap().doc.assets.len();
+ run_ui_pass(&mut app, &ctx, raw);
+ assert_eq!(app.session.active().unwrap().doc.assets.len(), assets_before + 2, "both files in the valid batch are placed");
+ assert!(app.pending_drops.is_empty());
+ let _ = std::fs::remove_file(first);
+ let _ = std::fs::remove_file(second);
+ }
}
#[cfg(test)]
diff --cc crates/ui-egui/src/object_control.rs
index ffa5ec2e6,0a845a38d..e95f7cc5a
--- a/crates/ui-egui/src/object_control.rs
+++ b/crates/ui-egui/src/object_control.rs
@@@ -56,6 -56,6 +56,7 @@@ fn toggle(ui: &mut Ui, group: Rect, x:
}
}
++/// Lay out the fixed two-row control groups for reference, geometry, transform, rotate/flip, appearance, wrap, corners, fitting, alignment and conditional columns.
pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) {
let language = app.ui.language.clone();
let tr = |text: &str| crate::i18n::tr(&language, text).to_owned();
diff --cc crates/ui-egui/src/panels/datamerge.rs
index c482637ff,f0ae77279..cbeb7f327
--- a/crates/ui-egui/src/panels/datamerge.rs
+++ b/crates/ui-egui/src/panels/datamerge.rs
@@@ -193,10 -184,10 +193,11 @@@ fn select_source(app: &mut DesignApp)
let _ = app.run("data.source.select", json!({"path": path}));
}
-fn choice(ui: &mut egui::Ui, id: &str, current: &str, options: &[(&str, &str)], lang: &str) -> Option<String> {
++/// Render a localized, named combo and return only a changed selection.
+fn choice(ui: &mut egui::Ui, id: &str, current: &str, options: &[(&str, &str)], lang: &str, name: &str) -> Option<String> {
let label = options.iter().find(|(value, _)| *value == current).map(|(_, text)| tr(lang, text)).unwrap_or(current);
let mut picked = None;
- egui::ComboBox::from_id_salt(id).selected_text(label).width(ui.available_width().min(200.0)).show_ui(ui, |ui| {
+ let combo = egui::ComboBox::from_id_salt(id).selected_text(label).width(ui.available_width().min(200.0)).show_ui(ui, |ui| {
for (value, text) in options {
if ui.selectable_label(*value == current, tr(lang, text)).clicked() {
picked = Some((*value).to_string());
@@@ -242,40 -232,3 +243,41 @@@ fn tr<'a>(lang: &str, s: &'a str) -> &'
fn w(ui: &egui::Ui, lang: &str, s: &str) -> egui::WidgetText {
crate::rtl::widget(ui, tr(lang, s))
}
+
+#[cfg(test)]
+mod tests {
+ use egui_kittest::{
+ Harness,
+ kittest::{NodeT, Queryable},
+ };
+
+ use super::*;
+
++ /// Records and Arrangement each expose exactly one named combo, and the accessibility check passes.
+ #[test]
+ fn arrangement_combo_is_accessible_and_distinct_from_the_records_combo() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ app.run("data.source.select", json!({"bytes": designcraft_engine::cmd::base64_encode(b"Name\nAda\nGrace\n"), "name": "people.csv"})).unwrap();
+ app.run("data.options", json!({"perPage": "multiple"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(420.0, 700.0)).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let key = egui::Id::unique("datamerge_test_fonts");
+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {
+ crate::theme::install_fonts(ui.ctx(), "");
+ ui.data_mut(|d| d.insert_temp(key, true));
+ return;
+ }
+ show(app, ui);
+ },
+ app,
+ );
+ h.run_steps(3);
+ let combos = |h: &Harness<'_, DesignApp>, label: &str| {
+ h.query_all_by_label(label).filter(|n| n.accesskit_node().role() == egui::accesskit::Role::ComboBox).count()
+ };
+ assert_eq!(combos(&h, "Merge options"), 1, "records selection keeps its name");
+ assert_eq!(combos(&h, "Arrangement"), 1, "the arrangement control has its own name");
+ h.check_accessibility();
+ }
+}
diff --cc crates/ui-egui/src/panels/notes.rs
index da250bff5,bcee4776f..ee6cc17a5
--- a/crates/ui-egui/src/panels/notes.rs
+++ b/crates/ui-egui/src/panels/notes.rs
@@@ -46,7 -46,10 +46,10 @@@ pub fn show(app: &mut DesignApp, ui: &m
if !author.is_empty() {
ui.label(egui::RichText::new(author).size(10.5).color(t.text_dim));
}
- ui.label(n["text"].as_str().unwrap_or(""));
+ let mut text = n["text"].as_str().unwrap_or("");
- let text_id = egui::Id::new(("note_text", story.as_u64(), nid.as_u64()));
++ let text_id = egui::Id::unique(("note_text", story.as_u64(), nid.as_u64()));
+ ui.add(egui::TextEdit::multiline(&mut text).id(text_id).frame(egui::Frame::NONE).desired_rows(1).desired_width(f32::INFINITY));
+ let split_at = split_point(ui.ctx(), text_id, text);
ui.horizontal(|ui| {
if ui.small_button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Go To"))).clicked() {
let _ = app.run("text.select", json!({"story": story, "anchor": at, "focus": at + 3}));
@@@ -61,3 -71,60 +71,60 @@@
});
}
}
+
+ /// The byte offset of the insertion point in a note's text field, when it lies strictly inside
+ /// the text and selects nothing.
+ fn split_point(ctx: &egui::Context, id: egui::Id, text: &str) -> Option<usize> {
+ let r = egui::TextEdit::load_state(ctx, id)?.cursor.char_range()?;
+ let k: usize = r.primary.index.into();
+ if r.primary.index != r.secondary.index || k == 0 {
+ return None;
+ }
+ text.char_indices().nth(k).map(|(i, _)| i)
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::{NodeT, Queryable};
+
+ use super::*;
+
+ #[test]
+ fn split_note_splits_the_note_at_the_insertion_point_in_its_text() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Draft copy."})).unwrap();
+ app.run("text.select", json!({"story": r["story"], "anchor": 5, "focus": 5})).unwrap();
+ app.run("note.new", json!({"text": "check this", "author": "Ed"})).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(320.0, 400.0)).build_ui_state(
+ |ui, app: &mut DesignApp| {
- let id = egui::Id::new("test_fonts");
++ let id = egui::Id::unique("test_fonts");
+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {
+ crate::theme::install_fonts(ui.ctx(), "");
+ ui.data_mut(|d| d.insert_temp(id, true));
+ return;
+ }
+ show(app, ui);
+ },
+ app,
+ );
+ h.run_steps(3);
+ assert!(h.get_by_label("Split Note").accesskit_node().is_disabled(), "no insertion point in the note yet");
+ let field = h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some("check this")).rect();
+ h.hover_at(field.center());
+ h.drag_at(field.center());
+ h.drop_at(field.center());
+ h.run_steps(2);
+ h.key_press(egui::Key::Home);
+ for _ in 0..6 {
+ h.key_press(egui::Key::ArrowRight);
+ }
+ h.run_steps(2);
+ h.get_by_label("Split Note").click();
+ h.run_steps(3);
+ let list = h.state_mut().session.execute("note.list", &json!({})).unwrap();
+ let texts: Vec<_> = list.as_array().unwrap().iter().map(|n| (n["text"].clone(), n["author"].clone())).collect();
+ assert_eq!(texts, [(json!("check "), json!("Ed")), (json!("this"), json!("Ed"))]);
+ }
+ }
diff --cc crates/ui-egui/src/rtl.rs
index 55473469d,cb88619ec..707231595
--- a/crates/ui-egui/src/rtl.rs
+++ b/crates/ui-egui/src/rtl.rs
@@@ -140,6 -191,6 +140,7 @@@ impl LayoutCache
}
}
++/// Lay out text without RTL candidates directly; otherwise use a bounded job cache that checks full job equality and invalidates on the font token.
fn layout(ctx: &egui::Context, job: LayoutJob) -> Arc<Galley> {
if !may_have_rtl(&job.text) {
return ctx.fonts_mut(|fonts| fonts.layout_job(job));
@@@ -160,11 -211,95 +161,12 @@@
galley
}
++/// Set paragraph direction to `Auto` and preserve the logical source, including line separators in a single-line label.
fn layout_uncached(ctx: &egui::Context, mut job: LayoutJob) -> Arc<Galley> {
- if !has_rtl(&job.text) {
- return ctx.fonts_mut(|fonts| fonts.layout_job(job));
- }
- let original = Arc::new(job.clone());
- if !job.break_on_newline {
- // Single-line widgets show line separators as spaces; byte offsets stay unchanged.
- job.text = job.text.replace(['\n', '\r'], " ");
- }
- let bidi = BidiInfo::new(&job.text, None);
- let shape = |range| ctx.fonts_mut(|fonts| fonts.layout_job(visual_line(&job, &bidi, range)));
- // Wrap in logical reading order BEFORE applying bidi separately to each line.
- let mut ranges = Vec::new();
- let mut start = 0;
- for paragraph in job.text.split_inclusive('\n') {
- let end = start + paragraph.len();
- let content_end = if paragraph.ends_with('\n') { end - 1 } else { end };
- if !job.wrap.max_width.is_finite() || shape(start..content_end).size().x <= job.wrap.max_width {
- ranges.push(start..content_end);
- start = end;
- continue;
- }
- let mut line_start = start;
- let mut word_break = start;
- for (offset, cluster) in job.text[start..content_end].grapheme_indices(true) {
- let index = start + offset;
- let boundary = index + cluster.len();
- if job.wrap.max_width.is_finite() && index > line_start && shape(line_start..boundary).size().x > job.wrap.max_width {
- let cut = if !job.wrap.break_anywhere && word_break > line_start { word_break } else { index };
- ranges.push(line_start..cut);
- line_start = cut;
- }
- if cluster.chars().all(char::is_whitespace) {
- word_break = boundary;
- }
- }
- ranges.push(line_start..content_end);
- start = end;
- }
- if job.text.ends_with('\n') {
- ranges.push(start..start);
- }
- let elided = ranges.len() > job.wrap.max_rows;
- ranges.truncate(job.wrap.max_rows);
- let mut lines = Vec::new();
- for (i, range) in ranges.iter().enumerate() {
- if elided && i + 1 == ranges.len() {
- // Append the ellipsis in logical order, then reorder and shape the final line.
- let mut last = LayoutJob::default();
- for section in &job.sections {
- let start = range.start.max(section.byte_range.start.into());
- let end = range.end.min(section.byte_range.end.into());
- if start < end {
- last.append(&job.text[start..end], 0.0, section.format.clone());
- }
- }
- let format = last.sections.last().or(job.sections.first()).map(|s| s.format.clone()).unwrap_or_default();
- let tail = job.wrap.overflow_character.map_or(String::new(), |c| c.to_string());
- let base = bidi.paragraphs.iter().find(|p| p.range.contains(&range.start)).map(|p| p.level);
- loop {
- let mut candidate = last.clone();
- candidate.append(&tail, 0.0, format.clone());
- let info = BidiInfo::new(&candidate.text, base);
- let shaped = ctx.fonts_mut(|fonts| fonts.layout_job(visual_line(&candidate, &info, 0..candidate.text.len())));
- if shaped.size().x <= job.wrap.max_width || last.text.is_empty() {
- lines.push(shaped);
- break;
- }
- let end = last.text.grapheme_indices(true).next_back().map_or(0, |(i, _)| i);
- last.text.truncate(end);
- for section in &mut last.sections {
- section.byte_range.end = usize::from(section.byte_range.end).min(end).into();
- }
- last.sections.retain(|s| s.byte_range.start < s.byte_range.end);
- }
- } else {
- lines.push(shape(range.clone()));
- }
- }
- let mut galley = Galley::concat(original, &lines, ctx.pixels_per_point());
- galley.elided = elided;
- // Each Arabic line shares the right edge; Latin runs and numbers remain LTR.
- let width = galley.rect.width();
- galley.mesh_bounds = Rect::NOTHING;
- for row in &mut galley.rows {
- row.pos.x += width - row.size.x;
- galley.mesh_bounds |= row.visuals.mesh_bounds.translate(row.pos.to_vec2());
- }
- Arc::new(galley)
+ job.direction = TextDirection::Auto;
+ // The 0.37 shaper owns single-line handling as well as bidi. Preserve the logical source
+ // for accessibility and cache equality, including line separators in a single-line label.
+ ctx.fonts_mut(|fonts| fonts.layout_job(job))
}
#[cfg(test)]
@@@ -318,16 -438,18 +320,18 @@@ mod tests
});
}
++ /// Latin, CJK, combining and emoji labels skip the RTL path; Arabic/Hebrew, controls and Arabic-Indic digits take it.
#[test]
- fn ordinary_multilingual_labels_skip_bidi_analysis() {
+ fn ordinary_multilingual_labels_skip_the_rtl_layout_cache() {
for text in ["", "File (123)", "Édition", "中文排版", "スウォッチ", "e\u{301}", "🎨 🙂"] {
assert!(!may_have_rtl(text), "{text:?}");
- assert!(!BidiInfo::new(text, None).has_rtl(), "{text:?}");
}
for text in ["ملف", "עברית", "PDF ملف 123", "\u{1e900}", "\u{200f}", "\u{202e}abc\u{202c}", "\u{2067}abc\u{2069}", "١٢٣"] {
assert!(may_have_rtl(text), "{text:?}");
}
}
++ /// Non-RTL widgets remain `RichText`, keep their text and lay out with finite bounds.
#[test]
fn non_rtl_widgets_keep_native_text_and_formatting() {
with_fonts(|ctx| {
@@@ -342,6 -464,6 +346,7 @@@
});
}
++ /// Source and glyph arrays stay logical; painting applies bidi, mirrors brackets, keeps `PDF 123` left-to-right and gives finite metrics.
#[test]
fn mixed_arabic_latin_digits_and_brackets_preserve_logical_source() {
with_fonts(|ctx| {
@@@ -381,8 -502,8 +386,9 @@@
});
}
++ /// Fallback shaping matches the native Auto-direction shaper in displayed glyphs, sizes, atlas UVs, advances and spaces.
#[test]
- fn joins_arabic_letters_using_one_font_including_spaces() {
+ fn arabic_fallback_matches_the_native_shaper_including_spaces() {
with_fonts(|ctx| {
let text = "بِدء مُستند جَديد";
let galley = plain(ctx, text, FontId::proportional(15.0), Color32::WHITE);
@@@ -406,6 -519,6 +412,7 @@@
});
}
++ /// Logical wrapping puts the first word first and every RTL row flush right within one pixel.
#[test]
fn wraps_first_logical_word_first_and_right_aligns_lines() {
with_fonts(|ctx| {
diff --cc crates/ui-egui/src/widgets.rs
index 83cc1b5eb,e820e21a8..8e72a0bb3
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@@ -94,6 -93,6 +94,7 @@@ impl<'a> NumField<'a>
pub fn number(id: &'a str, value: Option<f64>, suffix: &'a str, decimals: usize) -> Self {
Self::new(id, value, NumKind::Number { suffix, decimals })
}
++ /// Initialize a numeric field with no name, label or empty text, a 72-point width, no spinner or presets, the full range and the enabled state.
fn new(id: &'a str, value: Option<f64>, kind: NumKind<'a>) -> Self {
NumField {
id,
@@@ -371,6 -345,6 +372,7 @@@ pub fn dropdown(ui: &mut Ui, text: &str
dropdown_h(ui, text, width, FIELD_H)
}
++/// Paint a labelled combo with hover, border and chevron, clip its text, and expose a `ComboBox` role named by the visible text.
pub fn dropdown_h(ui: &mut Ui, text: &str, width: f32, h: f32) -> Response {
let t = Tokens::get(ui.ctx());
let (r, resp) = ui.allocate_exact_size(vec2(width, h), Sense::click());
@@@ -607,6 -579,6 +609,7 @@@ pub fn icon_toggle(ui: &mut Ui, icon: &
icon_toggle_sized(ui, icon, on, tip, vec2(23.0, 21.0))
}
++/// Paint an icon toggle at the requested size and expose it as a selected button named by its tooltip.
pub fn icon_toggle_sized(ui: &mut Ui, icon: &str, on: bool, tip: &str, size: egui::Vec2) -> Response {
let t = Tokens::get(ui.ctx());
let (r, resp) = ui.allocate_exact_size(size, Sense::click());
@@@ -835,68 -807,6 +838,70 @@@ mod tests
assert_eq!(m.parse("1p0+0p6"), Some(18.0));
assert_eq!(m.step(), 1.0);
}
+
++ /// A disabled field's preset button is disabled in AccessKit and cannot open a popup.
+ #[test]
+ fn disabled_numeric_presets_are_disabled_and_do_not_open() {
+ use egui_kittest::kittest::{NodeT, Queryable};
+
+ const PRESETS: &[f64] = &[0.0, 50.0, 100.0];
+ let mut h = egui_kittest::Harness::builder().with_size(vec2(420.0, 240.0)).build_ui(|ui| {
+ assert!(NumField::number("Opacity", Some(50.0), "%", 0).presets(PRESETS).enabled(false).show(ui).is_none());
+ });
+ h.run_steps(2);
+ assert!(h.get_by_label("Opacity presets").accesskit_node().is_disabled());
+ h.get_by_label("Opacity presets").click();
+ h.run_steps(3);
+ assert!(!egui::Popup::is_any_open(&h.ctx), "a disabled preset button must not open its menu");
+ h.check_accessibility();
+ }
+
++ /// Spinner buttons and presets inherit a disabled parent in both AccessKit and widget metadata.
+ #[test]
+ fn numeric_controls_inherit_a_disabled_parents_state() {
+ use egui_kittest::kittest::{NodeT, Queryable};
+
+ const PRESETS: &[f64] = &[0.0, 50.0, 100.0];
+ let mut h = egui_kittest::Harness::builder().with_size(vec2(420.0, 240.0)).build_ui(|ui| {
+ ui.disable();
+ let _ = NumField::number("Opacity", Some(50.0), "%", 0).spinner().presets(PRESETS).show(ui);
+ });
+ h.ctx.all_styles_mut(|style| style.debug.show_interactive_widgets = true);
+ h.run_steps(2);
+ let metadata_enabled = |label: &str| {
+ h.ctx.viewport(|viewport| {
+ let rects = &viewport.prev_pass.widgets;
+ rects
+ .layers()
+ .flat_map(|(_, widgets)| widgets)
+ .filter_map(|widget| rects.info(widget.id))
+ .find(|info| info.label.as_deref() == Some(label))
+ .map(|info| info.enabled)
+ })
+ };
+ for label in ["Increase Opacity", "Decrease Opacity", "Opacity presets"] {
+ assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} reports the disabled parent");
+ assert_eq!(metadata_enabled(label), Some(false), "{label} metadata reports the disabled parent");
+ }
+ h.get_by_label("Opacity presets").click();
+ h.run_steps(3);
+ assert!(!egui::Popup::is_any_open(&h.ctx), "a preset in a disabled parent must not open its menu");
+ h.check_accessibility();
+ }
+
+ /// Strict accessibility: every input in these fields is named and reports the right role.
+ #[test]
+ fn numeric_dropdown_and_checkbox_inputs_have_accessible_names_and_roles() {
+ const PRESETS: &[f64] = &[0.0, 50.0, 100.0];
+ let mut h = egui_kittest::Harness::builder().with_size(vec2(420.0, 240.0)).build_ui(|ui| {
+ let _ = NumField::number("Opacity", Some(50.0), "%", 0).spinner().presets(PRESETS).show(ui);
+ let _ = dropdown(ui, "Paragraph Styles", 160.0);
+ let mut on = true;
+ let _ = checkbox(ui, &mut on, "Preview");
+ });
+ h.run_steps(2);
+ h.check_accessibility();
+ }
}
/// `img` made to fit the GPU's largest texture (`max_side` pixels a side), sampled down