mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 18:54:31 +01:00
Merge main into feat/scripts-api-d6-save-export-open
main's Document member list held saveAs and close as members that are not available yet; this branch's save_open members implement them, so the merge drops them from that list and keeps main's other entries. The script host test lists take main's members together with this branch's open, userInteractionLevel, fullName, path, saved and option classes, and the heap accounting keeps main's ModuleNamespace arm beside the FsEntry string arm.
This commit is contained in:
commit
b1e9a4cbb3
333 files changed
+22539
-2096
No files matched your search
+218
-32
@@ -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
|
||||
@@ -109,6 +112,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.
|
||||
@@ -159,14 +169,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>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
@@ -199,25 +233,48 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else {
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
return r;
|
||||
}
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
/// 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>);
|
||||
@@ -274,15 +331,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))
|
||||
}
|
||||
@@ -295,6 +377,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);
|
||||
|
||||
@@ -310,8 +405,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();
|
||||
@@ -322,9 +418,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))?;
|
||||
}
|
||||
@@ -651,6 +750,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!({}))?;
|
||||
@@ -663,7 +768,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(),
|
||||
@@ -674,7 +779,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();
|
||||
@@ -789,9 +897,20 @@ fn on_doc<T>(
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
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, 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`.
|
||||
@@ -820,6 +939,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 {
|
||||
@@ -1176,6 +1317,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.
|
||||
@@ -1222,15 +1379,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| {
|
||||
@@ -1739,6 +1906,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()));
|
||||
@@ -1975,6 +2143,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
|
||||
|
||||
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let name = &text_arg(arg(a, 1), "name")?;
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
@@ -1993,11 +2162,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
|
||||
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
|
||||
/// or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let note = &text_arg(arg(a, 1), "note")?;
|
||||
if note.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the note is too long".into()));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
|
||||
if !same {
|
||||
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
|
||||
@@ -2031,8 +2200,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let hidden = boolean(arg(a, 1), "hidden")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
|
||||
}
|
||||
|
||||
@@ -2041,8 +2211,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let locked = boolean(arg(a, 1), "locked")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
@@ -2051,6 +2222,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let v = number(arg(a, 1), "opacity")?;
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
@@ -2060,7 +2232,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let item = this_item(h, a)?;
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
@@ -2106,12 +2277,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
|
||||
/// would still replace the blend mode a graph keeps for the item's series or kind.
|
||||
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
|
||||
let item = this_item(h, a)?;
|
||||
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
|
||||
@@ -2238,16 +2409,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let p = point(arg(a, 1), "position")?;
|
||||
move_to(h, a, Some(p[0]), Some(p[1]))
|
||||
}
|
||||
|
||||
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let x = coordinate(arg(a, 1), "left")?;
|
||||
move_to(h, a, Some(x), None)
|
||||
}
|
||||
|
||||
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let y = coordinate(arg(a, 1), "top")?;
|
||||
move_to(h, a, None, Some(y))
|
||||
}
|
||||
@@ -2256,12 +2430,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
|
||||
/// objects included.
|
||||
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let what = if width { "width" } else { "height" };
|
||||
let size = number(arg(a, 1), what)?;
|
||||
if size <= 0.0 || size > MAX_SIZE {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
@@ -2321,7 +2495,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
|
||||
/// The error of `move` and `duplicate` given an object of another document.
|
||||
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
|
||||
@@ -2648,6 +2822,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.
|
||||
@@ -2670,6 +2845,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", &[])),
|
||||
]);
|
||||
@@ -2744,15 +2921,16 @@ 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(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
@@ -2853,7 +3031,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.extend(save_open::classes(l));
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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", ¶ms)?;
|
||||
}
|
||||
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
@@ -50,6 +50,7 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod styles;
|
||||
pub(super) mod threads;
|
||||
|
||||
/// The error of a text range, or of a collection of one, whose frame's text changed other than
|
||||
@@ -201,6 +202,8 @@ pub(in crate::script) struct TextState {
|
||||
made: Cell<u64>,
|
||||
/// The span of each range object, by its number, whose `length` the script set.
|
||||
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
|
||||
/// The styles the run's style objects name.
|
||||
styles: styles::StyleState,
|
||||
}
|
||||
|
||||
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
|
||||
@@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
range.extend(attr_members(l));
|
||||
range.push(threads::range_member(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(styles::range_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
@@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
None,
|
||||
),
|
||||
];
|
||||
out.extend(styles::classes(l));
|
||||
out.extend(stories);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,802 @@
|
||||
//! Character and paragraph styles in the script object model: `document.characterStyles` and
|
||||
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
|
||||
//! of a `TextRange` uses, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A document's collection lists its Normal style first, then its other styles in the order the
|
||||
//! panel lists them.
|
||||
//! - A style object names its style for the rest of the run, also after the script renames it
|
||||
//! through `name`. Once the style is removed, or renamed or removed other than through the object
|
||||
//! model, or its document is closed or reverted with File › Revert, every member throws
|
||||
//! `Stale style`; a style added later under the same name is another style.
|
||||
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
|
||||
//! characters.
|
||||
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
|
||||
//! style does not set. Setting one redefines the style: text in the style takes the new value
|
||||
//! where it had the style's old one and keeps its other changes.
|
||||
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
|
||||
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
|
||||
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
|
||||
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
|
||||
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
|
||||
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
|
||||
//! no other style. They do not add or remove styles.
|
||||
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
|
||||
//! look and is in the Normal style after.
|
||||
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
|
||||
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::{
|
||||
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
|
||||
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
|
||||
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
|
||||
};
|
||||
use crate::DocState;
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
|
||||
use crate::script::dom::{Described, returns, typed};
|
||||
|
||||
/// The error of a style object whose style is gone.
|
||||
pub const STALE_STYLE: &str = "Stale style";
|
||||
/// The longest style name, in characters, after trimming.
|
||||
pub const MAX_STYLE_NAME: usize = 256;
|
||||
/// The most styles one run's style objects name.
|
||||
pub const MAX_HELD: usize = 4096;
|
||||
|
||||
/// A style that a run's style objects name: its document and the document's revert count then, its
|
||||
/// kind and its name now.
|
||||
struct Slot {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
para: bool,
|
||||
name: String,
|
||||
live: bool,
|
||||
}
|
||||
|
||||
/// A document's uid and its character and paragraph style lists when the slots were last checked.
|
||||
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
|
||||
|
||||
/// The styles a run's style objects name; an object holds its slot's number.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StyleState {
|
||||
slots: RefCell<Vec<Slot>>,
|
||||
seen: RefCell<Vec<Seen>>,
|
||||
}
|
||||
|
||||
/// Marks stale each style object whose style the command just run removed or renamed, so a style
|
||||
/// removed and made again under its name by later commands, or by later steps of the same batch,
|
||||
/// is another style. A document whose style lists did not change is not checked again. A live
|
||||
/// slot's style was in its document's list when the command started, so a step that removed or
|
||||
/// renamed it is in the trail's removed names.
|
||||
pub(in crate::script) fn after_command(h: &Host) {
|
||||
let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
if !slots.iter().any(|s| s.live) {
|
||||
return;
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if trail.reverted.contains(&slot.uid)
|
||||
|| (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
|
||||
{
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut seen = h.dom.text.styles.seen.borrow_mut();
|
||||
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
|
||||
for st in s.documents() {
|
||||
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
seen.retain(|(uid, ..)| *uid != st.uid);
|
||||
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
|
||||
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
|
||||
slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
|
||||
}
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if !s.documents().iter().any(|d| d.uid == slot.uid) {
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style objects' state when a savepoint was taken: each slot's name and whether it was
|
||||
/// live, and the style lists last checked.
|
||||
pub(in crate::script) struct Mark {
|
||||
slots: Vec<(String, bool)>,
|
||||
seen: Vec<Seen>,
|
||||
}
|
||||
|
||||
/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
|
||||
pub(in crate::script) fn mark(h: &Host) -> Mark {
|
||||
let styles = &h.dom.text.styles;
|
||||
let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
|
||||
Mark { slots, seen: styles.seen.borrow().clone() }
|
||||
}
|
||||
|
||||
/// Puts the style objects back as they were at `mark`, after the documents were put back to the
|
||||
/// savepoint taken with it. A slot added since then stays live only while its document has the
|
||||
/// style and no older live slot names it.
|
||||
pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
|
||||
let styles = &h.dom.text.styles;
|
||||
let mut slots = styles.slots.borrow_mut();
|
||||
let kept = mark.slots.len();
|
||||
for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
|
||||
slot.name = name;
|
||||
slot.live = live;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
for i in kept..slots.len() {
|
||||
let (older, newer) = slots.split_at_mut(i);
|
||||
let Some(slot) = newer.first_mut() else { break };
|
||||
let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
|
||||
slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
|
||||
}
|
||||
*styles.seen.borrow_mut() = mark.seen;
|
||||
}
|
||||
|
||||
fn normal(para: bool) -> &'static str {
|
||||
if para { NORMAL_PARA } else { NORMAL_CHAR }
|
||||
}
|
||||
|
||||
fn cmd(para: bool, verb: &str) -> String {
|
||||
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
|
||||
}
|
||||
|
||||
fn style_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyle" } else { "CharacterStyle" }
|
||||
}
|
||||
|
||||
fn list_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyles" } else { "CharacterStyles" }
|
||||
}
|
||||
|
||||
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
|
||||
if para { &st.doc.para_styles } else { &st.doc.char_styles }
|
||||
}
|
||||
|
||||
/// The document's style names of a kind, the Normal style first.
|
||||
fn names(st: &DocState, para: bool) -> Vec<String> {
|
||||
let mut out = vec![normal(para).to_string()];
|
||||
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
|
||||
out
|
||||
}
|
||||
|
||||
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
|
||||
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_STYLE.into())
|
||||
}
|
||||
|
||||
fn held_too_many() -> HostError {
|
||||
HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
|
||||
}
|
||||
|
||||
/// The style object for the style `name` of the document `uid`: the same slot as every other
|
||||
/// object naming it in this run.
|
||||
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if slots.len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
|
||||
slots.len() - 1
|
||||
}
|
||||
};
|
||||
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
|
||||
}
|
||||
|
||||
/// A style a style object names.
|
||||
struct Style {
|
||||
doc: Doc,
|
||||
para: bool,
|
||||
slot: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
|
||||
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
|
||||
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
|
||||
let Some((handle, para)) = found else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
|
||||
};
|
||||
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
|
||||
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
|
||||
let slot = usize_of(*slot).ok_or_else(stale)?;
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
|
||||
if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) {
|
||||
s.live = false;
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(Style { doc, para, slot, name: s.name.clone() })
|
||||
}
|
||||
|
||||
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
|
||||
style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)])
|
||||
}
|
||||
|
||||
/// Marks the slots of the styles `names` of the document `uid` as removed.
|
||||
fn forget(h: &Host, uid: u64, para: bool, names: &[String]) {
|
||||
for s in h.dom.text.styles.slots.borrow_mut().iter_mut() {
|
||||
if s.uid == uid && s.para == para && names.contains(&s.name) {
|
||||
s.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A style name a script gave, trimmed.
|
||||
fn style_name(v: &Data) -> std::result::Result<String, HostError> {
|
||||
let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) };
|
||||
if s.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return Err(HostError::Range("a style name must not be empty".into()));
|
||||
}
|
||||
if t.chars().count() > MAX_STYLE_NAME {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
if t.chars().any(char::is_control) {
|
||||
return Err(HostError::Range("a style name must not hold control characters".into()));
|
||||
}
|
||||
Ok(t.to_string())
|
||||
}
|
||||
|
||||
/// Runs the style command `verb` of the kind on the document of `doc`.
|
||||
fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params))
|
||||
}
|
||||
|
||||
// ---- CharacterStyle and ParagraphStyle ----
|
||||
|
||||
fn style_name_get(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_style(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = …`: renames the style; the Normal style keeps its name.
|
||||
fn style_name_set(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let to = style_name(arg(a, 1))?;
|
||||
if to == style.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be renamed", style.name)));
|
||||
}
|
||||
if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) {
|
||||
return Err(HostError::Error(format!("a style named {to} already exists")));
|
||||
}
|
||||
run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?;
|
||||
forget(h, style.doc.uid, style.para, std::slice::from_ref(&to));
|
||||
if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) {
|
||||
s.name = to;
|
||||
s.live = true;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn style_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, this_style(h, a)?.doc.uid))
|
||||
}
|
||||
|
||||
fn style_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(style_class(this_style(h, a)?.para)))
|
||||
}
|
||||
|
||||
fn attributes(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)]))
|
||||
}
|
||||
|
||||
fn style_character_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "CharacterStyleAttributes")
|
||||
}
|
||||
|
||||
fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "ParagraphStyleAttributes")
|
||||
}
|
||||
|
||||
/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after.
|
||||
fn style_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be removed", style.name)));
|
||||
}
|
||||
run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?;
|
||||
forget(h, style.doc.uid, style.para, &[style.name]);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The text a style is applied to: a text range, a text frame, or the characters, words or
|
||||
/// paragraphs of one.
|
||||
fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
|
||||
if handle_of(d, "TextFrame").is_some() {
|
||||
return Ok(whole_span(h, item_of(h, d)?)?.1);
|
||||
}
|
||||
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
|
||||
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
|
||||
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
|
||||
}
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
let clear = match arg(a, 2) {
|
||||
Data::Undefined => false,
|
||||
Data::Bool(b) => *b,
|
||||
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
|
||||
};
|
||||
if target.item.doc.uid != style.doc.uid {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
(ba, bb)
|
||||
} else {
|
||||
// An empty range inside text changes nothing; empty text takes the style on its runs.
|
||||
if s == e && index.len() > 0 {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
(index.byte(s, false), index.byte(e, true))
|
||||
};
|
||||
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
|
||||
run(h, style.doc, style.para, "apply", &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- the attributes of a style ----
|
||||
|
||||
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
|
||||
const CHAR_KEYS: [(&str, &str); 11] = [
|
||||
("size", "size"),
|
||||
("leading", "leading"),
|
||||
("tracking", "tracking"),
|
||||
("baselineShift", "baseline_shift"),
|
||||
("hScale", "h_scale"),
|
||||
("vScale", "v_scale"),
|
||||
("rotation", "rotation"),
|
||||
("underline", "underline"),
|
||||
("strikethrough", "strikethrough"),
|
||||
("font", "font_family"),
|
||||
("style", "font_style"),
|
||||
];
|
||||
|
||||
/// The script's `Justification` members and the alignments a paragraph style stores.
|
||||
const JUSTIFY: [(&str, &str); 7] = [
|
||||
("LEFT", "Left"),
|
||||
("CENTER", "Center"),
|
||||
("RIGHT", "Right"),
|
||||
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
|
||||
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
|
||||
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
|
||||
("FULLJUSTIFY", "JustifyAll"),
|
||||
];
|
||||
|
||||
/// The style an attributes object belongs to and the attributes it sets.
|
||||
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), HostError> {
|
||||
let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" };
|
||||
let style = style_of(h, arg(a, 0), &[(class, para)])?;
|
||||
let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?;
|
||||
Ok((style, attrs))
|
||||
}
|
||||
|
||||
fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
|
||||
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
|
||||
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
|
||||
match attr {
|
||||
Attr::Size => n("size"),
|
||||
Attr::Leading => n("leading"),
|
||||
Attr::AutoLeading => match m.get("leading") {
|
||||
Some(Value::Null) => Data::Bool(true),
|
||||
Some(v) if v.is_number() => Data::Bool(false),
|
||||
_ => Data::Undefined,
|
||||
},
|
||||
Attr::Tracking => n("tracking"),
|
||||
Attr::BaselineShift => n("baseline_shift"),
|
||||
Attr::HorizontalScale => n("h_scale"),
|
||||
Attr::VerticalScale => n("v_scale"),
|
||||
Attr::Rotation => n("rotation"),
|
||||
Attr::Underline => b("underline"),
|
||||
Attr::StrikeThrough => b("strikethrough"),
|
||||
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `characterAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, false)?;
|
||||
Ok(text("CharacterAttributes"))
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, true)?;
|
||||
Ok(text("ParagraphAttributes"))
|
||||
}
|
||||
|
||||
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, false)?;
|
||||
Ok(char_value(h, attr, &m))
|
||||
}
|
||||
|
||||
/// Redefines the style with `attrs`, unless they are what it has.
|
||||
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> Answer {
|
||||
if attrs == *old {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, false)?;
|
||||
// `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph
|
||||
// with the default justification.
|
||||
let base = CharStyle::default();
|
||||
let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size);
|
||||
let leading = old.get("leading").and_then(Value::as_f64);
|
||||
let sample = CharStyle { size, leading, ..base };
|
||||
let t = TextObject::point(Point::default(), "", sample.clone());
|
||||
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
|
||||
let mut attrs = old.clone();
|
||||
for (k, v) in param.as_object().into_iter().flatten() {
|
||||
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
|
||||
let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() };
|
||||
attrs.insert((*key).to_string(), v);
|
||||
}
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
fn para_key(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "justify",
|
||||
ParaAttr::FirstLineIndent => "first_line_indent",
|
||||
ParaAttr::LeftIndent => "left_indent",
|
||||
ParaAttr::RightIndent => "right_indent",
|
||||
ParaAttr::SpaceBefore => "space_before",
|
||||
ParaAttr::SpaceAfter => "space_after",
|
||||
}
|
||||
}
|
||||
|
||||
fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, true)?;
|
||||
let v = m.get(para_key(attr));
|
||||
Ok(match attr {
|
||||
ParaAttr::Justification => match v.and_then(Value::as_str) {
|
||||
Some("Auto") => text("Justification.LEFT"),
|
||||
Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
_ => v.and_then(Value::as_f64).map_or(Data::Undefined, num),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, true)?;
|
||||
let (_, _, wants) = para_param(attr, name, arg(a, 1))?;
|
||||
let value = match (&wants, attr) {
|
||||
(Data::String(s), ParaAttr::Justification) => {
|
||||
let m = s.strip_prefix("Justification.").unwrap_or(s);
|
||||
let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j);
|
||||
json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?)
|
||||
}
|
||||
(Data::Number(n), _) => json!(n),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a finite number"))),
|
||||
};
|
||||
let mut attrs = old.clone();
|
||||
attrs.insert(para_key(attr).to_string(), value);
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
/// The body of a member that captures what it reads or sets.
|
||||
type Body = Rc<dyn Fn(&Host, &[Data]) -> Answer>;
|
||||
|
||||
/// Members whose getter and setter each charge the call, as [`function`] does.
|
||||
fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember {
|
||||
let wrap = |f: Body| -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::super::current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
|
||||
f(&h, &a)
|
||||
})
|
||||
};
|
||||
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
|
||||
}
|
||||
|
||||
fn char_members(link: &Link) -> Vec<Described> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
(name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn para_members(link: &Link) -> Vec<Described> {
|
||||
PARA_ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
(name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- CharacterStyles and ParagraphStyles ----
|
||||
|
||||
/// What a collection of styles lists: a document's styles, or those a text range uses.
|
||||
enum Of {
|
||||
Doc(Doc),
|
||||
Range(Span),
|
||||
}
|
||||
|
||||
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
|
||||
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
|
||||
(Some(_), _) => false,
|
||||
(_, Some(_)) => true,
|
||||
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
|
||||
};
|
||||
let class = list_class(para);
|
||||
let len = handle_of(d, class).map_or(0, |v| v.len());
|
||||
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
|
||||
}
|
||||
|
||||
/// The document and the names of the styles a collection lists.
|
||||
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), HostError> {
|
||||
match of {
|
||||
Of::Doc(doc) => {
|
||||
let names = with_doc(h, *doc, |_, st| names(st, para));
|
||||
h.charge_call(names.len() as u64)?;
|
||||
Ok((*doc, names))
|
||||
}
|
||||
Of::Range(r) => {
|
||||
let (index, s, e, _) = resolve(h, *r)?;
|
||||
let used = with_doc(h, r.item.doc, |_, st| {
|
||||
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let used: Vec<Option<String>> = if para {
|
||||
let (paras, _, _) = para_range(&index, s, e);
|
||||
paras.map(|i| t.para_at(i).style_name.clone()).collect()
|
||||
} else {
|
||||
styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect()
|
||||
};
|
||||
h.charge_call(used.len() as u64)?;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in used {
|
||||
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
|
||||
if !out.contains(&n) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(normal(para).to_string());
|
||||
}
|
||||
Ok::<_, HostError>(out)
|
||||
})?;
|
||||
Ok((r.item.doc, used))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
|
||||
}
|
||||
|
||||
fn list_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, _) = list_of(h, arg(a, 0))?;
|
||||
match of {
|
||||
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
Of::Range(r) => {
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let found = match &of {
|
||||
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
|
||||
0 => Some(normal(para).to_string()),
|
||||
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
|
||||
})
|
||||
.map(|n| (*doc, n)),
|
||||
Of::Range(_) => {
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
names.get(i).cloned().map(|n| (doc, n))
|
||||
}
|
||||
};
|
||||
match found {
|
||||
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
match names.iter().find(|n| *n == name) {
|
||||
Some(n) => style_ref(h, doc.uid, para, n),
|
||||
None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a),
|
||||
Data::Number(_) => match list_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a document's collection; a range's collection cannot be changed.
|
||||
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
|
||||
match list_of(h, arg(a, 0))? {
|
||||
(Of::Doc(doc), para) => Ok((doc, para)),
|
||||
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(name)`: a new style that sets no attributes.
|
||||
fn list_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let name = style_name(arg(a, 1))?;
|
||||
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
|
||||
return Err(HostError::Error(format!("a style named {name} already exists")));
|
||||
}
|
||||
// The new style needs a slot of its own: a run that names as many styles as it may adds none.
|
||||
if h.dom.text.styles.slots.borrow().len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
|
||||
// An object of a removed style of this name stays stale.
|
||||
forget(h, doc.uid, para, std::slice::from_ref(&name));
|
||||
style_ref(h, doc.uid, para, &name)
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every style but the Normal style, in one command.
|
||||
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, doc, para, "delete", &json!({"names": gone}))?;
|
||||
forget(h, doc.uid, para, &gone);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
|
||||
let r = this_range(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
|
||||
}
|
||||
|
||||
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, false)
|
||||
}
|
||||
|
||||
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, true)
|
||||
}
|
||||
|
||||
/// `document.characterStyles` and `document.paragraphStyles`.
|
||||
pub(in crate::script) fn doc_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
|
||||
pub(super) fn range_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// The style classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let style = |para: bool| {
|
||||
let mut members = named(vec![
|
||||
("typename", get(l, style_typename), typed("string")),
|
||||
("name", property(l, style_name_get, style_name_set), typed("string")),
|
||||
("parent", get(l, style_parent), typed("Document")),
|
||||
("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])),
|
||||
("remove", method(l, style_remove), returns("undefined", &[])),
|
||||
]);
|
||||
if para {
|
||||
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes")));
|
||||
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
|
||||
} else {
|
||||
members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes")));
|
||||
}
|
||||
class(style_class(para), None, members, None)
|
||||
};
|
||||
let list = |para: bool| {
|
||||
let name = list_class(para);
|
||||
let item = style_class(para);
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of(name), typed("string")),
|
||||
("length", get(l, list_length), typed("number")),
|
||||
("parent", get(l, list_parent), typed("*")),
|
||||
("index", method(l, list_index), returns(item, &[("itemKey", "*")])),
|
||||
("getByName", method(l, list_by_name), returns(item, &[("name", "string")])),
|
||||
("add", method(l, list_add), returns(item, &[("name", "string")])),
|
||||
("removeAll", method(l, list_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, list_at)),
|
||||
)
|
||||
};
|
||||
let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]);
|
||||
chars.extend(char_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
style(false),
|
||||
style(true),
|
||||
list(false),
|
||||
list(true),
|
||||
class("CharacterStyleAttributes", None, chars, None),
|
||||
class("ParagraphStyleAttributes", None, paras, None),
|
||||
]
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
+232
-28
@@ -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::{
|
||||
@@ -162,6 +163,7 @@ pub fn refused_to_scripts(id: &str) -> bool {
|
||||
"edit.undoGroup.",
|
||||
"file.recovery.",
|
||||
"stroke.widthProfile.",
|
||||
"proof.",
|
||||
];
|
||||
const IDS: &[&str] = &[
|
||||
"text.addFontFiles",
|
||||
@@ -207,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>,
|
||||
}
|
||||
@@ -784,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)>>,
|
||||
@@ -979,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 };
|
||||
@@ -1152,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
|
||||
@@ -1295,6 +1320,7 @@ fn note_ids(s: &mut Session) {
|
||||
/// it, for a result that cannot cross to the script.
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
|
||||
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
@@ -1342,6 +1368,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
Ok((v, objects, bytes, save))
|
||||
}
|
||||
Err(e) => {
|
||||
s.script_style_trail = StyleTrail::default();
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1378,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);
|
||||
@@ -1420,12 +1449,81 @@ 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();
|
||||
}
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
/// A document's uid, revert count, and character and paragraph style lists.
|
||||
pub(crate) type StyleLists =
|
||||
(u64, u64, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
|
||||
|
||||
/// What the steps of a command a script runs did to the documents' style lists
|
||||
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
|
||||
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
|
||||
/// documents a step reverted.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> Self {
|
||||
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
|
||||
StyleTrail { lists, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs: notes the styles the step removed or renamed and the
|
||||
/// documents it reverted, so the style objects see a style the batch removed and made again under
|
||||
/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open
|
||||
/// document's lists, however many steps change them.
|
||||
pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);
|
||||
let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else {
|
||||
trail.lists.push((st.uid, st.reverts, c.clone(), p.clone()));
|
||||
continue;
|
||||
};
|
||||
if last.1 != st.reverts {
|
||||
if !trail.reverted.contains(&st.uid) {
|
||||
trail.reverted.push(st.uid);
|
||||
}
|
||||
} else {
|
||||
for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] {
|
||||
if vectorcraft_doc::Shared::ptr_eq(old, new) {
|
||||
continue;
|
||||
}
|
||||
let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect();
|
||||
for d in old.iter().filter(|d| !names.contains(d.name.as_str())) {
|
||||
trail.gone.insert((st.uid, para, d.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn retained_style_lists(s: &Session) -> usize {
|
||||
s.script_style_trail.lists.len()
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -1527,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![
|
||||
@@ -1541,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()));
|
||||
};
|
||||
@@ -1557,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),
|
||||
@@ -1667,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 {
|
||||
@@ -1987,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()));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2084,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,
|
||||
@@ -2115,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.
|
||||
@@ -2155,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()),
|
||||
@@ -2186,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()),
|
||||
@@ -2250,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());
|
||||
@@ -2273,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 });
|
||||
@@ -2327,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;
|
||||
@@ -2352,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;
|
||||
@@ -2689,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(|| {
|
||||
@@ -2696,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 {
|
||||
@@ -2710,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)]
|
||||
@@ -2726,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)]
|
||||
@@ -2752,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`].
|
||||
|
||||
Reference in new issue
Block a user