Skip to content

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

Merge upstream main a930276 into feat/ime: this branch's IME model replaces text.compose

aiongg06892bbc7e90
diff --cc ROADMAP.md
index 69c49ed1f,d60a6bf49..9f49f153f
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -86,14 -303,14 +303,14 @@@ Interface strings translated, of 1,724
| Language | Code | Status | Translated |
|---|---|---|---|
| English | en | full | 100% |
--| Simplified Chinese | zh | partial (no canvas IME) | 83% |
++| Simplified Chinese | zh | partial | 83% |
| Spanish | es | partial | 83% |
| Hindi | hi | none | 0% |
| Arabic | ar | partial (RTL UI and composition) | 85% |
| French | fr | partial | 83% |
| Portuguese (Brazil) | pt-br | partial | 61% |
| Indonesian | id | none | 0% |
--| Japanese | ja | partial (no canvas IME) | 95% |
++| Japanese | ja | partial | 95% |
| German | de | partial | 83% |
| Korean | ko | none | 0% |
| Vietnamese | vi | none | 0% |
@@@ -126,8 -343,52 +343,53 @@@ list) · [roadmap.md](docs/roadmap.md)
## Progress log
+ - **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
+
Newest first.
++- **2026-10-15** · Japanese, Chinese and Korean input methods type into stories with the Type tool: the marked text shows in place, underlined (the clause being converted twice), with the candidate window at the caret, and the commit is one undo step. Keys, shortcuts, the clipboard and Undo wait while the input method composes; a click, a tool switch or another command keeps the marked text as typed. Not yet checked by hand with a system input method. No readiness percentage change.
+ - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
+ - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
+ - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+ - **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
+ - **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
+ - **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
+ - **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
+ - **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
+ - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change.
+ - **2026-10-14** · Layout › Margins and Columns and Layout › Create Guides are laid out as InDesign's: Margins in Top/Bottom and Inside/Outside pairs with a link button that makes all four the same, Rows and Columns side by side, Fit Guides to Margins or Page, and a Preview checkbox that shows the change on the canvas before OK. A measurement field works out arithmetic when you leave it (`0.4375 in*2` becomes `0.875 in`). No readiness percentage change.
+ - **2026-10-14** · The Pathfinder panel is laid out as InDesign's: Paths (Join, Open, Close, Reverse), Pathfinder, Convert Shape and Convert Point, each a row of icon buttons. Join Path closes an open path or joins two at their nearest ends (`path.join`), and Convert Point makes the selected points plain, corner, smooth or symmetrical (`path.convertPoints`). No readiness percentage change.
+ - **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.
+ - **2026-10-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change.
+ - **2026-10-14** · Type › Fill with Placeholder Text fills a frame with paragraphs of a few sentences, as InDesign does, so one paragraph can be styled on its own (it was one long paragraph, and the filler ran sentences together, "interit.Ovid"). No readiness percentage change.
+ - **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
+ - **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
+ - **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.
+ - **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+ - **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.
+ - **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.
+ - **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.
+ - **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.
+ - **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.
+
+ - **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.
+ - **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.
+ - **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.
+ - **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.
+ - **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.
+ - **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.
+ - **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.
+ - **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.
+ - **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer
+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.
+ - **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.
+ - **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.
+ - **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.
+ - **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.
- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
diff --cc apps/designcraft-web/src/web.rs
index 1fb71d7b3,c532b5dca..dbe0c982e
--- a/apps/designcraft-web/src/web.rs
+++ b/apps/designcraft-web/src/web.rs
@@@ -106,8 -372,10 +372,10 @@@ impl eframe::App for WebShell
}
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
- designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused() || self.app.canvas_ime());
- self.app.raw_input_hook(raw);
+ let _ = self.graphics.run_if_healthy(|| {
- designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused());
++ designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused() || self.app.canvas_ime());
+ self.app.raw_input_hook(raw);
+ });
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
diff --cc apps/designcraft/Cargo.toml
index c88213a08,0f08ae8ed..176bcf8ad
--- a/apps/designcraft/Cargo.toml
+++ b/apps/designcraft/Cargo.toml
@@@ -32,7 -32,6 +32,9 @@@ arboard = { workspace = true
winit = { version = "0.30", default-features = false, features = ["x11"] }
[target.'cfg(target_os = "macos")'.dependencies]
+ # The same winit as eframe; only the native termination opt-in is used.
+ winit = { version = "0.30", default-features = false }
muda = { version = "0.21", default-features = false }
+# The input context, to drop the IME's marked text when the Type tool ends a composition.
+objc2 = "0.6"
+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSTextInputContext"] }
diff --cc apps/designcraft/src/main.rs
index 27e3941ea,2f90f6484..d4830babd
--- a/apps/designcraft/src/main.rs
+++ b/apps/designcraft/src/main.rs
@@@ -72,17 -72,25 +76,36 @@@ impl eframe::App for App
}
}
+/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as
+/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.
+#[cfg(target_os = "macos")]
+fn discard_marked_text() {
+ if let Some(mtm) = objc2::MainThreadMarker::new()
+ && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)
+ {
+ ic.discardMarkedText();
+ }
+}
+
+ /// Orderly OS termination can bypass egui's cancelable close event. Finish only a complete,
+ /// current quit plan; otherwise preserve every live document, including edits after the timer.
+ fn preserve_documents_on_exit(app: &mut DesignApp) -> Result<(), String> {
+ app.finish_confirmed_quit()?;
+ if app.session.documents().is_empty() {
+ return Ok(());
+ }
+ if app.session.recovery_dir.is_none() {
+ return if app.session.documents().iter().any(|d| d.is_dirty()) {
+ Err("Recovery is unavailable; unsaved documents could not be preserved on exit".into())
+ } else {
+ Ok(())
+ };
+ }
+ // Also discard stale recovery for clean documents (for example, Undo back to the saved
+ // state after the last timer tick). Never choose a fallback recovery path here.
+ app.run("file.recovery.save", serde_json::json!({})).map(|_| ())
+ }
+
/// `DESIGNCRAFT_NO_PREFS`: read and write nothing in the settings directory (tests, demos).
fn no_prefs() -> bool {
std::env::var_os("DESIGNCRAFT_NO_PREFS").is_some()
diff --cc crates/engine/src/cmd/edit.rs
index b0ff09d74,a6fc061ba..5d46b98dd
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@@ -168,7 -174,9 +174,9 @@@ pub fn specs() -> Vec<CommandSpec>
st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
st.doc = e.doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
+ // Pending typing overrides belong to the current edit state, not a restored snapshot.
+ s.typing_format = None;
Ok(json!({"undone": e.label}))
}),
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| {
@@@ -177,7 -185,8 +185,8 @@@
st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
st.doc = e.doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
+ s.typing_format = None;
Ok(json!({"redone": e.label}))
}),
cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| {
diff --cc crates/engine/src/cmd/file.rs
index d5a60bc4d,f63f0d6e9..8467f773d
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -237,17 -264,20 +264,20 @@@ fn file_save(s: &mut Session, p: &Value
.map(str::to_string)
.or_else(|| st.path.clone())
.ok_or_else(|| bad("file.save", "missing `path` (document has never been saved)"))?;
- {
- let mut d = (*st.doc).clone();
- super::datamerge::refresh_relative_paths(&mut d, std::path::Path::new(&path));
- if d.data_merge != st.doc.data_merge {
- st.doc = Arc::new(d);
- st.bump_revision();
- }
- }
- let bytes = to_bytes(&st.doc);
+ // Before anything about the document changes: a refused save leaves it as it was.
+ crate::file_access::check_write(&path).map_err(EngineError::Other)?;
+ // Prepare paths for the destination without changing the live document until persistence succeeds.
+ let mut saved = (*st.doc).clone();
+ super::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path));
+ let paths_changed = saved.data_merge != st.doc.data_merge;
+ let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() };
+ let bytes = to_bytes(&saved);
#[cfg(not(target_arch = "wasm32"))]
- std::fs::write(&path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?;
+ if paths_changed {
+ st.doc = saved;
- st.revision = st.revision.saturating_add(1);
++ st.bump_revision();
+ }
st.path = Some(path.clone());
st.saved_revision = st.revision;
st.saved_doc = st.doc.clone();
@@@ -647,10 -722,9 +722,9 @@@ fn file_revert(s: &mut Session, _: &Val
let mut fresh = DocState::new(d, Some(path.clone()));
fresh.fonts = fonts;
fresh.uid = uid;
- *st = fresh;
- if let Some(dir) = &s.recovery_dir {
- crate::recovery::discard(dir, uid);
- }
- fresh.revision = s.doc()?.revision + 1;
++ // A new state has a revision no state had before, so caches don't show the old document.
+ crate::recovery::discard_document(s, index, recovery_dir.as_deref());
+ *s.doc_mut()? = fresh;
Ok(json!({"path": path}))
}
#[cfg(target_arch = "wasm32")]
diff --cc crates/engine/src/cmd/find.rs
index 241feb4b6,f57845bab..83d137248
--- a/crates/engine/src/cmd/find.rs
+++ b/crates/engine/src/cmd/find.rs
@@@ -222,29 -389,44 +389,44 @@@ fn change(s: &mut Session, p: &Value) -
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
let re = build(p)?;
+ let mut context = scope(s, p)?;
let st = s.doc()?;
- let (start_story, start_pos) = st.selection.text.map(|t| (Some(t.story), t.range().end)).unwrap_or((None, 0));
- let mut order: Vec<StoryId> = st.doc.stories.keys().copied().collect();
- if let Some(ss) = start_story
- && let Some(i) = order.iter().position(|x| *x == ss)
- {
- order.rotate_left(i);
- }
let mut hit = None;
- for (k, sid) in order.iter().enumerate() {
- let Some(story) = st.doc.story(*sid) else { continue };
- let from = if k == 0 && start_story == Some(*sid) { start_pos.min(story.len()) } else { 0 };
- if let Some(m) = re.find_at(&story.text, from) {
- hit = Some((*sid, m.start(), m.end()));
+ while let Some((sid, r)) = context.order.get(context.target).and_then(|i| context.targets.get(*i)).cloned() {
+ let text = target_text(&st.doc, sid, &r)?;
+ let from = context.offset.checked_sub(r.start).ok_or_else(|| bad("find", "invalid search cursor"))?;
+ if text.get(from..).is_none() {
+ return Err(bad("find", "invalid UTF-8 search cursor"));
+ }
+ if let Some(m) = re.find_at(text, from) {
+ let (a, b) = (r.start + m.start(), r.start + m.end());
+ // Match find_iter/captures_iter: suppress an empty match adjacent to the
+ // previous match's end, but keep adjacent nonempty matches.
+ if m.is_empty() && context.last_match_end == Some(b) {
+ context.advance_empty(text, m.end(), b);
+ continue;
+ }
+ hit = Some((sid, a, b));
+ context.last_match_end = Some(b);
+ if m.is_empty() {
+ context.advance_empty(text, m.end(), b);
+ } else {
+ context.offset = b;
+ }
break;
}
+ context.advance_target();
}
- let Some((sid, a, b)) = hit else { return Ok(Value::Null) };
+ let Some((sid, a, b)) = hit else {
+ s.find_context = Some(context);
+ return Ok(Value::Null);
+ };
let frame = st.doc.story(sid).and_then(|x| x.frames.first().copied());
let stm = s.doc_mut()?;
- stm.selection = designcraft_doc::Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });
- stm.revision += 1;
- let _ = story::PAGE_NUMBER;
+ stm.selection = Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });
- stm.revision += 1;
++ stm.bump_revision();
+ context.acknowledge(stm);
+ s.find_context = Some(context);
Ok(json!({"story": sid.0, "start": a, "end": b}))
}
@@@ -277,6 -459,664 +459,664 @@@ mod tests
s.execute("find.next", &json!({"find": "or"})).unwrap();
assert!(s.doc().unwrap().selection.text.is_some());
}
+ fn scope_session(text: &str) -> (Session, designcraft_doc::StoryId) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let frame = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();
+ (s, designcraft_doc::StoryId(frame["story"].as_u64().unwrap()))
+ }
+
+ fn scope_select(s: &mut Session, sid: designcraft_doc::StoryId, a: usize, b: usize) {
+ s.execute("text.select", &json!({"story": sid.0, "anchor": a, "focus": b})).unwrap();
+ }
+
+ fn scope_hit(s: &mut Session, p: &serde_json::Value, sid: designcraft_doc::StoryId, a: usize, b: usize) {
+ assert_eq!(s.execute("find.next", p).unwrap(), json!({"story": sid.0, "start": a, "end": b}));
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((selected.story, selected.range(), selected.cell), (sid, a..b, None));
+ }
+
+ #[test]
+ fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selection() {
+ for (texts, first, explicit, grep, expected, count) in [
+ (vec!["red red", "red"], Some(true), false, false, vec!["blue red", "red"], 1),
+ (vec!["keep", "red red", "red"], Some(true), false, false, vec!["keep", "blue red", "red"], 1),
+ (vec!["keep", "other"], Some(true), false, false, vec!["keep", "other"], 0),
+ (vec!["red red", "red"], Some(false), false, false, vec!["blue blue", "blue"], 3),
+ (vec!["red red", "red"], None, false, false, vec!["blue blue", "blue"], 3),
+ (vec!["red red", "red"], Some(true), true, false, vec!["blue red", "red"], 1),
+ (vec!["red red", "red"], Some(false), true, false, vec!["blue blue", "red"], 2),
+ (vec!["", "é🙂"], Some(true), false, true, vec!["X", "é🙂"], 1),
+ (vec!["é", "🙂"], Some(false), false, true, vec!["XéX", "X🙂X"], 4),
+ ] {
+ let (mut s, sid) = scope_session(texts[0]);
+ let mut sids = vec![sid];
+ for text in texts.iter().skip(1) {
+ let frame = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": text})).unwrap();
+ sids.push(designcraft_doc::StoryId(frame["story"].as_u64().unwrap()));
+ }
+ assert_eq!(s.doc().unwrap().doc.stories.keys().copied().collect::<Vec<_>>(), sids);
+ // Document Change keeps canonical target order even with a later story current.
+ scope_select(&mut s, *sids.last().unwrap(), 0, 0);
+ let before = s.doc().unwrap().doc.clone();
+ let mut p = json!({
+ "find": if grep { "(?:)" } else { "red" },
+ "change": if grep { "X" } else { "blue" },
+ "scope": "document", "grep": grep
+ });
+ if let Some(first) = first {
+ p["first"] = json!(first);
+ }
+ if explicit {
+ p["story"] = json!(sid.0);
+ p["scope"] = json!("selection");
+ }
+ if first == Some(true) && !explicit && !grep && texts.last() == Some(&"red") {
+ let last = *sids.last().unwrap();
+ scope_hit(&mut s, &p, last, 0, 3);
+ let first_hit = sids[if texts.len() == 2 { 0 } else { 1 }];
+ assert_eq!(
+ s.execute("find.find", &p).unwrap(),
+ json!([
+ {"story": first_hit.0, "start": 0, "end": 3, "text": "red"},
+ {"story": first_hit.0, "start": 4, "end": 7, "text": "red"},
+ {"story": last.0, "start": 0, "end": 3, "text": "red"}
+ ]),
+ "Count remains canonical after Next paints the later story"
+ );
+ }
+ let selection = s.doc().unwrap().selection.clone();
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": count}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.selection, selection);
+ for (i, sid) in sids.iter().enumerate() {
+ assert_eq!(st.doc.story(*sid).unwrap().text, expected[i]);
+ if texts[i] == expected[i] {
+ assert_eq!(st.doc.story(*sid), before.story(*sid), "untouched story {i} stays entirely unchanged");
+ }
+ }
+ st.doc.check().unwrap();
+ }
+
+ // Identical replacement is still one counted match, not a reason to visit another story.
+ let (mut s, sid) = scope_session("red red");
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "red"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, other_sid, 0, 3);
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ assert_eq!(
+ s.execute("find.change", &json!({"find": "red", "change": "red", "scope": "document", "first": true})).unwrap(),
+ json!({"count": 1})
+ );
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid), before.story(other_sid));
+ assert_eq!(s.doc().unwrap().selection, selection);
+ s.doc().unwrap().doc.check().unwrap();
+
+ for reverse in [false, true] {
+ let (mut s, sid) = scope_session("éX X");
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "X"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, sid, if reverse { 3 } else { 2 }, if reverse { 2 } else { 3 });
+ let before = s.doc().unwrap().doc.clone();
+ let mut selection = s.doc().unwrap().selection.clone();
+ let t = selection.text.as_mut().unwrap();
+ (t.anchor, t.focus) = if reverse { (6, 2) } else { (2, 6) };
+ let p = json!({"find": "X", "change": "🙂", "scope": "document", "first": true});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 3);
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, "é🙂 X");
+ assert_eq!(st.doc.story(other_sid), before.story(other_sid));
+ assert_eq!(st.selection, selection, "first-match exit must follow final UTF-8 repair");
+ st.doc.check().unwrap();
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "🙂", "scope": "selection"})).unwrap(),
+ json!([{"story": sid.0, "start": 2, "end": 6, "text": "🙂"}])
+ );
+ }
+ }
+
+ #[test]
+ fn find_scope_exact_baseline_count_next_change() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let frame = s
+ .execute(
+ "frame.create",
+ &json!({
+ "rect": [36, 36, 300, 200], "content": "text", "text": "red red"
+ }),
+ )
+ .unwrap();
+ let sid = frame["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "red", "scope": "selection"})).unwrap(),
+ json!([{"story": sid, "start": 0, "end": 3, "text": "red"}])
+ );
+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "selection"})).unwrap(), json!({"story": sid, "start": 0, "end": 3}));
+ assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "scope": "selection"})).unwrap(), json!({"count": 1}));
+ assert_eq!(s.execute("story.get", &json!({"story": sid})).unwrap()["text"], "blue red");
+ }
+
+ #[test]
+ fn find_scope_change_growth_preserves_direction_and_full_scalar_hits() {
+ for (text, find, change, changed, start, old_end, new_end) in [("a", "a", "é", "é", 0, 1, 2), ("éX", "X", "🙂", "é🙂", 2, 3, 6)] {
+ for reverse in [false, true] {
+ let (mut s, sid) = scope_session(text);
+ // Real caret movement keeps the frame identity, unlike text.select.
+ s.execute("text.move", &json!({"dir": "left", "extend": reverse})).unwrap();
+ if !reverse {
+ s.execute("text.move", &json!({"dir": "right", "extend": true})).unwrap();
+ }
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((selected.anchor, selected.focus), if reverse { (old_end, start) } else { (start, old_end) });
+ assert!(selected.frame.is_some());
+ let mut expected = s.doc().unwrap().selection.clone();
+ let t = expected.text.as_mut().unwrap();
+ (t.anchor, t.focus) = if reverse { (new_end, start) } else { (start, new_end) };
+ let p = json!({"find": find, "change": change, "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": old_end, "text": find}]));
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, changed);
+ assert_eq!(st.selection, expected);
+ let t = st.selection.text.unwrap();
+ assert!(changed.is_char_boundary(t.anchor) && changed.is_char_boundary(t.focus));
+ assert!(s.find_context.is_none());
+ let p = json!({"find": change, "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": new_end, "text": change}]));
+ scope_hit(&mut s, &p, sid, start, new_end);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_change_repairs_final_boundaries_without_remapping_valid_offsets() {
+ for (text, (a, b), find, change, changed, (after_a, after_b), count) in [
+ ("aX", (1, 1), "a", "é", "éX", (0, 0), 1), // A caret stays collapsed and floors.
+ ("aX", (2, 2), "a", "é", "éX", (2, 2), 1), // A valid caret stays at its byte offset.
+ ("abc", (1, 2), "abc", "🙂", "🙂", (0, 4), 1), // Both endpoints need repair.
+ ("abc", (2, 1), "abc", "🙂", "🙂", (4, 0), 1),
+ ("é🙂", (2, 6), "🙂", "X", "éX", (2, 3), 1), // Existing shortening behavior.
+ ("é🙂", (6, 2), "🙂", "X", "éX", (3, 2), 1),
+ ("red", (0, 3), "red", "blue", "blue", (0, 3), 1), // Do not extend a valid upper bound.
+ ("aX", (1, 2), "a", "zz", "zzX", (1, 2), 1), // Do not track the original X.
+ ("aaX", (1, 2), "a", "é", "ééX", (0, 2), 2), // Per-edit repair would wrongly yield 0..4.
+ ("aaX", (2, 3), "a", "é", "ééX", (2, 4), 2),
+ ("abc", (1, 3), "abc", "", "", (0, 0), 1),
+ ("abc", (2, 3), "abc", "é", "é", (2, 2), 1), // EOF clamp may collapse a nonempty range.
+ ] {
+ let (mut s, sid) = scope_session(text);
+ scope_select(&mut s, sid, a, b);
+ let mut expected = s.doc().unwrap().selection.clone();
+ let t = expected.text.as_mut().unwrap();
+ (t.anchor, t.focus) = (after_a, after_b);
+ assert_eq!(s.execute("find.change", &json!({"find": find, "change": change, "scope": "document"})).unwrap(), json!({"count": count}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, changed, "{text} {a}->{b}");
+ assert_eq!(st.selection, expected, "{text} {a}->{b}");
+ assert!(changed.is_char_boundary(after_a) && changed.is_char_boundary(after_b));
+ if after_a == after_b {
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "(?:)", "grep": true, "scope": "selection"})).unwrap(),
+ json!([{"story": sid.0, "start": after_a, "end": after_a, "text": ""}])
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_change_other_story_and_no_hits_preserve_selection() {
+ for explicit in [false, true] {
+ let (mut s, sid) = scope_session("éX");
+ let frame = s.doc().unwrap().selection.text.unwrap().frame.unwrap();
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "a"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, sid, 3, 2);
+ let before = s.doc().unwrap().selection.clone();
+ let mut p = json!({"find": "a", "change": "🙂", "scope": "document"});
+ if explicit {
+ p["story"] = json!(other_sid.0);
+ }
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 0}));
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");
+
+ s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap();
+ let before = s.doc().unwrap().selection.clone();
+ assert!(before.text.is_none());
+ p["find"] = json!("🙂");
+ p["change"] = json!("é");
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "é");
+ }
+ }
+
+ #[test]
+ fn find_scope_mixed_grep_matches_count_next_and_change() {
+ for (text, pattern, expected, changed) in [
+ ("a", "a*", vec![(0, 1)], "X"),
+ ("aa", "a|(?:)", vec![(0, 1), (1, 2)], "XX"),
+ ("ab", "a*", vec![(0, 1), (2, 2)], "XbX"),
+ ("éa", "é|(?:)", vec![(0, 2), (3, 3)], "XaX"),
+ ] {
+ let (mut s, sid) = scope_session(text);
+ scope_select(&mut s, sid, 0, text.len());
+ let p = json!({"find": pattern, "grep": true, "scope": "selection", "change": "X"});
+ let counted = s.execute("find.find", &p).unwrap();
+ let ranges: Vec<_> =
+ counted.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap() as usize, m["end"].as_u64().unwrap() as usize)).collect();
+ assert_eq!(ranges, expected, "{pattern} on {text}");
+ for (a, b) in &expected {
+ scope_hit(&mut s, &p, sid, *a, *b);
+ }
+ for _ in 0..2 {
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "{pattern} on {text}");
+ }
+ assert_eq!(s.execute("find.find", &p).unwrap(), counted);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], expected.len());
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, changed);
+ }
+ }
+
+ #[test]
+ fn find_scope_capture_replacement_and_first_keep_original_domain() {
+ let (mut s, sid) = scope_session("a1 a2 | a3");
+ scope_select(&mut s, sid, 0, 5);
+ let p = json!({"find": r"a(\d)", "grep": true, "scope": "selection", "change": "b$1", "first": true});
+ scope_hit(&mut s, &p, sid, 0, 2);
+ scope_hit(&mut s, &p, sid, 3, 5);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "b1 a2 | a3");
+ }
+
+ #[test]
+ fn find_scope_selection_retains_nonempty_hits_count_change_and_native_text() {
+ for (a, b) in [(0, 7), (7, 0)] {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, a, b);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection", "attrs": {"fontStyle": "Italic"}});
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ let revision = s.doc().unwrap().revision;
+ let history = s.doc().unwrap().history.undo.len();
+ let strong = std::sync::Arc::strong_count(&before);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ assert_eq!(s.doc().unwrap().selection, selection);
+ assert_eq!(s.doc().unwrap().revision, revision);
+ assert_eq!(std::sync::Arc::strong_count(&before), strong, "search stores weak document identity");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ scope_hit(&mut s, &p, sid, 4, 7);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 2);
+ let changed = s.doc().unwrap().doc.story(sid).unwrap().clone();
+ assert_eq!(changed.text, "blue blue | red");
+ assert_eq!(changed.char_format_at(0).over.font_style.as_deref(), Some("Italic"));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
+ assert!(s.find_context.is_none());
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert!(s.find_context.is_none());
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap(), &changed);
+ let native = s.execute("file.serialize", &json!({})).unwrap();
+ s.execute("file.openBytes", &json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();
+ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.story(sid).unwrap()).unwrap(), serde_json::to_value(&changed).unwrap());
+ assert!(s.find_context.is_none());
+ }
+ }
+
+ #[test]
+ fn find_scope_matcher_restart_replacement_continuation_and_external_reselection() {
+ let (mut s, sid) = scope_session("red blue red | blue red");
+ scope_select(&mut s, sid, 0, 12);
+ let mut p = json!({"find": "red", "scope": "selection", "change": "one"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["change"] = json!("two");
+ p["attrs"] = json!({"fontStyle": "Italic"});
+ scope_hit(&mut s, &p, sid, 9, 12);
+ p["find"] = json!("blue");
+ scope_hit(&mut s, &p, sid, 4, 8);
+ p["find"] = json!("red");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["caseSensitive"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["grep"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3); // GREP alone changes matcher identity.
+ p["find"] = json!("r.d");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["wholeWord"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let hit = s.doc().unwrap().selection.text.unwrap();
+ scope_select(&mut s, sid, hit.anchor, hit.focus);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1, "same-range external reselection starts a new domain");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ scope_select(&mut s, sid, 20, 23);
+ p["find"] = json!("red");
+ scope_hit(&mut s, &p, sid, 20, 23);
+ }
+
+ #[test]
+ fn find_scope_word_reselection_at_same_hit_recaptures_bounds() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let selected = s.doc().unwrap().selection.clone();
+ let frame = selected.text.unwrap().frame.unwrap();
+ let point = {
+ let st = s.doc().unwrap();
+ let cs = s.cache.get(&st.doc, sid, None);
+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();
+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);
+ assert_eq!(cs.frames[fi].frame, frame);
+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1), "real point lies inside the current hit");
+ let loc = st.doc.find(frame).unwrap();
+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner
+ };
+ let before = s.doc().unwrap().doc.clone();
+ let revision = s.doc().unwrap().revision;
+ let history = s.doc().unwrap().history.undo.len();
+ s.execute("text.selectWord", &json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();
+ assert!(!s.text_drag, "explicit word reselection does not start a text drag");
+ assert_eq!(s.doc().unwrap().selection, selected, "same full selection, including frame");
- assert_eq!(s.doc().unwrap().revision, revision + 1);
++ assert!(s.doc().unwrap().revision > revision, "a new revision");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert!(s.find_context.is_none());
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+
+ #[test]
+ fn find_scope_story_explicit_story_document_order_and_scope_changes() {
+ let (mut s, a) = scope_session("black red");
+ let other = s.execute("frame.create", &json!({"rect": [150, 36, 100, 100], "content": "text", "text": "red"})).unwrap();
+ let b = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, a, 0, 9);
+ let story = json!({"find": "red", "scope": "story"});
+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "Story does not enter B or wrap to its prefix");
+ scope_select(&mut s, b, 0, 0);
+ let explicit = json!({"find": "black", "story": a.0, "scope": "selection"});
+ scope_hit(&mut s, &explicit, a, 0, 5);
+ let selection = s.doc().unwrap().selection.clone();
+ assert!(s.execute("find.next", &json!({"find": "red", "story": u64::MAX})).is_err());
+ assert_eq!(s.doc().unwrap().selection, selection);
+ scope_select(&mut s, a, 0, 9);
+ scope_hit(&mut s, &json!({"find": "red"}), b, 0, 3);
+ let counted = s.execute("find.find", &json!({"find": "red"})).unwrap();
+ assert_eq!(counted[0]["story"], a.0, "Count retains canonical story order");
+ assert_eq!(counted[1]["story"], b.0);
+ scope_select(&mut s, a, 0, 9);
+ scope_hit(&mut s, &json!({"find": "red", "scope": "selection"}), a, 6, 9);
+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "scope change uses the current caret");
+ s.execute("selection.set", &json!({"ids": []})).unwrap();
+ for command in ["find.find", "find.next", "find.change"] {
+ assert!(s.execute(command, &json!({"find": "red", "change": "blue", "scope": "selection"})).is_err());
+ }
+ }
+
+ #[test]
+ fn find_scope_substring_context_utf8_zero_width_and_invalid_ranges() {
+ let (mut s, sid) = scope_session("scat é🙂 red");
+ scope_select(&mut s, sid, 1, 4);
+ let p = json!({"find": "cat", "wholeWord": true, "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 1, 4);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_select(&mut s, sid, 1, 4);
+ let p = json!({"find": "^c|^a", "grep": true, "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 1, 2);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "cursor does not redefine ^");
+ scope_select(&mut s, sid, 5, 11);
+ let empty = json!({"find": "(?:)", "grep": true, "scope": "selection"});
+ for pos in [5, 7, 11] {
+ scope_hit(&mut s, &empty, sid, pos, pos);
+ }
+ for _ in 0..2 {
+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);
+ }
+ assert_eq!(s.execute("find.find", &empty).unwrap().as_array().unwrap().len(), 3);
+ scope_select(&mut s, sid, 7, 7);
+ scope_hit(&mut s, &empty, sid, 7, 7);
+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);
+ scope_select(&mut s, sid, 12, 15);
+ let nonempty = json!({"find": "red", "change": "blue", "scope": "selection"});
+ scope_hit(&mut s, &nonempty, sid, 12, 15);
+ assert_eq!(s.execute("find.change", &nonempty).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "scat é🙂 blue");
+ for range in [6..7, 0..usize::MAX] {
+ let st = s.doc_mut().unwrap();
+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel {
+ story: sid,
+ anchor: range.start,
+ focus: range.end,
+ frame: None,
+ cell: None,
+ });
- st.revision += 1;
++ st.bump_revision();
+ for command in ["find.find", "find.next", "find.change"] {
+ let before = s.doc().unwrap().doc.clone();
+ let err = s.execute(command, &json!({"find": "x", "change": "y", "scope": "selection"})).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_invalid_query_keeps_continuation_and_cross_boundary_nonmatches() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let selected = s.doc().unwrap().selection.clone();
+ assert!(s.execute("find.next", &json!({"find": "[", "grep": true, "scope": "selection"})).is_err());
+ assert_eq!(s.doc().unwrap().selection, selected);
+ scope_hit(&mut s, &p, sid, 4, 7);
+ assert_eq!(s.execute("find.find", &json!({"find": "red |", "scope": "selection"})).unwrap(), json!([]));
+ }
+
+ #[test]
+ fn find_scope_document_switch_edit_and_reset() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("file.new", &json!({})).unwrap();
+ s.set_active(0);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_select(&mut s, sid, 0, 7);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("story.setText", &json!({"story": sid.0, "text": "red"})).unwrap();
+ assert!(s.find_context.is_none());
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ s.reset_find_scope();
+ assert!(s.find_context.is_none());
+ }
+
+ #[test]
+ fn find_scope_real_preview_restores_before_resolving_bounds() {
+ let (mut s, sid) = scope_session("");
+ s.execute(
+ "data.source.select",
+ &json!({
+ "bytes": crate::cmd::base64_encode(b"x\nred red | red\n"), "name": "scope.csv"
+ }),
+ )
+ .unwrap();
+ s.execute("data.placeholder.add", &json!({"field": "x", "story": sid.0, "at": 0})).unwrap();
+ let template = s.doc().unwrap().doc.clone();
+ assert_eq!(template.story(sid).unwrap().text, "<<x>>");
+ s.execute("data.preview", &json!({"record": 1})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ // Install a viewport selection in the real preview. text.select is journaled
+ // and would itself restore the template before selecting.
+ let st = s.doc_mut().unwrap();
+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel { story: sid, anchor: 0, focus: 7, frame: None, cell: None });
- st.revision += 1;
++ st.bump_revision();
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ let history = s.doc().unwrap().history.undo.len();
+ let err = s.execute("find.change", &p).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "<<x>>");
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert!(s.doc().unwrap().preview_stash.is_none());
+ assert!(s.find_context.is_none());
+ // Valid fresh bounds are allowed after restoration; no cached preview range
+ // survives. A document query can see the preview, but Next sees the template.
+ s.execute("data.preview", &json!({"record": 1})).unwrap();
+ let document = json!({"find": "red"});
+ assert_eq!(s.execute("find.find", &document).unwrap().as_array().unwrap().len(), 3);
+ assert_eq!(s.execute("find.next", &document).unwrap(), serde_json::Value::Null);
+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));
+ assert_eq!(s.execute("find.find", &document).unwrap(), json!([]));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ }
+
+ fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) {
+ let (mut s, sid) = scope_session("red");
+ scope_select(&mut s, sid, 3, 3);
+ if note {
+ s.execute("footnote.insert", &json!({"text": child})).unwrap();
+ } else {
+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();
+ s.execute("text.insert", &json!({"text": child, "raw": true})).unwrap();
+ }
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ (s, sid, selected)
+ }
+
+ #[test]
+ fn find_scope_children_error_atomically_and_parent_requests_stay_top_level() {
+ for note in [false, true] {
+ for child in ["red", "red x", "é red red red red red"] {
+ let (mut s, sid, mut selected) = child_scope_session(note, child);
+ selected.anchor = 0;
+ selected.focus = child.len();
+ s.doc_mut().unwrap().selection = designcraft_doc::Selection::text(selected);
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ let history = s.doc().unwrap().history.undo.len();
+ let revision = s.doc().unwrap().revision;
+ let journal = s.journal.clone();
+ for scope in ["story", "selection"] {
+ for command in ["find.find", "find.next", "find.change"] {
+ let err = s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(err.to_string().contains("not supported"));
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().selection, selection);
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert_eq!(s.doc().unwrap().revision, revision);
+ assert_eq!(s.journal, journal);
+ }
+ }
+ for explicit in [false, true] {
+ let mut p = json!({"find": "red", "change": "blue"});
+ if explicit {
+ p["story"] = json!(sid.0);
+ p["scope"] = json!("selection");
+ }
+ s.doc_mut().unwrap().selection = selection.clone();
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.doc_mut().unwrap().selection = selection.clone();
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.text_story(sid, selected.cell).unwrap().text, child);
+ assert_eq!(s.doc().unwrap().selection, selection, "parent replacement does not clamp child offsets");
+ p["find"] = json!("blue");
+ p["change"] = json!("red");
+ s.execute("find.change", &p).unwrap();
+ }
+ }
+ }
+ let (mut s, _, _) = child_scope_session(false, "red");
+ s.execute("table.selectTable", &json!({})).unwrap();
+ for scope in ["story", "selection"] {
+ for command in ["find.find", "find.next", "find.change"] {
+ assert!(
+ s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err().to_string().contains("not supported")
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_threaded_overset_story_uses_logical_offsets() {
+ let text = format!("{}red", "word ".repeat(100));
+ let (mut s, sid) = scope_session(&text);
+ let a = s.doc().unwrap().doc.story(sid).unwrap().frames[0];
+ let next = s.execute("frame.create", &json!({"rect": [150, 36, 20, 1], "content": "text"})).unwrap();
+ let b = designcraft_doc::ItemId(next["id"].as_u64().unwrap());
+ s.edit(|d, _| Ok(d.thread(a, b)?)).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().frames.len(), 2);
+ scope_select(&mut s, sid, 0, 0);
+ scope_hit(&mut s, &json!({"find": "red", "scope": "story"}), sid, 500, 503);
+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "story"})).unwrap(), serde_json::Value::Null);
+ }
+
+ #[test]
+ fn find_scope_zero_width_story_explicit_and_document_endpoints_terminate() {
+ for scope in ["story", "explicit", "document"] {
+ let (mut s, sid) = scope_session("é🙂");
+ scope_select(&mut s, sid, 0, 0);
+ let mut p = json!({"find": "(?:)", "grep": true, "scope": scope});
+ if scope == "explicit" {
+ p["story"] = json!(sid.0);
+ }
+ for pos in [0, 2, 6] {
+ scope_hit(&mut s, &p, sid, pos, pos);
+ }
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_revert_releases_context_with_same_document_uid() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("scope.designcraft");
+ let (mut s, sid) = scope_session("red red | red");
+ s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let uid = s.doc().unwrap().uid;
+ s.execute("story.setText", &json!({"story": sid.0, "text": "red red"})).unwrap();
+ scope_select(&mut s, sid, 0, 7);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("file.revert", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().uid, uid);
+ assert!(s.find_context.is_none());
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range");
+ }
}
/// Objects matching Find/Change › Object criteria, in document order (nested ones included).
diff --cc crates/engine/src/cmd/layout.rs
index 8ec59862c,fe06ad3ee..489fc634e
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@@ -380,6 -465,44 +465,44 @@@ pub fn specs() -> Vec<CommandSpec>
has_doc,
page_size
),
+ cmd!(
+ "layout.pageOptions",
+ "Page Options",
+ [],
+ None,
+ "{pages: [1-based], showParentOverlay?: bool} — Page tool options (Show Parent Page Overlay: the parent page's size drawn over the page)",
+ has_doc,
+ page_options
+ ),
+ cmd!(
+ noundo "layout.selectPage",
+ "Select Page",
+ [],
+ None,
+ "{page: 1-based | null, ids?: [item ids] (objects selected with it: the Page tool on an object-based page)} — the page the Page tool selects (its handles, the Control panel)",
+ has_doc,
+ |s, p| {
+ let n = s.doc()?.doc.page_count();
+ let page = match p.get("page") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(v.as_u64().filter(|v| *v >= 1 && *v as usize <= n).ok_or_else(|| bad("layout.selectPage", format!("`page`: 1–{n}")))? as usize - 1),
+ };
+ let ids: Vec<designcraft_doc::ItemId> = {
+ let d = &s.doc()?.doc;
+ p.get("ids")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(Value::as_u64).map(designcraft_doc::ItemId).filter(|id| d.item(*id).is_some()).collect())
+ .unwrap_or_default()
+ };
+ let st = s.doc_mut()?;
+ if page.is_some() {
+ st.selection = designcraft_doc::Selection::items(ids);
+ }
+ st.selection.page = page;
- st.revision += 1;
++ st.bump_revision();
+ Ok(json!({"page": page.map(|p| p + 1)}))
+ }
+ ),
cmd!(
"layout.section",
"Numbering & Section Options…",
diff --cc crates/engine/src/cmd/scripts.rs
index 0fa89c598,5b6d288aa..1719f5e3e
--- a/crates/engine/src/cmd/scripts.rs
+++ b/crates/engine/src/cmd/scripts.rs
@@@ -8,15 -10,23 +10,23 @@@ use crate::Result
fn run(s: &mut crate::Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").ok_or_else(|| bad("script.run", "`text` required"))?;
let steps = crate::script::parse(text).map_err(|e| bad("script.run", e))?;
- // The steps' own undo entries collapse into this command's single one.
- let uid = s.active().map(|d| d.uid);
- let before = s.active().map_or(0, |d| d.history.undo.len());
+ // The steps' own undo entries collapse into this command's single one. A step that fails
+ // rolls the successful prefix back (document, selection and history), so a half-run script
+ // never strands edits that can't be undone (#709).
+ let before = s.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.history.clone()));
let report = s.run_script(&steps);
if let Some(st) = s.active_mut()
- && Some(st.uid) == uid
- && st.history.undo.len() > before
+ && let Some((uid, doc, selection, history)) = &before
+ && st.uid == *uid
{
- st.history.undo.truncate(before);
+ if report.failed.is_some() {
+ st.doc = Arc::clone(doc);
+ st.selection = selection.clone();
+ st.history = history.clone();
- st.revision = st.revision.saturating_add(1);
++ st.bump_revision();
+ } else if st.history.undo.len() > history.undo.len() {
+ st.history.undo.truncate(history.undo.len());
+ }
}
let out = json!({"results": report.results, "steps": steps.len()});
match report.failed {
diff --cc crates/engine/src/cmd/text.rs
index 04f01b949,432297f35..0e6e4bec6
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@@ -42,7 -50,8 +50,8 @@@ pub fn specs() -> Vec<CommandSpec>
let a = floor_char_boundary(text, p.get("anchor").and_then(Value::as_u64).unwrap_or(0) as usize);
let f = floor_char_boundary(text, p.get("focus").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(a));
st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: f, frame: None, cell: None });
- st.revision += 1;
+ st.bump_revision();
+ s.typing_format = None;
ok()
}),
cmd!("text.insert", "Type", [], None, "{text, raw?: bool (no typographer's quotes)} — replaces the selected text", has_text, insert),
@@@ -345,7 -387,8 +375,8 @@@ fn select_at(s: &mut Session, p: &Value
s.typing_format = None;
let st = s.doc_mut()?;
st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: e, frame: Some(frame), cell });
+ // Explicit reselection invalidates the Find scope even when the range is unchanged.
- st.revision = st.revision.wrapping_add(1);
+ st.bump_revision();
Ok(json!({"story": sid.0, "anchor": a, "focus": e}))
}
@@@ -565,7 -633,11 +597,12 @@@ fn insert(s: &mut Session, p: &Value) -
let pos = r.start + text.len() - trail;
sel.text = Some(TextSel { anchor: pos, focus: pos, ..t });
Ok(json!({"pos": pos}))
- })
+ });
- if result.is_ok() {
++ // A preview (IME marked text) leaves the typing format to the text typed in the end.
++ if result.is_ok() && s.active().is_none_or(|d| d.interaction.is_none()) {
+ s.typing_format = None;
+ }
+ result
}
fn smart_quotes(s: &Session, text: &str) -> String {
@@@ -742,6 -814,62 +779,62 @@@ pub fn prev_word(s: &str, i: usize) ->
}
0
}
+ /// Selects `bounds(text, byte)` around the byte under `point` in `frame`. Unlike a caret
+ /// placement, a press inside the current selection is no start of a text drag here: it is the
+ /// third or later click of a row, which lands in the word or sentence just selected.
+ fn select_around(s: &mut Session, p: &Value, id: &str, bounds: fn(&str, usize) -> (usize, usize)) -> Result<Value> {
+ let frame = id_param(p, "frame").ok_or_else(|| bad(id, "missing frame"))?;
+ let pt = point_param(p, "point").unwrap_or(Point::ZERO);
+ let (sid, b, cell) = hit_byte(s, frame, pt).ok_or_else(|| bad(id, "not a text frame"))?;
+ let st = s.doc_mut()?;
+ let text = st.doc.text_story(sid, cell).map(|x| x.text.clone()).unwrap_or_default();
+ let (anchor, focus) = bounds(&text, floor_char_boundary(&text, b));
+ st.selection = Selection::text(TextSel { story: sid, anchor, focus, frame: Some(frame), cell });
- st.revision += 1;
++ st.bump_revision();
+ Ok(json!({"story": sid.0, "anchor": anchor, "focus": focus}))
+ }
+
+ /// The paragraph around byte `i`, without its `\n`.
+ fn para_bounds(s: &str, i: usize) -> (usize, usize) {
+ let i = i.min(s.len());
+ let a = s.get(..i).and_then(|t| t.rfind('\n')).map_or(0, |k| k + 1);
+ let b = s.get(i..).and_then(|t| t.find('\n')).map_or(s.len(), |k| i + k);
+ (a, b)
+ }
+
+ /// The sentence around byte `i`, within its paragraph: it ends after `.`, `!`, `?` or `…` (and
+ /// any closing quotes or brackets) followed by a space or the paragraph end, or after a CJK full
+ /// stop, and takes the spaces after it, as deleting a sentence should leave none behind.
+ fn sentence_bounds(s: &str, i: usize) -> (usize, usize) {
+ let (pa, pb) = para_bounds(s, i);
+ let para = s.get(pa..pb).unwrap_or("");
+ let mut start = 0;
+ let mut it = para.char_indices().peekable();
+ while let Some((_, c)) = it.next() {
+ let cjk = matches!(c, '。' | '!' | '?');
+ if !cjk && !matches!(c, '.' | '!' | '?' | '…') {
+ continue;
+ }
+ while it.peek().is_some_and(|&(_, c)| {
+ matches!(c, '.' | '!' | '?' | '…' | '。' | '!' | '?' | '"' | '\'' | '”' | '’' | '»' | '›' | ')' | ']' | '」' | '』' | ')')
+ }) {
+ it.next();
+ }
+ if !cjk && it.peek().is_some_and(|&(_, c)| !c.is_whitespace()) {
+ continue;
+ }
+ while it.peek().is_some_and(|&(_, c)| c.is_whitespace()) {
+ it.next();
+ }
+ let end = it.peek().map_or(para.len(), |&(k, _)| k);
+ if pa + end > i || end == para.len() {
+ return (pa + start, pa + end);
+ }
+ start = end;
+ }
+ (pa + start, pb)
+ }
+
/// Type ▸ Story Direction.
fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {
let vertical = p.get("vertical").and_then(Value::as_bool).ok_or_else(|| bad("type.storyDirection", "missing vertical"))?;
@@@ -825,7 -953,7 +918,7 @@@ fn move_caret(s: &mut Session, p: &Valu
s.typing_format = None;
let stm = s.doc_mut()?;
stm.selection.text = Some(if extend { TextSel { focus: new, ..t } } else { TextSel { anchor: new, focus: new, ..t } });
-- stm.revision += 1;
++ stm.bump_revision();
Ok(json!({"pos": new}))
}
@@@ -2289,3 -2745,303 +2710,239 @@@ mod story_query_contract_tests
assert_eq!(s.execute("story.get", &json!({})).unwrap()["text"], "");
}
}
+
+ #[cfg(test)]
+ mod sentence_selection_tests {
+ use super::{para_bounds, sentence_bounds};
+
+ fn sentence(s: &str, at: &str) -> String {
+ let i = s.find(at).unwrap();
+ let (a, b) = sentence_bounds(s, i);
+ s[a..b].to_string()
+ }
+
+ #[test]
+ fn sentences_end_at_a_stop_before_a_space_or_the_paragraph_end() {
+ let s = "It costs 3.5 euros. \u{201C}Really?\u{201D} (Twice!) Yes\u{2026} fine.\nNext one. Last";
+ assert_eq!(sentence(s, "costs"), "It costs 3.5 euros. ");
+ assert_eq!(sentence(s, "Really"), "\u{201C}Really?\u{201D} ");
+ assert_eq!(sentence(s, "Twice"), "(Twice!) ");
+ assert_eq!(sentence(s, "Yes"), "Yes\u{2026} ");
+ assert_eq!(sentence(s, "fine"), "fine.");
+ assert_eq!(sentence(s, "one"), "Next one. ");
+ assert_eq!(sentence(s, "Last"), "Last");
+ // The caret at the very end of a paragraph is in its last sentence.
+ let end = s.find('\n').unwrap();
+ assert_eq!(sentence_bounds(s, end), (s.find("fine").unwrap(), end));
+ }
+
+ #[test]
+ fn cjk_full_stops_end_sentences_without_a_space() {
+ let s = "これは文です。次の文!最後";
+ assert_eq!(sentence(s, "次"), "次の文!");
+ assert_eq!(sentence(s, "最後"), "最後");
+ }
+
+ #[test]
+ fn paragraphs_stop_at_returns() {
+ let s = "One.\nTwo two.\n";
+ assert_eq!(para_bounds(s, 6), (5, 13));
+ assert_eq!(para_bounds(s, 0), (0, 4));
+ assert_eq!(para_bounds(s, s.len()), (s.len(), s.len()));
+ }
+ }
+
+ #[cfg(test)]
+ mod open_type_features_tests {
+ use serde_json::{Value, json};
+
+ use crate::Session;
+
+ fn feature<'a>(v: &'a Value, tag: &str) -> &'a Value {
+ v["features"].as_array().unwrap().iter().find(|f| f["tag"] == tag).unwrap_or(&Value::Null)
+ }
+
+ #[test]
+ fn the_selected_fonts_features_are_listed_with_their_state() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Hello fi"})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 8})).unwrap();
+ let v = s.execute("type.openTypeFeatures", &json!({})).unwrap();
+ assert_eq!(v["fonts"][0]["family"], "Source Serif 4", "{v}");
+ assert_eq!(feature(&v, "liga")["applied"], "all", "liga is on by default: {v}");
+ assert_eq!(feature(&v, "kern")["available"], "all", "{v}");
+ }
+
+ #[test]
+ fn a_feature_on_part_of_the_selection_is_some_and_on_all_of_it_is_all() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Hello world"})).unwrap();
+ let story = r["story"].clone();
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 5})).unwrap();
+ s.execute("type.feature", &json!({"features": {"lnum": true}})).unwrap();
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 11})).unwrap();
+ let v = s.execute("type.openTypeFeatures", &json!({})).unwrap();
+ assert_eq!(feature(&v, "lnum")["applied"], "some", "{v}");
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 5})).unwrap();
+ let v = s.execute("type.openTypeFeatures", &json!({})).unwrap();
+ assert_eq!(feature(&v, "lnum")["applied"], "all", "{v}");
+ s.execute("type.feature", &json!({"features": {"lnum": false}})).unwrap();
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 11})).unwrap();
+ let v = s.execute("type.openTypeFeatures", &json!({})).unwrap();
+ assert_eq!(feature(&v, "lnum")["applied"], "none", "{v}");
+ }
+ }
+
+ #[cfg(test)]
+ mod gradient_text_tests {
+ use serde_json::json;
+
+ /// Mean red and blue of the ink (pixels whose green is low: red → blue has none) in columns
+ /// `x0..x1`.
+ fn ink(img: &designcraft_render::Rendered, x0: u32, x1: u32) -> (f64, f64) {
+ let (mut r, mut b, mut n) = (0.0, 0.0, 0.0);
+ for x in x0..x1 {
+ for y in 0..img.height {
+ let p = img.pixel(x, y);
+ if p[1] < 100 {
+ (r, b, n) = (r + p[0] as f64, b + p[2] as f64, n + 1.0);
+ }
+ }
+ }
+ assert!(n > 50.0, "no ink in {x0}..{x1}");
+ (r / n, b / n)
+ }
+
+ /// Red ink at the frame's left, blue at its right.
+ fn check(img: &designcraft_render::Rendered, what: &str) {
+ let (lr, lb) = ink(img, 0, 60);
+ let (rr, rb) = ink(img, 200, 300);
+ assert!(lr > lb + 80.0, "{what}: the left ink is red ({lr:.0}, {lb:.0})");
+ assert!(rb > rr + 80.0, "{what}: the right ink is blue ({rr:.0}, {rb:.0})");
+ }
+
+ #[test]
+ fn a_gradient_on_text_spans_its_frame_on_screen_and_in_pdf() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"width": 300, "height": 120, "facingPages": false, "margins": 0})).unwrap();
+ // A gradient swatch (an off-page object's unnamed one), red → blue.
+ let shape = s.execute("frame.create", &json!({"rect": [-60, 0, -50, 10], "content": "unassigned"})).unwrap()["id"].clone();
+ s.execute("object.gradient", &json!({"ids": [shape], "stops": [{"location": 0, "color": "#ff0000"}, {"location": 100, "color": "#0000ff"}]}))
+ .unwrap();
+ let id = designcraft_doc::ItemId(shape.as_u64().unwrap());
+ let swatch = s.doc().unwrap().doc.item(id).unwrap().fill.swatch.clone();
+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 120], "content": "text", "text": "IIIIIIIIIIIIIIIIIIIIIIIIIIIIII"})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 30})).unwrap();
+ s.execute("type.char", &json!({"size": 60, "tracking": 0, "fill": swatch})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let mut rr = designcraft_render::Renderer::new();
+ check(&rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap(), "screen");
+ // The PDF, placed back and drawn: the same gradient.
+ let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
+ let mut p = crate::Session::new();
+ p.execute("file.new", &json!({"width": 300, "height": 120, "facingPages": false})).unwrap();
+ p.execute("file.place", &json!({"base64": super::super::file::base64_encode(&pdf), "name": "text.pdf", "x": 0, "y": 0, "width": 300}))
+ .unwrap();
+ let d = p.doc().unwrap().doc.clone();
+ check(&rr.render_page(&d, &p.cache, 0, 1.0, false, &Default::default()).unwrap(), "pdf");
+ }
+
+ /// The columns the red → blue ink spans (black table edges left out).
+ fn ink_span(img: &designcraft_render::Rendered) -> (u32, u32) {
+ let cols: Vec<u32> = (0..img.width)
+ .filter(|&x| {
+ (0..img.height).any(|y| {
+ let p = img.pixel(x, y);
+ p[1] < 100 && p[0].max(p[2]) > 100
+ })
+ })
+ .collect();
+ (*cols.first().unwrap(), *cols.last().unwrap())
+ }
+
+ /// Mean red and blue of the red → blue ink in columns `x0..x1`.
+ fn coloured_ink(img: &designcraft_render::Rendered, x0: u32, x1: u32) -> (f64, f64) {
+ let (mut r, mut b, mut n) = (0.0, 0.0, 0.0);
+ for x in x0..x1 {
+ for y in 0..img.height {
+ let p = img.pixel(x, y);
+ if p[1] < 100 && p[0].max(p[2]) > 100 {
+ (r, b, n) = (r + p[0] as f64, b + p[2] as f64, n + 1.0);
+ }
+ }
+ }
+ assert!(n > 20.0, "no ink in {x0}..{x1}");
+ (r / n, b / n)
+ }
+
+ #[test]
+ fn a_gradient_on_table_cell_text_spans_the_cells_text_in_pdf_as_on_screen() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"width": 300, "height": 120, "facingPages": false, "margins": 0})).unwrap();
+ // A gradient swatch (an off-page object's unnamed one), red → blue.
+ let shape = s.execute("frame.create", &json!({"rect": [-60, 0, -50, 10], "content": "unassigned"})).unwrap()["id"].clone();
+ s.execute("object.gradient", &json!({"ids": [shape], "stops": [{"location": 0, "color": "#ff0000"}, {"location": 100, "color": "#0000ff"}]}))
+ .unwrap();
+ let g = s.doc().unwrap().doc.item(designcraft_doc::ItemId(shape.as_u64().unwrap())).unwrap().fill.swatch.clone();
+ let r = s.execute("frame.create", &json!({"rect": [0, 0, 300, 120], "content": "text", "text": ""})).unwrap();
+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
+ s.execute("table.insert", &json!({"rows": 1, "cols": 3})).unwrap();
+ // A third of the frame's width: the cell's text, red → blue.
+ let mut d: designcraft_doc::Document = (*s.doc().unwrap().doc).clone();
+ let sid = d.stories.values().find(|st| !st.tables.is_empty()).unwrap().id;
+ let t = std::sync::Arc::make_mut(d.story_mut(sid).unwrap().tables.values_mut().next().unwrap());
+ let text = &mut t.cell_mut(0, 0).unwrap().text;
+ text.insert(0, "HHHH");
+ text.format_chars(0..4, |f| {
+ f.over.fill = Some(g.clone());
+ f.over.size = Some(24.0);
+ });
+ let mut rr = designcraft_render::Renderer::new();
+ let cache = designcraft_compose::Cache::new();
+ let screen = rr.render_page(&d, &cache, 0, 1.0, false, &Default::default()).unwrap();
+ let pdf = designcraft_pdf::export_pdf(&d, &cache, &Default::default()).unwrap();
+ let mut p = crate::Session::new();
+ p.execute("file.new", &json!({"width": 300, "height": 120, "facingPages": false})).unwrap();
+ p.execute("file.place", &json!({"base64": super::super::file::base64_encode(&pdf), "name": "cell.pdf", "x": 0, "y": 0, "width": 300}))
+ .unwrap();
+ let placed = rr.render_page(&p.doc().unwrap().doc.clone(), &p.cache, 0, 1.0, false, &Default::default()).unwrap();
+ let (x0, x1) = ink_span(&screen);
+ assert!(x1 < 120, "the text stays in the first column: {x0}..{x1}");
+ let q = (x1 - x0) / 4;
+ for (what, img) in [("screen", &screen), ("pdf", &placed)] {
+ let (lr, lb) = coloured_ink(img, x0, x0 + q);
+ let (rr, rb) = coloured_ink(img, x1 + 1 - q, x1 + 1);
+ assert!(lr > lb + 50.0, "{what}: the left ink is red ({lr:.0}, {lb:.0})");
+ assert!(rb > rr + 50.0, "{what}: the right ink is blue ({rr:.0}, {rb:.0})");
+ }
+ }
+ }
+
-#[cfg(test)]
-mod compose_tests {
- use serde_json::json;
-
- use crate::Session;
-
- /// A story "Ta" with the caret after "T" and 30 pt chosen for the next typing.
- fn session() -> (Session, u64) {
- let mut s = Session::new();
- s.execute("file.new", &json!({})).unwrap();
- let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 200], "content": "text", "text": "Ta"})).unwrap();
- let sid = r["story"].as_u64().unwrap();
- s.set_tool("type");
- s.execute("text.select", &json!({"story": sid, "anchor": 1})).unwrap();
- s.execute("type.char", &json!({"attrs": {"size": 30}})).unwrap();
- (s, sid)
- }
-
- fn text(s: &Session, sid: u64) -> String {
- s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone()
- }
-
- /// ⌥E shows the accent in the story, in the format it will be typed in, then I types "í":
- /// one undo step, and the accent was never part of the document.
- #[test]
- fn composed_text_shows_in_the_typing_format_until_it_is_typed() {
- let (mut s, sid) = session();
- let r = s.execute("text.compose", &json!({"text": "´"})).unwrap();
- assert_eq!(r["range"], json!([1, 3]));
- assert_eq!(text(&s, sid), "T´a");
- let size_at = |s: &Session, b| s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().char_format_at(b).over.size;
- assert_eq!(size_at(&s, 2), Some(30.0), "the accent is shown in the format chosen at the caret");
- assert_eq!(s.composition().map(|c| c.2), Some(1..3));
- s.execute("text.compose", &json!({"text": "¨"})).unwrap();
- assert_eq!(text(&s, sid), "T¨a", "a new composition replaces the last one");
- s.execute("text.compose", &json!({"text": ""})).unwrap();
- assert_eq!(text(&s, sid), "Ta");
- assert!(s.composition().is_none());
- s.execute("text.insert", &json!({"text": "í"})).unwrap();
- assert_eq!(text(&s, sid), "Tía");
- assert_eq!(size_at(&s, 2), Some(30.0), "the typing format survived the composition");
- s.execute("edit.undo", &json!({})).unwrap();
- assert_eq!(text(&s, sid), "Ta");
- }
-
- /// Anything else that edits, a tool change or a drag drops the uncommitted accent.
- #[test]
- fn other_edits_drop_the_composed_text() {
- for act in 0..3 {
- let (mut s, sid) = session();
- s.execute("text.compose", &json!({"text": "´"})).unwrap();
- match act {
- 0 => {
- s.execute("text.move", &json!({"dir": "right"})).unwrap();
- }
- 1 => s.set_tool("selection"),
- _ => s.begin_interaction("Move").unwrap(),
- }
- assert_eq!(text(&s, sid), "Ta", "case {act}");
- assert!(s.composition().is_none());
- }
- }
-}
-
+ #[cfg(test)]
+ mod placeholder_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ /// Fill with Placeholder Text gives paragraphs of a few sentences, as InDesign's does (it was one
+ /// paragraph, and the filler ran sentences together: "interit.Ovid").
+ #[test]
+ fn placeholder_text_comes_in_paragraphs() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 336, 736], "content": "text", "text": ""})).unwrap();
+ s.execute("type.fillWithPlaceholder", &json!({"frame": r["id"]})).unwrap();
+ let st = s.execute("story.get", &json!({"story": r["story"]})).unwrap();
+ let text = st["text"].as_str().unwrap();
+ let paragraphs: Vec<&str> = text.split('\n').collect();
+ assert!(paragraphs.len() >= 4, "{} paragraphs", paragraphs.len());
+ for p in &paragraphs {
+ assert!(p.ends_with('.') && !p.starts_with(' '), "a paragraph of whole sentences: {p:?}");
+ }
+ assert!(!text.contains(".O") && !text.contains(".L"), "sentences are spaced: {text}");
+ assert!(st["overset"].is_null(), "nothing overset: {}", st["overset"]);
+ assert!(text.len() > 1500, "the frame is filled: {}", text.len());
+ }
+ }
diff --cc crates/engine/src/guard.rs
index 4e4c9c030,74e16b882..92ef1332f
--- a/crates/engine/src/guard.rs
+++ b/crates/engine/src/guard.rs
@@@ -35,19 -35,25 +35,24 @@@ pub fn install_panic_hook()
impl Session {
/// Run command `id` (`f`) inside the guard.
pub(crate) fn guarded(&mut self, id: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
- let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone()));
+ // The whole command transaction: every open document with its undo/redo history and
+ // selection, which one is active, and the journal (nested commands journal too).
+ let docs = self.docs.clone();
+ let active = self.active;
- let revision = self.active().map_or(0, |d| d.revision);
+ let journal = self.journal.len();
match catch_unwind(AssertUnwindSafe(|| f(self))) {
Ok(r) => r,
Err(payload) => {
let msg = panic_message(payload.as_ref());
- // Keep the document as it was before the command.
- if let (Some((uid, doc, selection)), Some(st)) = (before, self.active_mut())
- && st.uid == uid
- {
- st.doc = doc;
- st.selection = selection;
+ // Keep the documents as they were before the command: a nested edit that
+ // succeeded before the panic is rolled back with its history entry, a document
+ // opened or switched by the command is gone, and redo it cleared is back.
+ self.docs = docs;
+ self.active = active;
+ self.journal.truncate(journal);
+ if let Some(st) = self.active_mut() {
st.interaction = None;
- st.revision = revision.max(st.revision).saturating_add(1);
+ st.bump_revision();
}
if let Some(dir) = self.recovery_dir.clone()
&& let Err(e) = crate::recovery::save(self, &dir)
diff --cc crates/engine/src/lib.rs
index 3a84c7365,745e45647..8b770aceb
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -368,20 -387,26 +399,33 @@@ impl Session
pub fn doc_mut(&mut self) -> Result<&mut DocState> {
self.active_mut().ok_or(EngineError::NoDocument)
}
+ /// Release the transient Find/Change domain when its caller starts or closes a search.
+ pub fn reset_find_scope(&mut self) {
+ self.find_context = None;
+ }
+
+ fn discard_stale_find_scope(&mut self) {
+ if self.find_context.as_ref().is_some_and(|c| self.active().is_none_or(|st| !c.is_current(st))) {
+ self.reset_find_scope();
+ }
+ }
+
pub fn set_active(&mut self, i: usize) {
if i < self.docs.len() && self.active != Some(i) {
+ // The composition belongs to the document it shows in.
+ if let Err(e) = self.end_composition() {
+ log::warn!("ending the IME composition: {e}");
+ }
+ self.reset_find_scope();
self.stop_data_preview();
self.active = Some(i);
}
}
pub fn add_document(&mut self, d: DocState) -> usize {
+ if let Err(e) = self.end_composition() {
+ log::warn!("ending the IME composition: {e}");
+ }
+ self.reset_find_scope();
self.stop_data_preview();
self.docs.push(d);
self.active = Some(self.docs.len() - 1);
@@@ -563,7 -592,8 +613,8 @@@
doc.sync_endnote_story();
st.doc = Arc::new(doc);
st.selection = sel;
- st.revision += 1;
+ st.bump_revision();
+ self.reset_find_scope();
Ok(r)
}
}
@@@ -581,8 -611,10 +632,12 @@@ pub(crate) use push_undo as record_undo
#[cfg(test)]
mod tests;
#[cfg(test)]
+ mod tests_file_guard;
+ #[cfg(test)]
mod tests_idml;
#[cfg(test)]
+mod tests_ime;
+#[cfg(test)]
+ mod tests_roots;
+ #[cfg(test)]
mod tests_table;
diff --cc crates/engine/src/recovery.rs
index 1011e1396,ac1d8d346..46c21ceee
--- a/crates/engine/src/recovery.rs
+++ b/crates/engine/src/recovery.rs
@@@ -229,9 -797,33 +797,33 @@@ fn open_with_publisher(s: &mut Session
st.fonts = fonts;
// Unsaved: the copy on disk (if any) is older than what was recovered.
st.saved_doc = std::sync::Arc::new((*st.doc).clone());
- st.revision += 1;
+ st.bump_revision();
- opened.push(s.add_document(st));
- discard(dir, uid);
+ let index = s.add_document(st);
+ opened.push(index);
+ // New uids are published without replacement, and the original is consumed only after
+ // both files succeed. Track a published primary even if metadata fails, so Save/Close can
+ // clean up every snapshot this document actually owns rather than an unrelated same uid.
+ if let Some(state) = s.docs.get_mut(index) {
+ let (document, metadata) = files(&destination, state.uid);
+ let published = designcraft_format::save(state.doc.as_ref())
+ .map_err(|e| EngineError::Other(e.to_string()))
+ .and_then(|bytes| publish(&document, &bytes));
+ match published {
+ Ok(()) => {
+ target.record(state.uid);
+ state.recovery_entries.push((destination.clone(), state.uid));
+ let meta = json!({"path": state.path, "title": state.title(), "saved": designcraft_doc::vars::now()});
+ match publish(&metadata, meta.to_string().as_bytes()) {
+ Ok(()) => {
+ discard(dir, uid);
+ state.recovery_entries = vec![(destination.clone(), state.uid)];
+ }
+ Err(e) => log::warn!("recovery entry {uid} kept: {e}"),
+ }
+ }
+ Err(e) => log::warn!("recovery entry {uid} kept: {e}"),
+ }
+ }
}
Ok(opened)
}
diff --cc crates/engine/src/tooling.rs
index 440eee8db,820c270f4..c4e3e6fbc
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@@ -58,11 -61,12 +60,15 @@@ impl Session
if self.tool.id() == id {
return;
}
- self.end_composition();
+ // A composition ends with the tool that shows it: its marked text stays as typed.
+ if let Err(e) = self.end_composition() {
+ log::warn!("ending the IME composition: {e}");
+ }
self.tool = designcraft_tools::create(id);
+ // Any other tool unloads the place cursor.
+ if id != "placeGun" {
+ self.loaded = None;
+ }
// Leaving the Type tool keeps the text frame selected.
if id != "type"
&& let Some(st) = self.active_mut()
diff --cc crates/tools/src/text.rs
index 625d998f3,e2fe043de..9e6a8506c
--- a/crates/tools/src/text.rs
+++ b/crates/tools/src/text.rs
@@@ -54,78 -37,6 +54,82 @@@ impl TypeTool
}
}
+/// Byte range in `s` of the characters `r` (IME ranges count characters; carets count bytes).
+/// `None` when `r` runs past the end of `s` or backwards.
+fn char_range_to_bytes(s: &str, r: Range<usize>) -> Option<Range<usize>> {
+ let n = s.chars().count();
+ let byte = |c: usize| if c == n { Some(s.len()) } else { s.char_indices().nth(c).map(|(i, _)| i) };
+ let (a, b) = (byte(r.start)?, byte(r.end)?);
+ (a <= b).then_some(a..b)
+}
+
+/// Text space → canvas for frame `fid` (with the quarter turn of a vertical frame).
+fn text_canvas_xf(cx: &ToolContext, fid: ItemId) -> Option<Affine> {
+ Some(cx.item_canvas_xf(fid)? * cx.doc.text_xf(cx.doc.item(fid)?))
+}
+
+/// Where the marked text starts: the preview typed it just before the caret.
+fn marked_start(cx: &ToolContext, ts: TextSel, p: &Preedit) -> usize {
+ let text = cx.doc.text_story(ts.story, ts.cell).map_or("", |s| s.text.as_str());
+ designcraft_doc::story::floor_char_boundary(text, ts.focus.saturating_sub(p.text.len()))
+}
+
+/// The caret line (top, bottom) at byte `pos` of the selection's text, in canvas space; `None`
+/// when `pos` isn't composed (overset).
+fn caret_line(cx: &ToolContext, ts: TextSel, pos: usize) -> Option<(Point, Point)> {
+ let cs = cx.cache.get(cx.doc, ts.story, None);
+ let (fi, x, bl, asc, desc) = match ts.cell {
+ Some(c) => match c.footnote_id() {
+ Some(id) => compose::note_caret(&cs, id, pos)?,
+ None => compose::cell_caret(&cs, c.table, c.row, c.col, pos)?,
+ },
+ None => compose::caret(&cs, pos)?,
+ };
- let m = text_canvas_xf(cx, cs.frames.get(fi)?.frame)?;
- Some((m * Point::new(x, bl - asc), m * Point::new(x, bl + desc)))
++ let ft = cs.frames.get(fi)?;
++ let m = text_canvas_xf(cx, ft.frame)?;
++ // Type on a path: the caret stands across the path where it is along it.
++ let map = cx.doc.item(ft.frame).filter(|_| ts.cell.is_none()).and_then(|it| compose::PathTextMap::new(it, ft));
++ let on = |p: Point| map.as_ref().map_or(p, |map| map.to_path(p));
++ Some((m * on(Point::new(x, bl - asc)), m * on(Point::new(x, bl + desc))))
+}
+
+/// Underlines (start, end in canvas space) under bytes `r` of the selection's text.
+fn underlines(cx: &ToolContext, ts: TextSel, r: Range<usize>) -> Vec<(Point, Point)> {
+ let mut out = Vec::new();
+ let mut add = |lines: &[compose::Line], m: Affine| {
+ for l in lines {
+ let (s, e) = (r.start.max(l.range.start), r.end.min(l.range.end));
+ if s < e {
+ out.extend(compose::highlight_quads(l, s, e, false).into_iter().map(|q| (m * q[3], m * q[2])));
+ }
+ }
+ };
+ let cs = cx.cache.get(cx.doc, ts.story, None);
+ match ts.cell {
+ // A cell's or footnote's text is composed on its own and placed in the frame.
+ Some(c) => {
+ let found = match c.footnote_id() {
+ Some(id) => compose::find_note(&cs, id).map(|(fi, n)| (fi, n.origin, n.text.clone())),
+ None => compose::find_cell(&cs, c.table, c.row, c.col).map(|(fi, _, pc)| (fi, pc.origin, pc.text.clone())),
+ };
+ if let Some((fi, origin, text)) = found
+ && let Some(m) = cs.frames.get(fi).and_then(|ft| text_canvas_xf(cx, ft.frame))
+ && let Some(ft) = text.frames.first()
+ {
+ add(&ft.lines, m * Affine::translate(origin.to_vec2()));
+ }
+ }
+ None => {
+ for ft in &cs.frames {
+ if let Some(m) = text_canvas_xf(cx, ft.frame) {
+ add(&ft.lines, m);
+ }
+ }
+ }
+ }
+ out
+}
+
impl Tool for TypeTool {
fn id(&self) -> &'static str {
if self.vertical { "verticalType" } else { "type" }
diff --cc crates/ui-egui/src/canvas.rs
index 95da053f5,40b146f56..749596aeb
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -982,9 -1078,14 +1079,11 @@@ fn draw_text_selection
cells: Option<designcraft_doc::TableSel>,
) {
let cs = app.session.cache.get(doc, ts.story, None);
- // Text an input method is composing at the caret is marked like it is in every Mac text
- // field: a yellow box behind the glyphs.
- let composing = app.session.composition().filter(|c| c.0 == ts.story && c.1 == ts.cell && ts.is_caret()).map(|c| c.2);
- let range = composing.clone().unwrap_or_else(|| ts.range());
- let tint = if composing.is_some() { COMPOSING_FILL.gamma_multiply(0.7) } else { Color32::from_rgba_unmultiplied(80, 140, 255, 110) };
+ let range = ts.range();
++ let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 110);
// Selected table cells: tint every selected cell.
if let Some(sel) = cells.filter(|c| c.story == ts.story) {
+ let selected = doc.story(sel.story).and_then(|s| s.tables.get(&sel.table)).map(|t| t.selected_owners(sel.range)).unwrap_or_default();
for ft in &cs.frames {
let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { continue };
let m = a * doc.text_xf(it);
@@@ -1056,12 -1179,15 +1177,14 @@@
&& let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame))
{
let m = a * doc.text_xf(it);
+ // Type on a path: the caret stands across the path where it is along it.
+ let on = |p: Point| compose::PathTextMap::new(it, ft).map_or(p, |map| map.to_path(p));
+ let p0 = xf.to_screen(m * on(Point::new(x, bl - asc)));
+ let p1 = xf.to_screen(m * on(Point::new(x, bl + desc)));
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
- let p0 = xf.to_screen(m * Point::new(x, bl - asc));
- let p1 = xf.to_screen(m * Point::new(x, bl + desc));
painter.line_segment([p0, p1], Stroke::new(1.0, Color32::BLACK));
}
- remember_ime_caret(painter, p0, p1);
painter.ctx().request_repaint_after(std::time::Duration::from_millis(330));
}
}
@@@ -1111,13 -1254,12 +1234,11 @@@ fn draw_cell_selection
}
{
let m = a * doc.text_xf(it);
+ let (p0, p1) = (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc)));
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
- painter.line_segment(
- [xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc))],
- Stroke::new(1.0, Color32::BLACK),
- );
+ painter.line_segment([p0, p1], Stroke::new(1.0, Color32::BLACK));
}
- remember_ime_caret(painter, p0, p1);
painter.ctx().request_repaint_after(std::time::Duration::from_millis(330));
}
}
@@@ -1998,6 -2507,144 +2542,147 @@@ mod tests
}
}
+ /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a
+ /// row must land within the double-click delay).
+ fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) {
+ 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, 400], "content": "text", "text": text})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ app.run("tool.select", json!({"tool": "type"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let ctx = ui.ctx().clone();
+ app.logic(&ctx);
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(4);
+ (h, id)
+ }
+
+ /// The screen point over the first line of frame `id` where a click puts the caret at a byte
+ /// in `bytes`.
+ fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range<usize>) -> Pos2 {
+ let mut x = 74.0;
+ let p = loop {
+ assert!(x < 400.0, "no point on the first line hits {bytes:?}");
+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap();
+ if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) {
+ break Point::new(x, 80.0);
+ }
+ x += 1.0;
+ };
+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();
+ let app = h.state();
+ let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p);
+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)
+ }
+
+ fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) {
+ for pressed in [true, false] {
+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.step();
+ }
+ }
+
+ fn selected(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {
+ h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default()
+ }
+
+ #[test]
+ fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() {
+ let text = "One two. Three four! Five six.\nSecond para here.";
+ let (mut h, id) = typing(text);
+ // Inside "Three": double-click selects the word, then line and paragraph with return.
+ let p = screen_at(&mut h, id, 10..14);
+ h.hover_at(p);
+ h.step();
+ let mut got = vec![];
+ for _ in 0..5 {
+ click(&mut h, p);
+ let r = selected(&h);
+ got.push(text[r].to_string());
+ }
+ assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}");
+ assert!(got[0].is_empty(), "one click places the caret: {got:?}");
+ }
+
+ #[test]
+ fn slow_clicks_do_not_add_up() {
+ let (mut h, id) = typing("One two. Three four!");
+ let p = screen_at(&mut h, id, 10..14);
+ h.hover_at(p);
+ h.step();
+ for _ in 0..3 {
+ click(&mut h, p);
+ h.run_steps(30);
+ }
+ assert!(selected(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected(&h));
+ }
+
+ /// ⌥E then I types "í" on a Mac: the input method composes the dead key's accent, which
+ /// it does only for a window that turned it on. The canvas never did, so ⌥E typed "e".
+ #[test]
+ fn dead_keys_compose_through_the_input_method() {
+ let (mut h, id) = typing("T");
+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [390.0, 80.0]})).unwrap();
+ h.run_steps(2);
+ assert!(h.output().platform_output.ime.is_some(), "a text caret turns the input method on");
+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "´".into(), active_range_chars: None }));
+ h.run_steps(2);
+ let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.stories.values().map(|s| s.text.clone()).collect::<String>();
- assert_eq!(text(&h), "T´", "the accent being composed shows in the story, in its format");
- assert!(h.state().session.composition().is_some(), "and is marked as composed, not typed");
++ assert_eq!(text(&h), "T´", "the accent being composed shows in the story");
++ assert!(h.state().session.tool_composing(), "and is marked as composed, not typed");
+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None }));
+ h.event(egui::Event::Ime(egui::ImeEvent::Commit("í".into())));
+ h.run_steps(2);
+ assert_eq!(text(&h), "Tí");
- assert!(h.state().session.composition().is_none());
- // Moving the caret mid-composition drops the accent and tells the input method so.
++ assert!(!h.state().session.tool_composing());
++ // Moving the caret mid-composition keeps the accent as typed and tells the input method
++ // to drop its copy.
+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "˜".into(), active_range_chars: None }));
+ h.run_steps(2);
+ h.state_mut().run("text.move", json!({"dir": "left"})).unwrap();
+ h.step();
- assert_eq!(text(&h), "Tí");
++ assert_eq!(text(&h), "Tí˜");
++ assert!(!h.state().session.tool_composing());
+ assert!(h.output().platform_output.ime.as_ref().is_some_and(|i| i.should_interrupt_composition));
++ assert!(h.state_mut().take_ime_discard());
+ // Another tool takes no text: the input method is off.
+ h.state_mut().run("tool.select", json!({"tool": "selection"})).unwrap();
+ h.run_steps(2);
+ assert!(h.output().platform_output.ime.is_none());
+ }
+
+ #[test]
+ fn tools_show_their_own_cursors_over_the_page() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let mut h = harness(app);
+ let p = h.state().canvas_rect.unwrap().center();
+ let mut shown = |tool: &str| {
+ h.state_mut().run("tool.select", json!({"tool": tool})).unwrap();
+ h.hover_at(p);
+ h.run_steps(2);
+ let out = &h.output().platform_output;
+ (out.cursor_icon, out.cursor_image.clone())
+ };
+ let (pen, direct, text) = (shown("pen"), shown("directSelection"), shown("type"));
+ let ppp = h.ctx.pixels_per_point();
+ let images = &mut h.state_mut().cursors;
+ match crate::cursors::MODE {
+ crate::cursors::Mode::Os => {
+ assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen");
+ assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection");
+ assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor");
+ }
+ crate::cursors::Mode::Painted => assert_eq!((pen.0, direct.0), (egui::CursorIcon::None, egui::CursorIcon::None)),
+ crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)),
+ }
+ }
+
#[test]
fn rulers_open_no_units_menu_without_a_document() {
let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));
@@@ -2006,152 -2653,156 +2691,305 @@@
assert!(h.query_by_label(" Points").is_none());
}
+ /// One frame of the whole app with `events`; returns what it asks of the system IME.
+ fn ime_frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Option<egui::output::IMEOutput> {
+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| {
+ app.logic(ui.ctx());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ out.platform_output.ime
+ }
+
+ /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames
+ /// drawn; returns the story id.
+ fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value {
+ app.run("file.new", json!({})).unwrap();
+ let f = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": text})).unwrap();
+ let sid = f["story"].clone();
+ app.session.execute("text.select", &json!({"story": sid, "anchor": text.len(), "focus": text.len()})).unwrap();
+ app.select_tool("type");
+ for _ in 0..4 {
+ ime_frame(app, ctx, vec![]);
+ }
+ sid
+ }
+
+ fn story_text(app: &mut DesignApp, sid: &Value) -> String {
+ app.session.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string()
+ }
+
+ /// Spread point `p` on screen.
+ fn on_screen(app: &DesignApp, p: Point) -> Pos2 {
+ let st = app.session.active().unwrap();
+ let c = CanvasLayout::new(&st.doc, st.editing_parents).to_canvas(SpreadRef::Doc(0), p);
+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)
+ }
+
+ fn preedit(t: &str, c: usize) -> egui::Event {
+ egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) })
+ }
+
+ #[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() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "曲:");
+ // At a text caret the IME is allowed, its window on the caret as the canvas draws it.
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("IME allowed at a text caret");
+ let (top, bottom) = {
+ let st = app.session.active().unwrap();
+ let cs = app.session.cache.get(&st.doc, designcraft_doc::StoryId(sid.as_u64().unwrap()), None);
+ let (fi, x, bl, asc, desc) = compose::caret(&cs, "曲:".len()).unwrap();
+ let fid = cs.frames[fi].frame;
+ let (a, _) = item_canvas_xf(&st.doc, &CanvasLayout::new(&st.doc, st.editing_parents), fid).unwrap();
+ let m = a * st.doc.text_xf(st.doc.item(fid).unwrap());
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
+ (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc)))
+ };
+ assert!(ime.rect.expand(1.0).contains(top) && ime.rect.expand(1.0).contains(bottom), "{:?} vs {top:?}–{bottom:?}", ime.rect);
+ assert_eq!(ime.cursor_rect, ime.rect);
+ assert!(!ime.should_interrupt_composition);
+ assert!(app.canvas_ime(), "the web build keeps whole words typed at the caret");
+ // "ni" → に → 日, with the events winit sends.
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Enabled), preedit("ni", 2)]);
+ assert_eq!(story_text(&mut app, &sid), "曲:ni", "marked text shows in place");
+ assert!(app.session.tool_composing());
+ // Keys, plain text, the clipboard and Undo (the native menu's ⌘Z) wait for the IME.
+ let steps = app.session.doc().unwrap().history.undo.len();
+ let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ ime_frame(
+ &mut app,
+ &ctx,
+ vec![key(egui::Key::Backspace, true), key(egui::Key::Backspace, false), egui::Event::Text("x".into()), egui::Event::Paste("y".into())],
+ );
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ assert!(!crate::menus::enabled(&app, "edit.undo"));
+ assert_eq!(story_text(&mut app, &sid), "曲:ni");
+ let ime2 = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("IME allowed while composing");
+ assert_eq!(story_text(&mut app, &sid), "曲:に");
+ assert!(ime2.rect.center().x > ime.rect.center().x, "the window follows the IME's cursor: {:?} {:?}", ime2.rect, ime.rect);
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Ime(egui::ImeEvent::Disabled)]);
+ assert_eq!(story_text(&mut app, &sid), "曲:日");
+ assert!(!app.session.tool_composing());
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the commit is one undo step");
+ assert_eq!(app.session.journal.last(), Some(&("text.insert".to_string(), json!({"text": "日"}))));
+ // After the commit, typing and Undo work again.
+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]);
+ assert_eq!(story_text(&mut app, &sid), "曲:日!");
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ assert_eq!(story_text(&mut app, &sid), "曲:");
+ // Without a text caret the IME is off: single-key tool shortcuts keep working.
+ app.select_tool("selection");
+ assert!(ime_frame(&mut app, &ctx, vec![]).is_none());
+ assert!(!app.canvas_ime());
+ }
+
+ /// Both panes of a split window see the same keyboard events: only the pane last clicked
+ /// types them.
+ #[test]
+ fn a_split_window_types_once() {
+ 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");
+ app.run("window.split", json!({"on": true})).unwrap();
+ for _ in 0..3 {
+ ime_frame(&mut app, &ctx, vec![]);
+ }
+ assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some(), "both panes are drawn");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("c".into())]);
+ assert_eq!(story_text(&mut app, &sid), "abc");
+ let key = |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ ime_frame(&mut app, &ctx, vec![key(true), key(false)]);
+ assert_eq!(story_text(&mut app, &sid), "ab");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Paste("de".into())]);
+ assert_eq!(story_text(&mut app, &sid), "abde");
+ ime_frame(&mut app, &ctx, vec![preedit("に", 1)]);
+ assert_eq!(story_text(&mut app, &sid), "abdeに");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]);
+ assert_eq!(story_text(&mut app, &sid), "abde日");
+ }
+
+ #[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());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "");
+ ime_frame(&mut app, &ctx, vec![preedit("しょうこ", 4)]);
+ assert!(app.session.tool_composing());
+ // A click in the frame (macOS and Windows send nothing for it): the marked text stays as
+ // typed and the IME is told to drop its composition, once.
+ 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() };
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true)]).expect("still at a text caret");
+ assert!(ime.should_interrupt_composition);
+ ime_frame(&mut app, &ctx, vec![press(false)]);
+ assert!(!app.session.tool_composing());
+ assert_eq!(story_text(&mut app, &sid), "しょうこ");
+ assert!(app.take_ime_discard(), "the host tells the system IME to drop its marked text");
+ assert!(!ime_frame(&mut app, &ctx, vec![]).expect("still at a text caret").should_interrupt_composition);
+ assert!(!app.take_ime_discard());
+ // A bare line break from the IME confirms a composition: the marked text, no new paragraph.
+ ime_frame(&mut app, &ctx, vec![preedit("がく", 2)]);
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("\n".into()))]);
+ assert!(!app.session.tool_composing());
+ let typed = story_text(&mut app, &sid);
+ assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}");
+ }
++
+ #[test]
+ fn baseline_grid_lines_are_the_ones_on_the_page() {
+ // A start far above the page used to be walked line by line, without end.
+ for start in [-1e9, -1e17] {
+ let mut far = baseline_grid_lines(start, 12.0, 792.0);
+ assert_eq!((far.next(), far.count()), (Some(8.0), 65));
+ }
+ let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::<Vec<_>>();
+ assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line");
+ assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm");
+ assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]);
+ assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES);
+ }
+ }
+
+ #[cfg(test)]
+ mod scrollbar_tests {
+ use egui::{Event, Modifiers, PointerButton};
+ use egui_kittest::Harness;
+
+ use super::*;
+ use crate::test_window::{Window, open, wheel};
+
+ fn window() -> Harness<'static, Window> {
+ let mut h = open(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()), vec2(1440.0, 900.0));
+ // Zoomed in so both axes scroll.
+ set_zoom(&mut h.state_mut().app, 2.0);
+ h.run_steps(3);
+ h
+ }
+
+ fn origin(h: &Harness<'static, Window>) -> Point {
+ h.state().app.view().map(|v| v.origin).unwrap_or_default()
+ }
+
+ /// The scrollbar's track and thumb as the canvas lays them out for the current view, and
+ /// the content pixels per thumb pixel.
+ fn bar(h: &Harness<'static, Window>, vertical: bool) -> (Rect, Rect, f32) {
+ let app = &h.state().app;
+ let rect = app.canvas_rect.unwrap();
+ let st = app.session.active().unwrap();
+ let xf = Xf::new(rect, app.view().unwrap());
+ let cb = xf.rect(CanvasLayout::new(&st.doc, st.editing_parents).pasteboard);
+ let outer = Rect::from_min_max(rect.min, rect.max + vec2(SCROLLBAR, SCROLLBAR));
+ scrollbar_rects(outer, rect, cb, vertical)
+ }
+
+ /// A primary-button drag from `a` to `b` in a few moves, with `mods` held throughout.
+ fn drag(h: &mut Harness<'static, Window>, a: Pos2, b: Pos2, mods: Modifiers) {
+ h.event(Event::ModifiersChanged(mods));
+ h.hover_at(a);
+ h.step();
+ h.event(Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: mods });
+ h.step();
+ for n in 1..=4 {
+ h.hover_at(a + (b - a) * n as f32 / 4.0);
+ h.step();
+ }
+ h.event(Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: mods });
+ h.event(Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(3);
+ }
+
+ #[test]
+ fn document_views_have_scrollbars_beside_the_view() {
+ let h = window();
+ let rect = h.state().app.canvas_rect.unwrap();
+ for vertical in [true, false] {
+ let r = h.ctx.read_response(egui::Id::new(("canvas_scrollbar", 0u8, vertical))).expect("scrollbar").rect;
+ let (track, thumb, k) = bar(&h, vertical);
+ assert_eq!(r, track);
+ assert!(k > 0.0, "the zoomed-in view scrolls");
+ if vertical {
+ assert_eq!((r.min.x, r.width(), r.min.y, r.max.y), (rect.max.x, SCROLLBAR, rect.min.y, rect.max.y));
+ assert!(thumb.height() < track.height());
+ } else {
+ assert_eq!((r.min.y, r.height(), r.min.x, r.max.x), (rect.max.y, SCROLLBAR, rect.min.x, rect.max.x));
+ assert!(thumb.width() < track.width());
+ }
+ }
+ }
+
+ #[test]
+ fn dragging_a_thumb_pans_and_clicking_the_track_pages() {
+ let mut h = window();
+ let zoom = h.state().app.view().unwrap().zoom;
+ // Vertical thumb: down 40 px moves the view down by 40 thumb pixels' worth of content.
+ let (_, thumb, k) = bar(&h, true);
+ let before = origin(&h);
+ drag(&mut h, thumb.center(), thumb.center() + vec2(0.0, 40.0), Modifiers::NONE);
+ let after = origin(&h);
+ let want = 40.0 * k as f64 / zoom;
+ assert!((after.y - before.y - want).abs() < want * 0.2, "{before:?} → {after:?}, want +{want}");
+ assert_eq!(after.x, before.x);
+ // Horizontal thumb: left 30 px.
+ let (_, thumb, k) = bar(&h, false);
+ drag(&mut h, thumb.center(), thumb.center() - vec2(30.0, 0.0), Modifiers::NONE);
+ let next = origin(&h);
+ let want = 30.0 * k as f64 / zoom;
+ assert!((after.x - next.x - want).abs() < want * 0.2, "{after:?} → {next:?}, want -{want}");
+ assert_eq!(next.y, after.y);
+ // A click on the vertical track above the thumb pages up by one view.
+ let (track, thumb, _) = bar(&h, true);
+ assert!(thumb.min.y - track.min.y > 4.0);
+ crate::test_window::click_at(&mut h, pos2(track.center().x, track.min.y + 2.0));
+ let paged = origin(&h);
+ let view = h.state().app.canvas_rect.unwrap().height() as f64 / zoom;
+ assert!((next.y - paged.y - view).abs() < 0.01, "{next:?} → {paged:?}, want -{view}");
+ }
+
+ #[test]
+ fn scrolling_the_view_moves_the_thumbs() {
+ let mut h = window();
+ let (_, v0, _) = bar(&h, true);
+ let (_, h0, _) = bar(&h, false);
+ let c = h.state().app.canvas_rect.unwrap().center();
+ wheel(&mut h, c, vec2(-50.0, -80.0));
+ let (_, v1, _) = bar(&h, true);
+ let (_, h1, _) = bar(&h, false);
+ assert!(v1.min.y > v0.min.y && h1.min.x > h0.min.x, "{v0:?} → {v1:?}, {h0:?} → {h1:?}");
+ let r = h.ctx.read_response(egui::Id::new(("canvas_scrollbar", 0u8, true))).expect("scrollbar");
+ assert_eq!(r.rect, bar(&h, true).0);
+ }
+
+ #[test]
+ fn alt_drag_while_editing_text_pans_and_keeps_the_caret() {
+ let mut h = window();
+ let app = &mut h.state_mut().app;
+ let rect = app.canvas_rect.unwrap();
+ let xf = Xf::new(rect, app.view().unwrap());
+ // A text frame filling the visible part of the page, with the caret in it.
+ let (a, b) = (xf.to_canvas(rect.min + vec2(20.0, 20.0)), xf.to_canvas(rect.max - vec2(20.0, 20.0)));
+ let r = app.run("frame.create", json!({"rect": [a.x, a.y, b.x, b.y], "content": "text", "text": "Hello brave world"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ app.run("tool.select", json!({"tool": "type"})).unwrap();
+ app.run("text.select", json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();
+ assert!(app.session.wants_text());
+ h.run_steps(2);
+ let caret = h.state().app.session.doc().unwrap().selection.text;
+ let before = origin(&h);
+ let zoom = h.state().app.view().unwrap().zoom;
+ let from = rect.center();
+ drag(&mut h, from, from + vec2(60.0, 40.0), Modifiers::ALT);
+ let after = origin(&h);
+ assert!(after.x < before.x && after.y < before.y, "{before:?} → {after:?}");
+ assert!((before.x - after.x - 60.0 / zoom).abs() < 15.0 / zoom, "{before:?} → {after:?}");
+ assert_eq!(h.state().app.session.doc().unwrap().selection.text, caret);
+ assert!(h.state_mut().app.session.wants_text(), "still editing text");
+ // Without Alt the same drag selects text and leaves the view alone.
+ drag(&mut h, from, from + vec2(60.0, 40.0), Modifiers::NONE);
+ assert_eq!(origin(&h), after);
+ }
}
diff --cc crates/ui-egui/src/dialogs.rs
index 66d179bbb,7d02776a2..a2947806d
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -3861,6 -5101,722 +5101,722 @@@ mod tests
}
}
+ fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
+ let (request, _reply) = crate::control::ControlRequest::new(method, params);
+ let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") };
+ assert_eq!(value["ok"], true, "{value}");
+ value["result"].clone()
+ }
+
+ fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) {
+ let labels = dialog_frame(app, ctx, screen, vec![]);
+ let pos = visible_label(&labels, screen, label).center();
+ click_dialog(app, ctx, screen, pos);
+ }
+
+ fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ scope_dialog_with_selection("red red | red", 7)
+ }
+
+ fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ scope_dialog_with_tool(text, end, None)
+ }
+
+ fn scope_dialog_with_tool(
+ text: &str,
+ end: usize,
+ tool: Option<&str>,
+ ) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.language = "en".into();
+ app.run("file.new", json!({})).unwrap();
+ let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();
+ let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap());
+ let ctx = dialog_context("en");
+ if let Some(tool) = tool {
+ scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool}));
+ }
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap();
+ app.run("app.findChange", json!({})).unwrap();
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));
+ for (field, value) in [("find", "red"), ("change", "unused")] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ for _ in 0..3 {
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ scope_click(&mut app, &ctx, screen, "document");
+ scope_click(&mut app, &ctx, screen, "selection");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection");
+ (app, ctx, screen, sid)
+ }
+
+ fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) {
+ let t = app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None));
+ }
+
+ fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) {
+ let after = app.session.doc().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc));
+ assert_eq!(after.uid, before.uid);
+ assert_eq!(after.revision, before.revision);
+ assert_eq!(after.selection, before.selection);
+ assert_eq!(after.history.limit, before.history.limit);
+ for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] {
+ assert_eq!(actual.len(), expected.len());
+ for (a, b) in actual.iter().zip(expected) {
+ assert_eq!(a.label, b.label);
+ assert_eq!(a.selection, b.selection);
+ assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc));
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_control_effective_noops_retain_bounds() {
+ for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() {
+ for physical in [false, true] {
+ for (text, pattern, hits, changed) in [
+ ("é", "é|(?:)", vec![(0, 2)], "X"),
+ ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"),
+ ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"),
+ ] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0);
+ for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "GREP");
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));
+ for &(a, b) in &hits {
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found");
+ scope_selected(&app, sid, a, b);
+ let before = app.session.doc().unwrap().clone();
+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");
+ let next = if cur == "selection" { "document" } else { "selection" };
+ if physical {
+ scope_click(&mut app, &ctx, screen, &cur);
+ scope_click(&mut app, &ctx, screen, next);
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));
+ }
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0));
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));
+ }
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ // An ignored scope change must not revive an exhausted endpoint either.
+ let before = app.session.doc().unwrap().clone();
+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");
+ let next = if cur == "selection" { "document" } else { "selection" };
+ if physical {
+ scope_click(&mut app, &ctx, screen, &cur);
+ scope_click(&mut app, &ctx, screen, next);
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));
+ }
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len()));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed);
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_explicit_story_transitions_reset_cursor() {
+ for remove_override in [false, true] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0);
+ let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap();
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
+ for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "GREP");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 0);
+ let before = app.session.doc().unwrap().clone();
+ let value = if remove_override { Value::Null } else { other["story"].clone() };
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));
+ scope_state_unchanged(&app, &before);
+ // Away and back still releases continuation even if no Find command intervenes.
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 0);
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 2, 2);
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂");
+ let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap());
+ assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other");
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_control_mode_changes_release_bounds() {
+ for object_mode in [false, true] {
+ let (mut app, ctx, _, sid) = scope_dialog();
+ if object_mode {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true}));
+ }
+ // Direct Session consumers share the retained domain even while Object is shown.
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count.as_array().unwrap().len(), 2);
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p}));
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode);
+ scope_state_unchanged(&app, &before);
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_tool_replacement_releases_bounds() {
+ for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));
+ assert_eq!(app.session.tool_id(), tool);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation();
+ let x = off.x + before.doc.spreads[0].pages[0].x + 200.0;
+ let y = off.y + 200.0;
+ // The Page tool opens Page Size on a double-click (a click selects the page).
+ let events = if tool == "page" {
+ json!([{"kind": "doubleclick", "x": x, "y": y}])
+ } else {
+ json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}])
+ };
+ // Real tool -> Action::Dialog -> after_engine; no injected UI request.
+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement);
+ assert!(app.session.ui_requests.is_empty());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Cancel");
+ assert!(app.ui.dialog.is_none());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ scope_state_unchanged(&app, &before);
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_tool_without_replacement_retains_bounds() {
+ for tool in ["page", "rectangleFrame"] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();
+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_native_pdf_replacement_releases_bounds() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("three.pdf");
+ std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap();
+ for dismissal in ["Cancel", "Escape", "control"] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen_pick = picked.clone();
+ let seen_read = read.clone();
+ let pick_path = path.to_string_lossy().to_string();
+ let read_path = pick_path.clone();
+ app.services.pick_open = Some(Box::new(move |purpose| {
+ assert_eq!(purpose, "place");
+ seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Some(pick_path.clone())
+ }));
+ app.services.read = Some(Box::new(move |path| {
+ assert_eq!(path, read_path);
+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ std::fs::read(path).map_err(|e| e.to_string())
+ }));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement.
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let dialog = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(dialog.id, "pdfImport");
+ assert_eq!(dialog.s("path"), path.to_string_lossy());
+ assert_eq!(dialog.fields["pages"], 3);
+ assert_eq!(dialog.s("page"), "1");
+ assert!(!dialog.b("async"));
+ assert_eq!(dialog.fields["target"], json!(before.uid));
+ assert!(app.session.ui_requests.is_empty());
+ assert!(app.pending_pdf.is_none());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ match dismissal {
+ "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"),
+ "Escape" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ }
+ _ => panic!("known dismissal"),
+ }
+ assert!(app.ui.dialog.is_none());
+ assert!(app.pending_pdf.is_none());
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ scope_state_unchanged(&app, &before);
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_native_picker_cancel_retains_bounds() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen = picked.clone();
+ app.services.pick_open = Some(Box::new(move |purpose| {
+ assert_eq!(purpose, "place");
+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ None
+ }));
+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen_read = read.clone();
+ app.services.read = Some(Box::new(move |_| {
+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Err("canceled picker must not read".into())
+ }));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+
+ #[test]
+ fn find_scope_dialog_exact_baseline_buttons() {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red");
+ }
+
+ #[test]
+ fn find_scope_dialog_grep_tab_alone_restarts_original_selection() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "GREP");
+ assert!(app.ui.dialog.as_ref().unwrap().b("grep"));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Text");
+ assert!(!app.ui.dialog.as_ref().unwrap().b("grep"));
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ }
+
+ #[test]
+ fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let history = app.session.doc().unwrap().history.undo.len();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
+ scope_click(&mut app, &ctx, screen, "Cancel");
+ assert!(app.ui.dialog.is_none());
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ app.run("edit.redo", json!({})).unwrap();
+ let native = app.run("file.serialize", json!({})).unwrap();
+ app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ }
+
+ fn scope_confirm_case(action: &str) {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ match action {
+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),
+ "Enter" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Enter,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2);
+ }
+ _ => panic!("known confirmation route"),
+ }
+ assert!(app.ui.dialog.is_none());
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ // The closed dialog cannot leave its old seven-byte range for a later direct query.
+ let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap();
+ assert_eq!(matches.as_array().unwrap().len(), 0);
+ }
+
+ #[test]
+ fn find_scope_dialog_ok_consumes_retained_bounds() {
+ scope_confirm_case("OK");
+ }
+
+ #[test]
+ fn find_scope_dialog_enter_consumes_retained_bounds() {
+ scope_confirm_case("Enter");
+ }
+
+ #[test]
+ fn find_scope_dialog_control_confirm_consumes_retained_bounds() {
+ scope_confirm_case("control");
+ }
+
+ #[test]
+ fn find_scope_dialog_query_reselection_cancel_and_reopen() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"}));
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap();
+ app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap();
+ scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ app.run("app.findChange", json!({})).unwrap();
+ for (field, value) in [("find", "red"), ("scope", "selection")] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ }
+
+ #[test]
+ fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let selected = app.session.doc().unwrap().selection.clone();
+ let frame = selected.text.unwrap().frame.unwrap();
+ let point = {
+ let st = app.session.doc().unwrap();
+ let cs = app.session.cache.get(&st.doc, sid, None);
+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();
+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);
+ assert_eq!(cs.frames[fi].frame, frame);
+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1));
+ let loc = st.doc.find(frame).unwrap();
+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner
+ };
+ let before = app.session.doc().unwrap().doc.clone();
+ let revision = app.session.doc().unwrap().revision;
+ app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();
+ assert_eq!(app.session.doc().unwrap().selection, selected);
- assert_eq!(app.session.doc().unwrap().revision, revision + 1);
++ assert!(app.session.doc().unwrap().revision > revision, "a new revision");
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_failed_native_drop_alert_releases_bounds() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("broken.designcraft");
+ std::fs::write(&path, b"not a native document").unwrap();
+ for dismissal in ["OK", "Escape", "control"] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().doc.clone();
+ let selected = app.session.doc().unwrap().selection.clone();
+ let revision = app.session.doc().unwrap().revision;
+ let history = app.session.doc().unwrap().history.undo.len();
+ let uid = app.session.doc().unwrap().uid;
+ let error = app.open_dropped(&path.to_string_lossy()).unwrap_err();
+ let alert = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(alert.id, "alert");
+ assert_eq!(alert.s("title"), "Can't Open the File");
+ assert_eq!(alert.s("message"), error);
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ assert_eq!(app.session.doc().unwrap().selection, selected);
+ assert_eq!(app.session.doc().unwrap().revision, revision);
+ assert_eq!(app.session.doc().unwrap().uid, uid);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ match dismissal {
+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),
+ "Escape" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ }
+ _ => panic!("known dismissal"),
+ }
+ assert!(app.ui.dialog.is_none());
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_child_errors_and_explicit_parent() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap();
+ app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap();
+ app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap();
+ let child = app.session.doc().unwrap().selection.text.unwrap();
+ let before = app.session.doc().unwrap().doc.clone();
+ let selection = app.session.doc().unwrap().selection.clone();
+ let history = app.session.doc().unwrap().history.undo.len();
+ for label in ["Count", "Find Next", "Change All"] {
+ scope_click(&mut app, &ctx, screen, label);
+ assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported"));
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ assert_eq!(app.session.doc().unwrap().selection, selection);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ }
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)");
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child");
+ assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue"));
+ }
+
+ #[test]
+ fn find_scope_dialog_error_confirmation_and_escape_release_context() {
+ for escape in [false, true] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ if escape {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));
+ scope_click(&mut app, &ctx, screen, "OK");
+ }
+ assert!(app.ui.dialog.is_none());
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_domain_and_object_changes_release_original_range() {
+ for route in ["scope", "object", "menu", "command"] {
+ let (mut app, ctx, screen, _) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ match route {
+ "scope" => {
+ for scope in ["story", "selection"] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope}));
+ }
+ }
+ "object" => {
+ scope_click(&mut app, &ctx, screen, "Object");
+ scope_click(&mut app, &ctx, screen, "Text");
+ }
+ "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null),
+ "command" => {
+ app.run("app.newDocumentDialog", json!({})).unwrap();
+ }
+ _ => panic!("known reset route"),
+ }
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ }
+ }
+
#[test]
fn dialog_title_and_actions_fit_scaled_viewports() {
for language in ["en", "ar"] {
diff --cc crates/ui-egui/src/lib.rs
index 368d5a046,59c7ebb59..68f198b1d
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -527,14 -560,20 +560,28 @@@ pub struct DesignApp
/// (no native menu: without it the paste keys produce no paste event), or what it held then
/// (native menu). It is never pasted as text: Paste with it pastes the copied objects.
object_clip_text: Option<String>,
+ /// The marked text the system IME last sent (`None` once it commits or clears). When the
+ /// composition ends some other way (a click, a tool switch), the IME is told to drop it.
+ pub(crate) ime_marked: Option<String>,
+ /// The system IME must drop its marked text (see [`Self::take_ime_discard`]).
+ pub(crate) ime_discard: bool,
+ /// The canvas asked for the system IME in the last frame (the web build's text input has the
+ /// keyboard then).
+ pub(crate) canvas_ime: bool,
+ /// Quit was chosen: close the window on the next frame, as its close button does.
+ quit_requested: bool,
+ /// Close the window without asking about unsaved changes (the control channel's `app.quit`).
+ pub(crate) quit_without_asking: bool,
+ /// No document is discarded until every unsaved document has an up-to-date approval.
+ quitting: Option<QuitState>,
+ /// The tool cursor bitmaps handed to the OS.
+ pub cursors: cursors::Images,
+ }
+
+ struct QuitState {
+ original_active: Option<u64>,
+ accepted: HashMap<u64, u64>,
+ pending: Option<u64>,
}
impl DesignApp {
@@@ -575,9 -618,10 +626,13 @@@
egui_ctx: None,
in_control: false,
object_clip_text: None,
+ ime_marked: None,
+ ime_discard: false,
+ canvas_ime: false,
+ quit_requested: false,
+ quit_without_asking: false,
+ quitting: None,
+ cursors: cursors::Images::default(),
}
}
diff --cc crates/ui-egui/src/menus.rs
index 0ac8abc04,a35261d59..89e8ec318
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -1832,11 -2012,11 +2026,14 @@@ pub fn checked(app: &DesignApp, id: &st
/// Enablement for menu display (UI commands need a document unless they're app/window-level).
pub fn menu_enabled(app: &DesignApp, id: &str) -> bool {
+ if waits_for_ime(app, id) {
+ return false;
+ }
+ if id.starts_with("fit.") {
+ return enabled(app, "object.fit");
+ }
if ui_label(id).is_some() {
- return app.session.active().is_some() || id.starts_with("app.") || id.starts_with("window.");
+ return app.session.active().is_some() || id.starts_with("app.") || id.starts_with("window.") || id.starts_with("help.");
}
enabled(app, id)
}
@@@ -1859,9 -2039,14 +2056,17 @@@ pub fn close_document(app: &mut DesignA
/// A menu item was chosen. An engine command whose label ends in "…" and that takes parameters
/// opens a dialog built from its parameter documentation (see [`crate::dialogs::command_fields`]).
pub fn activate(app: &mut DesignApp, id: &str, params: &Value) {
+ if waits_for_ime(app, id) {
+ return;
+ }
+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");
+ activate_inner(app, id, params);
+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {
+ app.session.reset_find_scope();
+ }
+ }
+
+ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) {
if params.is_null() && id == "file.close" {
close_document(app, None);
return;
diff --cc docs/control-protocol.md
index ed16482d1,25136a807..88e466f7e
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@@ -39,8 -39,7 +39,8 @@@ so only enable it while you use it. Tra
| `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) |
| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) |
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) |
+| `ui.ime` | `{preedit?, active?: [start, end], commit?}` | Input method events as the system IME sends them: marked text (shown in place, `active` is the clause being converted, in characters) and the committed text (typed as one `text.insert`) |
- | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle` | Real egui pointer input — reaches every widget, menu and panel |
+ | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle`, `count?: positive integer` (click/drag, default 1), `steps?: positive integer` (drag, default 8) | Real egui pointer input — reaches every widget, menu and panel |
| `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state |
| `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` or `characterStyleOptions` with `{name, section}`, or `{new: true}` for a new style) |
| `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel` | `{field, value}` | Fill and confirm the open dialog |
diff --cc docs/gaps.md
index 31c443d64,21a18b369..4b8226356
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -97,9 -99,9 +99,9 @@@ Kind: **F** feature · **U** UI/UX · *
## High
--### 8. Canvas text input has no IME (U, L)
--- **Missing:** composition input for Chinese, Japanese and Korean on the canvas (#322).
-- VectorCraft has an implementation to port.
++### 8. Canvas IME not checked with real input methods (U, L)
++- **Have:** IME composition in the Type tool on macOS, Windows, Linux and the web (#322).
++- **Missing:** a check by hand with a system IME on each platform, and the fixes it finds.
- **Estimate:** 10–20 h. **Doc:** [localization-parity.md](localization-parity.md)
### 9. PDF output presets and standards (FF)
diff --cc docs/localization-parity.md
index d36053202,ea07c62b4..b69eec33c
--- a/docs/localization-parity.md
+++ b/docs/localization-parity.md
@@@ -28,16 -28,16 +28,16 @@@ come as Middle East editions with an En
| Language | Code | InDesign 2026 UI | UI strings translated | Dialogs / tooltips / help | Script support (documents and UI) | Native review | Status | To `full` (h) |
|---|---|---|---|---|---|---|---|---|
| English | en | ✓ | 1,724 / 1,724 (100%) | all / all / none | Latin ✓ | yes | full | 0 |
--| Simplified Chinese (Mandarin) | zh | ✓ (zh_CN) | 1,438 (83%) | menus, panels, most dialogs; tooltips partly; no help | CJK typesetting ✓ (cjk.md); **no canvas IME** (#322); CJK UI font not embedded in release builds, so boxes on Linux (#332) | no | partial | 25–40 |
++| Simplified Chinese (Mandarin) | zh | ✓ (zh_CN) | 1,438 (83%) | menus, panels, most dialogs; tooltips partly; no help | CJK typesetting ✓ (cjk.md); canvas IME ✓, not checked by hand with a system IME (#322); CJK UI font not embedded in release builds, so boxes on Linux (#332) | no | partial | 25–40 |
| Spanish | es | ✓ | 1,438 (83%) | menus, panels, most dialogs; no help | Latin ✓; Spanish hyphenation ✓ (#222) | no | partial | 5–8 |
| Hindi | hi | ✗ | 0 (0%) | none | Devanagari shaped by harfrust in documents but untested; no Hindi hyphenation or spelling | no | none | 20–30 |
| Arabic | ar | Middle East edition (English/French UI) | 1,459 (85%) | menus, panels, most dialogs; no help | RTL UI text (`rtl.rs`: bidi + shaping); Arabic composition, kashida, digits, RTL stories and tables ✓ (arabic-typography.md); list bullets and multi-column RTL open (#100) | no | partial | 15–25 |
| French | fr | ✓ | 1,438 (83%) | menus, panels, most dialogs; no help | Latin ✓; no French hyphenation | no | partial | 6–10 |
- | Portuguese (Brazil) | pt-br | ✓ (pt) | 1,057 (61%) | menus, panels, some dialogs; no help | Latin ✓; no Portuguese hyphenation | no | partial | 8–12 |
+ | Portuguese (Brazil) | pt-br | ✓ (pt) | 1,057 (61%) | menus, panels, some dialogs; no help | Latin ✓; Portuguese hyphenation ✓ | no | partial | 8–12 |
| Indonesian | id | ✗ | 0 (0%) | none | Latin ✓ | no | none | 12–18 |
--| Japanese | ja | ✓ | 1,644 (95%) | whole interface (#272), vertical-type commands; no help | vertical text, kinsoku, aki, ruby, warichu ✓ (partial depth, cjk.md); **no canvas IME** (#322); Japanese UI and Mincho fonts from craft-fonts | no | partial | 6–10 (+ IME, shared with zh) |
++| Japanese | ja | ✓ | 1,644 (95%) | whole interface (#272), vertical-type commands; no help | vertical text, kinsoku, aki, ruby, warichu ✓ (partial depth, cjk.md); canvas IME ✓, not checked by hand (#322); Japanese UI and Mincho fonts from craft-fonts | no | partial | 6–10 (+ IME checks, shared with zh) |
| German | de | ✓ | 1,438 (83%) | menus, panels, most dialogs; no help | Latin ✓; no German hyphenation (InDesign ships 2006 reform patterns) | no | partial | 6–10 |
--| Korean | ko | ✓ | 0 (0%) | none | Korean line breaking at spaces ✓; **no IME** (#322) | no | none | 15–25 |
++| Korean | ko | ✓ | 0 (0%) | none | Korean line breaking at spaces ✓; canvas IME ✓, not checked by hand (#322) | no | none | 15–25 |
| Vietnamese | vi | ✗ | 0 (0%) | none | Latin with stacked diacritics via harfrust, untested | no | none | 12–18 |
Percentages are of the 1,724 measured strings. A language is `full` only when every user-visible
@@@ -67,7 -68,7 +68,7 @@@ locale shaping. See [typography-parity.
| Fill the 83–85% catalogs (de, fr, es, zh, ar, it, uk; ~290 strings each) | 25–40 |
| pt-BR to full | 8–12 |
| New: Hindi, Indonesian, Korean, Vietnamese (1,724 strings, plural rules, tests) | 50–75 |
--| Canvas IME (zh, ja, ko) | 10–20 |
++| Canvas IME (zh, ja, ko): checks by hand with system IMEs, and fixes | 10–20 |
| CJK UI font in every release build; Devanagari and Vietnamese rendering tests | 10–15 |
| Catalog completeness test: every `tr` key and command label present in every catalog | 4–8 |
| Help content (at least English, then the twelve) | 15–25 |
diff --cc docs/roadmap.md
index 85424132d,85424132d..331807156
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@@ -57,7 -57,7 +57,7 @@@ set exists; depth gaps are in gaps.md
|---|---|---|
| M0 | Skeleton + vertical slice | ✅ |
| M1 | Selection, transform, layers, pages, MCP | ✅ core; handle and snapping issues (#186, #188, #337) |
--| M2 | Type I (Type tool, threading, Character/Paragraph, composer) | partial: Type tool, composer and threading ✅; Primary Text Frame pages (#165, alpha blocker); caret formatting (#289); no IME (#322) |
++| M2 | Type I (Type tool, threading, Character/Paragraph, composer) | partial: Type tool, composer and threading ✅; Primary Text Frame pages (#165, alpha blocker); caret formatting (#289); IME not checked by hand (#322) |
| M3 | Styles (nested/GREP, bullets, keeps, span columns) | ✅; style editing reliability (#169) |
| M4 | Color & effects | ✅ core; colour management depth |
| M5 | Graphics & links | ✅ core; EPS preview only |
diff --cc docs/target-app-parity.md
index 0a138bf41,62ba7f08a..3abe87f18
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -59,9 -59,9 +59,9 @@@ they receive, setting type exactly, an
| Dimension | Weight | Ready | Remaining (Opus 5.5 h) | Evidence | Doc |
|---|---|---|---|---|---|
| Features (depth of each area) | 25% | 55% | 250–400 | 275 catalogue rows exist; many lack options (e.g. Books is 258 lines of engine code, Liquid Layout 329); see the area table | this file |
- | Typography and composition fidelity | 15% | 45% | 120–200 | Knuth–Plass composer, keeps, grids, CJK, Arabic all exist; no comparison with InDesign's line breaks; optical kerning falls back to metrics (#181); overset rule differs (#180); hyphenation patterns for English and Spanish only | [typography-parity.md](typography-parity.md) |
+ | Typography and composition fidelity | 15% | 45% | 120–200 | Knuth–Plass composer, keeps, grids, CJK, Arabic all exist; no comparison with InDesign's line breaks; optical kerning falls back to metrics (#181); overset rule differs (#180); hyphenation patterns for English, Spanish, Portuguese and Norwegian only | [typography-parity.md](typography-parity.md) |
| File formats | 20% | 40% | 150–250 (+20–60 for INDD integration) | INDD cannot be opened (#21); IDML both ways and verified in InDesign 2026, but real-file bugs open (#193, #338, #339, #340); PDF export strong; PDF/X-4 only | [file-format-parity.md](file-format-parity.md) |
--| UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165), canvas IME (#322) failing | [ui-parity.md](ui-parity.md) |
++| UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165) failing | [ui-parity.md](ui-parity.md) |
| Stability | 10% | 45% | 60–100 | Never-crash rules and last-resort guards; startup failures on some GPUs and machines (#334, #273, #220, #192, #167, #166); no CI runs the tests on pull requests | [gaps.md](gaps.md) |
| Performance | 5% | 65% | 40–80 | 300k characters compose in ~38 ms warm; typing repaints in < 1 ms (damage regions); no incremental composition; nothing benchmarked against InDesign; no large real documents | [gaps.md](gaps.md) |
| Localization | 3% | 45% | 120–180 | 9 translations beyond English; Japanese 95%, most others 83–85%, pt-BR 61%; Hindi, Indonesian, Korean, Vietnamese none | [localization-parity.md](localization-parity.md) |
@@@ -211,7 -211,7 +211,7 @@@ table is the one summed
| Fill, stroke, colour | 100% | 60% | 20–35 | hex entry (#323); Assign Profiles / Convert to Profile; color-managed proofing depth; Adobe Color Themes OOS |
| Effects & transparency | 100% | 50% | 20–30 | effects fidelity vs InDesign unmeasured; Clear Effects / Clear All Transparency; flattener depth |
| Placing & links | 93% | 55% | 20–35 | EPS is preview-only (no PostScript interpreter); Edit Original; placed PDF layer visibility; INDD page place |
--| Type & text frames | 99% | 45% | 40–60 | Primary Text Frame pages users can't delete (alpha blocker, #165); autoflow doesn't fill existing pages; no threading into grouped frames with the loaded cursor; caret formatting discarded (#289); canvas IME (#322); Notes/Track Changes menus; frame grids |
++| Type & text frames | 99% | 45% | 40–60 | Primary Text Frame pages users can't delete (alpha blocker, #165); autoflow doesn't fill existing pages; no threading into grouped frames with the loaded cursor; caret formatting discarded (#289); Notes/Track Changes menus; frame grids |
| Typography | 100% | 45% | (typography dimension) | see [typography-parity.md](typography-parity.md) |
| Styles | 100% | 60% | 15–25 | Paragraph Styles edit/delete reported failing (#169); style options depth |
| Tables | 100% | 55% | 25–40 | anchored objects in cells not drawn (#163); Table ▸ Table Options submenus, Diagonal Lines, Convert Rows, Edit Header/Footer |
diff --cc docs/ui-parity.md
index ee6db4232,30512bdf9..a66d3b64b
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@@ -39,7 -40,7 +40,7 @@@ basics of editing fail for too many use
| Threading: click out port, load text cursor, click frame | ✓ | ✗ ports drawn only; no thread/unthread command; Primary Text Frame and autoflow on Place | ✗ | **alpha blocker** (#352, #194, #165, #140) |
| Copy / cut / paste objects and text, Paste Into / in Place | ✓ | ✓ on macOS | ~ | **failing on Windows/Linux** (#351, #348, #312, #185, #164, #201, #212) |
| Context menus (canvas, panels, rulers) | ✓ everywhere | 9 context-menu sites, ruler units by right-click | ~ | **not opening for several users** (#238, #187, #160) |
--| IME text input on the canvas | ✓ | ✗ | ✗ | #322 |
++| IME text input on the canvas | ✓ | ✓ | ~ | not checked by hand with a system IME (#322) |
| Font menu: search, preview, favourites, type-ahead | ✓ | ✓ | ~ | search field focus on macOS (#335, #86) |
| Keyboard shortcuts: InDesign defaults, editor, sets | ✓ | ✓ editor; defaults from 09-shortcuts.md | ✓ | |
| Quick Apply | ✓ | ✓ | ✓ | |
@@@ -63,7 -64,7 +64,7 @@@ context menus, typing at a caret) are t
| Work | Opus 5.5 h |
|---|---|
| Copy/paste, context menus, threading clicks, caret formatting on every platform, with control-channel regression tests | 30–50 |
--| Canvas IME (port from VectorCraft) | 10–20 |
++| Canvas IME: checks by hand with system IMEs, and fixes | 10–20 |
| Missing menu items (~150) and panels (Tabs, Navigator, Trap Presets) | 40–70 |
| Handle/tool feel fixes (#186, #188, #337), font search focus | 10–20 |
| Dialog depth pass against 07-dialogs.md | 30–40 |