diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index efcd2b1e13..78d24a20b5 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Move Direction Handles", [], None, - "{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused", + "{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused", has_doc, move_handles ), @@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result { } // A move by nothing changes only the kind of anchors that become corners: those with both // handles listed, or every listed one with `independent`. + // The other anchors are left out, so a live shape that only they lie on is not expanded. if d == Vec2::ZERO { - let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| { + anchors.retain(|&(id, si, ai), &mut (inn, out)| { (independent || (inn && out)) && doc .node(id) @@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result { .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) .is_some_and(|a| a.kind != AnchorKind::Corner) }); - if !corners { + if anchors.is_empty() { return ok(); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ca6f72d0ef..5a4bb380c0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -92,6 +92,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod tags; +mod text; mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -167,6 +168,7 @@ pub(super) struct State { items: RefCell>, locked: RefCell>, saving: Cell, + text: text::TextState, presets: RefCell>>, preset_bytes: Cell, preset_limit: u64, @@ -305,8 +307,8 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it, -/// so a script that checks for the member first skips it, and `reflect` leaves it out. +/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is +/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -317,9 +319,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> Described { "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "TextRange" => { + text::check_range(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -2598,6 +2603,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + text::install_enums(realm)?; for (name, members) in ENUMS { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; @@ -2630,6 +2636,7 @@ fn classes(link: &Link) -> Vec { ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), ("toString", class_text("Application"), returns("string", &[])), ]); + application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); @@ -2698,12 +2705,13 @@ fn classes(link: &Link) -> Vec { returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), ), ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -2806,7 +2814,8 @@ fn classes(link: &Link) -> Vec { ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(text::classes(l)); classes.extend(variables::classes(l)); classes.push(class( "Layer", diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs new file mode 100644 index 0000000000..7452051580 --- /dev/null +++ b/crates/engine/src/script/dom/text.rs @@ -0,0 +1,1787 @@ +//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and +//! `paragraphAttributes`, and `app.textFonts`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so +//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves +//! out to the whole character. One item of `characters` is one code point. +//! - `contents` gives each paragraph break as `\r` and each forced line break as `\u0003`; written +//! text may use `\r`, `\n` or `\r\n` for a paragraph break. +//! - A word is a run of characters that are not white space. A paragraph ends after its break, and +//! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. +//! - A range keeps its place while the script edits the frame through the object model: an edit +//! before it moves it, an edit over one of its ends takes that end to the edge of the edit's new +//! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins +//! it. When a member finds the frame's text different from the text the model last saw, because +//! `vc.run` or an undo changed it, every range made before is stale and throws +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. After +//! File › Revert every range made before is stale, even when the file read back holds the same +//! text. +//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no +//! longer kept is stale. +//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member +//! that gives a range gives a new object. +//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and +//! `addBefore` before its first. An added word is kept apart from the characters next to it by a +//! space, and an added paragraph by a paragraph break. +//! - A character attribute read on a range whose characters differ gives the first character's +//! value; set on an empty range it changes nothing. A paragraph attribute reads the first +//! paragraph the range touches and sets every one of them. A text range has the members of +//! both its `characterAttributes` and its `paragraphAttributes`. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; + +use super::{ + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, + editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, + returns, text, typed, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a text range, or of a collection of one, whose frame's text changed other than +/// through the object model. +pub const STALE_RANGE: &str = "Stale text range"; +/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit +/// is stale. +const MAX_EDITS: usize = 100_000; + +/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. +pub(super) struct Index { + text: String, + /// The UTF-16 offset of each character's start, and the text's length last. + chars: Vec, + /// The byte offset of each character's start, and the text's length in bytes last. + bytes: Vec, + words: Vec<(usize, usize)>, + paras: Vec<(usize, usize)>, +} + +impl Index { + fn new(text: String) -> Self { + let mut chars = Vec::with_capacity(text.len() + 1); + let mut bytes = Vec::with_capacity(text.len() + 1); + let (mut words, mut paras) = (Vec::new(), Vec::new()); + let (mut u, mut word, mut para) = (0, None, 0); + for (b, c) in text.char_indices() { + chars.push(u); + bytes.push(b); + if c.is_whitespace() { + if let Some(w) = word.take() { + words.push((w, u)); + } + } else if word.is_none() { + word = Some(u); + } + u += c.len_utf16(); + if c == '\n' { + paras.push((para, u)); + para = u; + } + } + if let Some(w) = word { + words.push((w, u)); + } + paras.push((para, u)); + chars.push(u); + bytes.push(text.len()); + Self { text, chars, bytes, words, paras } + } + + fn len(&self) -> usize { + self.chars.last().copied().unwrap_or(0) + } + + /// The byte offset of UTF-16 offset `u`; inside a surrogate pair, the start of its character, + /// or with `up` the end of it. + fn byte(&self, u: usize, up: bool) -> usize { + let i = self.chars.partition_point(|&c| c < u); + match self.chars.get(i) { + Some(&c) if c == u || up => self.bytes.get(i).copied().unwrap_or(self.text.len()), + _ => i.checked_sub(1).and_then(|i| self.bytes.get(i)).copied().unwrap_or(0), + } + } + + /// The characters whose start is in `s..e`, each as a UTF-16 span. + fn chars_in(&self, s: usize, e: usize) -> std::ops::Range { + let count = self.chars.len().saturating_sub(1); + let a = self.chars[..count].partition_point(|&c| c < s); + let b = self.chars[..count].partition_point(|&c| c < e); + a..b.max(a) + } + + fn char_span(&self, i: usize) -> Option<(usize, usize)> { + Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) + } +} + +/// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty +/// range, the one with a character at it, or the last one when it ends there. Only an empty range +/// touches the empty paragraph after a break at the end of the text. +fn touched(spans: &[(usize, usize)], s: usize, e: usize) -> std::ops::Range { + if s == e { + let i = spans.partition_point(|&(_, y)| y <= s); + if spans.get(i).is_some_and(|&(x, _)| x <= s) { + return i..i + 1; + } + return match spans.last() { + Some(&(_, y)) if i == spans.len() && y == s => i - 1..i, + _ => i..i, + }; + } + let a = spans.partition_point(|&(_, y)| y <= s); + let b = spans.partition_point(|&(x, _)| x < e); + a..b.max(a) +} + +#[derive(Clone, Copy)] +struct Edit { + stamp: u64, + at: usize, + removed: usize, + inserted: usize, +} + +/// What the object model knows of one frame's text: the document it was read from and its revert +/// count then, the text, the edits made through the model, and the oldest range generation still +/// valid. +struct Log { + doc: Weak, + reverts: u64, + index: Rc, + stamp: u64, + floor: u64, + edits: VecDeque, +} + +impl Log { + /// Records an edit the model made: `removed` units at `at` replaced by `inserted` units. Past + /// [`MAX_EDITS`] the oldest edit is dropped, and ranges made before it go stale. + fn push(&mut self, at: usize, removed: usize, inserted: usize) { + self.stamp += 1; + self.edits.push_back(Edit { stamp: self.stamp, at, removed, inserted }); + if self.edits.len() > MAX_EDITS + && let Some(dropped) = self.edits.pop_front() + { + self.floor = dropped.stamp; + } + } +} + +/// A document's uid, the document, and the ids of its type objects then. +type FrameList = (u64, Weak, Rc>); + +/// Word or paragraph spans, in UTF-16 units. +type Spans = [(usize, usize)]; + +/// The text state of one run. +#[derive(Default)] +pub(in crate::script) struct TextState { + frames: RefCell>, + /// A document's uid, the document, and the ids of its type objects, topmost first. + list: RefCell>, + /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character + /// names that is not installed is added at the end. + fonts: RefCell>>, + /// The number of text range objects made, which numbers the next one. + made: Cell, + /// The span of each range object, by its number, whose `length` the script set. + resized: RefCell>, +} + +fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { + match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn same_text(t: &TextObject, s: &str) -> bool { + let mut rest = s; + for r in &t.runs { + match rest.strip_prefix(r.text.as_str()) { + Some(after) => rest = after, + None => return false, + } + } + rest.is_empty() +} + +/// The frame's index and its generation now, read again when its document changed. After File › +/// Revert every earlier range goes stale, even when the file read back holds the same text. +fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { + let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut frames = h.dom.text.frames.borrow_mut(); + let key = (st.uid, id.0); + let now = Arc::as_ptr(&st.doc); + match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + if l.reverts != st.reverts || !same_text(t, &l.index.text) { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(t.plain_text())); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let l = Log { + doc: Arc::downgrade(&st.doc), + reverts: st.reverts, + index: Rc::new(Index::new(t.plain_text())), + stamp: 0, + floor: 0, + edits: VecDeque::new(), + }; + frames.insert(key, l); + } + } + let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A text range: its frame, its span in UTF-16 units and the generation it was made at. +#[derive(Clone, Copy)] +struct Span { + item: Item, + start: usize, + end: usize, + stamp: u64, +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.item.doc, |_, st| { + let (index, stamp) = observe(h, st, r.item.id)?; + let frames = h.dom.text.frames.borrow(); + let l = frames.get(&(st.uid, r.item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let len = index.len(); + let e = e.min(len); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. +fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let now = t.plain_text(); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let mut frames = h.dom.text.frames.borrow_mut(); + let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if expected && l.reverts == st.reverts { + l.push(at, removed, inserted.encode_utf16().count()); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = Rc::new(Index::new(now)); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + Ok(()) + }) +} + +// ---- handles ---- + +fn usize_of(n: f64) -> Option { + whole(n).and_then(|v| usize::try_from(v).ok()) +} + +/// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each +/// object is numbered, so setting one range's `length` leaves every other range as it is. The +/// first five numbers are the frame's page item handle, so a range goes stale with its frame, +/// after `file.revert` too. +fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(item.id); + let reverts = h.session.borrow().documents().get(item.doc.index).map_or(0, |d| d.reverts); + let made = &h.dom.text.made; + made.set(made.get() + 1); + host_ref( + class, + &[float(h.run), float(item.doc.uid), high, low, float(reverts), float(s as u64), float(e as u64), float(stamp), float(made.get())], + ) +} + +/// The span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + span_and_number(h, d, classes).map(|(span, _)| span) +} + +/// The span `d` names and the number of its object, when it is an object of one of `classes`. +fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, reverts, s, e, stamp, number]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low, reverts])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else { + return Err(HostError::Error(STALE_RANGE.into())); + }; + let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp)); + Ok((Span { item: frame, start, end, stamp }, number)) +} + +/// The text frame `this` names. +fn this_frame(h: &Host, a: &[Data]) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_none() { + return Err(HostError::Type("this is not a TextFrame".into())); + } + item_of(h, arg(a, 0)) +} + +/// The whole text of the frame as a span. +fn whole_span(h: &Host, item: Item) -> std::result::Result<(Rc, Span), HostError> { + with_doc(h, item.doc, |_, st| { + let (index, stamp) = observe(h, st, item.id)?; + let len = index.len(); + Ok((index, Span { item, start: 0, end: len, stamp })) + }) +} + +fn this_range(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["TextRange"]) +} + +/// Fails when `d` is not a text range, or is a stale one. +pub(super) fn check_range(h: &Host, d: &Data) -> std::result::Result<(), HostError> { + resolve(h, span_of(h, d, &["TextRange"])?).map(|_| ()) +} + +/// The span of `this`: a text range, or a text frame's whole text. +fn this_text(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, arg(a, 0))?)?.1); + } + span_of(h, arg(a, 0), &[class]) +} + +// ---- contents ---- + +/// The model's text as `contents` gives it. +fn to_script(s: &str) -> String { + s.chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect() +} + +/// Text a script wrote, as the model keeps it. +fn from_script(s: &str) -> String { + s.replace("\r\n", "\n") + .chars() + .map(|c| match c { + '\r' => '\n', + '\u{3}' => '\u{2028}', + c => c, + }) + .collect() +} + +fn read_contents(h: &Host, r: Span) -> Answer { + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[a..b]))) +} + +/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it. +fn contents_of(value: &Data) -> std::result::Result { + match value { + Data::String(v) => Ok(from_script(v)), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + _ => Err(HostError::Type("contents must be a string or a number".into())), + } +} + +/// Replaces the text of `r` with `value`, as one `text.editRange`. +fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { + let insert = contents_of(value)?; + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + record(h, r.item, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn frame_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + read_contents(h, r) +} + +fn frame_set_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + write_contents(h, r, arg(a, 1)) +} + +fn range_contents(h: &Host, a: &[Data]) -> Answer { + read_contents(h, this_range(h, a)?) +} + +fn range_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, arg(a, 1)) +} + +// ---- TextFrame ---- + +fn frame_kind(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(match t.kind { + TextKind::Point => "TextType.POINTTEXT", + TextKind::Area { .. } => "TextType.AREATEXT", + TextKind::OnPath { .. } => "TextType.PATHTEXT", + })) + }) +} + +fn frame_orientation(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(if t.vertical { "TextOrientation.VERTICAL" } else { "TextOrientation.HORIZONTAL" })) + }) +} + +fn frame_range(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = whole_span(h, item)?; + Ok(range_ref(h, item, r.start, r.end, r.stamp, "TextRange")) +} + +fn sub(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_text(h, a, "TextRange")?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, class)) +} + +fn characters(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Characters") +} + +fn words(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Words") +} + +fn paragraphs(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Paragraphs") +} + +fn character_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "CharacterAttributes") +} + +fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "ParagraphAttributes") +} + +/// The id a command's result, as the command gave it, holds under `ids` (the first) or `id`. It is +/// read from the JSON, where an id above 2^53 is still exact. +fn result_id(v: &Value) -> Option { + v.get("ids").and_then(|ids| ids.get(0)).or_else(|| v.get("id")).and_then(Value::as_u64).map(NodeId) +} + +fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { + let id = id.ok_or_else(|| HostError::Error("the command made no object".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, id)) +} + +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines, or +/// `null` when the type has nothing to outline and the command removed it. +fn frame_outline(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + super::command_value(h, "type.createOutlines", &json!({})) + })?; + match result_id(&r) { + Some(id) => new_ref(h, item.doc, Some(id)), + None => Ok(Data::Null), + } +} + +/// Converts area type to point type (`area` false) or point type to area type. +fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { + let item = this_frame(h, a)?; + let kind_ok = with_doc(h, item.doc, |_, st| { + text_of(st, item.id).map(|t| if to_area { matches!(t.kind, TextKind::Point) } else { matches!(t.kind, TextKind::Area { .. }) }) + }); + match kind_ok { + None => return Err(HostError::Error(STALE_ITEM.into())), + Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), + Some(true) => {} + } + let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; + let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; + new_ref(h, item.doc, result_id(&r).or(Some(item.id))) +} + +fn frame_to_point(h: &Host, a: &[Data]) -> Answer { + convert(h, a, false) +} + +fn frame_to_area(h: &Host, a: &[Data]) -> Answer { + convert(h, a, true) +} + +// ---- TextRange ---- + +fn range_parent(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + resolve(h, r)?; + Ok(with_doc(h, r.item.doc, |_, st| item_ref(h, st, r.item.id))) +} + +fn range_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn range_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn range_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text +/// does not change. A length that is not a whole number from 0 to the units left in the frame +/// throws. +fn range_set_length(h: &Host, a: &[Data]) -> Answer { + let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?; + let (index, s, _, stamp) = resolve(h, r)?; + let n = super::number(arg(a, 1), "length")?; + let left = index.len() - s; + let Some(n) = usize_of(n).filter(|n| *n <= left) else { + return Err(HostError::Range(format!("length must be a whole number from 0 to {left}"))); + }; + h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp)); + Ok(Data::Undefined) +} + +/// `remove()`: deletes the range's text. +fn range_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, &text("")) +} + +/// `getParagraphLength()`: the length of the first paragraph the range touches, its break included. +fn range_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_range(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +/// `getTextRunLength()`: the length from the range's start to the end of the run of characters +/// with one style it starts in, within the range. +fn range_run_length(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + let b = index.byte(s, false); + let run_end = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut at = 0; + for run in &t.runs { + at += run.text.len(); + if at > b { + return Ok(at); + } + } + Ok(at) + })?; + let u = index.text[..run_end.min(index.text.len())].encode_utf16().count(); + Ok(num(float((u.min(e).max(s) - s) as u64))) +} + +// ---- collections of a range ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Part { + Characters, + Words, + Paragraphs, +} + +const PARTS: [(&str, Part); 3] = [("Characters", Part::Characters), ("Words", Part::Words), ("Paragraphs", Part::Paragraphs)]; + +fn part_of(d: &Data) -> Option { + PARTS.iter().find(|(c, _)| handle_of(d, c).is_some()).map(|(_, p)| *p) +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(Span, Part), HostError> { + let part = part_of(arg(a, 0)).ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &["Characters", "Words", "Paragraphs"])?, part)) +} + +/// The spans of a collection, as a range of item numbers and the spans to look them up in. +fn part_spans(index: &Index, part: Part, s: usize, e: usize) -> (std::ops::Range, Option<&Spans>) { + match part { + Part::Characters => (index.chars_in(s, e), None), + Part::Words => (touched(&index.words, s, e), Some(&index.words)), + Part::Paragraphs => (touched(&index.paras, s, e), Some(&index.paras)), + } +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) +} + +/// Where `add` puts its text: before or after the relative object. +fn text_placement(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(true), + Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false), + Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true), + _ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())), + } +} + +/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`: +/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or +/// before or after `relativeObject`, a text range or text frame of the same frame, as one +/// `text.editRange`. A word gets a space on each side that touches another character that is not +/// white space; a paragraph gets a paragraph break on each side that touches another paragraph. +/// → the range of `contents`. +fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { + let (r, part) = this_part(h, a)?; + let contents = contents_of(arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (items, spans) = part_spans(&index, part, s, e); + let span = |k: usize| match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + if before { + items.clone().next().and_then(span).map_or(s, |(x, _)| x) + } else { + items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + } + } else { + let rel = arg(a, 2); + let target = if handle_of(rel, "TextFrame").is_some() { + whole_span(h, item_of(h, rel)?)?.1 + } else { + span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + }; + if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { + return Err(HostError::Error("relativeObject must be text of the same text frame".into())); + } + let (_, ts, te, _) = resolve(h, target)?; + if text_placement(arg(a, 3))? { te } else { ts } + }; + if contents.is_empty() { + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); + } + let b = index.byte(at, false); + let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); + let (lead, trail) = match part { + Part::Characters => ("", ""), + Part::Words => { + let apart = |c: Option| c.is_some_and(|c| !c.is_whitespace()); + let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" }; + let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" }; + (lead, trail) + } + Part::Paragraphs => ( + if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" }, + if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" }, + ), + }; + let insert = format!("{lead}{contents}{trail}"); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + record(h, r.item, &index, at, 0, &insert)?; + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + let start = at + lead.encode_utf16().count(); + Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange")) +} + +fn part_add_after(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, false) +} + +fn part_add_before(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, true) +} + +// ---- character attributes ---- + +#[derive(Clone, Copy)] +enum Attr { + Size, + Leading, + AutoLeading, + Tracking, + BaselineShift, + HorizontalScale, + VerticalScale, + Rotation, + Underline, + StrikeThrough, + TextFont, +} + +const ATTRS: [(&str, Attr); 11] = [ + ("size", Attr::Size), + ("leading", Attr::Leading), + ("autoLeading", Attr::AutoLeading), + ("tracking", Attr::Tracking), + ("baselineShift", Attr::BaselineShift), + ("horizontalScale", Attr::HorizontalScale), + ("verticalScale", Attr::VerticalScale), + ("rotation", Attr::Rotation), + ("underline", Attr::Underline), + ("strikeThrough", Attr::StrikeThrough), + ("textFont", Attr::TextFont), +]; + +/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with +/// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty +/// range, the style of the character before it, or of the first one. With `first`, only the first +/// entry. +fn styles_in(t: &TextObject, a: usize, b: usize, first: bool) -> std::result::Result, HostError> { + let mut out = Vec::new(); + let (mut at, mut para) = (0, 0); + let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + let breaks = |from: usize, to: usize| bytes.get(from - at..to - at).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + if a == b && at < a.max(1) && a <= end { + let lo = a.saturating_sub(1).max(at); + out.push((effective(&run.style)?, para + breaks(at, lo))); + break; + } + if a < end && at < b { + let (lo, hi) = (a.max(at), b.min(end)); + let style = effective(&run.style)?; + let mut p = para + breaks(at, lo); + out.push((style.clone(), p)); + if first { + return Ok(out); + } + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + p += 1; + if lo + k + 1 < hi { + out.push((style.clone(), p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + if out.is_empty() + && let Some(r) = t.runs.first() + { + out.push((effective(&r.style)?, 0)); + } + Ok(out) +} + +/// The bytes in `a..b` whose characters have auto leading, each stretch with the leading its +/// characters' auto leading sets them with, in document points; touching stretches with the same +/// leading are one. +fn auto_leading_spans(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out: Vec<(usize, usize, f64)> = Vec::new(); + let mut push = |from: usize, to: usize, leading: f64| match out.last_mut() { + Some(last) if last.1 == from && same(&num(last.2), &num(leading)) => last.1 = to, + _ => out.push((from, to, leading)), + }; + let (mut at, mut para) = (0, 0); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + if a < end && at < b { + let style = t.effective_char_style(&run.style).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into()))?; + if style.leading.is_none() { + let (lo, hi) = (a.max(at), b.min(end)); + let auto = |p: usize| t.para_at(p).justification.auto_leading_for(style.size); + let mut p = para + bytes.get(..lo - at).unwrap_or_default().iter().filter(|&&c| c == b'\n').count(); + let mut from = lo; + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + let to = lo + k + 1; + push(from, to, auto(p)); + p += 1; + from = to; + } + if from < hi { + push(from, hi, auto(p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + Ok(out) +} + +fn same(a: &Data, b: &Data) -> bool { + match (a, b) { + (Data::Number(x), Data::Number(y)) => (x - y).abs() < 1e-9, + _ => a == b, + } +} + +fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) -> Data { + match attr { + Attr::Size => num(s.size), + Attr::Leading => num(s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size))), + Attr::AutoLeading => Data::Bool(s.leading.is_none()), + Attr::Tracking => num(s.tracking), + Attr::BaselineShift => num(s.baseline_shift), + Attr::HorizontalScale => num(s.h_scale), + Attr::VerticalScale => num(s.v_scale), + Attr::Rotation => num(s.rotation), + Attr::Underline => Data::Bool(s.underline), + Attr::StrikeThrough => Data::Bool(s.strikethrough), + Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + } +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. +fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { + let finite = || number(v, name); + Ok(match attr { + Attr::Size => { + let n = finite()?; + if !(0.1..=1296.0).contains(&n) { + return Err(HostError::Range("size must be from 0.1 to 1296 points".into())); + } + (json!({"size": n}), num(n)) + } + Attr::Leading => { + let n = finite()?; + if !(0.1..=5000.0).contains(&n) { + return Err(HostError::Range("leading must be from 0.1 to 5000 points".into())); + } + (json!({"leading": n}), num(n)) + } + Attr::AutoLeading => { + if boolean(v, name)? { + (json!({"leading": "auto"}), Data::Bool(true)) + } else { + let (t, s, para) = first; + let n = s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size)); + (json!({"leading": n}), Data::Bool(false)) + } + } + Attr::Tracking => { + let n = finite()?; + if !(-1000.0..=10_000.0).contains(&n) { + return Err(HostError::Range("tracking must be from -1000 to 10000".into())); + } + (json!({"tracking": n}), num(n)) + } + Attr::BaselineShift => { + let n = finite()?; + if n.abs() > 1296.0 { + return Err(HostError::Range("baselineShift must be from -1296 to 1296 points".into())); + } + (json!({"baselineShift": n}), num(n)) + } + Attr::HorizontalScale | Attr::VerticalScale => { + let n = finite()?; + if !(1.0..=10_000.0).contains(&n) { + return Err(HostError::Range(format!("{name} must be from 1 to 10000 percent"))); + } + let key = if matches!(attr, Attr::HorizontalScale) { "hScale" } else { "vScale" }; + (json!({ key: n }), num(n)) + } + Attr::Rotation => { + let n = finite()?; + if n.abs() > 360.0 { + return Err(HostError::Range("rotation must be from -360 to 360 degrees".into())); + } + (json!({"rotation": n}), num(n)) + } + Attr::Underline => { + let b = boolean(v, name)?; + (json!({"underline": b}), Data::Bool(b)) + } + Attr::StrikeThrough => { + let b = boolean(v, name)?; + (json!({"strikethrough": b}), Data::Bool(b)) + } + Attr::TextFont => { + let (family, style) = font_of(h, v)?; + (json!({"font": family, "style": style}), font_ref(h, &family, &style)) + } + }) +} + +/// The span of `this` for a character or paragraph attribute: a text range, its +/// `characterAttributes` or `paragraphAttributes`, or a text frame's whole text. +fn attr_span(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextRange").is_some() { + return this_range(h, a); + } + this_text(h, a, class) +} + +fn read_attr(h: &Host, a: &[Data], attr: Attr) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(styles_in(t, ba, bb, true)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + }) +} + +fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let styles = styles_in(t, ba, bb, false)?; + let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + // A leading set on characters with auto leading fixes it even where auto gives that value. + let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); + let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + let fixed = match (attr, &wants) { + (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), + _ => None, + }; + if let Some(bad) = fixed.iter().flatten().map(|(_, _, l)| *l).find(|l| !(0.1..=5000.0).contains(l)) { + return Err(HostError::Range(format!("autoLeading cannot be turned off: the auto leading here is {bad} points, outside 0.1 to 5000"))); + } + Ok::<_, HostError>((param, unchanged, fixed)) + })?; + if unchanged { + return Ok(Data::Undefined); + } + if let Some(spans) = fixed { + // Each character with auto leading keeps the leading it is set with now. + super::atomically(h, |h| { + for (start, end, leading) in &spans { + let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); + edit_item(h, r.item, "text.setRangeStyle", &p)?; + } + Ok(()) + })?; + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + if let Attr::TextFont = attr { + let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; + } + Ok(Data::Undefined) +} + +/// Fails, after the font is set, when `text.setRangeStyle` warned that the font is not available +/// or when characters in bytes `a..b` kept another font because Missing Glyph Protection is on. +fn font_applied(h: &Host, item: Item, (a, b): (usize, usize), (family, style): (&str, &str), answer: &Data) -> std::result::Result<(), HostError> { + if let Data::Object(o) = answer + && let Some((_, Data::String(w))) = o.iter().find(|(k, _)| k == "warning") + { + return Err(HostError::Error(format!("textFont: {w}"))); + } + let kept = with_doc(h, item.doc, |_, st| { + let Some(t) = text_of(st, item.id) else { return 0 }; + let mut at = 0; + let mut kept = 0; + for run in &t.runs { + let end = at + run.text.len(); + let other = !run.style.font_family.eq_ignore_ascii_case(family) || !run.style.font_style.eq_ignore_ascii_case(style); + if other && a < end && at < b { + kept += run.text.get(a.max(at) - at..b.min(end) - at).map_or(0, |s| s.chars().count()); + } + at = end; + } + kept + }); + if kept > 0 { + let noun = if kept == 1 { "character, which keeps its" } else { "characters, which keep their" }; + return Err(HostError::Error(format!("textFont: the font has no glyph for {kept} {noun} font because Missing Glyph Protection is on"))); + } + Ok(()) +} + +// ---- paragraph attributes ---- + +#[derive(Clone, Copy)] +enum ParaAttr { + Justification, + FirstLineIndent, + LeftIndent, + RightIndent, + SpaceBefore, + SpaceAfter, +} + +const PARA_ATTRS: [(&str, ParaAttr); 6] = [ + ("justification", ParaAttr::Justification), + ("firstLineIndent", ParaAttr::FirstLineIndent), + ("leftIndent", ParaAttr::LeftIndent), + ("rightIndent", ParaAttr::RightIndent), + ("spaceBefore", ParaAttr::SpaceBefore), + ("spaceAfter", ParaAttr::SpaceAfter), +]; + +const JUSTIFICATIONS: [(&str, &str); 7] = [ + ("LEFT", "left"), + ("CENTER", "center"), + ("RIGHT", "right"), + ("FULLJUSTIFYLASTLINELEFT", "justifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "justifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "justifyRight"), + ("FULLJUSTIFY", "justifyAll"), +]; + +/// The text of paragraph `i` of `index`, its break included. +fn para_text(index: &Index, i: usize) -> &str { + index.paras.get(i).and_then(|&(x, y)| index.text.get(index.byte(x, false)..index.byte(y, false))).unwrap_or_default() +} + +/// The value of `attr` in paragraph `i` of `t`, whose text `index` holds. Auto alignment reads as +/// the side it aligns to: right in a right-to-left paragraph, left otherwise. +fn para_value(attr: ParaAttr, t: &TextObject, index: &Index, i: usize) -> Data { + let p = t.para_at(i); + match attr { + ParaAttr::Justification => text(format!( + "Justification.{}", + match p.justify { + Justify::Auto if vectorcraft_text::paragraph_is_rtl(para_text(index, i), p.direction) => "RIGHT", + Justify::Auto | Justify::Left => "LEFT", + Justify::Center => "CENTER", + Justify::Right => "RIGHT", + Justify::JustifyLeft => "FULLJUSTIFYLASTLINELEFT", + Justify::JustifyCenter => "FULLJUSTIFYLASTLINECENTER", + Justify::JustifyRight => "FULLJUSTIFYLASTLINERIGHT", + Justify::JustifyAll => "FULLJUSTIFY", + } + )), + ParaAttr::FirstLineIndent => num(p.first_line_indent), + ParaAttr::LeftIndent => num(p.left_indent), + ParaAttr::RightIndent => num(p.right_indent), + ParaAttr::SpaceBefore => num(p.space_before), + ParaAttr::SpaceAfter => num(p.space_after), + } +} + +/// The command and parameter that set `attr` to `v`, and the value it reads as after. +fn para_param(attr: ParaAttr, name: &str, v: &Data) -> std::result::Result<(&'static str, Value, Data), HostError> { + if let ParaAttr::Justification = attr { + let found = match v { + Data::String(s) => s.strip_prefix("Justification.").and_then(|m| JUSTIFICATIONS.iter().find(|(k, _)| *k == m)), + _ => None, + }; + let (_, value) = found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?; + return Ok(("text.setStyle", json!({"justify": value}), v.clone())); + } + let n = number(v, name)?; + if n.abs() > 1296.0 { + return Err(HostError::Range(format!("{name} must be from -1296 to 1296 points"))); + } + let key = match attr { + ParaAttr::FirstLineIndent => "firstLineIndent", + ParaAttr::LeftIndent => "leftIndent", + ParaAttr::RightIndent => "rightIndent", + ParaAttr::SpaceBefore => "spaceBefore", + _ => "spaceAfter", + }; + Ok(("text.setFormat", json!({ key: n }), num(n))) +} + +/// The paragraphs a range touches, by number, and the bytes from the first one's start to the last +/// one's start, which select exactly those paragraphs for `text.setFormat` and `text.setStyle`. +fn para_range(index: &Index, s: usize, e: usize) -> (std::ops::Range, usize, usize) { + let paras = touched(&index.paras, s, e); + let start = |i: usize| index.paras.get(i).map_or(index.text.len(), |&(x, _)| index.byte(x, false)); + let (ba, bb) = (start(paras.start), start(paras.end.saturating_sub(1).max(paras.start))); + (paras, ba, bb) +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, _, _) = para_range(&index, s, e); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(para_value(attr, t, &index, paras.start)) + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (id, param, wants) = para_param(attr, name, arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, ba, bb) = para_range(&index, s, e); + let unchanged = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // An explicit alignment replaces Auto even where Auto aligns to the same side. + let auto = |i: usize| matches!(attr, ParaAttr::Justification) && t.para_at(i).justify == Justify::Auto; + Ok::<_, HostError>(paras.clone().all(|i| !auto(i) && same(¶_value(attr, t, &index, i), &wants))) + })?; + if unchanged { + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + edit_item(h, r.item, id, &p)?; + Ok(Data::Undefined) +} + +// ---- TextFrames ---- + +fn doc_text_frames_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("TextFrames", &[float(h.run), float(doc.uid)])) +} + +/// `document.textFrames`. +pub(super) fn doc_text_frames(link: &Link) -> HostMember { + get(link, doc_text_frames_impl) +} + +/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the +/// document is unchanged. +fn frame_ids(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return ids.clone(); + } + let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let ids = Rc::new(ids); + *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); + ids +} + +fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "TextFrames") +} + +fn frames_length(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) +} + +fn frames_parent(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn frames_at(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn frames_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn frames_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => frames_by_name(h, a), + Data::Number(_) => match frames_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `TextOrientation` as `text.create`'s `vertical`, `undefined` horizontal. +fn vertical_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(false), + Data::String(s) if s == "TextOrientation.HORIZONTAL" => Ok(false), + Data::String(s) if s == "TextOrientation.VERTICAL" => Ok(true), + _ => Err(HostError::Type("orientation must be a TextOrientation value".into())), + } +} + +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. +fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { + let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; + let (_, r) = + on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `add()`: empty point type at the origin. +fn frames_add(h: &Host, a: &[Data]) -> Answer { + point_text(h, frames_doc(h, a)?, None, false) +} + +/// `pointText(anchor, orientation?)`. +fn frames_point_text(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let anchor = point(arg(a, 1), "anchor")?; + point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) +} + +/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { + let doc = frames_doc(h, a)?; + if handle_of(arg(a, 1), "PathItem").is_none() { + return Err(HostError::Type("textPath must be a PathItem".into())); + } + let path = item_of(h, arg(a, 1))?; + if path.doc.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { + return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + } + let orientation = if on_path { 4 } else { 2 }; + let vertical = vertical_of(arg(a, orientation))?; + let mode = if on_path { "onPath" } else { "area" }; + let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + new_ref(h, doc, result_id(&r)) +} + +/// `areaText(textPath, orientation?, baseFrame?, postFix?)`. +fn frames_area_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, false, &[3, 4]) +} + +/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. +fn frames_path_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, true, &[2, 3, 5, 6]) +} + +/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- fonts ---- + +/// The run's font list, read once. +fn with_fonts(h: &Host, f: impl FnOnce(&mut Vec<(String, String)>) -> T) -> T { + let mut fonts = h.dom.text.fonts.borrow_mut(); + let list = fonts.get_or_insert_with(|| { + let db = vectorcraft_text::FontDb::global(); + let mut v = Vec::new(); + for family in db.menu_family_list().iter() { + for style in db.styles(family) { + v.push((family.clone(), style)); + } + } + v + }); + f(list) +} + +/// A `TextFont` for `family` and `style`, added to the run's list when it is not there. +fn font_ref(h: &Host, family: &str, style: &str) -> Data { + let i = with_fonts(h, |list| match list.iter().position(|(f, s)| f.eq_ignore_ascii_case(family) && s.eq_ignore_ascii_case(style)) { + Some(i) => i, + None => { + list.push((family.to_string(), style.to_string())); + list.len() - 1 + } + }); + host_ref("TextFont", &[float(h.run), float(i as u64)]) +} + +/// The family and style of the `TextFont` `d`. +fn font_of(h: &Host, d: &Data) -> std::result::Result<(String, String), HostError> { + let Some(&[run, i]) = handle_of(d, "TextFont").as_deref() else { return Err(HostError::Type("textFont must be a TextFont".into())) }; + if whole(run) != Some(h.run) { + return Err(HostError::Error("Stale text font".into())); + } + usize_of(i).and_then(|i| with_fonts(h, |list| list.get(i).cloned())).ok_or_else(|| HostError::Error("Stale text font".into())) +} + +fn fonts_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(with_fonts(h, |l| l.len()) as u64))) +} + +fn fonts_at(h: &Host, a: &[Data]) -> Answer { + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = with_fonts(h, |l| i < l.len()); + Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) +} + +/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family +/// and style with a space. +fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone())); + let i = with_fonts(h, |l| { + h.charge_call(l.len() as u64)?; + let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); + Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) + })?; + match (i, named) { + (Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])), + (None, Some((family, style))) => Ok(font_ref(h, &family, &style)), + (None, None) => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn fonts_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => fonts_by_name(h, a), + Data::Number(_) => match fonts_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +fn font_family(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.0)) +} + +fn font_style(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.1)) +} + +/// The font's PostScript name, or its family and style joined by a hyphen when the font is not +/// installed. +fn font_name(h: &Host, a: &[Data]) -> Answer { + let (family, style) = font_of(h, arg(a, 0))?; + let face = vectorcraft_text::FontDb::global().face(&family, &style); + Ok(text(face.map_or_else(|| format!("{family}-{style}").replace(' ', ""), |f| f.postscript_name()))) +} + +fn app_text_fonts_impl(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("TextFonts", &[])) +} + +/// `app.textFonts`. +pub(super) fn app_text_fonts(link: &Link) -> HostMember { + get(link, app_text_fonts_impl) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// A font's `parent`, `app`, once the font is checked. +fn font_parent(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(host_ref("Application", &[])) +} + +// ---- classes ---- + +fn range_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_range(h, a)?)?; + Ok(text("TextRange")) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(PARTS.iter().find(|(_, p)| *p == part).map_or("Characters", |(c, _)| c))) +} + +fn char_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["CharacterAttributes"])?)?; + Ok(text("CharacterAttributes")) +} + +fn para_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["ParagraphAttributes"])?)?; + Ok(text("ParagraphAttributes")) +} + +fn frames_typename(h: &Host, a: &[Data]) -> Answer { + frames_doc(h, a)?; + Ok(text("TextFrames")) +} + +fn font_typename(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(text("TextFont")) +} + +/// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the +/// read's own checks of `this`. +fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { + let message = format!("{class}.{name} cannot be set yet"); + let get = function(link, g); + let read = get.clone(); + HostMember::Property { + get, + set: Rc::new(move |a: Vec| { + read(a.into_iter().take(1).collect())?; + Err(HostError::Error(message.clone())) + }), + } +} + +fn attr_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_attr(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_attr(&h, &a, attr, name) + }); + let data_type = match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + }; + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type))); + } + out +} + +fn para_members(link: &Link) -> Vec { + let mut out = Vec::new(); + for (name, attr) in PARA_ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_para(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_para(&h, &a, attr, name) + }); + let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" }; + out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type))); + } + out +} + +/// The enumerations type uses. +const ENUMS: &[(&str, &[&str])] = &[ + ("TextType", &["AREATEXT", "PATHTEXT", "POINTTEXT"]), + ("TextOrientation", &["HORIZONTAL", "VERTICAL"]), + ( + "Justification", + &["CENTER", "FULLJUSTIFY", "FULLJUSTIFYLASTLINECENTER", "FULLJUSTIFYLASTLINELEFT", "FULLJUSTIFYLASTLINERIGHT", "LEFT", "RIGHT"], + ), +]; + +/// Adds the enumerations type uses to `realm`. +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +/// The classes of type, `TextFrame` among them, which inherits from `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let mut frame = named(vec![ + ("kind", get(l, frame_kind), typed("TextType")), + ("contents", property(l, frame_contents, frame_set_contents), typed("string")), + ("textRange", get(l, frame_range), typed("TextRange")), + ("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }), + ("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }), + ("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }), + ("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")), + ("createOutline", method(l, frame_outline), returns("GroupItem", &[])), + ("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])), + ("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])), + ]); + frame.extend(super::variables::item_members(l, "TextFrame")); + frame.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "nextFrame", + "previousFrame", + "textPath", + "anchor", + "antialias", + "columnCount", + "columnGutter", + "rowCount", + "rowGutter", + "startTValue", + "endTValue", + "opticalAlignment", + "matrix", + "textSelection", + ] + .into_iter() + .map(|m| super::later(l, "TextFrame", m)), + ); + let mut range = named(vec![ + ("typename", get(l, range_typename), typed("string")), + ("parent", get(l, range_parent), typed("*")), + ("contents", property(l, range_contents, range_set_contents), typed("string")), + ("start", read_only(l, range_start, "TextRange", "start"), typed("number")), + ("end", read_only(l, range_end, "TextRange", "end"), typed("number")), + ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")), + ("length", property(l, range_length, range_set_length), typed("number")), + ("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }), + ("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }), + ("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }), + ("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")), + ("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")), + ("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])), + ("getTextRunLength", method(l, range_run_length), returns("number", &[("charIndex", "number")])), + ("remove", method(l, range_remove), returns("undefined", &[])), + ]); + range.extend(attr_members(l)); + range.extend(para_members(l)); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .map(|m| super::later(l, "TextRange", m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![ + ("typename", get(l, part_typename), typed("string")), + ("length", get(l, part_length), typed("number")), + ("parent", get(l, part_parent), typed("*")), + ("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])), + ("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])), + ]), + Some(function(l, part_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, char_attrs_typename), typed("string"))]); + chars.extend(attr_members(l)); + let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]); + paras.extend(para_members(l)); + vec![ + class("TextFrame", Some("PageItem"), frame, None), + class("TextRange", None, range, None), + part("Characters"), + part("Words"), + part("Paragraphs"), + class("CharacterAttributes", None, chars, None), + class("ParagraphAttributes", None, paras, None), + class( + "TextFrames", + None, + named(vec![ + ("typename", get(l, frames_typename), typed("string")), + ("length", get(l, frames_length), typed("number")), + ("parent", get(l, frames_parent), typed("Document")), + ("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])), + ("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])), + ("add", method(l, frames_add), returns("TextFrame", &[])), + ("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])), + ("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])), + ("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])), + ("removeAll", method(l, frames_remove_all), returns("undefined", &[])), + ]), + Some(function(l, frames_at)), + ), + class( + "TextFonts", + None, + named(vec![ + ("typename", typename_of("TextFonts"), typed("string")), + ("length", get(l, fonts_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])), + ("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])), + ]), + Some(function(l, fonts_at)), + ), + class( + "TextFont", + None, + named(vec![ + ("typename", get(l, font_typename), typed("string")), + ("name", get(l, font_name), typed("string")), + ("family", get(l, font_family), typed("string")), + ("style", get(l, font_style), typed("string")), + ("parent", get(l, font_parent), typed("Application")), + ]), + None, + ), + ] +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::Weak; + + use super::{Index, Log, MAX_EDITS, touched}; + + #[test] + fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { + let mut l = Log { doc: Weak::new(), reverts: 0, index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + for _ in 0..MAX_EDITS { + l.push(0, 0, 1); + } + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 0)); + l.push(0, 0, 1); + // Only the first edit is dropped: a range made after it still moves through every later edit. + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 1)); + assert_eq!(l.edits.front().map(|x| x.stamp), Some(2)); + } + + #[test] + fn index_counts_utf16_units_and_splits_words_and_paragraphs() { + let i = Index::new("a\u{1F600}b c\nd".into()); + assert_eq!(i.len(), 8); + assert_eq!(i.chars, vec![0, 1, 3, 4, 5, 6, 7, 8]); + assert_eq!(i.byte(2, false), 1); + assert_eq!(i.byte(2, true), 5); + assert_eq!(i.words, vec![(0, 4), (5, 6), (7, 8)]); + assert_eq!(i.paras, vec![(0, 7), (7, 8)]); + assert_eq!(i.chars_in(1, 4), 1..3); + } + + #[test] + fn only_an_empty_range_touches_the_empty_paragraph_at_the_end() { + let i = Index::new("a\n".into()); + assert_eq!(i.paras, vec![(0, 2), (2, 2)]); + assert_eq!(touched(&i.paras, 0, 2), 0..1); + assert_eq!(touched(&i.paras, 0, 1), 0..1); + assert_eq!(touched(&i.paras, 2, 2), 1..2); + assert_eq!(touched(&i.paras, 1, 1), 0..1); + let e = Index::new(String::new()); + assert_eq!(touched(&e.paras, 0, 0), 0..1); + assert_eq!(touched(&e.words, 0, 0), 0..0); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cbfd14550b..71d7cc1399 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -186,6 +186,7 @@ mod script_io; mod script_run; mod script_scriptui; mod script_tags; +mod script_text; mod script_variables; mod script_xmp; mod scripts; diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0272e95212..184f43cc4a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs new file mode 100644 index 0000000000..2935fd0566 --- /dev/null +++ b/crates/engine/src/tests/script_text.rs @@ -0,0 +1,629 @@ +//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`. + +use serde_json::{Value, json}; +use vectorcraft_doc::Justify; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn text_frames_add_point_area_and_path_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ + var pt = d.textFrames.add(); pt.contents = 'Point';\ + var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ + vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ + vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ + vc.log([d.textFrames[0].contents, d.textFrames[3].contents]); vc.log(d.textFrames[9] === undefined);\ + vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); + // Topmost first, as `pageItems` lists them: the newest type, then the area type on the rectangle. + assert_eq!( + out[2..], + [json!("TextFrame"), json!(true), json!(["At", "Area"]), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")] + ); + assert_eq!(undo_steps(&s), before + 1); + // A path of another kind, or no path, is refused. + assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation")); + assert_eq!(undo_steps(&s), before + 1); + // pathText takes its orientation fourth, after the start and end positions it does not take yet. + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap(); + let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];"; + assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet")); + let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);")); + assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]); +} + +#[test] +fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { + let (mut s, id) = doc_with("x"); + let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); + assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); + assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number")); +} + +#[test] +fn contents_takes_a_number_as_its_text() { + let (mut s, id) = doc_with("x"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\ + t.textRange.characters[0].contents = 2.5; vc.log(t.contents);", + ); + assert_eq!(out, vec![json!("7"), json!("2.5")]); + assert_eq!(plain(&s, id), "2.5"); +} + +#[test] +fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() { + let (mut s, _) = doc_with("a\u{1F600}b cd"); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\ + vc.log([r.length, r.start, r.end, c.length]);\ + vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\ + vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\ + vc.log(app.activeDocument.textFrames[0].contents.length === r.length);", + ); + assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]); +} + +#[test] +fn the_first_character_of_each_word_grows_in_one_undo_step() { + let (mut s, id) = doc_with("one two"); + let before = undo_steps(&s); + log( + &mut s, + "var text = app.activeDocument.textFrames[0].textRange;\ + for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }", + ); + assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn ranges_follow_model_edits_and_go_stale_after_other_edits() { + let (mut s, id) = doc_with("one two three"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\ + w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\ + second.contents = ''; vc.log([second.length, third.contents, t.contents]);", + ); + assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]); + let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;"); + assert!(e.contains("Stale text range"), "{e}"); + // A change reversed before the range is read leaves the text the range knew. + let (mut s, id) = doc_with("one two"); + let source = format!( + "var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\ + vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);", + id.0 + ); + assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); +} + +#[test] +fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var now = app.activeDocument.textFrames[0];\ + vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + vc.log(now.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!("one two"), "the reverted file holds the same text"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text"); +} + +#[test] +fn a_frame_and_its_ranges_held_across_file_revert_go_stale() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-held-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words;\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + try { vc.log(t.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + try { vc.log(w.length); } catch (e) { vc.log(e.message); }\ + var now = app.activeDocument.textFrames[0], r2 = now.textRange;\ + vc.log(r2.contents); r2.contents = 'three'; vc.log(now.contents);", + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale page item")), "{out:?}"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("one two"), "a range made after the revert reads the reverted text"); + assert_eq!(out[4], json!("three"), "a frame found after the revert can be edited"); +} + +#[test] +fn a_range_an_edit_covers_holds_the_edits_new_text() { + let (mut s, _) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\ + t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\ + t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);", + ); + // A range that ends where an edit starts keeps its end; one inside the edit takes the new text. + assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]); +} + +#[test] +fn bad_attribute_values_are_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + for (src, want) in [ + ("r.size = 0;", "size must be from 0.1"), + ("r.size = 'big';", "size must be a finite number"), + ("r.size = NaN;", "not a finite number"), + ("r.leading = 0;", "leading must be from 0.1"), + ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.underline = 1;", "underline must be true or false"), + ("r.textFont = 'Arial';", "textFont must be a TextFont"), + ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), + ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), + ("r.length = -1;", "length must be a whole number from 0 to 3"), + ("r.length = 1.5;", "length must be a whole number from 0 to 3"), + ("r.length = 4;", "length must be a whole number from 0 to 3"), + ("r.length = 'two';", "length must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]); +} + +#[test] +fn setting_the_value_a_range_has_records_no_undo_step() { + let (mut s, _) = doc_with("abc"); + let before = undo_steps(&s); + log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\ + t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;", + ); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);"); + assert_eq!(out, vec![json!([false, 14.4])]); + assert_eq!(undo_steps(&s), before + 1); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + _ => panic!("not text"), + } + // A fixed leading set to its own value is still no change. + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn paragraph_attributes_set_the_paragraphs_a_range_touches() { + let (mut s, _) = doc_with("first\nsecond"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs;\ + vc.log([p.length, p[0].contents, p[1].contents]);\ + p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\ + vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);", + ); + assert_eq!(out[0], json!([2, "first\r", "second"])); + assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"])); + assert_eq!(out[2], json!([0, 9, 6])); + // A paragraph whose range ends after its break sets only itself. + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ + p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + // The empty paragraph after a final break belongs only to an empty range at the end. + let (mut s, id) = doc_with("a\n"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([1, 1, 4])]); + let after: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(), + _ => panic!("not text"), + }; + assert_eq!(after, vec![4.0, 0.0]); +} + +#[test] +fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { + let (mut s, id) = doc_with("first\nsecond"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\ + p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);", + ); + assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(), + _ => panic!("not text"), + }; + assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]); +} + +#[test] +fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { + let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); + if !covers(from) || covers(to) { + return; // Installed fonts of these names cover other characters. + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap(); + let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');"); + let e = failure(&mut s, &format!("{pick} r.textFont = f;")); + assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}"); + // Characters the font can draw take it without an error. + let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);")); + assert_eq!(out, vec![json!(to)]); +} + +#[test] +fn turning_auto_leading_off_keeps_each_characters_leading() { + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(), + _ => panic!("not text"), + }; + let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)]; + assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::>()); + // Paragraphs and runs with the same leading take one command. + let (mut s, _) = doc_with("one\ntwo\nthree"); + let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap(); + let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect(); + assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]); + // Auto leading that a fixed leading cannot hold is refused before anything changes. + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;"); + assert!(e.contains("autoLeading cannot be turned off"), "{e}"); + assert_eq!(undo_steps(&s), before); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + _ => panic!("not text"), + } +} + +#[test] +fn an_explicit_alignment_replaces_auto_alignment() { + let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).justify, + _ => panic!("not text"), + }; + for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] { + let (mut s, id) = doc_with(text); + assert_eq!(justify(&s, id), Justify::Auto); + let before = undo_steps(&s); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\ + a.justification = Justification.LEFT; vc.log(a.justification);", + ); + assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}"); + assert_eq!(justify(&s, id), Justify::Left, "{text}"); + assert_eq!(undo_steps(&s), before + 1, "{text}"); + } + // Each paragraph on Auto reads by its own text. + let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd"); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);", + ); + assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]); +} + +#[test] +fn a_stale_range_has_no_parent() { + let (mut s, id) = doc_with("abc"); + let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); +} + +#[test] +fn a_stale_range_and_its_collections_have_no_typename() { + let (mut s, id) = doc_with("abc"); + let source = format!( + "var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\ + var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\ + vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\ + for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);", + id.0 + ); + let out = log(&mut s, &source); + assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"])); + assert_eq!(out[1], json!(vec!["Stale text range"; 6])); +} + +#[test] +fn members_not_built_yet_throw_after_the_stale_check() { + let (mut s, id) = doc_with("abc"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;"); + assert!(e.contains("TextFrame.lines is not available yet"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;"); + assert!(e.contains("TextRange.lines is not available yet"), "{e}"); + for member in ["r.lines", "r.start = 1"] { + let source = + format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{member}: {e}"); + } +} + +#[test] +fn text_fonts_list_and_assign_fonts_by_name() { + // The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character. + let db = vectorcraft_text::FontDb::global(); + let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect(); + let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c))); + let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else { + return; // No installed font draws "abc". + }; + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + &format!( + "var f = app.textFonts, m = '';\ + try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ + vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" + ), + ); + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]); + let set = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()), + _ => panic!("not text"), + }; + assert_eq!(&set, &(family.clone(), style.clone())); +} + +#[test] +fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() { + let (mut s, id) = doc_with("hello world"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\ + vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\ + w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\ + t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);", + ); + assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]); + assert_eq!(plain(&s, id), "Jello world"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn collections_of_text_add_words_characters_and_paragraphs() { + let cases = [ + ("t.words.add('x')", "hello world", "hello world x", "x"), + ("t.words.addBefore('x')", "hello world", "x hello world", "x"), + ("t.words[0].words.add('x')", "hello world", "hello x world", "x"), + ("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"), + ("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"), + ("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"), + ("t.words.add('x')", "hello world ", "hello world x ", "x"), + ("t.words.add('x')", "", "x", "x"), + ("t.words.add(7)", "a", "a 7", "7"), + ("t.characters.add('!')", "hi", "hi!", "!"), + ("t.characters[0].characters.add('x')", "hi", "hxi", "x"), + ("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"), + ("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"), + ("t.paragraphs.addBefore('top')", "one", "top\none", "top"), + ]; + for (call, text, after, added) in cases { + let (mut s, id) = doc_with(text); + let before = undo_steps(&s); + let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);")); + assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}"); + assert_eq!(plain(&s, id), after, "{call} on {text:?}"); + assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}"); + } + // Empty contents add nothing; bad arguments throw before anything changes. + let (mut s, id) = doc_with("ab"); + s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let before = undo_steps(&s); + // `textFrames` lists the topmost first, so the newer "other" is [0]. + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); + assert_eq!(out, vec![json!([0, 5])]); + for (call, want) in [ + ("t.words.add(null)", "contents must be a string or a number"), + ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), + ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), + ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + ] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); + assert!(e.contains(want), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, id), "ab"); +} + +#[test] +fn text_fonts_find_a_bundled_face_by_its_postscript_name() { + let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { + return; // Built without the bundled fonts. + }; + let ps = face.postscript_name(); + let (mut s, _) = doc_with("abc"); + let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);")); + assert_eq!(out, vec![json!([face.family, face.style, ps])]); +} + +#[test] +fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() { + let (mut s, id) = doc_with("first\nsecond\nthird"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\ + vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\ + t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);", + ); + assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]); + let justify: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(), + _ => panic!("not text"), + }; + assert_eq!(justify, vec![Justify::Center; 3]); + assert_eq!(undo_steps(&s), before + 1); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';"); + assert!(e.contains("Justification value"), "{e}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn create_outline_and_conversions_return_the_new_objects() { + let (mut s, id) = doc_with("Hi"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], m = '';\ + try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\ + var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\ + var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\ + var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);", + ); + assert_eq!(out[0], json!("the text frame is not area type")); + assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn outlining_type_with_nothing_to_outline_gives_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);"); + assert_eq!(out, vec![json!([true, 0])]); +} + +#[test] +fn type_made_with_a_large_id_is_the_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + "var d = app.activeDocument, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\ + vc.log([a === b, a.contents, b.createOutline().typename]);", + ); + assert_eq!(out, vec![json!([false, "", "GroupItem"])]); + assert_eq!(plain(&s, NodeId(big)), ""); +} + +#[test] +fn text_members_refuse_objects_of_other_classes() { + let (mut s, _) = doc_with("abc"); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); + assert!(e.contains("this is not a TextFrame"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); + assert!(e.contains("this is not a TextRange"), "{e}"); + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A font from an earlier run of a named engine is stale. + run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap(); + for member in ["held.family", "held.parent"] { + let e = failure(&mut s, &format!("#targetengine keepfont\n{member};")); + assert!(e.contains("Stale text font"), "{member}: {e}"); + } +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 98e6ad0d41..a59d50e88b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ - getIsFileOpen redraw selection selection= toString typename", + getIsFileOpen redraw selection selection= textFonts toString typename", ), ("DocumentPreset.", "prototype"), ( @@ -107,7 +107,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames toString \ typename views width", ), ("Views.", "prototype"), @@ -152,6 +152,63 @@ const INSIDE: &[(&str, &str)] = &[ ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + ( + "", + "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ + TextOrientation TextRange TextType Words", + ), + ("TextFrames.", "prototype"), + ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), + ("TextFrame.", "prototype"), + ( + "TextFrame.prototype.", + "anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \ + contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ + insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ + opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ + rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + textSelection= words", + ), + ("TextRange.", "prototype"), + ( + "TextRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ + characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ + horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ + verticalScale= words", + ), + ("Characters.", "prototype"), + ("Characters.prototype.", "add addBefore constructor length parent typename"), + ("Words.", "prototype"), + ("Words.prototype.", "add addBefore constructor length parent typename"), + ("Paragraphs.", "prototype"), + ("Paragraphs.prototype.", "add addBefore constructor length parent typename"), + ("CharacterAttributes.", "prototype"), + ( + "CharacterAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphAttributes.", "prototype"), + ( + "ParagraphAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("TextFonts.", "prototype"), + ("TextFonts.prototype.", "constructor getByName index length parent typename"), + ("TextFont.", "prototype"), + ("TextFont.prototype.", "constructor family name parent style typename"), + ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), + ("TextOrientation.", "HORIZONTAL VERTICAL"), + ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s // `visibilityVariable` is in its row above. ("", "Dataset Datasets Variable VariableKind Variables"), @@ -173,7 +230,7 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index b45b6b16b6..7b5469c278 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -1,7 +1,7 @@ //! Direct Selection picks several direction handles and drags them together (`path.moveHandles`). use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_engine::{Session, ViewInfo}; use vectorcraft_geom::{Anchor, AnchorKind, Point}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -191,3 +191,22 @@ fn move_handles_checks_its_params() { near(anchor(&s, id, 2).h_in, Point::new(305.0, 140.0)); assert_eq!(undo_len(&s), undo + 1); } + +/// A move by nothing that makes one path's smooth anchor a corner leaves a listed handle of a live +/// rectangle, which needs no change, alone: the rectangle stays live. +#[test] +fn a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live() { + let (mut s, id) = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 100, "height": 60})).unwrap(); + let rect = NodeId(rect["id"].as_u64().unwrap()); + let live = |s: &Session| matches!(&s.doc().unwrap().doc.node(rect).unwrap().kind, NodeKind::Path { live: Some(_), .. }); + assert!(live(&s), "shape.rectangle makes a live rectangle"); + let handles = json!([ + {"id": id.0, "anchor": 1, "which": "in"}, + {"id": id.0, "anchor": 1, "which": "out"}, + {"id": rect.0, "anchor": 0, "which": "out"} + ]); + s.execute("path.moveHandles", &json!({"handles": handles, "dx": 0, "dy": 0})).unwrap(); + assert_eq!(anchor(&s, id, 1).kind, AnchorKind::Corner, "both handles listed make the smooth anchor a corner"); + assert!(live(&s), "the rectangle's listed handle needed no change, so the rectangle stays live"); +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 49cc392f80..5264414cb3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -403,11 +403,32 @@ impl SubPath { /// Bend segment `seg` so its point at `t` moves by `dv`: both inner control points move by /// dv / 3t(1-t), since B(t) moves by 3t(1-t) times that. A smooth anchor stays smooth: its other /// handle turns with the moved one. False when there is no such segment. + /// + /// A straight segment's handles lie on its anchors, so moving them as they are curls its ends + /// round (#9225). It is bent as the same line with its handles at its thirds instead, so it + /// bows evenly, the point at `t` still landing `dv` away. pub fn bend_segment(&mut self, seg: usize, t: f64, dv: kurbo::Vec2) -> bool { let n = self.anchors.len(); if seg >= self.segment_count() || n == 0 { return false; } + if dv == kurbo::Vec2::ZERO { + return true; + } + let mut t = t; + if self.segment_is_line(seg) { + let c = self.segment(seg); + let third = (c.p3 - c.p0) / 3.0; + if let Some(a) = self.anchors.get_mut(seg % n) { + a.set_handle(true, c.p0 + third, false); + } + if let Some(b) = self.anchors.get_mut((seg + 1) % n) { + b.set_handle(false, c.p3 - third, false); + } + // With its handles on its anchors, the line is at t²(3 - 2t) of the way along at t; with + // them at its thirds, that far along is where it is at that same parameter. + t = t * t * (3.0 - 2.0 * t); + } let v = dv / (3.0 * t * (1.0 - t)); if let Some(a) = self.anchors.get_mut(seg % n) { a.set_handle(true, a.h_out + v, false); @@ -940,6 +961,28 @@ fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: P #[cfg(test)] mod tests { + /// #9225: a straight segment bent from its middle bows evenly: its handles leave from along the + /// line, toward the middle, not straight out of its anchors, and the grabbed point follows. + #[test] + fn bending_a_straight_segment_pulls_its_handles_from_along_the_line() { + for t in [0.5, 0.3, 0.1] { + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + let grabbed = sp.segment(0).eval(t); + let dv = kurbo::Vec2::new(0.0, 60.0); + assert!(sp.bend_segment(0, t, dv)); + let (a, b) = (sp.anchors[0], sp.anchors[1]); + assert!(a.h_out.x > a.p.x + 1.0 && b.h_in.x < b.p.x - 1.0, "t {t}: {a:?} {b:?}"); + let landed = sp.segment(0).nearest(grabbed + dv, 1e-9).distance_sq.sqrt(); + assert!(landed < 1e-6, "t {t}: the grabbed point is {landed} off the pointer"); + } + // No move leaves it as it was, a smooth end's other handle included. + let mut sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(300.0, 0.0)], false); + sp.anchors[1].h_out = Point::new(300.0, 50.0); + sp.anchors[1].kind = AnchorKind::Smooth; + let before = sp.clone(); + assert!(sp.bend_segment(0, 0.5, kurbo::Vec2::ZERO)); + assert_eq!(sp.anchors, before.anchors); + } use super::*; /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 95719bf965..dc4a942d6c 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -568,6 +568,18 @@ fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() { assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default"); } +#[test] +fn an_ok_button_in_a_hidden_or_disabled_group_is_not_the_default_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); var off = w.add('group'); off.enabled = false; off.add('button', undefined, 'OK'); \ + var hid = w.add('group'); hid.visible = false; hid.add('group').add('button', undefined, 'Cancel'); \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let described = &seen.borrow().descriptions[0]; + assert_eq!(field(described, "defaultElement"), &Data::Number(6.0), "the OK button outside the disabled group is the default"); + assert_eq!(field(described, "cancelElement"), &Data::Number(7.0), "the Cancel button outside the hidden group is the cancel element"); +} + #[test] fn an_ok_or_cancel_button_in_a_hidden_or_disabled_group_is_not_found_by_its_text() { let (mut r, seen, _) = realm(vec![close()]); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2e05fca92b..2eece1125f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -843,12 +843,13 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> b.inflate(o, o) } -/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its -/// spine-placed keys and steps: what it draws when its object effects leave it as it is -/// (Revolve builds no art from type). +/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]), a blend's to hold its +/// spine-placed keys and steps and a radial or mirror repeat's to hold its placed copies: what it +/// draws when its object effects leave it as it is (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { let b = match &n.kind { NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), + NodeKind::Repeat(_) => vectorcraft_geom::union_opt(n.visual_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), _ => n.visual_bounds_with(symbols), }?; Some(match &n.kind { @@ -860,7 +861,8 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { /// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are /// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source /// need not cover what they paint. -/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps. +/// Without effects inside it, the renderer keeps the quick bounds without evaluating the copies or +/// steps; `n`'s own effects run on the placed whole and are measured by the caller. fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { match &n.kind { NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {} @@ -869,12 +871,13 @@ fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } let mut has_effects = false; n.walk(&mut |c| { - has_effects |= has_fx(c) - || has_object_fx(c) - || match &c.kind { - NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), - _ => false, - }; + has_effects |= !std::ptr::eq(c, n) + && (has_fx(c) + || has_object_fx(c) + || match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), + _ => false, + }); }); if !has_effects { return None; diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 4440c06baf..d97bfd7baf 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -227,6 +227,39 @@ fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() { } } +#[test] +fn moving_a_shadowed_radial_or_mirror_repeat_redraws_the_effects_on_its_copies() { + for radial in [true, false] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + let repeat = if radial { + vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0)) + } else { + vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0) + }; + let id = old.alloc_id(); + let mut node = Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat)); + // The repeat's own effect sends its bounds through the object-effects branch. + node.appearance.effects.push(shadow()); + old.insert(Some(old.layers[0].id), 0, node).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + #[test] fn adding_removing_and_restacking_change_those_objects() { let (old, [loose, _, _, _, other]) = document(); diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 10028d3c4b..fc8fd14c9d 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -313,6 +313,8 @@ mod tests { #[test] fn gallery_cutout_setting_uses_its_localized_label() { + // The Japanese pass measures Cutout in one frame and clicks it in a later one. + crate::testing::wait_for_cjk_fonts(); let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); let mut shown_labels = Vec::new(); for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] { diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 49f355273a..9bb66b6696 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -94,6 +94,15 @@ pub struct Mosaic { delete_raster: bool, } +/// The warnings the dialog gave for being away from its image, one for each place it shows one. +#[derive(Default)] +struct Away { + /// OK's held refusal. + held: Option