Merge main into feat/spell-check

Cargo.toml: #10049 moved craft-libs to 186a229c; the font store crates this
branch adds move with it, so every craft-libs crate stays at one rev.
This commit is contained in:
ruchirguitar committed 2026-11-29 22:41:45 +05:30
commit a4659724f6
287 files changed
+18179 -1784

No files matched your search

+190 -21
View File
@@ -44,6 +44,9 @@
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
//! - `app.activeDocument` with no document open throws `No active document`.
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
//! made; with no such step they change nothing, and with no document open they throw
//! `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
@@ -108,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
variables::after_command(h, before);
}
mod colors;
mod defaults;
mod paths;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -158,14 +168,38 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
/// open, the settings of each `DocumentPreset` the run made, with the size of the values they hold
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
/// gave out.
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
/// written yet, how many times each path's points went stale and each path as the run last saw its
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Vec<ItemList>>,
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
paths: RefCell<Vec<ItemList>>,
/// A path and its subpaths with the point changes the run has made to it and not written yet
/// ([`flush`]).
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
/// The index of the first point of each subpath of the path whose points the run read last,
/// and what they were counted from ([`paths`]).
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
/// How many times the points the run read of each path went stale, by document uid and path id
/// ([`paths`]).
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
/// Each path whose points the run read, as the run last saw it, by document uid and then path
/// id ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
/// The path whose points the object model is writing with `path.setAnchors`, the only path
/// that command changes ([`paths`]).
one_path: Cell<Option<Item>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
/// change.
editing: Cell<Option<Item>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
text: text::TextState,
@@ -220,6 +254,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
const KEPT_LISTS: usize = 8;
/// The list kept in `lists` for the document `st`, while that document is unchanged.
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
}
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
let mut l = lists.borrow_mut();
l.retain(|(uid, ..)| *uid != st.uid);
if l.len() >= KEPT_LISTS {
l.remove(0);
}
l.push((st.uid, st.doc.clone(), ids.clone()));
}
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
@@ -276,15 +328,40 @@ type Answer = std::result::Result<Data, HostError>;
/// A member function: the run's host and the call's arguments, `this` first.
type Member = fn(&Host, &[Data]) -> Answer;
/// A member function that first writes the point changes waiting in [`State`] ([`flush`]).
fn function(link: &Link, f: Member) -> HostFunction {
call(link, f, true)
}
/// A member function of the points of a path, which reads and adds to the point changes waiting in
/// [`State`] instead of writing them first.
fn point_function(link: &Link, f: Member) -> HostFunction {
call(link, f, false)
}
fn call(link: &Link, f: Member, flushing: bool) -> HostFunction {
let l = link.clone();
Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16 + a.iter().map(data_size).sum::<u64>())?;
if flushing {
flush(&h)?;
}
f(&h, &a)
})
}
/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]).
pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
paths::flush(h)
}
/// Notes the changes a command made to the points of the paths the run has read
/// ([`paths::see_all_points`]).
pub(super) fn see_points(h: &Host) {
paths::see_all_points(h)
}
fn get(link: &Link, f: Member) -> HostMember {
HostMember::Get(function(link, f))
}
@@ -297,6 +374,19 @@ fn method(link: &Link, f: Member) -> HostMember {
HostMember::Method(function(link, f))
}
/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]).
fn point_get(link: &Link, f: Member) -> HostMember {
HostMember::Get(point_function(link, f))
}
fn point_property(link: &Link, g: Member, s: Member) -> HostMember {
HostMember::Property { get: point_function(link, g), set: point_function(link, s) }
}
fn point_method(link: &Link, f: Member) -> HostMember {
HostMember::Method(point_function(link, f))
}
/// A member of a class with what `reflect` tells of it.
pub(super) type Described = (String, HostMember, MemberInfo);
@@ -312,8 +402,9 @@ pub(super) 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, 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.
/// the check that a document, page item, path point 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.
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
@@ -324,9 +415,12 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"Document" => {
doc_of(&h, arg(&a, 0), "Document")?;
}
"PageItem" | "TextFrame" => {
"PageItem" | "PathItem" | "TextFrame" => {
item_of(&h, arg(&a, 0))?;
}
"PathPoint" => {
paths::this_point(&h, &a)?;
}
"TextRange" => {
text::check_range(&h, arg(&a, 0))?;
}
@@ -653,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
return Ok(());
}
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
// Anchors and segments the change removed (a path opened or given fewer points) are left out.
let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| {
doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test))
};
let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len());
let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true));
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
if kept.is_empty() {
command(h, "select.none", &json!({}))?;
@@ -665,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
.iter()
.map(|i| {
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(),
// A path with only segments selected gets them back below, with no anchors.
None if before.segments.contains_key(i) => Vec::new(),
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
@@ -676,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?;
}
for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) {
let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect();
let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect();
if segments.is_empty() {
continue;
}
command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?;
}
let guides: Vec<NodeId> = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect();
@@ -796,9 +899,15 @@ pub(super) fn after_kept_command(h: &Host) {
text::styles::after_command(h);
}
/// Runs `id` with `params` on the item's document, its selection kept.
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
/// paths stay valid through the change ([`paths::see_all_points`]).
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
h.dom.editing.set(kept);
r
}
/// Reads the document of `doc` with `f`.
@@ -827,6 +936,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
/// only the steps the run made. With no step to undo or redo they change nothing.
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
let has_step = {
let s = h.session.borrow();
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
};
if has_step {
command(h, id, &json!({}))?;
}
Ok(Data::Undefined)
}
fn app_undo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.undo", false)
}
fn app_redo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.redo", true)
}
fn app_selection(h: &Host, _: &[Data]) -> Answer {
let uid = h.session.borrow().active().map(|st| st.uid);
match uid {
@@ -1183,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
})
}
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
/// built-in preset with `presetSettings` over them.
const BUILT_IN_SETTINGS: &[&str] = &[
"width",
"height",
"units",
"artboards",
"artboardLayout",
"bleed",
"backgroundContents",
"colorMode",
"rasterEffectsPpi",
"previewMode",
"alignNewObjectsToPixelGrid",
];
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
/// place of the profile's.
@@ -1229,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
}
// The document starts from the first preset of the profile's category (Print: Letter).
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
if let Some(m) = mode {
p.entry("colorMode").or_insert_with(|| json!(m));
}
// The document starts from the first built-in preset of the profile's category (Print:
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
// does not stand in for it. Settings the built-in preset refuses are an error.
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
if let Value::Object(settings) = full.to_json() {
for key in BUILT_IN_SETTINGS {
if let Some(v) = settings.get(*key) {
p.insert((*key).into(), v.clone());
}
}
}
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
// A profile whose file could not be read throws, and the document `file.new` made with the
// defaults is put back, with the Recent sizes as they were.
atomically(h, |h| {
@@ -1746,6 +1903,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
d => vec![d],
};
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
// The ids listed so far; `ids` keeps them in the order they were first listed.
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
// The document is read once for every object: nothing changes it while the list is checked.
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
@@ -2655,6 +2813,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
realm.define_host_object("BlendModes", blend_modes)?;
variables::define_enums(realm)?;
paths::install_enums(realm)?;
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
let l = link;
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
@@ -2677,6 +2836,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
("redraw", method(l, app_redraw), returns("undefined", &[])),
("undo", method(l, app_undo), returns("undefined", &[])),
("redo", method(l, app_redo), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
("toString", class_text("Application"), returns("string", &[])),
]);
@@ -2750,17 +2911,17 @@ 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") }),
("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }),
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
("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(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
.into_iter()
.map(|m| later(l, "Document", m)),
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
);
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
@@ -2861,7 +3022,15 @@ 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().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
let mut members = variables::item_members(l, c);
if *c == "PathItem" {
members.extend(paths::path_item_members(l));
}
class(c, Some("PageItem"), members, None)
}));
classes.extend(paths::classes(l));
classes.extend(colors::classes(l));
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.push(class(
+189
View File
@@ -0,0 +1,189 @@
//! The color classes of the script object model, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RGBColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/LabColor/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/> describe them.
//!
//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components,
//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time.
//! Components are checked when a color is assigned to an object, and a value out of range throws a
//! `RangeError` with nothing changed.
//!
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
//! assigned yet.
use std::rc::Rc;
use serde_json::Value;
use vectorcraft_color::{Color, Paint};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
use super::{Link, current, num, text};
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
/// The components of each color class, with the value `new` gives them.
const CLASSES: &[(&str, &[&str])] = &[
("RGBColor", &["red", "green", "blue"]),
("CMYKColor", &["cyan", "magenta", "yellow", "black"]),
("GrayColor", &["gray"]),
("LabColor", &["l", "a", "b"]),
("NoColor", &[]),
("GradientColor", &[]),
("SpotColor", &["tint"]),
("PatternColor", &[]),
];
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
let mut items = vec![("typename".to_string(), text(class))];
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
Data::Object(items)
}
/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that
/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read
/// from an object gives that object the same color.
fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 {
let mut scale = 1e4;
for _ in 4..=9 {
let r = (exact * scale).round() / scale;
if back(r) == v {
return r;
}
scale *= 10.0;
}
exact
}
/// A component stored as `v`, from 0 to 1, that the script sees times `scale`.
fn shown(v: f32, scale: f64) -> f64 {
shown_as(f64::from(v) * scale, v, |r| unit(r, scale))
}
/// The color object for a solid color.
fn of_color(c: &Color) -> Data {
match *c {
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
Color::Cmyk { c, m, y, k } => color_object(
"CMYKColor",
&[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))],
),
Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]),
Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]),
}
}
/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor`
/// with its `tint` for a color linked to a global or spot swatch.
pub(super) fn of_paint(paint: &Paint) -> Data {
match paint {
Paint::None => color_object("NoColor", &[]),
Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]),
Paint::Solid { color, .. } => of_color(color),
Paint::Gradient(_) => color_object("GradientColor", &[]),
Paint::Pattern { .. } => color_object("PatternColor", &[]),
}
}
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
/// stand for an ink amount that no Gray value names exactly).
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
match (assigned, now) {
(None, Paint::None) => true,
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
_ => false,
}
}
/// Whether the color object `d` has the class and every component of `shown`.
fn shows(d: &Data, shown: &Data) -> bool {
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
}
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
None | Some(Data::Undefined) => Ok(0.0),
Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n),
Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))),
Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))),
}
}
#[allow(clippy::cast_possible_truncation)]
fn unit(v: f64, scale: f64) -> f32 {
(v / scale) as f32
}
/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property.
pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color>, HostError> {
let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) };
let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) {
Some(Data::String(s)) => s.as_str(),
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
};
let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max);
Ok(Some(match class {
"NoColor" => return Ok(None),
"RGBColor" => {
Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) }
}
"CMYKColor" => Color::Cmyk {
c: unit(c("cyan", 0.0, 100.0)?, 100.0),
m: unit(c("magenta", 0.0, 100.0)?, 100.0),
y: unit(c("yellow", 0.0, 100.0)?, 100.0),
k: unit(c("black", 0.0, 100.0)?, 100.0),
},
"GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) },
"LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) },
l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))),
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
}))
}
/// `color` as `paint.setFill` and `paint.setStroke` take it.
pub(super) fn param(color: &Color) -> Value {
serde_json::to_value(color).unwrap_or(Value::Null)
}
/// The constructors of the color classes, and `cmykColor`.
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
let make = |name: &str, components: &'static [&'static str]| {
let l = link.clone();
let class = name.to_string();
let f: HostFunction = Rc::new(move |_| {
current(&l)?.charge_call(64)?;
let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect();
Ok(color_object(&class, &zeros))
});
f
};
let mut out: Vec<HostClass> = CLASSES
.iter()
.map(|(name, components)| HostClass {
name: (*name).into(),
parent: None,
members: Vec::new(),
info: Vec::new(),
index: None,
construct: Some(make(name, components)),
})
.collect();
out.push(HostClass {
name: "cmykColor".into(),
parent: None,
members: Vec::new(),
info: Vec::new(),
index: None,
construct: Some(make("CMYKColor", CLASSES[1].1)),
});
out
}
+211
View File
@@ -0,0 +1,211 @@
//! A document's default fill and stroke in the script object model, the `Document` members whose
//! names start with `default` that the help page
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/> describes, and `scaleFactor`.
//!
//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for
//! every open document, as the help page says of these global settings. Reading one reads new
//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the
//! selection, its art, the active proxy and the recent colors as they were. A value that changes
//! nothing runs no command, and a bad value throws an error with nothing changed.
//!
//! VectorCraft's own rules, which the help page does not state:
//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or
//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or
//! `defaultStroked` set to true with no default fill or stroke gives black.
//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores
//! it.
//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of
//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a
//! dash pattern unless it is 0.
//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default
//! throws an error, since new art then takes that object's appearance.
//! - `scaleFactor` is 1: VectorCraft draws every document at its own size.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, LineCap, LineJoin};
use vectorcraft_js::{Data, HostError, MemberInfo};
use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths};
use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed};
/// New art's appearance, after the check that the document `this` names is still open.
fn new_art(h: &Host, a: &[Data]) -> std::result::Result<Appearance, HostError> {
this_doc(h, a)?;
Ok(h.session.borrow().new_art())
}
/// Runs `appearance.setNewArt` with `params`, unless `same`.
fn set(h: &Host, same: bool, params: Value) -> Answer {
if !same {
command(h, "appearance.setNewArt", &params)?;
}
Ok(Data::Undefined)
}
fn top_paint(ap: &Appearance, fill: bool) -> Paint {
if fill { ap.fill_paint() } else { ap.stroke_paint() }
}
fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill)))
}
fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
let color = colors::assigned(arg(a, 1), what)?;
let now = top_paint(&new_art(h, a)?, fill);
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
let paint = match color {
Some(c) => json!({"color": colors::param(&c)}),
None => json!({"none": true}),
};
let key = if fill { "fill" } else { "stroke" };
set(h, same, json!({ key: paint }))
}
fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none()))
}
fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?;
let now = !top_paint(&new_art(h, a)?, fill).is_none();
let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) };
let key = if fill { "fill" } else { "stroke" };
set(h, now == on, json!({ key: paint }))
}
fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
let ap = new_art(h, a)?;
Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) }))
}
fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") };
let on = boolean(arg(a, 1), what)?;
let now = default_overprint(h, a, fill)? == Data::Bool(on);
set(h, now, json!({ key: on }))
}
/// New art's top stroke option `f` reads, or `none` when new art has no stroke.
fn stroke_option<T>(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result<T, HostError> {
Ok(new_art(h, a)?.stroke().map_or(none, f))
}
fn default_stroke_width(h: &Host, a: &[Data]) -> Answer {
this_doc(h, a)?;
Ok(num(h.session.borrow().paint.stroke_width))
}
fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
let w = number(arg(a, 1), "defaultStrokeWidth")?;
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into()));
}
this_doc(h, a)?;
let now = h.session.borrow().paint.stroke_width;
set(h, now == w, json!({"weight": w}))
}
fn default_cap(h: &Host, a: &[Data]) -> Answer {
let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
}
fn set_default_cap(h: &Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
_ => None,
};
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("defaultStrokeCap must be a StrokeCap value".into())) };
let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
set(h, now == cap, json!({"cap": name}))
}
fn default_join(h: &Host, a: &[Data]) -> Answer {
let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
}
fn set_default_join(h: &Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
_ => None,
};
let Some(&(join, _, name)) = found else { return Err(HostError::Type("defaultStrokeJoin must be a StrokeJoin value".into())) };
let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
set(h, now == join, json!({"join": name}))
}
fn default_miter(h: &Host, a: &[Data]) -> Answer {
Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?))
}
fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "defaultStrokeMiterLimit")?;
if !(1.0..=500.0).contains(&v) {
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
}
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
set(h, now == v, json!({"miterLimit": v}))
}
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone()))
}
fn default_dashes(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect()))
}
fn set_default_dashes(h: &Host, a: &[Data]) -> Answer {
let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?;
let now = dashes(h, a)?;
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
set(h, now == lengths, json!({"dash": dash}))
}
fn default_dash_offset(h: &Host, a: &[Data]) -> Answer {
Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?))
}
fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "defaultStrokeDashOffset")?;
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into()));
}
if dashes(h, a)?.is_empty() && v != 0.0 {
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
}
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
set(h, now == v, json!({"dashOffset": v}))
}
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
this_doc(h, a)?;
Ok(num(1.0))
}
/// The `Document` members of this module.
pub(super) fn document_members(l: &Link) -> Vec<Described> {
named(vec![
("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")),
("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")),
("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")),
("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")),
("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")),
("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")),
(
"defaultStrokeWidth",
property(l, default_stroke_width, set_default_stroke_width),
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
),
("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")),
("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")),
("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")),
("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")),
("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")),
("scaleFactor", get(l, scale_factor), typed("number")),
])
}
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,4 +1,4 @@
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
//!
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
+166 -8
View File
@@ -37,11 +37,21 @@
//!
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
//! the file it is in.
//!
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
//! so a link that leads out of the script's folder is refused as well. Module files count against
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
//! that differ only in letter case on Windows) give one module.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use vectorcraft_js::{DirectiveName, Options};
use vectorcraft_js::{DirectiveName, LoadError, Options};
use crate::file_access::{ScriptRead, ScriptScope};
@@ -219,13 +229,65 @@ pub(crate) struct Files {
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
/// is in, below the script's folder.
module_dirs: HashMap<String, Vec<String>>,
/// The key of each module path read, below the script's folder.
module_paths: HashMap<String, String>,
/// The key [`Files::module_entry`] gave the script, in a module run.
entry_key: Option<String>,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
/// run as ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
}
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
pub(crate) fn module_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
}
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
/// number, so two paths to one file give one module; elsewhere its real path, which on Windows
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
/// folder that ignores case give one module and two files in a folder that does not stay two.
fn module_key(real: &Path) -> String {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let Ok(m) = std::fs::metadata(real) {
return format!("{}:{}", m.dev(), m.ino());
}
}
display(real).to_string()
}
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
/// not `root` or below it, or has a name that is not Unicode.
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
}
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
return wrong("must start with './' or '../'");
}
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
return wrong("must not contain \\, : or control characters");
}
let names: Vec<&str> = specifier.split('/').collect();
let file = names.last().copied().unwrap_or_default();
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
return wrong("must name a .mjs or .js file");
}
Ok(names)
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -321,9 +383,91 @@ impl Files {
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
module_dirs: HashMap::new(),
module_paths: HashMap::new(),
entry_key: None,
}
}
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
pub(crate) fn read_es2015(&mut self) {
self.es2015 = true;
}
/// The module `text`, the script's own, as a source of one file. → its key and the source.
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
self.bytes = self.bytes.saturating_add(text.len());
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
self.module_dirs.insert(key.clone(), Vec::new());
self.entry_key = Some(key.clone());
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
}
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
/// this function gave). → the module's key, with its text and source map the first time the
/// run reads it.
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
let names = specifier_names(specifier)?;
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
for name in names {
match name {
"" | "." => {}
".." => {
if path.pop().is_none() {
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
}
}
name => path.push(name.to_string()),
}
}
let relative = path.join("/");
if let Some(key) = self.module_paths.get(&relative) {
return Ok((key.clone(), None));
}
let root =
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
self.probes += 1;
if self.probes > MAX_PROBES {
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
}
let candidate = path.iter().fold(root.clone(), |p, name| p.join(name));
// Another path to a module already read gives that module: the file is not read again, and
// its text is not counted again.
let loaded = &self.module_dirs;
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
let (real, bytes) = match read {
Ok(found) => found,
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
};
let key = module_key(&real);
let Some(bytes) = bytes else {
self.module_paths.insert(relative, key.clone());
return Ok((key, None));
};
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
}
if self.files >= MAX_FILES {
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
}
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
self.bytes += bytes.len();
self.files += 1;
self.module_paths.insert(relative, key.clone());
// The module's relative imports start from the folder the file is in, whichever path to it
// was read first; the path as written stands in when that folder is not below the script's.
path.pop();
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
self.module_dirs.insert(key.clone(), dir);
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
Ok((key, Some((text, map))))
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
@@ -362,12 +506,26 @@ impl Files {
self.expand(shown, dir, text, true)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
let names = self.module_dirs.get(key)?;
let root = self.frames.first().and_then(|f| f.dir.clone())?;
Some(names.iter().fold(root, |p, name| p.join(name)))
}
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
/// or `None` for a script run.
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
self.module_dir(self.entry_key.as_deref()?)
}
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
/// becomes the file being run until [`Files::end_eval`].
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
let dir = self.frames.last().and_then(|f| f.dir.clone());
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
let shown = display(&real);
+162 -28
View File
@@ -66,7 +66,8 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
Realm, RunError, RunErrorKind,
};
use crate::{
@@ -208,6 +209,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
pub module: bool,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
@@ -785,6 +788,9 @@ struct Host {
script_map: RefCell<include::SourceMap>,
/// The same for each source `$.evalFile` gave, in order.
eval_maps: RefCell<Vec<include::SourceMap>>,
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
/// module's, by its index there.
module_maps: RefCell<HashMap<usize, String>>,
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
/// order: the error's mark ([`HostError::Marked`]) is its index.
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
@@ -980,6 +986,22 @@ impl Host {
}
}
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
/// run).
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
let script = self.script_tag.get();
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
return None;
}
let n = tag.checked_sub(script)?;
if n == 0 {
return self.files.borrow().entry_module_dir();
}
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
self.files.borrow().module_dir(&key)
}
/// Adds a line to the run's console and, during a slice, to the session's.
fn line(&self, entry: console::Entry, cut: bool) {
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
@@ -1153,6 +1175,8 @@ struct Job {
name: String,
/// The file-access scope `script.run` came in, which every slice runs in.
scope: crate::file_access::ScopeHandle,
/// The script has ended, and the run waits for the person's growth answer before it is kept.
finished: bool,
}
/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in
@@ -1381,6 +1405,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
// Point changes that wait in the object model are written before any command runs.
dom::flush(host)?;
let session = host.session.clone();
let started = clock();
let before = dom::before_command(host, id);
@@ -1425,6 +1451,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
dom::after_kept_command(host);
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
@@ -1496,6 +1523,7 @@ pub(crate) fn retained_style_lists(s: &Session) -> usize {
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
/// of a crossing throws a `RangeError`.
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
dom::flush(host)?;
let s = host.session.borrow();
let Some(st) = s.active() else { return Ok(Data::Null) };
let ids: Vec<u64> = st.selection.objects.iter().take(1_000).map(|i| i.0).collect();
@@ -1597,6 +1625,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
}),
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
site: true,
}
};
let mut items = vec![
@@ -1611,9 +1640,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
}
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
/// milliseconds, is taken and not waited on: the file is read at once.
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
/// run (for a call in a module the script imported, that module's file), with its preprocessor
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
/// waited on: the file is read at once. `args` starts with the call's place, as
/// [`HostItem::Evaluator`] gives it with `site`.
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
let tag = match args.first() {
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
_ => vectorcraft_js::UNKNOWN_SOURCE,
};
args.drain(..3.min(args.len()));
let module_dir = host.module_dir_at(tag);
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
};
@@ -1627,7 +1664,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
}
host.charge_call(path.len() as u64 + 2)?;
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
let error = match f.kind {
include::FailKind::Limit => HostError::Abort(message),
@@ -1737,6 +1774,22 @@ fn explained(e: &RunError) -> String {
}
}
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
/// the modules are read, which is the order of their sources' tags.
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
let source = read.map(|(text, map)| {
let mut maps = host.eval_maps.borrow_mut();
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
maps.push(map);
drop(maps);
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
text
});
Ok(LoadedModule { key, source })
}
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
let (kind, message) = match f.kind {
@@ -2057,7 +2110,7 @@ impl Session {
if h.waiting.replace(false) {
h.continues.set(h.continues.get() + 1);
h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects()));
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES));
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes()));
}
});
}
@@ -2154,7 +2207,19 @@ impl Session {
self.script_stop.clear();
self.script_report = None;
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
let expanded = files.expand_script(&request.source);
if request.module {
files.read_es2015();
}
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
// `module_key` names it among the modules it imports.
let (expanded, module_key) = if request.module {
match files.module_entry(&request.source) {
Ok((key, expanded)) => (Ok(expanded), Some(key)),
Err(f) => (Err(f), None),
}
} else {
(files.expand_script(&request.source), None)
};
let name = match &expanded {
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
_ => request.name,
@@ -2185,9 +2250,8 @@ impl Session {
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
// `.js` run that names it, and keeps it as it keeps its globals.
let es2015 = include::es2015_script(request.file.as_deref());
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
let es2015 = request.module || include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
@@ -2225,7 +2289,7 @@ impl Session {
bytes_kept: Cell::new(0),
bridge: Cell::new(0),
allowance_objects: Cell::new(growth_objects()),
allowance_bytes: Cell::new(GROWTH_BYTES),
allowance_bytes: Cell::new(growth_bytes()),
continues: Cell::new(0),
waiting: Cell::new(false),
log: RefCell::new(Vec::new()),
@@ -2256,6 +2320,7 @@ impl Session {
files: RefCell::new(files),
script_map: RefCell::default(),
eval_maps: RefCell::default(),
module_maps: RefCell::default(),
eval_failures: RefCell::default(),
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
report_name: Arc::from(name.as_str()),
@@ -2320,7 +2385,13 @@ impl Session {
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
let r = realm.start(&expanded.source);
let r = match &module_key {
None => realm.start(&expanded.source),
Some(key) => {
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
}
};
// Source that does not compile defines no code, so its map is not kept.
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
host.script_tag.set(realm.script_tag());
@@ -2343,7 +2414,7 @@ impl Session {
}
let scope = crate::file_access::ScopeHandle::capture();
let (run, line_name) = (host.run, host.name.clone());
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope };
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false };
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
self.script_key = Some(JobKey { id, run, name: line_name });
@@ -2397,6 +2468,28 @@ impl Session {
self.script_key = Some(key);
return None;
}
// A run whose script ended past its growth allowance is kept once the person lets it go on,
// and put back when they stop it.
if job.finished {
if self.script_stop.is_set() {
let kind = LimitKind::Interrupted;
let e =
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
// One more allowance may still leave the growth past it: the person is asked again
// while they may be, and past that the run ends unkept.
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
if job.host.waiting.get() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
return None;
}
return Some(self.script_ended(job));
}
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
if job.realm.waits() {
let kind = LimitKind::Interrupted;
@@ -2422,24 +2515,35 @@ impl Session {
self.script_key = Some(key);
None
}
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
let n = job.host.dialogs.unused();
let kind = LimitKind::Host;
let message = if n == 1 {
format!("`answers` has {n} answer the script did not use")
} else {
format!("`answers` has {n} answers the script did not use")
};
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
}
Ok(Ok(Progress::Done(_))) => {
let r = self.script_commit(job);
self.trim_histories();
Some(r)
// The point changes written as the script ended went past the growth allowance.
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
job.finished = true;
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
None
}
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
}
}
/// Ends the run whose script has ended: it fails when answers it was given went unused, and is
/// kept otherwise.
fn script_ended(&mut self, job: Job) -> Result<Value> {
let n = job.host.dialogs.unused();
if n > 0 {
let kind = LimitKind::Host;
let message = if n == 1 {
format!("`answers` has {n} answer the script did not use")
} else {
format!("`answers` has {n} answers the script did not use")
};
return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false });
}
let r = self.script_commit(job);
self.trim_histories();
r
}
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
job.host.dialogs.stopped();
job.host.disk.borrow_mut().picker = None;
@@ -2759,6 +2863,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
std::mem::swap(s, &mut *cell.borrow_mut());
let scope = job.scope.clone();
let realm = &mut job.realm;
let host = &job.host;
let started = clock();
let r = scope.run(|| {
guard::catch_panic(|| {
@@ -2766,7 +2871,14 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
if PANIC_IN_SLICE.with(Cell::get) {
panic!("a slice failed");
}
realm.advance(SLICE_FUEL)
// Point changes that still wait in the object model are written when the script ends. Between
// slices the run's documents are put aside, so they can wait across slices.
realm.advance(SLICE_FUEL).and_then(|progress| {
if matches!(progress, Progress::Done(_)) {
dom::flush(host).map_err(end_flush_error)?;
}
Ok(progress)
})
})
});
if let Some(started) = started {
@@ -2780,6 +2892,17 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
r
}
/// The error that ends a run when the point changes waiting at the end of its script cannot be
/// written.
fn end_flush_error(e: HostError) -> RunError {
let message = match e {
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m,
HostError::Marked { error, .. } => return end_flush_error(*error),
HostError::Wait => "a host function waited for its result where the run cannot pause".into(),
};
RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }
}
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
/// job was removed.
#[cfg(test)]
@@ -2796,6 +2919,15 @@ fn growth_objects() -> u64 {
GROWTH_OBJECTS
}
/// The bytes of new document data a run may keep before it is asked to continue or stop.
fn growth_bytes() -> u64 {
#[cfg(test)]
if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) {
return n;
}
GROWTH_BYTES
}
/// The data a run may pass to and from commands.
fn bridge_bytes() -> u64 {
#[cfg(test)]
@@ -2822,6 +2954,8 @@ thread_local! {
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].