Files
deckcraft/crates/engine/src/cmd/text.rs
T
Dylan M. Taylor 14e27ecbbd shell-w9: net change of 3 commits
- shell-w9: written from its sheet
- shell-w9: review fixes (review-1)
- shell-w9: review fixes (review-1)
2026-11-27 14:51:29 +00:00

443 lines
22 KiB
Rust

//! In-place text editing: entering/leaving text, typing, deleting, caret movement and selection.
use std::sync::Arc;
use deckcraft_geom::{Affine, Point, Rect};
use deckcraft_model::edit::{self as ed, Pos};
use deckcraft_model::resolve::{self, Ctx};
use deckcraft_model::text::{Align, AutoFit, Hyperlink, Paragraph, Run, RunKind, RunProps, TextBody};
use deckcraft_model::{Presentation, Shape, ShapeId, ShapeKind};
use serde_json::{Value, json};
use super::{
CommandSpec, NO_TEXT_POINT, SELECT_TEXT_OR_SHAPE, always, bad, bool_or, cmd, edit_shapes, has_doc, has_slide, has_text, id_param, ok, shape_of,
str_param, xfrm_of,
};
use crate::{DocState, HistoryEntry, Result, Selection, Session, Target, TextSel, push_undo};
mod autocorrect;
mod caret;
mod editing;
mod formatting;
mod ime;
mod layout;
use autocorrect::autocorrect_options;
pub use autocorrect::{AUTOCORRECT, AutoList, correct_word};
pub(crate) use caret::{apply_leading_tabs, delete_dir};
use caret::{delete, delete_surrounding, get, insert, move_caret, select, select_all, select_para, select_word, set};
pub(crate) use editing::{insert_field, insert_text, paste_body};
pub use formatting::format_range;
use formatting::{fonts_used, replace_font};
pub(crate) use formatting::{format_body, format_para, format_run, format_run_levels, link_text};
pub use ime::{cell_range_underlines, range_underlines};
use ime::{commit, compose};
pub(crate) use layout::ctx_for;
pub use layout::{caret_line, fit_text_box, layout_for, text_frame, text_pos_at};
/// Catalogue text-editing, selection, autocorrect, font, IME, and surrounding-deletion commands
/// with their parameter docs and enabled predicates.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "font.used", "Fonts in Presentation", [], None, "{} → [family] (theme fonts resolved)", has_doc, fonts_used),
cmd!(
"font.replace",
"Replace Fonts",
["Home", "Editing", "Replace"],
None,
"{from, to} — every explicit use of family `from`, theme fonts included → {replaced}",
has_doc,
replace_font
),
cmd!(noundo "text.edit", "Edit Text", [], Some("Enter"), "{id?, at?: [paragraph, char], end?: bool, cell?: [row, col], notes?: bool}", has_slide, edit),
cmd!(noundo "text.exit", "Stop Editing Text", [], None, "{}", has_doc, exit),
cmd!(
noundo "text.autocorrect",
"AutoCorrect Options",
["Tools"],
None,
"{on?, twoInitials?, sentenceCaps?, days?, capsLock?, fractions?, ordinals?, lists?: bool, add?: [from, to], remove?: from} → the options and the replacement list",
always,
autocorrect_options
),
cmd!("text.insert", "Type Text", [], None, "{text} (\\n = new paragraph, \\u000b = line break)", has_text, insert),
// The input method's composition: shown in place, an undo step only once committed.
CommandSpec {
id: "text.compose",
label: "Compose Text",
menu: &[],
shortcut: None,
params: "{text, active?: [start, end]} — an input method's composition (preedit) at the insertion point; empty text cancels it",
enabled: has_text,
run: compose,
journal: false,
undoable: false,
},
cmd!(
noundo "text.commit",
"Commit Composition",
[],
None,
"{text} — the input method's result replaces its composition, as one undo step",
has_text,
commit
),
cmd!(
"text.delete",
"Delete Text",
[],
Some("Backspace"),
"{dir?: backward|forward|wordBackward|wordForward} — the word directions are Ctrl+Backspace/Delete: they work from the start of a selection without deleting it",
has_text,
delete
),
// An input method asks for text around the caret to be removed (macOS press-and-hold,
// dictation, Wayland text-input). Internal: the keyboard and control protocol keep the
// existing text.delete spelling. `bytes` says the counts are UTF-8 bytes (winit's
// `Ime::DeleteSurrounding`), otherwise characters, both in the logical coordinates
// the editor publishes: a paragraph mark or soft line break is one `\n` byte, so a
// range may cross paragraphs. The selection and pre-edit are kept; byte ranges round
// inward to whole scalars. A deletion while composing stays in the composition's single
// undo step.
//
// `undoable: false` is deliberate even though a non-composing deletion is undoable: the
// handler pushes its own history entry from a snapshot taken before the composition is
// replaced, so the generic post-run undo hook must not add a duplicate. `journal` stays
// off for the same reason an input-method edit is not a replayable document command.
CommandSpec {
id: "text.deleteSurrounding",
label: "Delete Surrounding Text",
menu: &[],
shortcut: None,
params: "{before, after, bytes?: bool}",
enabled: has_text,
run: delete_surrounding,
journal: false,
undoable: false,
},
cmd!(noundo "text.move", "Move Insertion Point", [], None, "{to: left|right|up|down|wordLeft|wordRight|lineStart|lineEnd|paraStart|paraEnd|paraUp|paraDown|start|end, extend?: bool} — left/right are on screen: in a right-to-left paragraph left goes forward", has_text, move_caret),
cmd!(noundo "text.select", "Select Text", [], None, "{anchor: [p, c], caret: [p, c]}", has_text, select),
cmd!(noundo "text.selectAll", "Select All Text", [], None, "{}", has_text, select_all),
cmd!(noundo "text.selectWord", "Select Word", [], None, "{at?: [p, c]}", has_text, select_word),
cmd!(noundo "text.selectParagraph", "Select Paragraph", [], None, "{at?: [p, c]}", has_text, select_para),
cmd!(
"text.set",
"Set Text",
[],
None,
"{id?, text, cell?: [r, c]} — replaces the whole text, keeping the first run's formatting",
has_slide,
set
),
cmd!(query "text.get", "Get Text", [], None, "{id?} → {text, paragraphs}", has_slide, get),
]
}
/// Applies one replacement inside the session's guarded, rollback-capable transaction.
/// The handler records per-insert history; live preedits retain their original undo snapshot.
pub(crate) fn replace_text_range(
s: &mut Session,
range: std::ops::Range<usize>,
text: &str,
kind: crate::TextReplaceKind,
) -> Result<crate::TextReplaceResult> {
use crate::TextReplaceKind;
let st = s.doc()?;
let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?;
if !selection.notes && st.shape(selection.shape).is_none_or(|shape| shape.locked) {
return Err(bad("text.replaceRange", "the text being edited is unavailable or locked"));
}
let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?;
let invalid = || bad("text.replaceRange", "the range is not in the text");
if range.start > range.end {
return Err(invalid());
}
let from = flat_pos(body, range.start).ok_or_else(invalid)?;
let to = flat_pos(body, range.end).ok_or_else(invalid)?;
let old_text = (kind == TextReplaceKind::Typed).then(|| body.text());
let composing = st.composition.is_some();
if range.is_empty() && text.is_empty() && !composing {
return Ok(crate::TextReplaceResult { range, selection });
}
s.begin_text_edit_session()?;
if !matches!(kind, TextReplaceKind::Composing | TextReplaceKind::Committed | TextReplaceKind::Deleted) {
s.settle_composition();
}
let st = s.doc()?;
let (before, before_selection) = (st.doc.clone(), st.selection.clone());
let vertex_kind = s.tool.vertex_kind.clone();
match kind {
TextReplaceKind::Composing | TextReplaceKind::Committed => ime::replace_marked(s, from, to, text, kind == TextReplaceKind::Committed)?,
TextReplaceKind::Deleted if composing => ime::delete_range(s, range.clone(), text)?,
TextReplaceKind::Typed | TextReplaceKind::Pasted | TextReplaceKind::Deleted => {
if let Some(t) = s.doc_mut()?.selection.text.as_mut() {
// Setting the replacement endpoints is part of this edit, not a selection command
// that could settle composition or seal the session's cancellation boundary.
t.anchor = from;
t.caret = to;
t.line_end = None;
}
if kind == TextReplaceKind::Typed {
insert_text(s, text, None)?;
} else if from != to || !text.is_empty() {
editing::replace_selection(s, text, None)?;
}
let st = s.doc_mut()?;
if !Arc::ptr_eq(&before, &st.doc) {
let command = match kind {
TextReplaceKind::Pasted => "edit.paste",
TextReplaceKind::Deleted => "text.delete",
_ => "text.insert",
};
let label = super::find_command(command).ok_or_else(|| bad("text.replaceRange", "the edit command is not registered"))?.label;
push_undo(st, HistoryEntry { label: label.into(), doc: before, selection: before_selection, vertex_kind });
}
}
}
let st = s.doc()?;
let selection = st.selection.text.clone().ok_or_else(|| bad("text.replaceRange", NO_TEXT_POINT))?;
let body = body_of(st, &selection).ok_or_else(|| bad("text.replaceRange", "the text being edited is gone"))?;
let caret = flat_offset(body, selection.caret).ok_or_else(invalid)?;
let inserted = if kind == TextReplaceKind::Composing && !text.is_empty() {
let c = st.composition.as_ref().ok_or_else(|| bad("text.replaceRange", "the composition was refused"))?;
let start = flat_offset(body, c.start).ok_or_else(invalid)?;
start..start + c.len
} else if kind == TextReplaceKind::Deleted {
range.start..range.start
} else if text.is_empty() {
caret..caret
} else if let Some(old_text) = old_text {
// AutoCorrect can replace text preceding the requested insertion, such as (c) plus Space.
let after = body.text();
let unchanged = old_text.chars().zip(after.chars()).take_while(|(a, b)| a == b).count();
range.start.min(unchanged).min(caret)..caret
} else {
range.start.min(caret)..caret
};
Ok(crate::TextReplaceResult { range: inserted, selection })
}
/// Character offsets count each paragraph separator once, including empty paragraphs.
fn flat_pos(body: &TextBody, mut offset: usize) -> Option<Pos> {
if body.paragraphs.is_empty() {
return (offset == 0).then_some((0, 0));
}
for (pi, para) in body.paragraphs.iter().enumerate() {
let len = para.char_len();
if offset <= len {
return Some((pi, offset));
}
offset = offset.checked_sub(len.checked_add(1)?)?;
}
None
}
fn flat_offset(body: &TextBody, pos: Pos) -> Option<usize> {
if body.paragraphs.is_empty() {
return (pos == (0, 0)).then_some(0);
}
let para = body.paragraphs.get(pos.0)?;
if pos.1 > para.char_len() {
return None;
}
body.paragraphs.iter().take(pos.0).try_fold(pos.1, |offset, para| offset.checked_add(para.char_len())?.checked_add(1))
}
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
let result = editing::edit(s, p)?;
s.begin_text_edit_session()?;
Ok(result)
}
fn exit(s: &mut Session, p: &Value) -> Result<Value> {
s.finish_text_edit_session(false)?;
editing::exit(s, p)
}
/// The text body a text selection edits.
pub fn body_of<'a>(st: &'a DocState, t: &TextSel) -> Option<&'a TextBody> {
if t.notes {
return st.current_slide().map(|s| &s.notes);
}
let sh = st.shape(t.shape)?;
if let (Some((r, c)), ShapeKind::Table(tb)) = (t.cell, &sh.kind) {
return tb.cell(r, c).map(|x| &x.text);
}
sh.text.as_ref()
}
fn body_mut<'a>(doc: &'a mut Presentation, sel: &Selection, t: &TextSel) -> Option<&'a mut TextBody> {
if t.notes {
return doc.slides.get_mut(sel.slide).map(|s| &mut Arc::make_mut(s).notes);
}
let shapes = crate::shapes_mut(doc, sel)?;
let sh = deckcraft_model::find_shape_mut(shapes, t.shape)?;
if let Some((r, c)) = t.cell {
if let ShapeKind::Table(tb) = &mut sh.kind {
return tb.cell_mut(r, c).map(|x| &mut x.text);
}
return None;
}
Some(sh.text.get_or_insert_with(TextBody::default))
}
/// Edit the active text body and selection; refits auto-sizing text boxes afterwards.
pub(crate) fn edit_text<T>(s: &mut Session, f: impl FnOnce(&mut TextBody, &mut TextSel) -> T) -> Result<T> {
let t0 = s.doc()?.selection.text.clone().ok_or_else(|| bad("text", NO_TEXT_POINT))?;
// Materialise an inherited placeholder box before editing (so autofit can change it).
let r = s.edit(|doc, sel| {
let mut t = t0.clone();
let body = body_mut(doc, sel, &t).ok_or_else(|| bad("text", "the text being edited is gone"))?;
let r = f(body, &mut t);
// The saved shrink-on-overflow scale was for the old text: fit the new text afresh. A
// body whose file carried no `fontScale` keeps none (100 %) here; `fit_shrink_scale`
// below fills in the computed scale when the new text overflows (#724).
if let Some(AutoFit::Shrink { font_scale, line_reduction }) = &mut body.body.autofit {
if font_scale.is_some() {
*font_scale = Some(1.0);
}
*line_reduction = 0.0;
}
sel.text = Some(t);
Ok(r)
})?;
if !t0.notes && t0.cell.is_none() {
fit_text_box(s, t0.shape)?;
}
Ok(r)
}
#[cfg(test)]
mod font_script_tests {
use super::*;
/// Every run's (latin, east asian, complex script) typefaces in the deck.
fn typefaces(s: &mut Session) -> Vec<(Option<String>, Option<String>, Option<String>)> {
s.doc()
.unwrap()
.doc
.slides
.iter()
.flat_map(|sl| sl.shapes.iter())
.filter_map(|sh| sh.text.as_ref())
.flat_map(|t| t.paragraphs.iter())
.flat_map(|para| para.runs.iter())
.map(|r| (r.props.font.clone(), r.props.font_ea.clone(), r.props.font_cs.clone()))
.collect()
}
#[test]
fn format_font_sets_the_east_asian_and_complex_script_typefaces() {
// A run carries a typeface per script; setting only the Latin one leaves a CJK run
// drawing, and saving, in whatever `a:ea` named before (#786).
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
// All three at once.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC", "complexScript": "Noto Sans Arabic"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// The Latin-only call keeps its old meaning: the other two are left alone, which is
// what makes the new parameters additive.
s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// And they reach the file: the issue is that a saved deck kept asking for the old
// East Asian font.
let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
// The text box is on whichever slide was current, so look across all of them.
let mut xml = String::new();
for i in 0..zip.len() {
let mut f = zip.by_index(i).unwrap();
if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") {
std::io::Read::read_to_string(&mut f, &mut xml).unwrap();
}
}
assert!(xml.contains(r#"<a:ea typeface="Noto Sans CJK SC"/>"#), "no a:ea in the saved slides");
assert!(xml.contains(r#"<a:cs typeface="Noto Sans Arabic"/>"#), "no a:cs in the saved slides");
assert!(xml.contains(r#"<a:latin typeface="Comic Neue"/>"#), "no a:latin in the saved slides");
// Read back, they are still there.
s.execute("file.openBytes", &json!({"name": "f.pptx", "data": crate::cmd::base64_encode(&bytes)})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
}
#[test]
fn format_font_rejects_an_unusable_typeface_name() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
for p in [json!({"family": " "}), json!({"family": "Lato", "eastAsia": ""}), json!({"family": "Lato", "complexScript": "x".repeat(201)})] {
assert!(s.execute("format.font", &p).is_err(), "{p} should be rejected");
}
// A script key that is present but not a string is refused, not read as absent. It used
// to set `family` and report success with the script typeface untouched, so the one thing
// the call asked for was the one thing that did not happen (noted in review).
for p in [
json!({"family": "Lato", "eastAsia": 42}),
json!({"family": "Lato", "complexScript": true}),
json!({"family": "Lato", "eastAsia": ["Noto Sans CJK SC"]}),
json!({"family": "Lato", "complexScript": {"name": "Noto Sans Arabic"}}),
json!({"family": 42}),
] {
let e = s.execute("format.font", &p).expect_err(&format!("{p} should be rejected"));
assert!(format!("{e}").contains("is not a typeface name"), "{p}: {e}");
}
// Nothing above changed a run: the first call in this test left `family` unset, and a
// refused call must not have set it on the way to the error.
assert_eq!(typefaces(&mut s), vec![(None, None, None)]);
// An explicit `null` reads as absent, as it does for an index or a shape id, so the
// script keeps whatever typeface it had.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap();
s.execute("format.font", &json!({"family": "Lato", "eastAsia": null})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
// A name with spaces around it is kept, trimmed.
s.execute("format.font", &json!({"family": " Lato ", "eastAsia": " Noto Sans CJK SC "})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
}
/// Each script's typeface is set on its own, and a run whose text is entirely CJK takes its
/// East Asian one: that is the run #786 is about, where `a:latin` alone changes nothing that
/// is drawn (noted in review).
#[test]
fn a_cjk_run_takes_the_east_asian_typeface_and_each_script_is_set_on_its_own() {
let mut s = Session::with_new();
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "你好世界"})).unwrap();
s.execute("text.exit", &json!({})).unwrap();
// `eastAsia` alone (with the required `family`): the complex-script typeface is untouched.
s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]);
// `complexScript` alone: the East Asian typeface just set is kept, not cleared.
s.execute("format.font", &json!({"family": "Lato", "complexScript": "Noto Sans Arabic"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// A Latin-only call on the CJK run changes `a:latin` and nothing a CJK glyph is drawn in.
s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap();
assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]);
// The saved run carries its text and the East Asian typeface together.
let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
for i in 0..zip.len() {
let mut f = zip.by_index(i).unwrap();
if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") {
std::io::Read::read_to_string(&mut f, &mut xml).unwrap();
}
}
let run = xml.find("你好世界").and_then(|at| xml[..at].rfind("<a:r>").map(|start| &xml[start..at])).unwrap_or_default();
assert!(run.contains(r#"<a:ea typeface="Noto Sans CJK SC"/>"#), "the CJK run has no a:ea: {run}");
}
}