mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
1026 lines
53 KiB
Rust
1026 lines
53 KiB
Rust
//! 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 character_color_attributes_reflect_as_color() {
|
||
let (mut s, _) = doc_with("color");
|
||
let out = log(
|
||
&mut s,
|
||
"var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\
|
||
vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);",
|
||
);
|
||
assert_eq!(out, [json!("Color"), json!("Color")]);
|
||
}
|
||
|
||
#[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.baselineShift = -1297;", "baselineShift must be from -1296 to 1296"),
|
||
("r.horizontalScale = 0.9;", "horizontalScale must be from 1 to 10000"),
|
||
("r.characterAttributes.verticalScale = 10001;", "verticalScale must be from 1 to 10000"),
|
||
("r.rotation = 361;", "rotation must be from -360 to 360"),
|
||
("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);
|
||
}
|
||
|
||
fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> {
|
||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(),
|
||
_ => panic!("not text"),
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn character_attributes_paint_only_their_own_characters() {
|
||
let (mut s, id) = doc_with("abc");
|
||
let before = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
"var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\
|
||
var red = new RGBColor(); red.red = 255; b.fillColor = red;\
|
||
var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\
|
||
vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\
|
||
vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);",
|
||
);
|
||
let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN);
|
||
assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}");
|
||
assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given");
|
||
assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill");
|
||
assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke");
|
||
let runs = paints(&s, id);
|
||
let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own");
|
||
assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||
assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||
assert!(b.3 > 1.0);
|
||
assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}");
|
||
assert!(undo_steps(&s) > before);
|
||
|
||
let steps = undo_steps(&s);
|
||
log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;");
|
||
assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step");
|
||
log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();");
|
||
assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away");
|
||
}
|
||
|
||
#[test]
|
||
fn an_rgb_paint_a_cmyk_document_already_stores_records_no_undo_step() {
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||
s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
"var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red; vc.log(r.fillColor.typename);",
|
||
);
|
||
assert_eq!(out[0], json!("CMYKColor"), "the document stores the color as CMYK");
|
||
let steps = undo_steps(&s);
|
||
log(&mut s, "var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red;");
|
||
assert_eq!(undo_steps(&s), steps, "assigning the color the text already stores records no undo step");
|
||
}
|
||
|
||
#[test]
|
||
fn an_rgb_paint_on_text_in_a_background_rgb_document_is_kept_as_rgb() {
|
||
let (mut s, id) = doc_with("abc");
|
||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||
s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
"var front = app.activeDocument, back = app.documents[0] === front ? app.documents[1] : app.documents[0];\
|
||
var red = new RGBColor(); red.red = 255;\
|
||
var f = front.textFrames[0].textRange, b = back.textFrames[0].textRange;\
|
||
f.fillColor = red; b.fillColor = f.fillColor; b.fillColor = red; vc.log(b.fillColor.typename);",
|
||
);
|
||
assert_eq!(out[0], json!("RGBColor"), "the RGB document keeps the RGB color it is given: {out:?}");
|
||
let rgb = s.documents().iter().find(|d| d.doc.color_mode == vectorcraft_doc::ColorMode::Rgb).expect("the RGB document");
|
||
let NodeKind::Text(t) = &rgb.doc.node(id).expect("the RGB document's text").kind else { panic!("not text") };
|
||
assert!(t.runs.iter().all(|r| r.style.fill == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "{:?}", t.runs);
|
||
}
|
||
|
||
#[test]
|
||
fn stroke_weight_reads_back_in_document_points_on_scaled_type() {
|
||
let (mut s, id) = doc_with("abc");
|
||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);");
|
||
assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}");
|
||
let stored = paints(&s, id)[0].3;
|
||
assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}");
|
||
let steps = undo_steps(&s);
|
||
log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;");
|
||
assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has");
|
||
}
|
||
|
||
#[test]
|
||
fn bad_text_paint_is_refused_without_a_change() {
|
||
let (mut s, id) = doc_with("abc");
|
||
let before = undo_steps(&s);
|
||
let runs = paints(&s, id);
|
||
for (src, want) in [
|
||
("r.fillColor = 'red';", "fillColor must be a color object"),
|
||
("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"),
|
||
("r.fillColor = new GradientColor();", "not available yet"),
|
||
("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"),
|
||
("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight 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!(paints(&s, id), runs);
|
||
}
|
||
|
||
#[test]
|
||
fn hidden_or_locked_type_is_not_edited() {
|
||
let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||
NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify),
|
||
_ => panic!("not text"),
|
||
};
|
||
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;",
|
||
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);",
|
||
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);",
|
||
"var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);",
|
||
] {
|
||
// Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden.
|
||
let (mut s, id) = doc_with("abc");
|
||
let before = state(&s, id);
|
||
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!(state(&s, id), before, "{hide} {edit}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[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");
|
||
// Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's
|
||
// end joins the range.
|
||
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");
|
||
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_eq!(t.plain_text(), "abc");
|
||
assert!(!t.runs.is_empty() && 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();
|
||
// Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is
|
||
// missing, and without them it is skipped. A lookup that falls back to another face counts
|
||
// as missing.
|
||
let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular");
|
||
let faces = regular(from).zip(regular(to));
|
||
assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available");
|
||
if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) {
|
||
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_eq!(t.plain_text(), "ab\ncd");
|
||
assert!(!t.runs.is_empty() && t.runs.iter().all(|r| r.style.leading.is_none()), "{:?}", t.runs);
|
||
}
|
||
_ => 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);\
|
||
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);
|
||
}
|
||
|
||
/// A length that ends inside a surrogate pair moves the range's end out to the end of the character.
|
||
#[test]
|
||
fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() {
|
||
let (mut s, _) = doc_with("a\u{1F600}b");
|
||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);");
|
||
assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]);
|
||
}
|
||
|
||
/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard.
|
||
#[test]
|
||
fn remove_all_type_refuses_type_on_a_locked_artboard() {
|
||
let (mut s, id) = doc_with("kept");
|
||
s.edit("Lock Artboard", |d, _| {
|
||
d.artboards[0].locked = true;
|
||
Ok(())
|
||
})
|
||
.unwrap();
|
||
let steps = undo_steps(&s);
|
||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}");
|
||
assert!(s.active().unwrap().doc.node(id).is_some());
|
||
assert_eq!(undo_steps(&s), steps);
|
||
}
|
||
|
||
#[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");
|
||
let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().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"),
|
||
// A range of a frame that is gone stays stale rather than of the wrong type.
|
||
(
|
||
"var o = app.activeDocument.textFrames[1].characters[0]; app.activeDocument.textFrames[1].remove(); t.words.add('x', o)",
|
||
"Stale text range",
|
||
),
|
||
] {
|
||
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, other), "other");
|
||
assert_eq!(plain(&s, id), "ab");
|
||
// A range of a frame that was removed is stale, not of the wrong class.
|
||
let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);");
|
||
assert!(e.contains("Stale text range"), "{e}");
|
||
assert_eq!(plain(&s, id), "ab");
|
||
}
|
||
|
||
/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are
|
||
/// not changed.
|
||
#[test]
|
||
fn protected_type_and_paths_are_not_converted_or_edited() {
|
||
let (mut s, id) = doc_with("abc");
|
||
s.edit("Lock Artboard", |d, _| {
|
||
d.artboards[0].locked = true;
|
||
Ok(())
|
||
})
|
||
.unwrap();
|
||
let steps = undo_steps(&s);
|
||
for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] {
|
||
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}"));
|
||
assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}");
|
||
}
|
||
assert_eq!(plain(&s, id), "abc");
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap();
|
||
for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] {
|
||
let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};"));
|
||
assert!(e.contains("Cannot edit PathItem"), "{call}: {e}");
|
||
assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]);
|
||
}
|
||
}
|
||
|
||
/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as
|
||
/// `pathItems.removeAll()` does.
|
||
#[test]
|
||
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
|
||
let (mut s, id) = doc_with("ab");
|
||
let lock = |s: &mut Session, locked: bool| {
|
||
s.edit("Lock Artboard", |d, _| {
|
||
d.artboards[0].locked = locked;
|
||
Ok(())
|
||
})
|
||
.unwrap();
|
||
};
|
||
lock(&mut s, true);
|
||
let steps = undo_steps(&s);
|
||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||
assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}");
|
||
assert_eq!(plain(&s, id), "ab");
|
||
assert_eq!(undo_steps(&s), steps);
|
||
lock(&mut s, false);
|
||
log(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]);
|
||
}
|
||
|
||
/// Text added after a range that ends inside a character goes after the whole character, and the
|
||
/// range returned holds the added text.
|
||
#[test]
|
||
fn text_added_after_half_a_character_goes_after_it() {
|
||
let (mut s, id) = doc_with("a\u{1F600}b");
|
||
let out = log(
|
||
&mut s,
|
||
"var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\
|
||
var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);",
|
||
);
|
||
assert_eq!(out, vec![json!([3, "X"])]);
|
||
assert_eq!(plain(&s, id), "a\u{1F600}Xb");
|
||
}
|
||
|
||
#[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)), "");
|
||
}
|
||
|
||
/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a
|
||
/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type
|
||
/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current.
|
||
const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\
|
||
function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\
|
||
put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\
|
||
var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\
|
||
var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\
|
||
var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\
|
||
function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }";
|
||
|
||
#[test]
|
||
fn a_layers_and_a_groups_text_frames_list_only_their_own_type() {
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&format!(
|
||
"{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\
|
||
vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\
|
||
vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\
|
||
vc.log(d.textFrames.length);"
|
||
),
|
||
);
|
||
assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"]));
|
||
assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"]));
|
||
assert_eq!(out[2], json!(["front", "back", true]));
|
||
assert_eq!(out[3], json!(6));
|
||
// Type inside the layer's group or sublayer is not the layer's own.
|
||
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');"));
|
||
assert!(e.contains("Not found"), "{e}");
|
||
}
|
||
|
||
#[test]
|
||
fn text_frames_of_a_layer_or_group_put_new_type_in_it() {
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap();
|
||
let before = undo_steps(&s);
|
||
// The rectangle is in the first layer, which becomes `base`; `other` is current while the
|
||
// collections of `base` and `g` add type.
|
||
let out = log(
|
||
&mut s,
|
||
&format!(
|
||
"var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\
|
||
var t = L0.textFrames.add(); t.name = 'added';\
|
||
vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\
|
||
var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\
|
||
var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\
|
||
g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);"
|
||
),
|
||
);
|
||
assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"]));
|
||
assert_eq!(out[1], json!(["g", "g-added"]));
|
||
assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"]));
|
||
// removeAll takes the group's own type and leaves the type inside its group.
|
||
assert_eq!(out[3], json!(["gg", "added,front,back"]));
|
||
assert_eq!(undo_steps(&s), before + 1);
|
||
// A locked layer and a hidden group take no new type, and the run changes nothing.
|
||
let before = undo_steps(&s);
|
||
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();"));
|
||
assert!(e.contains("hidden or locked"), "{e}");
|
||
let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);"));
|
||
assert!(e.contains("hidden or locked"), "{e}");
|
||
assert_eq!(undo_steps(&s), before);
|
||
}
|
||
|
||
/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the
|
||
/// type stays an ordinary member and is not made the clipping path.
|
||
#[test]
|
||
fn text_frames_remove_all_releases_a_mask_the_type_clips() {
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||
let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||
s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap();
|
||
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||
s.execute("select.none", &json!({})).unwrap();
|
||
let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id);
|
||
assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path");
|
||
let steps = undo_steps(&s);
|
||
let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);");
|
||
assert_eq!(out, [json!(false)]);
|
||
let st = s.active().unwrap();
|
||
assert!(!st.doc.node(g).unwrap().clips());
|
||
assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2);
|
||
// The run is one undo step, and undoing it puts back both the type and its mask.
|
||
assert_eq!(undo_steps(&s), steps + 1);
|
||
s.execute("edit.undo", &json!({})).unwrap();
|
||
assert!(s.active().unwrap().doc.node(g).unwrap().clips());
|
||
assert_eq!(first(&s), Some(NodeId(t)));
|
||
}
|
||
|
||
#[test]
|
||
fn text_create_puts_type_in_the_layer_or_group_it_names() {
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||
// A new layer is current, and a locked one takes no type.
|
||
let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap();
|
||
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
|
||
let before = undo_steps(&s);
|
||
for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] {
|
||
assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}");
|
||
}
|
||
assert_eq!(undo_steps(&s), before);
|
||
let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap();
|
||
let d = &s.active().unwrap().doc;
|
||
assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group)));
|
||
assert_eq!(undo_steps(&s), before + 1);
|
||
}
|
||
|
||
#[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}");
|
||
}
|
||
}
|