diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..6595cfb926 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -3,7 +3,8 @@ //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , //! , -//! and +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: @@ -33,6 +34,8 @@ //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. A text range has the members of //! both its `characterAttributes` and its `paragraphAttributes`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +43,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, - frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, - whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, + float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -789,9 +793,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -803,6 +810,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -905,9 +915,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + /// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); @@ -976,6 +995,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let paint = color.map_or(Paint::None, Paint::solid); + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..7d70741e69 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -225,6 +225,78 @@ fn setting_the_value_a_range_has_records_no_undo_step() { 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 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 a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a1893c17cf..016b0acd37 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,12 +177,14 @@ const INSIDE: &[(&str, &str)] = &[ "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= \ + duplicate duplicate= end end= fillColor fillColor= 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 \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -195,9 +197,9 @@ const INSIDE: &[(&str, &str)] = &[ ("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=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 08f1c2fc98..afa5506833 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2719,8 +2719,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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 + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, + `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and + `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), 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` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50d76e869f..57c3304e95 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: 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`). Layers and the other classes are not there yet. `crates/engine/src/tests/script_dom.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: `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, fill and stroke colors, stroke weight) 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/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ 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 and tab stops are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.