Merge main into fix/craft-libs-f762f98

This commit is contained in:
dotCooCoo committed 2026-11-28 17:12:34 -08:00
commit 6d2bfe6640
20 files changed
+2819 -33

No files matched your search

+4 -3
View File
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
}
// 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<Value> {
.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();
}
}
+14 -5
View File
@@ -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<Vec<ItemList>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
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<HostClass> {
("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<HostClass> {
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<HostClass> {
);
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",
File diff suppressed because it is too large. Load diff
+1
View File
@@ -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;
+1 -1
View File
@@ -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"),
+629
View File
@@ -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<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
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<f64> = 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<f64>)> = 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<i64>)> = 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::<Vec<_>>());
// 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<Justify> = 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}");
}
}
@@ -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.
+20 -1
View File
@@ -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");
}
+43
View File
@@ -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<SubPath>, 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,
+12
View File
@@ -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()]);
+13 -10
View File
@@ -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<Rect> {
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<Rect> {
/// 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<Rect> {
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<Rect> {
}
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;
+33
View File
@@ -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();
@@ -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", "レベル数")] {
+104 -3
View File
@@ -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<Label>,
/// Use Ratio's note.
note: Option<Label>,
}
/// Create Object Mosaic on the dialog host.
pub struct ObjectMosaicDialog {
id: DialogId,
@@ -108,6 +117,9 @@ pub struct ObjectMosaicDialog {
note: Option<Label>,
/// Use Ratio was pressed; [`pump`] works out the counts.
use_ratio: bool,
/// Why OK and why Use Ratio last found the dialog away from its image (another drawing, or the
/// image not selected), each warning on its own. Back on the image, [`sync`] takes them away.
away: Away,
/// OK, until [`pump`] has run the command on it.
held: HeldAnswer<Mosaic>,
}
@@ -202,10 +214,15 @@ pub(crate) fn sync(app: &mut VectorcraftApp) {
let Some(dialogs) = app.dialogs() else { return };
let selected = selected_image(app);
let lengths = crate::canvas::general_lengths(app);
let Some(source) = dialogs.with(|host| host.get_mut::<ObjectMosaicDialog>().map(|dialog| dialog.source)) else { return };
let back = source.size(app).is_ok();
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() {
let size = selected.filter(|(source, _)| *source == dialog.source).map(|(_, size)| size);
dialog.sync(size, lengths);
if back {
dialog.came_back();
}
}
});
}
@@ -234,7 +251,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
match work {
None => {}
Some(Work::Ratio(mut values, source)) => {
let counts = source.size(app).and_then(|image| {
let image = source.size(app);
let away = image.as_ref().err().map(|why| Label::from(why.clone()));
let counts = image.and_then(|image| {
follow_ratio(&mut values, image);
let mut p = params(&values, image);
p["useRatio"] = json!(values.side.key());
@@ -242,6 +261,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
});
dialogs.with(|host| {
let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() else { return };
if away.is_some() {
dialog.away.note = away;
}
match counts {
Ok((cols, rows)) => {
dialog.values.columns = cols as f64;
@@ -253,8 +275,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
});
}
Some(Work::Run(mut values, source)) => {
let answer = source
.size(app)
let image = source.size(app);
let away = image.as_ref().err().map(|why| Label::from(why.clone()));
let answer = image
.and_then(|image| {
follow_ratio(&mut values, image);
app.run(COMMAND, params(&values, image)).map(|_| ())
@@ -262,6 +285,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
.map_err(Label::from);
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() {
if away.is_some() {
dialog.away.held = away;
}
dialog.held.answer(answer);
}
});
@@ -280,6 +306,7 @@ impl ObjectMosaicDialog {
lengths,
note: None,
use_ratio: false,
away: Away::default(),
held: HeldAnswer::new(),
}
}
@@ -296,6 +323,21 @@ impl ObjectMosaicDialog {
}
}
}
/// The dialog is on its image again: the warning that being away gave goes. A refusal of the
/// values themselves, and one after Revert or Undo (which never comes back), stays.
fn came_back(&mut self) {
if let Some(away) = self.away.note.take()
&& self.note.as_ref().is_some_and(|n| n.as_str() == away.as_str())
{
self.note = None;
}
if let Some(away) = self.away.held.take()
&& self.held.refusal().is_some_and(|(reason, _)| reason.as_str() == away.as_str())
{
self.held.clear_refusal();
}
}
}
/// The image's size with no zero side, for dividing by.
@@ -968,4 +1010,63 @@ mod tests {
assert_eq!(mosaic(&app), Some((100.0, 50.0, 4)));
assert!(!is_open(&mut app));
}
/// The warning in the dialog's notice: a held refusal, or a refused Use Ratio's note.
fn warning(app: &mut VectorcraftApp) -> Option<String> {
with_dialog(app, |d| d.note.clone().or_else(|| d.held.refusal().map(|(reason, _)| reason.clone())).map(|l| l.as_str().to_owned())).flatten()
}
/// Use Ratio as a click: the dialog asks, and the app works out the counts.
fn use_ratio(app: &mut VectorcraftApp) {
with_dialog(app, |d| d.use_ratio = true).expect("an open dialog");
crate::dialogs::host::pump(app, &crate::testing::ui_context());
}
/// The warning that OK or Use Ratio gave in another drawing shows only while the dialog is away
/// from its image: back on it, with the fields unchanged, the warning goes.
#[test]
fn a_warning_from_another_drawing_goes_on_return_to_the_original_image() {
let mut app = app_with_image();
open(&mut app, &json!({"columns": 2, "rows": 2})).unwrap();
add_image(&mut app);
let away = tl!("Return to the original drawing to create the mosaic.");
ok(&mut app);
assert_eq!(warning(&mut app).as_deref(), Some(away));
sync(&mut app);
assert_eq!(warning(&mut app).as_deref(), Some(away), "still away, the warning stays");
app.run("document.activate", json!({"index": 0})).unwrap();
sync(&mut app);
assert_eq!(warning(&mut app), None, "back on the image, OK's warning goes");
app.run("document.activate", json!({"index": 1})).unwrap();
use_ratio(&mut app);
assert_eq!(warning(&mut app).as_deref(), Some(away));
app.run("document.activate", json!({"index": 0})).unwrap();
sync(&mut app);
assert_eq!(warning(&mut app), None, "back on the image, Use Ratio's warning goes");
ok(&mut app);
assert_eq!(mosaic(&app), Some((100.0, 50.0, 4)));
}
/// OK's warning and Use Ratio's are taken away each on its own: a later, different one from
/// Use Ratio leaves OK's to go as well once the dialog is back on its image.
#[test]
fn both_away_warnings_go_on_return_to_the_original_image() {
let mut app = app_with_image();
let source = image_id(&app);
open(&mut app, &json!({"columns": 2, "rows": 2})).unwrap();
add_image(&mut app);
ok(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": []})).unwrap();
use_ratio(&mut app);
sync(&mut app);
assert!(warning(&mut app).is_some(), "with no image selected the dialog is still away");
app.run("select.set", json!({"ids": [source]})).unwrap();
sync(&mut app);
assert_eq!(with_dialog(&mut app, |d| d.held.refusal().is_none() && d.note.is_none()), Some(true), "{:?}", warning(&mut app));
}
}
@@ -77,6 +77,8 @@ fn compact_objects_on_path_options_pivot_rotate_reset_and_save() {
}
const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"];
// The Japanese pass measures the controls once and clicks them frames later.
crate::testing::wait_for_cjk_fonts();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut untranslated = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
+2 -1
View File
@@ -722,7 +722,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
return;
}
let Some(w) = app.session.script_window() else { return };
if with_window(app, |d| d.shown()) != Some(w.shown) {
// A question open over the dialog keeps its queued events until the dialog is on top again.
if with_window(app, |d| d.shown()) != Some(w.shown) || !is_top(app) {
return;
}
if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() {
+21
View File
@@ -290,6 +290,27 @@ fn quitting_while_a_handler_runs_keeps_the_events_still_queued() {
assert_eq!(log(&app), json!([[1, "Ann!"]]));
}
#[test]
fn a_question_open_over_the_dialog_keeps_its_queued_click_until_it_is_answered() {
let mut app = app();
start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());"));
assert!(until_window(&mut app));
with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap();
crate::dialogs::script_run::ask_to_close(&mut app);
assert!(is_open::<CloseQuestion>(&app));
for _ in 0..3 {
pump(&mut app);
script_runs::poll(&mut app);
}
assert!(matches!(queued(&app).as_slice(), [Queued::Click(_)]), "the click waits under the question");
assert!(app.session.script_window().is_some(), "the run still waits at the dialog");
cancel_close_question(&mut app);
assert!(until_window(&mut app), "the dialog shows again");
step(&mut app, Vec::new());
assert!(!until_window(&mut app), "the queued click on OK closes the dialog");
assert_eq!(log(&app), json!([1]));
}
#[test]
fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() {
let mut app = app();
+4 -3
View File
@@ -846,9 +846,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
## G6 Automation and scripting
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the
other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new
documents, each document's selection and its page items, and each document's variables, data sets and variable
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads
of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
documents, new documents, each document's selection and its page items, its text frames with their text ranges and
character and paragraph attributes, the installed fonts, and each document's variables, data sets and variable
libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
runs a script in a named engine whose globals last between runs,
File › Scripts lists the scripts of the Scripts folder, and
+65 -2
View File
@@ -2978,6 +2978,67 @@ other files through `$`:
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members
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 path's fill, are not defined yet and read as `undefined`.
- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type
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`
value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not
available yet. A `TextFrame`
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
outline and the command removes it), `convertPointObjectToAreaObject()` and
`convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has
`contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`,
`words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and
`remove()`, and the character and paragraph attributes themselves. `contents` takes a string, or a number as
`String(number)` writes it. Setting `length` to a whole number from 0 to the units left in the frame moves the range's
end and leaves the text as it is. The `characters`, `words` and `paragraphs` collections
(https://ai-scripting.docsforadobe.dev/jsobjref/Words/) have `length`, `parent`, `[i]`,
`add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its
range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to
5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`,
set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are
`justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`,
or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`,
`spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts`
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with
`length`, `[i]`, `index(key)` and `getByName(name)`, which takes the PostScript name of a bundled or installed font, or
the family and style joined by a space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`,
`TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`.
VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset
inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a
paragraph break as `\r` and a forced line break as `\u0003`, and takes `\r`, `\n` or `\r\n` for a paragraph break. A
word is a run of characters that are not white space; a range's `words` and `paragraphs` are the whole words and
paragraphs it touches, a paragraph's break belonging to it; the empty paragraph after a break at the end of the text
belongs only to an empty range there. A range keeps its place while the script edits the frame
through these objects: 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 these objects last saw, because `vc.run` or an undo changed
it, a range made before throws `Stale text range`, and so does its `typename`; a change that was reversed before
that read leaves the text as the range knew it, and the range keeps working. After `file.revert`, a range made
before throws `Stale text range` even when the file read back holds the same text. These objects keep a record of the
frame's last 100,000 edits, and a range made before an edit that is no longer in that record throws
`Stale text range` too. A character attribute
read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting
`autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its
own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters
that take the same leading; when one of those values is outside 0.1 to 5000 pt, it throws
and changes nothing. A paragraph attribute reads the first paragraph the range touches and sets every one of them. A value a range already
has runs no command; a `leading` set on characters with auto leading turns their auto leading off even when it equals
the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws
when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the
font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws
`Stale text font`. Each read of a member that gives a range gives a new object, so setting one range's `length`
leaves the others as they are. `add` without a relative object inserts after the collection's last item, and
`addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and
`PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is
kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty
string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story`
and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`,
`characterOffset` and `orientation` cannot be set yet.
- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and
`exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables`
(https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets`
@@ -7968,8 +8029,10 @@ same way for a blend's spine point; without `handle` it is refused. These rules
on one path or several, by the same offset as one undo step. An anchor with one handle listed places it as
`path.setHandle` does, so a smooth anchor turns its other handle in line at its own length; an anchor with both handles
listed moves both and becomes a corner. `independent: true` makes the anchor of every listed handle a corner and leaves
its other handle where it is. A handle listed twice moves once, and a move by 0, 0 that makes no anchor a corner leaves
the document as it is and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`,
its other handle where it is. A handle listed twice moves once. A move by 0, 0 changes only the anchors it makes corners, so a live
shape whose listed anchors need no change stays live, and a live shape with an anchor it makes a corner becomes a plain
path; when it makes no anchor a corner it leaves the document as it is
and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`,
an object that is not a path, a missing subpath or anchor, a `dx` or `dy` that is missing, not a number or 1e9 pt or
more in size, and an `independent` that is not true or false are refused, and the document does not change. With Direct
Selection, a click on the end of a direction handle of a path picks that handle, a Shift-click adds it to the picked
+2 -1
View File
@@ -1111,6 +1111,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
@@ -1605,7 +1606,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character.
With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group.
VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`).
Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner` in `crates/engine/tests/it/several_handles.rs`).
Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner; a move by 0, 0 leaves a live shape live when it makes none of its anchors a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner`, `a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live` in `crates/engine/tests/it/several_handles.rs`).
VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`).
VectorCraft's own preference General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`, off by default, part of #8326): on, a double-click without modifier keys on a path segment with Direct Selection adds an anchor at the clicked point, keeping the curve's shape, with only the new anchor selected, in one undo step (`path.insertAnchor` with `selectAnchor`); on an anchor, a handle, a center point, a blend's spine point or a fill the double-click does what it did before, and a clipping path's segment gets the anchor (`with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there`, `with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment`, `with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths`, `with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step`, `the_double_click_and_delete_preferences_are_separate`).
A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included).