Scripts: text edits refuse hidden or locked type, and lists start with the topmost frame

- Text edits (contents, added text, character and paragraph attributes)
  throw Cannot edit with nothing changed when the frame, or a layer or
  group it is in, is hidden or locked.
- Text added after a range that ends inside a character goes after that
  character, and styling an empty range changes nothing.
- Point changes that wait are written before a call that is put back on
  failure, and before the points of another path are read, so a failed
  call does not drop them.
- A new path's id is read exactly from the command's result.
- A saved or Recent preset's rows above 1,000 read as 1,000, so file.new
  takes the preset as file.newPresets lists it.
- textFrames lists type topmost first, as pageItems does on main; the
  tests and docs/mcp.md follow.
This commit is contained in:
dotCooCoo
2026-11-25 21:21:28 -08:00
parent bc731da716
commit a22c730c03
8 changed files with 140 additions and 35 deletions
+9 -2
View File
@@ -171,8 +171,9 @@ pub struct DocSettings {
pub layout: ArtboardLayout,
/// Columns of a grid layout.
pub columns: u32,
/// Rows of a grid by column, in place of `columns` when more than 0.
#[serde(skip_serializing_if = "is_zero")]
/// Rows of a grid by column, in place of `columns` when more than 0 (a saved or Recent preset's
/// value above `MAX_ARTBOARDS` is read as `MAX_ARTBOARDS`).
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
pub rows: u32,
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
/// outside that range is read as the nearer end).
@@ -594,6 +595,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
}
/// A saved or Recent preset's rows, rounded and kept to 0 (no rows) to [`MAX_ARTBOARDS`], the
/// counts `file.new` takes.
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32)
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
+3 -1
View File
@@ -158,11 +158,13 @@ impl State {
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
/// and no change to the document's saved state.
/// and no change to the document's saved state. Point changes that wait in [`State`] are written
/// first, so a failure in `f` does not put them back.
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
if h.dom.saving.get() {
return f(h);
}
flush(h)?;
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
h.dom.saving.set(true);
let r = f(h);
+9 -10
View File
@@ -164,13 +164,15 @@ fn same_path(a: Item, b: Item) -> bool {
a.doc.uid == b.doc.uid && a.id == b.id
}
/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included.
/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. The
/// waiting point changes of another path are written first.
fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result<T, HostError> {
if let Some((waiting, subs)) = &*h.dom.pending.borrow()
&& same_path(*waiting, item)
{
return Ok(f(subs));
}
flush(h)?;
read_path(h, item, |_, _, pd| f(&pd.subpaths))
}
@@ -372,20 +374,17 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// The id in the result of a command that made an object.
fn made_id(r: &Data) -> std::result::Result<NodeId, HostError> {
let id = match r {
Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }),
_ => None,
};
id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
}
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
/// and reverses the new path's direction when `reversed`. → the new path.
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
let made = on_doc(h, doc.uid, true, |h| {
let id = made_id(&drawing_normally(h, || command(h, id, params))?)?;
let id = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?;
if reversed {
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
}
@@ -544,7 +543,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
let ap = h.session.borrow().new_art();
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
};
let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?;
let id = made_id(&drawing_normally(h, || super::command_value(h, "path.create", &json!({"d": ""})))?)?;
if unpainted {
keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?;
}
+26 -13
View File
@@ -193,7 +193,7 @@ type Spans = [(usize, usize)];
#[derive(Default)]
pub(in crate::script) struct TextState {
frames: RefCell<HashMap<(u64, u64), Log>>,
/// A document's uid, the document, and the ids of its type objects in paint order.
/// A document's uid, the document, and the ids of its type objects, topmost first.
list: RefCell<Option<FrameList>>,
/// 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.
@@ -301,6 +301,15 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc<Index>, usize, usize, u
})
}
/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing
/// changed, when the frame or a layer or group it is in is hidden or locked.
fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) {
return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0)));
}
edit_item(h, item, id, params)
}
/// 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> {
@@ -445,7 +454,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
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}))?;
edit_text(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)
}
@@ -719,16 +728,17 @@ 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) {
// The place, and whether it is the end of a range, which rounds up to a character boundary.
let (at, after) = 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)
(items.clone().next().and_then(span).map_or(s, |(x, _)| x), false)
} else {
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
(items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true)
}
} else {
let rel = arg(a, 2);
@@ -741,13 +751,15 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
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 text_placement(arg(a, 3))? { (te, true) } else { (ts, false) }
};
// A place inside a character (between the two halves of a surrogate pair) moves to its edge.
let b = index.byte(at, after);
let at = index.text[..b].encode_utf16().count();
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 => ("", ""),
@@ -763,7 +775,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
),
};
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}))?;
edit_text(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();
@@ -1042,7 +1054,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
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));
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
let unchanged = s == e || 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,
@@ -1060,7 +1073,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
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)?;
edit_text(h, r.item, "text.setRangeStyle", &p)?;
}
Ok(())
})?;
@@ -1072,7 +1085,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?;
let answer = edit_text(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)?;
@@ -1234,7 +1247,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
edit_item(h, r.item, id, &p)?;
edit_text(h, r.item, id, &p)?;
Ok(Data::Undefined)
}
@@ -1250,7 +1263,7 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
get(link, doc_text_frames_impl)
}
/// The ids of the document's type objects in paint order, kept while the document is unchanged.
/// The ids of the document's type objects, topmost first, kept while the document is unchanged.
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
&& *uid == st.uid
+19
View File
@@ -272,6 +272,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() {
assert_eq!(boards(&s).iter().map(|r| r.x0).collect::<Vec<_>>(), [0.0, 100.0, 200.0], "side by side, not overlapping");
}
/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that
/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows.
#[test]
fn a_saved_preset_with_too_many_rows_reads_in_range() {
let mut s = Session::new();
let prefs = json!({
"newDocPresets": [
{"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001},
{"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0},
],
});
s.apply_prefs(serde_json::from_value(prefs).unwrap());
let saved = presets(&mut s, "Saved");
assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]);
assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]);
s.execute("file.new", &saved[0]).unwrap();
assert_eq!(boards(&s).len(), 4);
}
/// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest
/// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names
/// the limit in points and, when the document's units aren't points, in those units too.
@@ -1207,3 +1207,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;");
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
}
/// A point change made before a call that fails and is put back, here a new document whose
/// profile cannot be read, is kept.
#[test]
fn a_point_change_before_a_failed_new_document_is_kept() {
let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap();
let (mut s, a, _) = doc();
s.attach_new_doc_profiles(dir.clone());
let before = node(&s, a).path_data().unwrap().subpaths.clone();
let out = log(
&mut s,
"app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\
try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }",
);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(out, vec![json!("refused")]);
assert_eq!(s.documents().len(), 1);
assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept");
}
+51 -8
View File
@@ -56,13 +56,13 @@ fn text_frames_add_point_area_and_path_type() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems;\
var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\
var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\
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[3].contents); vc.log(d.textFrames[9] === undefined);\
vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\
vc.log(at.orientation); vc.log(d.textFrames.parent.typename);",
);
assert_eq!(out[0], json!(4));
@@ -297,6 +297,49 @@ fn bad_text_paint_is_refused_without_a_change() {
assert_eq!(paints(&s, id), runs);
}
#[test]
fn hidden_or_locked_type_is_not_edited() {
let (mut s, id) = doc_with("abc");
let (runs, text) = (paints(&s, id), plain(&s, id));
for hide in ["t.locked = true;", "t.hidden = true;"] {
for edit in [
"r.characters[1].fillColor = red;",
"r.size = 30;",
"r.contents = 'xyz';",
"r.characters.add('!');",
"r.justification = Justification.CENTER;",
] {
let e = failure(
&mut s,
&format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"),
);
assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}");
}
}
assert_eq!((paints(&s, id), plain(&s, id)), (runs, text));
}
#[test]
fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() {
let (mut s, id) = doc_with("abc");
let out = log(
&mut s,
"var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\
var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);",
);
assert_eq!(plain(&s, id), "\u{1F600}!X");
assert_eq!(out, vec![json!(["!", "\u{1F600}"])]);
// An empty range there sits after the character too, and styling it changes nothing.
let runs = paints(&s, id);
let out = log(
&mut s,
"var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\
var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);",
);
assert_eq!(out, vec![json!(0)]);
assert_eq!(paints(&s, id), runs);
}
#[test]
fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() {
let (mut s, id) = doc_with("abc");
@@ -504,7 +547,7 @@ fn text_fonts_list_and_assign_fonts_by_name() {
&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);\
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);"
@@ -564,16 +607,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() {
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);
let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);");
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[0])", "same text frame"),
("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[1]; {call};"));
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);
@@ -658,7 +701,7 @@ fn type_made_with_a_large_id_is_the_new_type() {
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[1]);");
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}");
+1 -1
View File
@@ -2838,7 +2838,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
themselves, such as a placed item's `file`, are not defined yet and read as `undefined`.
- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type
objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and
objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and
`removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`