e4f86d11fe8a
text.rs
//! 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};
use editing::{edit, exit};
pub(crate) use editing::{insert_field, insert_text, paste_body};
pub use formatting::format_range;
use formatting::{fonts_used, replace_font};
pub(crate) use formatting::{format_body, format_para, format_run, format_run_levels, link_text};
pub use ime::{IME_SURROUNDING_MAX_BYTES, ImeSurrounding, cell_range_underlines, composition_underlines, ime_surrounding, range_underlines};
use ime::{commit, compose};
pub(crate) use layout::ctx_for;
pub use layout::{caret_color, caret_line, fit_text_box, layout_for, text_frame, text_pos_at};
/// 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 text
// `ime_surrounding` 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),
]
}
/// 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}");
}
}
No file is open. Choose one in the tree, or press Ctrl+O (βO on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.