mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into feat/scripts-api-d8b-tracing
This commit is contained in:
commit
73499bb62f
766 files changed
+86482
-6052
No files matched your search
@@ -0,0 +1,354 @@
|
||||
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
|
||||
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
|
||||
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
|
||||
//!
|
||||
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
|
||||
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
|
||||
//! they are the Actions panel's.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference does not state:
|
||||
//! - The action and its set are matched by their exact names; a name that matches no action, or
|
||||
//! more than one, throws before any step runs.
|
||||
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
|
||||
//! the run's transaction and its one undo step for each changed document, it is counted as a host
|
||||
//! call, it reads and writes files only where the script may, and a step that fails is put back
|
||||
//! and throws an error that names the step and the action, while the steps before it stay done.
|
||||
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
|
||||
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
|
||||
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
|
||||
//! another action, so it cannot play itself.
|
||||
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
|
||||
//! changes nothing.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostMember};
|
||||
|
||||
use super::{Host, Link, command, current, refused_to_scripts};
|
||||
|
||||
/// The most actions a run's request may carry.
|
||||
pub const MAX_ACTIONS: usize = 4096;
|
||||
/// The most steps one action may have, after a `command.batch` step gives its own steps.
|
||||
pub const MAX_ACTION_STEPS: usize = 10_000;
|
||||
/// The most steps the actions of one request may have in all.
|
||||
pub const MAX_ALL_STEPS: usize = 100_000;
|
||||
/// The most bytes of the request's actions, as JSON.
|
||||
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
|
||||
/// The longest name of an action or a set, in bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 1024;
|
||||
/// The longest command id of a step, in bytes.
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
/// The command id of a stop, which waits for the person in the Actions panel.
|
||||
pub const STOP_STEP: &str = "action.stop";
|
||||
|
||||
/// An action a run can play: its set's name, its name and the steps playback runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playable {
|
||||
set: String,
|
||||
name: String,
|
||||
steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
|
||||
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
|
||||
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
place: String,
|
||||
id: String,
|
||||
params: Value,
|
||||
bytes: u64,
|
||||
artboard: Option<u64>,
|
||||
}
|
||||
|
||||
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
|
||||
/// step's place in the action (1 for the first; default its place in the list), within the limits
|
||||
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
|
||||
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
|
||||
let Some(v) = v else { return Ok(Vec::new()) };
|
||||
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
|
||||
if list.len() > MAX_ACTIONS {
|
||||
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
|
||||
}
|
||||
if let Some(place) = super::too_deep(v) {
|
||||
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
|
||||
}
|
||||
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
|
||||
return Err("`actions` is larger than 16 MiB".into());
|
||||
}
|
||||
let mut all = 0usize;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("`actions[{i}]`");
|
||||
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(a, &["set", "name", "steps"], &at)?;
|
||||
let set = name_of(a, "set", &at)?;
|
||||
let name = name_of(a, "name", &at)?;
|
||||
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
|
||||
let mut steps = Vec::new();
|
||||
for (j, s) in given.iter().enumerate() {
|
||||
let at = format!("{at}.steps[{j}]");
|
||||
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(s, &["command", "params", "step"], &at)?;
|
||||
let place = match s.get("step") {
|
||||
None => (j + 1).to_string(),
|
||||
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
|
||||
Some(n) => n.to_string(),
|
||||
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
|
||||
},
|
||||
};
|
||||
let (id, params) = command_of(s, &at)?;
|
||||
match params.get("commands") {
|
||||
Some(Value::Array(inner)) if id == "command.batch" => {
|
||||
// The batch's `artboard`, for its steps that act on the active artboard, as
|
||||
// `command.batch` reads it.
|
||||
let artboard = params.get("artboard").and_then(Value::as_u64);
|
||||
for (k, c) in inner.iter().enumerate() {
|
||||
let at = format!("{at}.params.commands[{k}]");
|
||||
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
|
||||
let (id, params) = command_of(c, &at)?;
|
||||
if id == "command.batch" {
|
||||
return Err(format!("{at} is a command.batch inside a command.batch"));
|
||||
}
|
||||
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
|
||||
}
|
||||
}
|
||||
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
|
||||
_ => steps.push(step(place, id, params, None)),
|
||||
}
|
||||
if steps.len() > MAX_ACTION_STEPS {
|
||||
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
|
||||
}
|
||||
}
|
||||
all += steps.len();
|
||||
if all > MAX_ALL_STEPS {
|
||||
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
|
||||
}
|
||||
out.push(Playable { set, name, steps });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Playable {
|
||||
/// The steps the action runs.
|
||||
pub fn len(&self) -> usize {
|
||||
self.steps.len()
|
||||
}
|
||||
|
||||
/// Whether the action runs no step.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
|
||||
match o.get(key) {
|
||||
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
|
||||
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
|
||||
_ => Err(format!("{at}.{key} must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's `command` and `params` (default `{}`).
|
||||
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
|
||||
let id = match o.get("command") {
|
||||
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
|
||||
_ => return Err(format!("{at}.command must be a command id")),
|
||||
};
|
||||
let params = match o.get("params") {
|
||||
None => json!({}),
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
Some(_) => return Err(format!("{at}.params must be an object")),
|
||||
};
|
||||
Ok((id, params))
|
||||
}
|
||||
|
||||
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
|
||||
let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64);
|
||||
Step { place, id, params, bytes, artboard }
|
||||
}
|
||||
|
||||
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
|
||||
/// as U+FFFD.
|
||||
fn shown(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
|
||||
if text.chars().nth(MAX).is_some() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of `app` this module adds.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
|
||||
let l = link.clone();
|
||||
let play = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
do_script(&h, &a)
|
||||
});
|
||||
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
|
||||
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
|
||||
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
|
||||
members
|
||||
}
|
||||
|
||||
fn arg(a: &[Data], i: usize) -> &Data {
|
||||
a.get(i).unwrap_or(&Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
|
||||
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if a.len() > 4 {
|
||||
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
|
||||
}
|
||||
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
|
||||
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
|
||||
};
|
||||
if action.is_empty() || set.is_empty() {
|
||||
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
|
||||
}
|
||||
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
|
||||
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
|
||||
}
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
|
||||
// they were.
|
||||
for s in &p.steps {
|
||||
if let Some((place, id)) = refused_step(s) {
|
||||
let name = shown(&p.name);
|
||||
return Err(HostError::Error(if id == STOP_STEP {
|
||||
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
|
||||
} else {
|
||||
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
|
||||
}));
|
||||
}
|
||||
}
|
||||
for s in &p.steps {
|
||||
// A run asked to stop runs no further step; the realm ends it at its next instruction and
|
||||
// puts the documents back.
|
||||
if h.session.borrow().script_stop.is_set() {
|
||||
break;
|
||||
}
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The place and command of the first command step `s` would run that a script may not run: the
|
||||
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
|
||||
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
|
||||
/// engine does not have are refused.
|
||||
fn refused_step(s: &Step) -> Option<(String, String)> {
|
||||
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
|
||||
if refused(&s.id) {
|
||||
return Some((s.place.clone(), s.id.clone()));
|
||||
}
|
||||
if s.id != "action.batch" {
|
||||
return None;
|
||||
}
|
||||
let commands = s.params.get("commands").and_then(Value::as_array)?;
|
||||
commands.iter().enumerate().find_map(|(k, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `params` of step `id`, with the active artboard of the active document added as a
|
||||
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
|
||||
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
|
||||
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
|
||||
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
|
||||
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
|
||||
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
|
||||
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
|
||||
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
|
||||
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
|
||||
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
|
||||
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
|
||||
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
|
||||
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
|
||||
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
|
||||
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
|
||||
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
|
||||
let mut params = params.clone();
|
||||
let Some(st) = s.active() else { return params };
|
||||
let n = st.doc.artboards.len();
|
||||
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
|
||||
(Some(_), _) if n == 0 => return params,
|
||||
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
|
||||
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
|
||||
(None, None) => super::dom::active_artboard(st),
|
||||
};
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let fit_art = id == "artboard.fitToArt";
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"artboard"
|
||||
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"index"
|
||||
} else {
|
||||
return params;
|
||||
};
|
||||
let Some(p) = params.as_object_mut() else { return params };
|
||||
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
|
||||
return params;
|
||||
}
|
||||
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
|
||||
let kept: Vec<usize> = match start.picks {
|
||||
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
|
||||
list.iter().copied().filter(|i| *i < n).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if kept.len() >= 2 {
|
||||
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
|
||||
} else if picks.is_empty() {
|
||||
p.insert(key.into(), json!(active));
|
||||
} else if fit_art {
|
||||
p.insert("indices".into(), json!(picks));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
|
||||
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
|
||||
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
|
||||
pub(crate) struct Start<'a> {
|
||||
pub active: &'a [(u64, usize)],
|
||||
pub picks: Option<&'a (u64, Vec<usize>)>,
|
||||
pub batch: Option<u64>,
|
||||
}
|
||||
@@ -21,8 +21,9 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
use super::{Host, console};
|
||||
|
||||
/// The most bytes (UTF-8) of a dialog's message.
|
||||
@@ -48,6 +49,8 @@ pub enum DialogKind {
|
||||
Alert,
|
||||
Confirm,
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
@@ -57,6 +60,7 @@ impl DialogKind {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +89,8 @@ pub enum DialogAnswer {
|
||||
Confirm(bool),
|
||||
/// OK with the field's text, or Cancel (`None`), for `prompt`.
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -93,13 +99,14 @@ impl DialogAnswer {
|
||||
Self::Ok => DialogKind::Alert,
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
match self {
|
||||
Self::Ok => Data::Undefined,
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
@@ -112,6 +119,7 @@ impl DialogAnswer {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
|
||||
/// took before dialogs existed, is an empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, Stri
|
||||
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
|
||||
}
|
||||
|
||||
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
|
||||
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
|
||||
fn answer(a: &Value) -> Result<DialogAnswer, String> {
|
||||
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) };
|
||||
if o.len() != 2 || !o.contains_key("value") {
|
||||
return Err("must have exactly `kind` and `value`");
|
||||
return Err("must have exactly `kind` and `value`".into());
|
||||
}
|
||||
if o.get("kind").and_then(Value::as_str) == Some("window") {
|
||||
return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window);
|
||||
}
|
||||
known_answer(o).map_err(String::from)
|
||||
}
|
||||
|
||||
fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
|
||||
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
|
||||
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
|
||||
@@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm or prompt"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +215,15 @@ pub(crate) struct Dialogs {
|
||||
record_bytes: Cell<usize>,
|
||||
count: Cell<u64>,
|
||||
truncated: Cell<bool>,
|
||||
/// The ScriptUI dialog whose `show()` is running.
|
||||
window: RefCell<Option<Showing>>,
|
||||
/// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler
|
||||
/// opens is listed after it; `None` when the list had stopped at its limit.
|
||||
window_slot: Cell<Option<usize>>,
|
||||
/// That dialog waits for what the person does.
|
||||
window_waiting: Cell<bool>,
|
||||
/// The `show()` calls the run has made.
|
||||
shows: Cell<u64>,
|
||||
}
|
||||
|
||||
impl Dialogs {
|
||||
@@ -213,6 +238,10 @@ impl Dialogs {
|
||||
record_bytes: Cell::new(0),
|
||||
count: Cell::new(0),
|
||||
truncated: Cell::new(false),
|
||||
window: RefCell::default(),
|
||||
window_slot: Cell::new(None),
|
||||
window_waiting: Cell::new(false),
|
||||
shows: Cell::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +251,176 @@ impl Dialogs {
|
||||
}
|
||||
|
||||
pub(crate) fn is_waiting(&self) -> bool {
|
||||
self.waiting.borrow().is_some()
|
||||
self.waiting.borrow().is_some() || self.window_waiting.get()
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog that waits for what the person does.
|
||||
pub(crate) fn waiting_window(&self) -> Option<ScriptUiDialog> {
|
||||
if !self.window_waiting.get() {
|
||||
return None;
|
||||
}
|
||||
self.window.borrow().as_ref().map(|s| s.dialog.clone())
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs.
|
||||
pub(crate) fn showing_window(&self) -> Option<ScriptUiDialog> {
|
||||
self.window.borrow().as_ref().map(|s| s.dialog.clone())
|
||||
}
|
||||
|
||||
/// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog.
|
||||
pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> {
|
||||
if !self.window_waiting.get() {
|
||||
return Err("no script dialog waits".into());
|
||||
}
|
||||
let event = {
|
||||
let mut window = self.window.borrow_mut();
|
||||
let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) };
|
||||
let event = scriptui::check_event(&showing.dialog, event)?;
|
||||
showing.events = showing.events.saturating_add(1);
|
||||
event
|
||||
};
|
||||
self.window_waiting.set(false);
|
||||
if let Err(e) = realm.answer(event.data()) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cannot_wait(&self) -> Result<(), HostError> {
|
||||
if self.framed && !self.can_wait.get() {
|
||||
return Err(HostError::Error(
|
||||
"show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a
|
||||
/// `window` answer.
|
||||
pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> {
|
||||
self.cannot_wait()?;
|
||||
self.shows.set(self.shows.get().saturating_add(1));
|
||||
dialog.shown = self.shows.get();
|
||||
let mut showing = Showing { dialog, steps: None, events: 0 };
|
||||
if !self.framed {
|
||||
let next = self.answers.borrow_mut().pop_front();
|
||||
match next {
|
||||
Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()),
|
||||
Some(a) => {
|
||||
self.push_record(showing.record(json!("missing")));
|
||||
return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id())));
|
||||
}
|
||||
None => {
|
||||
self.push_record(showing.record(json!("missing")));
|
||||
return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.window_slot.set(self.reserve_record());
|
||||
*self.window.borrow_mut() = Some(showing);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count
|
||||
/// once the dialog ends. → the place, or `None` when the list stopped at its limit.
|
||||
fn reserve_record(&self) -> Option<usize> {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let mut records = self.records.borrow_mut();
|
||||
if self.truncated.get() || records.len() >= MAX_RECORDS {
|
||||
self.truncated.set(true);
|
||||
return None;
|
||||
}
|
||||
records.push(Value::Null);
|
||||
Some(records.len() - 1)
|
||||
}
|
||||
|
||||
/// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took
|
||||
/// in the list when it opened. When the dialogs a handler opened left no room for it, the list
|
||||
/// drops the last of them until it fits, or stops before the dialog when it does not fit
|
||||
/// alone, so it still holds the first dialogs in the order they opened, and is marked as
|
||||
/// stopped at its limit.
|
||||
fn end_record(&self, showing: &Showing, answer: Value) {
|
||||
let Some(i) = self.window_slot.take() else { return };
|
||||
let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len());
|
||||
let r = showing.record(answer);
|
||||
let bytes = size(&r);
|
||||
let mut records = self.records.borrow_mut();
|
||||
if i >= records.len() {
|
||||
return;
|
||||
}
|
||||
while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 {
|
||||
let last = records.pop().map_or(0, |r| size(&r));
|
||||
self.record_bytes.set(self.record_bytes.get().saturating_sub(last));
|
||||
self.truncated.set(true);
|
||||
}
|
||||
if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
|
||||
records.truncate(i);
|
||||
self.truncated.set(true);
|
||||
return;
|
||||
}
|
||||
self.record_bytes.set(self.record_bytes.get() + bytes);
|
||||
if let Some(slot) = records.get_mut(i) {
|
||||
*slot = r;
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the
|
||||
/// next step of its answer.
|
||||
pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result<Data, HostError> {
|
||||
self.cannot_wait()?;
|
||||
let mut window = self.window.borrow_mut();
|
||||
let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) };
|
||||
dialog.shown = showing.dialog.shown;
|
||||
showing.dialog = dialog;
|
||||
let Some(steps) = showing.steps.as_mut() else {
|
||||
drop(window);
|
||||
self.window_waiting.set(true);
|
||||
return Err(HostError::Wait);
|
||||
};
|
||||
let failure = match steps.pop_front() {
|
||||
None => "show: the dialog's answer in `answers` has no step left".to_string(),
|
||||
Some(step) => match scriptui::step_event(&showing.dialog, &step) {
|
||||
Ok(event) => {
|
||||
showing.events = showing.events.saturating_add(1);
|
||||
return Ok(event.data());
|
||||
}
|
||||
Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"),
|
||||
},
|
||||
};
|
||||
if let Some(showing) = window.take() {
|
||||
self.end_record(&showing, json!("missing"));
|
||||
}
|
||||
Err(HostError::Abort(failure))
|
||||
}
|
||||
|
||||
/// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask
|
||||
/// must have used every step of the dialog's answer.
|
||||
pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> {
|
||||
self.window_waiting.set(false);
|
||||
let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) };
|
||||
let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len);
|
||||
let steps = if left == 1 { "step" } else { "steps" };
|
||||
let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use");
|
||||
if normal && left > 0 {
|
||||
self.end_record(&showing, json!("missing"));
|
||||
return Err(HostError::Abort(unused));
|
||||
}
|
||||
// A show that a handler's error ended still ends the run when steps are left: the script
|
||||
// can catch that error, and the run must not finish as if it took every step.
|
||||
if left > 0 {
|
||||
let mut failed = self.failed.borrow_mut();
|
||||
if failed.is_none() {
|
||||
*failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false });
|
||||
}
|
||||
}
|
||||
let answer = match result {
|
||||
_ if !normal => json!("error"),
|
||||
r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64),
|
||||
r => json!(r),
|
||||
};
|
||||
self.end_record(&showing, answer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error that ended the run when its answer could not reach the script.
|
||||
@@ -257,10 +455,13 @@ impl Dialogs {
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
}
|
||||
self.window_waiting.set(false);
|
||||
if let Some(showing) = self.window.borrow_mut().take() {
|
||||
self.end_record(&showing, json!("stop"));
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
@@ -269,9 +470,14 @@ impl Dialogs {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
let r = Value::Object(r);
|
||||
self.push_record(Value::Object(r));
|
||||
}
|
||||
|
||||
fn push_record(&self, r: Value) {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
|
||||
let mut records = self.records.borrow_mut();
|
||||
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
|
||||
@@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
(text(args, 2), false, false, preset)
|
||||
}
|
||||
DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())),
|
||||
};
|
||||
if message.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
|
||||
|
||||
+931
-159
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -18,11 +18,11 @@ use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
|
||||
|
||||
use super::{
|
||||
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::NodeId;
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, host_ref};
|
||||
|
||||
/// The error for a tag that was deleted, or that came from an earlier run.
|
||||
pub const STALE_TAG: &str = "Stale tag";
|
||||
@@ -286,21 +286,21 @@ fn tag_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// The `Tags` and `Tag` classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let tags: Vec<(String, HostMember)> = named(vec![
|
||||
("typename", get(l, tags_typename)),
|
||||
("length", get(l, tags_length)),
|
||||
("parent", get(l, tags_parent)),
|
||||
("index", method(l, tags_index)),
|
||||
("getByName", method(l, tags_by_name)),
|
||||
("add", method(l, tags_add)),
|
||||
("removeAll", method(l, tags_remove_all)),
|
||||
let tags = named(vec![
|
||||
("typename", get(l, tags_typename), typed("string")),
|
||||
("length", get(l, tags_length), typed("number")),
|
||||
("parent", get(l, tags_parent), typed("*")),
|
||||
("index", method(l, tags_index), returns("Tag", &[("itemKey", "*")])),
|
||||
("getByName", method(l, tags_by_name), returns("Tag", &[("name", "string")])),
|
||||
("add", method(l, tags_add), returns("Tag", &[])),
|
||||
("removeAll", method(l, tags_remove_all), returns("undefined", &[])),
|
||||
]);
|
||||
let tag = named(vec![
|
||||
("typename", get(l, tag_typename)),
|
||||
("name", property(l, tag_name, tag_set_name)),
|
||||
("value", property(l, tag_value, tag_set_value)),
|
||||
("parent", get(l, tag_parent)),
|
||||
("remove", method(l, tag_remove)),
|
||||
("typename", get(l, tag_typename), typed("string")),
|
||||
("name", property(l, tag_name, tag_set_name), typed("string")),
|
||||
("value", property(l, tag_value, tag_set_value), typed("string")),
|
||||
("parent", get(l, tag_parent), typed("PageItem")),
|
||||
("remove", method(l, tag_remove), returns("undefined", &[])),
|
||||
]);
|
||||
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,829 @@
|
||||
//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and
|
||||
//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Story/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Stories/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story,
|
||||
//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null`
|
||||
//! breaks that link, and no text moves across it. Point type, a frame of another
|
||||
//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden
|
||||
//! or locked frame in either story are refused with nothing changed. Assigning the frame that is
|
||||
//! already linked, or `null` where there is no link, changes nothing.
|
||||
//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the
|
||||
//! frame is deleted, it throws `Stale story`.
|
||||
//! - `document.stories` lists one story for each type object in no thread and one for each thread,
|
||||
//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose
|
||||
//! first frame has that name.
|
||||
//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep
|
||||
//! their place through edits made through them, as a frame's ranges do, and are stale after any
|
||||
//! other change to the story's text and after File › Revert. A story of one frame gives that
|
||||
//! frame's own ranges.
|
||||
//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when
|
||||
//! `postFix` is false; `postFix` is true when it is left out.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::TextKind;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::super::{
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get,
|
||||
handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc,
|
||||
};
|
||||
use super::{
|
||||
ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched,
|
||||
usize_of, whole_span,
|
||||
};
|
||||
use crate::cmd::threads::story_of;
|
||||
use crate::{DocState, Document, NodeId};
|
||||
|
||||
/// The error of a `Story` whose frame was deleted, or that came from an earlier run.
|
||||
pub const STALE_STORY: &str = "Stale story";
|
||||
|
||||
/// A document's uid, the document, and the first frame of each of its stories then.
|
||||
type StoryList = (u64, Weak<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The story state of one run: the text of each story of two or more frames that a range was made
|
||||
/// of, by document and the frame the `Story` was read from, and the last list of stories.
|
||||
#[derive(Default)]
|
||||
pub(in crate::script) struct StoryState {
|
||||
logs: RefCell<HashMap<(u64, u64), Log>>,
|
||||
list: RefCell<Option<StoryList>>,
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone.
|
||||
fn frames_of(st: &DocState, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(&st.doc, id);
|
||||
let mut seen = HashSet::new();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, charged to the run.
|
||||
fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
h.charge_call(st.doc.text_threads.len() as u64)?;
|
||||
let frames = frames_of(st, id);
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Whether type object `id` is area type or type on a path.
|
||||
fn threadable(st: &DocState, id: NodeId) -> bool {
|
||||
text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point))
|
||||
}
|
||||
|
||||
// ---- nextFrame and previousFrame ----
|
||||
|
||||
fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f)))
|
||||
})
|
||||
}
|
||||
|
||||
fn next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`.
|
||||
fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let name = if next { "nextFrame" } else { "previousFrame" };
|
||||
let item = this_frame(h, a)?;
|
||||
let other = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))),
|
||||
};
|
||||
if other.is_some_and(|o| o.doc.uid != item.doc.uid) {
|
||||
return Err(HostError::Error(format!("{name}: the two frames are in different documents")));
|
||||
}
|
||||
let now = with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) {
|
||||
return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded")));
|
||||
}
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(current.copied())
|
||||
})?;
|
||||
if now == other.map(|o| o.id) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let side = if next { "next" } else { "previous" };
|
||||
let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)});
|
||||
edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e {
|
||||
HostError::Error(m) => HostError::Error(format!("{name}: {m}")),
|
||||
e => e,
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn set_previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// `TextFrame.story`.
|
||||
fn frame_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
Ok(story_ref(h, item))
|
||||
}
|
||||
|
||||
/// `TextRange.story`: the story of the range's frame.
|
||||
fn range_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = super::this_range(h, a)?;
|
||||
super::resolve(h, r)?;
|
||||
Ok(story_ref(h, r.item))
|
||||
}
|
||||
|
||||
// ---- creating a frame threaded to another ----
|
||||
|
||||
/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame
|
||||
/// is made: the frame to thread the new one to, and whether the new one goes after it.
|
||||
pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result<Option<(Item, bool)>, HostError> {
|
||||
if matches!(base, Data::Undefined | Data::Null) {
|
||||
return Ok(None);
|
||||
}
|
||||
if handle_of(base, "TextFrame").is_none() {
|
||||
return Err(HostError::Type("baseFrame must be a TextFrame".into()));
|
||||
}
|
||||
let item = item_of(h, base)?;
|
||||
if item.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("baseFrame: the frame is in another document".into()));
|
||||
}
|
||||
let postfix = match post {
|
||||
Data::Undefined => true,
|
||||
d => boolean(d, "postFix")?,
|
||||
};
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) {
|
||||
return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into()));
|
||||
}
|
||||
let editable = st.doc.editable();
|
||||
if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) {
|
||||
return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some((item, postfix)))
|
||||
}
|
||||
|
||||
/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type:
|
||||
/// `text.thread.add` does not thread type there.
|
||||
pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> {
|
||||
if in_compound(h, path) {
|
||||
return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Threads the new frame `id` after `base`, or before it when `postfix` is false.
|
||||
pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> {
|
||||
edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Story ----
|
||||
|
||||
fn story_ref(h: &Host, item: Item) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref("Story", &[float(h.run), float(item.doc.uid), high, low])
|
||||
}
|
||||
|
||||
/// The frame the story `d` was read from, which must still be a type object.
|
||||
fn story_of_data(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
match with_doc(h, doc, |_, st| text_of(st, id).is_some()) {
|
||||
true => Ok(Item { doc, id }),
|
||||
false => Err(HostError::Error(STALE_STORY.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn this_story(h: &Host, a: &[Data]) -> std::result::Result<Item, HostError> {
|
||||
story_of_data(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn story_frames(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect())))
|
||||
}
|
||||
|
||||
fn story_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
Ok(doc_ref(h, story.doc.uid))
|
||||
}
|
||||
|
||||
/// The story's one frame, or `None` for a story of two or more frames.
|
||||
fn single(h: &Host, story: Item) -> std::result::Result<Option<Item>, HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
Ok(match frames[..] {
|
||||
[one] => Some(Item { doc: story.doc, id: one }),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn story_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(num(float(index.len() as u64)))
|
||||
}
|
||||
|
||||
/// A range or a collection of the whole story, as `frame_class` for a story of one frame and
|
||||
/// `story_class` for a longer one.
|
||||
fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
if let Some(frame) = single(h, story)? {
|
||||
let (_, r) = whole_span(h, frame)?;
|
||||
return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class));
|
||||
}
|
||||
let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(span_ref(h, story, 0, index.len(), stamp, story_class))
|
||||
}
|
||||
|
||||
fn story_text_range(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "TextRange", "StoryRange")
|
||||
}
|
||||
|
||||
fn story_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Characters", "StoryCharacters")
|
||||
}
|
||||
|
||||
fn story_words(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Words", "StoryWords")
|
||||
}
|
||||
|
||||
fn story_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Paragraphs", "StoryParagraphs")
|
||||
}
|
||||
|
||||
// ---- the text of a story of two or more frames ----
|
||||
|
||||
/// The frames of the story and the text of each, in thread order.
|
||||
fn story_text(st: &DocState, frames: &[NodeId]) -> String {
|
||||
frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect()
|
||||
}
|
||||
|
||||
/// The story's index and its generation now, read again when its document changed. The stories
|
||||
/// read from the frames of one story share one index of its text while the document is unchanged.
|
||||
fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<Index>, u64), HostError> {
|
||||
if text_of(st, anchor).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let key = (st.uid, anchor.0);
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts;
|
||||
if !logs.get(&key).is_some_and(current) {
|
||||
let frames = charged_frames(h, st, anchor)?;
|
||||
// Another frame of the same story read at this state of the document has the same text;
|
||||
// a frame listed in two threads can belong to another story, so its frames must match.
|
||||
let mut shared = None;
|
||||
if frames.len() > 1 {
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
if let Some((f, l)) =
|
||||
frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l)))
|
||||
&& charged_frames(h, st, f)? == frames
|
||||
{
|
||||
shared = Some(l.index.clone());
|
||||
}
|
||||
}
|
||||
let index = match shared {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let text = story_text(st, &frames);
|
||||
// Joining the frames' text costs its length, as rebuilding the index does elsewhere.
|
||||
h.charge_call(text.len() as u64)?;
|
||||
match logs.get(&key) {
|
||||
Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(),
|
||||
_ => Rc::new(Index::new(text)),
|
||||
}
|
||||
}
|
||||
};
|
||||
match logs.get_mut(&key) {
|
||||
Some(l) => {
|
||||
if l.reverts != st.reverts || index.text != l.index.text {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index;
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
None => {
|
||||
logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
Ok((l.index.clone(), l.stamp))
|
||||
}
|
||||
|
||||
/// A range of a story: the frame the story was read from, its span in UTF-16 units and the
|
||||
/// generation it was made at.
|
||||
#[derive(Clone, Copy)]
|
||||
struct StorySpan {
|
||||
story: Item,
|
||||
start: usize,
|
||||
end: usize,
|
||||
stamp: u64,
|
||||
}
|
||||
|
||||
const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)];
|
||||
|
||||
fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
|
||||
let [high, low] = id_parts(story.id);
|
||||
host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
|
||||
}
|
||||
|
||||
/// The story span `d` names, when it is an object of one of `classes`.
|
||||
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<StorySpan, HostError> {
|
||||
let handle = classes.iter().find_map(|c| handle_of(d, c));
|
||||
let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
|
||||
};
|
||||
let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?;
|
||||
let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
Ok(StorySpan { story, start, end, stamp })
|
||||
}
|
||||
|
||||
fn this_span(h: &Host, a: &[Data]) -> std::result::Result<StorySpan, HostError> {
|
||||
span_of(h, arg(a, 0), &["StoryRange"])
|
||||
}
|
||||
|
||||
/// The span and index of `r` now.
|
||||
fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc<Index>, usize, usize, u64), HostError> {
|
||||
with_doc(h, r.story.doc, |_, st| {
|
||||
let (index, stamp) = observe(h, st, r.story.id)?;
|
||||
let logs = h.dom.text.stories.logs.borrow();
|
||||
let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?;
|
||||
if r.stamp < l.floor || r.stamp > l.stamp {
|
||||
return Err(HostError::Error(STALE_RANGE.into()));
|
||||
}
|
||||
let (mut s, mut e) = (r.start, r.end);
|
||||
let from = l.edits.partition_point(|x| x.stamp <= r.stamp);
|
||||
for x in l.edits.range(from..) {
|
||||
let moved = |v: usize| v - x.removed + x.inserted;
|
||||
s = if s <= x.at {
|
||||
s
|
||||
} else if s >= x.at + x.removed {
|
||||
moved(s)
|
||||
} else {
|
||||
x.at
|
||||
};
|
||||
// An end inside the removed text goes to the end of the new text.
|
||||
e = if e < x.at || (e == x.at && x.removed > 0) {
|
||||
e
|
||||
} else if e >= x.at + x.removed {
|
||||
moved(e)
|
||||
} else {
|
||||
x.at + x.inserted
|
||||
};
|
||||
}
|
||||
let e = e.min(index.len());
|
||||
Ok((index, s.min(e), e, stamp))
|
||||
})
|
||||
}
|
||||
|
||||
/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`.
|
||||
/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the
|
||||
/// same story read from its other frames record the edit too, when they knew the text before it.
|
||||
fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
let now = story_text(st, &frames);
|
||||
let (a, b) = (before.byte(at, false), before.byte(at + removed, true));
|
||||
let expected = before.text.len() - (b - a) + inserted.len() == now.len()
|
||||
&& now.as_bytes().starts_with(&before.text.as_bytes()[..a])
|
||||
&& now.as_bytes().ends_with(&before.text.as_bytes()[b..])
|
||||
&& now.get(a..a + inserted.len()) == Some(inserted);
|
||||
let members: HashSet<u64> = frames.iter().map(|f| f.0).collect();
|
||||
let index = Rc::new(Index::new(now));
|
||||
let inserted = inserted.encode_utf16().count();
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let mut found = false;
|
||||
for (&(uid, anchor), l) in logs.iter_mut() {
|
||||
if uid != st.uid || !members.contains(&anchor) {
|
||||
continue;
|
||||
}
|
||||
let own = anchor == story.id.0;
|
||||
let current = l.reverts == st.reverts;
|
||||
if !own {
|
||||
h.charge_call(l.index.text.len() as u64)?;
|
||||
if !expected || !current || l.index.text != before.text {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
found |= own;
|
||||
if expected && current {
|
||||
l.push(at, removed, inserted);
|
||||
} else {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index.clone();
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with
|
||||
/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in
|
||||
/// place while the frames after it flow again.
|
||||
fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> {
|
||||
loop {
|
||||
let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut at = 0;
|
||||
let spans = charged_frames(h, st, story.id)?
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum());
|
||||
at += n;
|
||||
(f, at - n, at)
|
||||
})
|
||||
.collect();
|
||||
Ok(spans)
|
||||
})?;
|
||||
let target =
|
||||
if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) };
|
||||
let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
let item = Item { doc: story.doc, id: f };
|
||||
if x <= a {
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?;
|
||||
return Ok(());
|
||||
}
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?;
|
||||
b = x;
|
||||
}
|
||||
}
|
||||
|
||||
fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer {
|
||||
let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) };
|
||||
let insert = from_script(v);
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let (a, b) = (index.byte(s, false), index.byte(e, true));
|
||||
if index.text[a..b] == insert {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
|
||||
replace(h, r.story, a, b, &insert)?;
|
||||
record(h, r.story, &index, s, e - s, &insert)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn span_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let (x, y) = (index.byte(s, false), index.byte(e, true));
|
||||
Ok(text(to_script(&index.text[x..y])))
|
||||
}
|
||||
|
||||
fn span_set_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, arg(a, 1))
|
||||
}
|
||||
|
||||
fn span_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, &text(""))
|
||||
}
|
||||
|
||||
fn span_start(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, _, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(s as u64)))
|
||||
}
|
||||
|
||||
fn span_end(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(e as u64)))
|
||||
}
|
||||
|
||||
fn span_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float((e - s) as u64)))
|
||||
}
|
||||
|
||||
fn span_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(story_ref(h, r.story))
|
||||
}
|
||||
|
||||
fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x);
|
||||
Ok(num(float(p as u64)))
|
||||
}
|
||||
|
||||
fn span_part(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, class))
|
||||
}
|
||||
|
||||
fn span_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryCharacters")
|
||||
}
|
||||
|
||||
fn span_words(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryWords")
|
||||
}
|
||||
|
||||
fn span_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryParagraphs")
|
||||
}
|
||||
|
||||
fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> {
|
||||
let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p);
|
||||
let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?;
|
||||
Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part))
|
||||
}
|
||||
|
||||
fn part_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(text(match part {
|
||||
Part::Characters => "Characters",
|
||||
Part::Words => "Words",
|
||||
Part::Paragraphs => "Paragraphs",
|
||||
}))
|
||||
}
|
||||
|
||||
fn span_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
resolve(h, this_span(h, a)?)?;
|
||||
Ok(text("TextRange"))
|
||||
}
|
||||
|
||||
fn story_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_story(h, a)?;
|
||||
Ok(text("Story"))
|
||||
}
|
||||
|
||||
fn part_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
Ok(num(float(part_spans(&index, part, s, e).0.len() as u64)))
|
||||
}
|
||||
|
||||
fn part_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, _) = this_part(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, "StoryRange"))
|
||||
}
|
||||
|
||||
fn part_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let (index, s, e, stamp) = resolve(h, r)?;
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) };
|
||||
let span = match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange")))
|
||||
}
|
||||
|
||||
// ---- Stories ----
|
||||
|
||||
fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("Stories", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `document.stories`.
|
||||
pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember {
|
||||
get(link, doc_stories_impl)
|
||||
}
|
||||
|
||||
/// The first frame of each story of the document in paint order, kept while the document is
|
||||
/// unchanged.
|
||||
fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
let mut seen = HashSet::new();
|
||||
for thread in &st.doc.text_threads {
|
||||
let live: Vec<NodeId> = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect();
|
||||
if live.len() >= 2 {
|
||||
first.insert(live[0]);
|
||||
threaded.extend(live);
|
||||
}
|
||||
}
|
||||
let heads: Vec<NodeId> = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect();
|
||||
let heads = Rc::new(heads);
|
||||
*h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone()));
|
||||
Ok(heads)
|
||||
}
|
||||
|
||||
fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Stories")
|
||||
}
|
||||
|
||||
fn stories_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn stories_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
stories_doc(h, a)?;
|
||||
Ok(text("Stories"))
|
||||
}
|
||||
|
||||
fn stories_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn stories_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?;
|
||||
Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id })))
|
||||
}
|
||||
|
||||
/// `stories.index(key)`: by number, or by the name of a story's first frame.
|
||||
fn stories_index(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::Number(_) => match stories_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::String(name) => {
|
||||
let id = with_doc(h, doc, |_, st| {
|
||||
let list = heads(h, st)?;
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())))
|
||||
})?;
|
||||
id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- classes ----
|
||||
|
||||
/// A member of the range of a story of two or more frames that is not available yet: reading or
|
||||
/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out.
|
||||
fn range_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("TextRange.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
resolve(&h, this_span(&h, &a)?)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
|
||||
/// that the story is still there, and `reflect` leaves it out.
|
||||
fn story_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("Story.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
this_story(&h, &a)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// The members of `TextFrame` this module adds.
|
||||
pub(super) fn frame_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")),
|
||||
("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")),
|
||||
("story", get(l, frame_story), typed("Story")),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.story`.
|
||||
pub(super) fn range_member(l: &Link) -> Described {
|
||||
("story".into(), get(l, range_story), typed("Story"))
|
||||
}
|
||||
|
||||
/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut story = named(vec![
|
||||
("typename", get(l, story_typename), typed("string")),
|
||||
("parent", get(l, story_parent), typed("Document")),
|
||||
("length", get(l, story_length), typed("number")),
|
||||
("textFrames", get(l, story_frames), typed("Array")),
|
||||
("textRange", get(l, story_text_range), typed("*")),
|
||||
("characters", get(l, story_characters), collection("*")),
|
||||
("words", get(l, story_words), collection("*")),
|
||||
("paragraphs", get(l, story_paragraphs), collection("*")),
|
||||
]);
|
||||
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
|
||||
let mut range = named(vec![
|
||||
("typename", get(l, span_typename), typed("string")),
|
||||
("parent", get(l, span_story), typed("Story")),
|
||||
("story", get(l, span_story), typed("Story")),
|
||||
("contents", property(l, span_contents, span_set_contents), typed("string")),
|
||||
("start", read_only(l, span_start, "TextRange", "start"), typed("number")),
|
||||
("end", read_only(l, span_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", read_only(l, span_length, "TextRange", "length"), typed("number")),
|
||||
("characters", get(l, span_characters), collection("StoryCharacters")),
|
||||
("words", get(l, span_words), collection("StoryWords")),
|
||||
("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")),
|
||||
("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])),
|
||||
("remove", method(l, span_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"characterAttributes",
|
||||
"paragraphAttributes",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
"deSelect",
|
||||
"duplicate",
|
||||
"move",
|
||||
"getTextRunLength",
|
||||
"getLocalCharOverridesJSON",
|
||||
"getLocalParaOverridesJSON",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ATTRS.iter().map(|(n, _)| *n))
|
||||
.map(|m| range_later(l, m)),
|
||||
);
|
||||
let part = |name: &'static str| {
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("StoryRange")),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
class("Story", None, story, None),
|
||||
class("StoryRange", None, range, None),
|
||||
part("StoryCharacters"),
|
||||
part("StoryWords"),
|
||||
part("StoryParagraphs"),
|
||||
class(
|
||||
"Stories",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, stories_typename), typed("string")),
|
||||
("length", get(l, stories_length), typed("number")),
|
||||
("parent", get(l, stories_parent), typed("Document")),
|
||||
("index", method(l, stories_index), returns("number", &[("itemKey", "*")])),
|
||||
]),
|
||||
Some(function(l, stories_at)),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
//! Variables and data sets in the script object model: `Document.variables`, `dataSets`,
|
||||
//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`,
|
||||
//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the
|
||||
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Variables/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Variable/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/> describe them. Every change runs
|
||||
//! one of the `variable.*` and `dataset.*` commands.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change
|
||||
//! made through the object keeps the object working; once the name leaves the document any other
|
||||
//! way (a delete, a rename by another command, an undo, a kind change by another command, or an
|
||||
//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or
|
||||
//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most
|
||||
//! [`MAX_HANDLES`] of each.
|
||||
//! - Collections list variables and data sets in the order the document holds them, counted from
|
||||
//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`.
|
||||
//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first
|
||||
//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data
|
||||
//! set named `Data Set 1` and so on, which becomes the active one.
|
||||
//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`,
|
||||
//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file
|
||||
//! declared without one VectorCraft knows, and cannot be given.
|
||||
//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order.
|
||||
//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows
|
||||
//! its values in the art, as `display()` does.
|
||||
//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the
|
||||
//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the
|
||||
//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all.
|
||||
//! An embedded image (`RasterItem`) cannot take an image variable.
|
||||
//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the
|
||||
//! script may read, or write, as its `File` objects may: the files of the open documents do not
|
||||
//! count.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostItem, MemberInfo, Realm, RunError, file_ref_path, host_ref};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float,
|
||||
function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::doc::{DataSet, Node, Variable, VariableKind};
|
||||
use crate::file_access::Access;
|
||||
|
||||
/// The error for a `Variable` whose variable left the document, or that came from an earlier run.
|
||||
pub const STALE_VARIABLE: &str = "Stale variable";
|
||||
/// The error for a `Dataset` whose data set left the document, or that came from an earlier run.
|
||||
pub const STALE_DATASET: &str = "Stale data set";
|
||||
/// The most `Variable` objects, and the most `Dataset` objects, one run gives out.
|
||||
pub const MAX_HANDLES: usize = 10_000;
|
||||
|
||||
/// The kinds, each with the name of its `VariableKind` member.
|
||||
const KINDS: [(VariableKind, &str); 5] = [
|
||||
(VariableKind::Text, "TEXTUAL"),
|
||||
(VariableKind::Visibility, "VISIBILITY"),
|
||||
(VariableKind::Image, "IMAGE"),
|
||||
(VariableKind::Graph, "GRAPH"),
|
||||
(VariableKind::Unknown, "Unknown"),
|
||||
];
|
||||
|
||||
/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a
|
||||
/// variable (`None` for a data set) and whether it still names it.
|
||||
struct Entry {
|
||||
uid: u64,
|
||||
name: String,
|
||||
kind: Option<VariableKind>,
|
||||
alive: bool,
|
||||
}
|
||||
|
||||
/// The objects of one class a run gave out: each one's handle is its index here.
|
||||
#[derive(Default)]
|
||||
struct Table {
|
||||
entries: Vec<Entry>,
|
||||
/// The entry that names each document's name, while it does.
|
||||
live: HashMap<(u64, String), usize>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// The entry for `name` of the document `uid`, made when there is none.
|
||||
fn slot(&mut self, uid: u64, name: &str, kind: Option<VariableKind>, what: &str) -> std::result::Result<usize, HostError> {
|
||||
if let Some(&at) = self.live.get(&(uid, name.to_string()))
|
||||
&& self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind)
|
||||
{
|
||||
return Ok(at);
|
||||
}
|
||||
if self.entries.len() >= MAX_HANDLES {
|
||||
return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run")));
|
||||
}
|
||||
self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true });
|
||||
let at = self.entries.len() - 1;
|
||||
self.live.insert((uid, name.to_string()), at);
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// The entry `at` no longer names anything.
|
||||
fn kill(&mut self, at: usize) {
|
||||
if let Some(e) = self.entries.get_mut(at) {
|
||||
e.alive = false;
|
||||
let k = (e.uid, std::mem::take(&mut e.name));
|
||||
if self.live.get(&k) == Some(&at) {
|
||||
self.live.remove(&k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry `at` names `name`, of `kind`, from now on: a rename made through it.
|
||||
fn rename(&mut self, at: usize, name: &str, kind: Option<VariableKind>) {
|
||||
let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return };
|
||||
self.kill(at);
|
||||
if let Some(e) = self.entries.get_mut(at) {
|
||||
*e = Entry { uid, name: name.to_string(), kind, alive: true };
|
||||
}
|
||||
self.live.insert((uid, name.to_string()), at);
|
||||
}
|
||||
|
||||
/// Kills each live entry `keep` refuses.
|
||||
fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) {
|
||||
let gone: Vec<usize> = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect();
|
||||
for at in gone {
|
||||
self.kill(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last
|
||||
/// checked against it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Handles {
|
||||
vars: RefCell<Table>,
|
||||
sets: RefCell<Table>,
|
||||
seen: RefCell<Vec<(u64, u64)>>,
|
||||
}
|
||||
|
||||
/// The data sets of the active document before a command that may replace them (an import), while
|
||||
/// the run holds a `Dataset`; `None` for any other command.
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<DataSet>)> {
|
||||
if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let s = h.session.try_borrow().ok()?;
|
||||
s.active().map(|st| (st.uid, st.doc.variables.datasets.clone()))
|
||||
}
|
||||
|
||||
/// After each command a script runs: the objects whose variable or data set it removed stop
|
||||
/// working, so one made again under the same name does not bring them back. An import that leaves
|
||||
/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset`
|
||||
/// of that document, also when the new data sets reuse the names; an import that failed, was put
|
||||
/// back or left the data sets as they were stops none.
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<DataSet>)>) {
|
||||
let hs = &h.dom.vars;
|
||||
if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Ok(s) = h.session.try_borrow() else { return };
|
||||
let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid));
|
||||
let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect();
|
||||
let changed: HashSet<u64> = {
|
||||
let seen = hs.seen.borrow();
|
||||
now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect()
|
||||
};
|
||||
*hs.seen.borrow_mut() = now;
|
||||
if changed.is_empty() && replaced.is_none() {
|
||||
return;
|
||||
}
|
||||
let mut kinds: HashMap<u64, HashMap<&str, VariableKind>> = HashMap::new();
|
||||
let mut sets: HashMap<u64, HashSet<&str>> = HashMap::new();
|
||||
for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) {
|
||||
let vars = &st.doc.variables;
|
||||
kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect());
|
||||
sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect());
|
||||
}
|
||||
hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind);
|
||||
hs.sets
|
||||
.borrow_mut()
|
||||
.sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str()))));
|
||||
}
|
||||
|
||||
fn kind_text(k: VariableKind) -> Data {
|
||||
let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n);
|
||||
text(format!("VariableKind.{name}"))
|
||||
}
|
||||
|
||||
fn kind_of(d: &Data) -> std::result::Result<VariableKind, HostError> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k),
|
||||
_ => None,
|
||||
};
|
||||
match found {
|
||||
Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())),
|
||||
Some(k) => Ok(k),
|
||||
None => Err(HostError::Type("kind must be a VariableKind value".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes.
|
||||
fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> {
|
||||
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
|
||||
if s.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("the {what} is too long")));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The `name` field of a command's result.
|
||||
fn result_name(d: &Data) -> Option<String> {
|
||||
let Data::Object(o) = d else { return None };
|
||||
o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None })
|
||||
}
|
||||
|
||||
fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer {
|
||||
let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?;
|
||||
Ok(host_ref("Variable", &[float(h.run), float(at as u64)]))
|
||||
}
|
||||
|
||||
fn set_ref(h: &Host, uid: u64, name: &str) -> Answer {
|
||||
let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?;
|
||||
Ok(host_ref("Dataset", &[float(h.run), float(at as u64)]))
|
||||
}
|
||||
|
||||
/// A variable or data set an object names: its document, its handle's index and its name.
|
||||
struct Named {
|
||||
doc: Doc,
|
||||
at: usize,
|
||||
name: String,
|
||||
kind: Option<VariableKind>,
|
||||
}
|
||||
|
||||
/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its
|
||||
/// document.
|
||||
fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result<Named, HostError> {
|
||||
let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) };
|
||||
let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) };
|
||||
let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) };
|
||||
let stale = || HostError::Error(stale.into());
|
||||
if whole(run) != Some(h.run) {
|
||||
return Err(stale());
|
||||
}
|
||||
let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?;
|
||||
let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets };
|
||||
let (uid, name, kind) = {
|
||||
let t = table.borrow();
|
||||
let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?;
|
||||
(e.uid, e.name.clone(), e.kind)
|
||||
};
|
||||
let doc = find_doc(h, float(h.run), float(uid));
|
||||
let there = doc.is_some_and(|doc| {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() }
|
||||
})
|
||||
});
|
||||
match doc {
|
||||
Some(doc) if there => Ok(Named { doc, at, name, kind }),
|
||||
_ => {
|
||||
table.borrow_mut().kill(at);
|
||||
Err(stale())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn this_var(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
|
||||
named_of(h, arg(a, 0), true)
|
||||
}
|
||||
|
||||
fn this_set(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
|
||||
named_of(h, arg(a, 0), false)
|
||||
}
|
||||
|
||||
/// The index argument of a collection's indexer: a whole number, or `None`.
|
||||
fn index_arg(d: &Data) -> Option<usize> {
|
||||
match d {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Document ----
|
||||
|
||||
fn this_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Document")
|
||||
}
|
||||
|
||||
fn doc_variables(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Variables", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_datasets(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked)))
|
||||
}
|
||||
|
||||
/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so.
|
||||
fn doc_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) };
|
||||
if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) {
|
||||
Some(name) => set_ref(h, doc.uid, &name),
|
||||
None => Ok(Data::Null),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active
|
||||
/// one and the art already shows it.
|
||||
fn display(h: &Host, set: &Named) -> Answer {
|
||||
let shown = with_doc(h, set.doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values()))
|
||||
});
|
||||
if !shown {
|
||||
on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
if handle_of(arg(a, 1), "Dataset").is_none() {
|
||||
return Err(HostError::Type("activeDataset must be a Dataset".into()));
|
||||
}
|
||||
let set = named_of(h, arg(a, 1), false)?;
|
||||
if set.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("the data set is in another document".into()));
|
||||
}
|
||||
display(h, &set)
|
||||
}
|
||||
|
||||
/// The path of the `File` argument of `what`, which must be a file the script may reach for
|
||||
/// `access` through its own `File` objects.
|
||||
fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result<String, HostError> {
|
||||
let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) };
|
||||
if path.chars().count() > super::super::files::MAX_PATH_CHARS {
|
||||
return Err(HostError::Range(format!("{what}: the path is too long")));
|
||||
}
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
gate.check(path, access).map_err(HostError::Error)?;
|
||||
Ok(path.to_string())
|
||||
}
|
||||
|
||||
/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's
|
||||
/// variables and data sets with the library's.
|
||||
fn doc_import(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_arg(h, a, "importVariables", Access::Read)?;
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `exportVariables(file)`: `variable.saveLibrary` into the file.
|
||||
fn doc_export(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_arg(h, a, "exportVariables", Access::Write)?;
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Variables ----
|
||||
|
||||
fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Variables")
|
||||
}
|
||||
|
||||
fn vars_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
vars_doc(h, a)?;
|
||||
Ok(text("Variables"))
|
||||
}
|
||||
|
||||
fn vars_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64)))
|
||||
}
|
||||
|
||||
fn vars_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn vars_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) {
|
||||
Some(v) => var_ref(h, doc.uid, &v),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn vars_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let name = name_arg(arg(a, 1), "name")?;
|
||||
let found = with_doc(h, doc, |_, st| {
|
||||
h.charge_call(st.doc.variables.variables.len() as u64)?;
|
||||
Ok::<_, HostError>(st.doc.variables.variable(name).cloned())
|
||||
})?;
|
||||
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v))
|
||||
}
|
||||
|
||||
fn vars_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => vars_by_name(h, a),
|
||||
Data::Number(_) => match vars_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the
|
||||
/// first free name). → the new variable.
|
||||
fn vars_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let name = with_doc(h, doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
(1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default()
|
||||
});
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?;
|
||||
var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text })
|
||||
}
|
||||
|
||||
/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is
|
||||
/// none.
|
||||
fn vars_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect());
|
||||
if !names.is_empty() {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Variable ----
|
||||
|
||||
fn var_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_var(h, a)?;
|
||||
Ok(text("Variable"))
|
||||
}
|
||||
|
||||
fn var_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
Ok(doc_ref(h, v.doc.uid))
|
||||
}
|
||||
|
||||
fn var_name(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_var(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = text`: `variable.rename`, which trims it, with no command when the name stays.
|
||||
fn var_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
let to = name_arg(arg(a, 1), "name")?;
|
||||
if to.trim() == v.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?;
|
||||
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
|
||||
h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn var_kind(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown)))
|
||||
}
|
||||
|
||||
/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot
|
||||
/// hold it and drops the variable's values, with no command when the kind stays.
|
||||
fn var_set_kind(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
let kind = kind_of(arg(a, 1))?;
|
||||
if Some(kind) == v.kind {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?;
|
||||
h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn var_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
with_doc(h, v.doc, |_, st| {
|
||||
let ids: Vec<crate::NodeId> =
|
||||
st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
|
||||
if ids.len() > MAX_LISTED {
|
||||
return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects")));
|
||||
}
|
||||
h.charge_call(16 * ids.len() as u64)?;
|
||||
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values.
|
||||
fn var_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?;
|
||||
h.dom.vars.vars.borrow_mut().kill(v.at);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Datasets ----
|
||||
|
||||
fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Datasets")
|
||||
}
|
||||
|
||||
fn sets_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
sets_doc(h, a)?;
|
||||
Ok(text("Datasets"))
|
||||
}
|
||||
|
||||
fn sets_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64)))
|
||||
}
|
||||
|
||||
fn sets_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn sets_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) {
|
||||
Some(name) => set_ref(h, doc.uid, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn sets_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let name = name_arg(arg(a, 1), "name")?;
|
||||
let found = with_doc(h, doc, |_, st| {
|
||||
h.charge_call(st.doc.variables.datasets.len() as u64)?;
|
||||
Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone()))
|
||||
})?;
|
||||
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n))
|
||||
}
|
||||
|
||||
fn sets_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => sets_by_name(h, a),
|
||||
Data::Number(_) => match sets_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new
|
||||
/// data set and makes it the active one. → the new data set.
|
||||
fn sets_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?;
|
||||
let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?;
|
||||
set_ref(h, doc.uid, &name)
|
||||
}
|
||||
|
||||
/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is
|
||||
/// none.
|
||||
fn sets_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect());
|
||||
if !names.is_empty() {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Dataset ----
|
||||
|
||||
fn set_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_set(h, a)?;
|
||||
Ok(text("Dataset"))
|
||||
}
|
||||
|
||||
fn set_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
Ok(doc_ref(h, d.doc.uid))
|
||||
}
|
||||
|
||||
fn set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_set(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays.
|
||||
fn set_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
let to = name_arg(arg(a, 1), "name")?;
|
||||
if to.trim() == d.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?;
|
||||
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
|
||||
h.dom.vars.sets.borrow_mut().rename(d.at, &name, None);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_display(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
display(h, &d)
|
||||
}
|
||||
|
||||
/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no
|
||||
/// command when it already holds what the bound objects hold.
|
||||
fn set_update(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
let same = with_doc(h, d.doc, |_, st| {
|
||||
let doc = &st.doc;
|
||||
let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some());
|
||||
bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values()))
|
||||
});
|
||||
if !same {
|
||||
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `dataset.remove()`: `dataset.delete` of this data set.
|
||||
fn set_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?;
|
||||
h.dom.vars.sets.borrow_mut().kill(d.at);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Page items ----
|
||||
|
||||
/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its
|
||||
/// content.
|
||||
fn slot_kind(n: &Node, content: bool) -> std::result::Result<VariableKind, HostError> {
|
||||
if !content {
|
||||
return Ok(VariableKind::Visibility);
|
||||
}
|
||||
crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into()))
|
||||
}
|
||||
|
||||
/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's
|
||||
/// kind bound to the object, in the order the variables are defined, or `null`.
|
||||
fn binding(h: &Host, a: &[Data], content: bool) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let found = with_doc(h, item.doc, |_, st| {
|
||||
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let kind = slot_kind(n, content)?;
|
||||
let vars = &st.doc.variables;
|
||||
let bound = vars.bindings.get(&item.id);
|
||||
Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned())
|
||||
})?;
|
||||
match found {
|
||||
Some(v) => var_ref(h, item.doc.uid, &v),
|
||||
None => Ok(Data::Null),
|
||||
}
|
||||
}
|
||||
|
||||
/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of
|
||||
/// the object's document, or with none for `null`. No command runs when the object already has just
|
||||
/// that binding of the slot's kind.
|
||||
fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let variable = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "Variable").is_some() => {
|
||||
let v = named_of(h, d, true)?;
|
||||
if v.doc.uid != item.doc.uid {
|
||||
return Err(HostError::Error("the variable is in another document".into()));
|
||||
}
|
||||
Some(v.name)
|
||||
}
|
||||
_ => return Err(HostError::Type("give a Variable or null".into())),
|
||||
};
|
||||
let same = with_doc(h, item.doc, |_, st| {
|
||||
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let kind = slot_kind(n, content)?;
|
||||
let vars = &st.doc.variables;
|
||||
let bound = vars.bindings.get(&item.id);
|
||||
let held: Vec<&str> =
|
||||
vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect();
|
||||
Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::<Vec<_>>())
|
||||
})?;
|
||||
if !same {
|
||||
let slot = if content { "content" } else { "visibility" };
|
||||
edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn item_visibility(h: &Host, a: &[Data]) -> Answer {
|
||||
binding(h, a, false)
|
||||
}
|
||||
|
||||
fn item_set_visibility(h: &Host, a: &[Data]) -> Answer {
|
||||
set_binding(h, a, false)
|
||||
}
|
||||
|
||||
fn item_content(h: &Host, a: &[Data]) -> Answer {
|
||||
binding(h, a, true)
|
||||
}
|
||||
|
||||
fn item_set_content(h: &Host, a: &[Data]) -> Answer {
|
||||
set_binding(h, a, true)
|
||||
}
|
||||
|
||||
// ---- Registration ----
|
||||
|
||||
/// The members this module adds to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("variables", get(l, doc_variables), MemberInfo { collection: true, ..typed("Variables") }),
|
||||
("dataSets", get(l, doc_datasets), MemberInfo { collection: true, ..typed("Datasets") }),
|
||||
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset), typed("Dataset")),
|
||||
("variablesLocked", property(l, doc_locked, doc_set_locked), typed("boolean")),
|
||||
("importVariables", method(l, doc_import), returns("undefined", &[("fileSpec", "File")])),
|
||||
("exportVariables", method(l, doc_export), returns("undefined", &[("fileSpec", "File")])),
|
||||
])
|
||||
}
|
||||
|
||||
/// The members this module adds to `PageItem`.
|
||||
pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility), typed("Variable"))])
|
||||
}
|
||||
|
||||
/// The members this module adds to the page item class `class`.
|
||||
pub(super) fn item_members(l: &Link, class: &str) -> Vec<Described> {
|
||||
match class {
|
||||
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => {
|
||||
named(vec![("contentVariable", property(l, item_content, item_set_content), typed("Variable"))])
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The classes this module adds.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
vec![
|
||||
class(
|
||||
"Variables",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, vars_typename), typed("string")),
|
||||
("length", get(l, vars_length), typed("number")),
|
||||
("parent", get(l, vars_parent), typed("Document")),
|
||||
("index", method(l, vars_index), returns("Variable", &[("itemKey", "*")])),
|
||||
("getByName", method(l, vars_by_name), returns("Variable", &[("name", "string")])),
|
||||
("add", method(l, vars_add), returns("Variable", &[])),
|
||||
("removeAll", method(l, vars_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, vars_at)),
|
||||
),
|
||||
class(
|
||||
"Variable",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, var_typename), typed("string")),
|
||||
("parent", get(l, var_parent), typed("Document")),
|
||||
("name", property(l, var_name, var_set_name), typed("string")),
|
||||
("kind", property(l, var_kind, var_set_kind), typed("VariableKind")),
|
||||
("pageItems", get(l, var_page_items), typed("Array")),
|
||||
("remove", method(l, var_remove), returns("undefined", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
class(
|
||||
"Datasets",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, sets_typename), typed("string")),
|
||||
("length", get(l, sets_length), typed("number")),
|
||||
("parent", get(l, sets_parent), typed("Document")),
|
||||
("index", method(l, sets_index), returns("Dataset", &[("itemKey", "*")])),
|
||||
("getByName", method(l, sets_by_name), returns("Dataset", &[("name", "string")])),
|
||||
("add", method(l, sets_add), returns("Dataset", &[])),
|
||||
("removeAll", method(l, sets_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, sets_at)),
|
||||
),
|
||||
class(
|
||||
"Dataset",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, set_typename), typed("string")),
|
||||
("parent", get(l, set_parent), typed("Document")),
|
||||
("name", property(l, set_name, set_set_name), typed("string")),
|
||||
("display", method(l, set_display), returns("undefined", &[])),
|
||||
("update", method(l, set_update), returns("undefined", &[])),
|
||||
("remove", method(l, set_remove), returns("undefined", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings.
|
||||
pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> {
|
||||
let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect();
|
||||
realm.define_host_object("VariableKind", items)
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+311
-36
@@ -48,13 +48,16 @@
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
@@ -63,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::{
|
||||
@@ -135,7 +139,7 @@ impl Written {
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
/// The features `vc.api.has` knows.
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
@@ -204,6 +208,10 @@ 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>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -779,6 +787,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)>>,
|
||||
@@ -804,6 +815,15 @@ struct Host {
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
|
||||
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
|
||||
/// steps `app.doScript` plays read them here.
|
||||
artboard_picks: Option<(u64, Vec<usize>)>,
|
||||
/// The documents open when the run began as the person last left them, each with its own file
|
||||
/// and the file it was read from ([`crate::DocState::as_person_left`],
|
||||
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
|
||||
@@ -965,6 +985,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 };
|
||||
@@ -1107,6 +1143,20 @@ impl Host {
|
||||
self.pause.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about
|
||||
/// it, for [`Host::put_growth_back`].
|
||||
fn growth_mark(&self) -> (u64, u64, bool) {
|
||||
(self.objects.get(), self.bytes_kept.get(), self.waiting.get())
|
||||
}
|
||||
|
||||
/// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added
|
||||
/// it were put back.
|
||||
fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) {
|
||||
self.objects.set(objects);
|
||||
self.bytes_kept.set(bytes);
|
||||
self.waiting.set(waiting);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run in progress.
|
||||
@@ -1124,6 +1174,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
|
||||
@@ -1267,6 +1319,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));
|
||||
@@ -1314,6 +1367,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)
|
||||
{
|
||||
@@ -1350,16 +1404,17 @@ 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> {
|
||||
let id = id.to_string();
|
||||
let params = params.clone();
|
||||
// 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);
|
||||
let r = {
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, &id, ¶ms)
|
||||
step(&mut s, host, id, params)
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
let mut times = host.commands.borrow_mut();
|
||||
let row = times.entry(spec.id).or_insert((0, 0, 0));
|
||||
@@ -1372,13 +1427,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())),
|
||||
Err(e) => return Err(HostError::Error(e.to_string())),
|
||||
};
|
||||
let mark = host.growth_mark();
|
||||
let crossed = host.charge_growth(objects, added).and_then(|()| {
|
||||
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
|
||||
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
|
||||
host.charge_call(data_size(&data))?;
|
||||
Ok(data)
|
||||
});
|
||||
// A command whose result does not reach the script is put back, like one that failed.
|
||||
// A command whose result does not reach the script is put back, like one that failed, and so is
|
||||
// the growth it was charged.
|
||||
if crossed.is_err() {
|
||||
host.put_growth_back(mark);
|
||||
}
|
||||
if let Some(save) = save {
|
||||
let mut s = session.borrow_mut();
|
||||
if crossed.is_ok() {
|
||||
@@ -1387,12 +1447,82 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
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();
|
||||
@@ -1494,6 +1624,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![
|
||||
@@ -1508,9 +1639,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()));
|
||||
};
|
||||
@@ -1524,7 +1663,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),
|
||||
@@ -1623,7 +1762,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
/// `e`'s message, with what to do about a failure that comes from a script written for another
|
||||
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
|
||||
fn explained(e: &RunError) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
|
||||
const HOST_OBJECTS: &[&str] = &["BridgeTalk"];
|
||||
let message = &e.message;
|
||||
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
|
||||
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
|
||||
@@ -1634,6 +1773,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 {
|
||||
@@ -1889,6 +2044,32 @@ impl Session {
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run
|
||||
/// asked to stop no longer waits: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_window(&self) -> Option<ScriptUiDialog> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten()
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs
|
||||
/// one of its handlers. A run asked to stop is in none.
|
||||
pub fn script_window_showing(&self) -> Option<ScriptUiDialog> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten()
|
||||
}
|
||||
|
||||
/// Gives the ScriptUI dialog the running script waits at `event`; the next
|
||||
/// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still
|
||||
/// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]).
|
||||
pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) };
|
||||
with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into()))
|
||||
}
|
||||
|
||||
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
|
||||
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
|
||||
/// longer waits.
|
||||
@@ -1928,7 +2109,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()));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2016,13 +2197,28 @@ impl Session {
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
|
||||
}
|
||||
// The Artboard tool's selection, which the fresh tool state below drops.
|
||||
let picks = cmd::artboard_tool_picks(self);
|
||||
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
|
||||
self.reset_tool();
|
||||
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
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,
|
||||
@@ -2053,9 +2249,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.
|
||||
@@ -2093,7 +2288,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()),
|
||||
@@ -2124,6 +2319,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()),
|
||||
@@ -2134,7 +2330,10 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::default(),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
actions: request.actions,
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
@@ -2181,10 +2380,17 @@ impl Session {
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) })
|
||||
.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());
|
||||
@@ -2207,7 +2413,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 });
|
||||
@@ -2261,6 +2467,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;
|
||||
@@ -2269,6 +2497,12 @@ impl Session {
|
||||
}
|
||||
job.host.calls_this_slice.set(0);
|
||||
let outcome = run_slice(self, &mut job);
|
||||
// A failure a dialog recorded in the slice (steps a show left unused) ends the run, even
|
||||
// when the script went on.
|
||||
let outcome = match (outcome, job.host.dialogs.take_failure()) {
|
||||
(Ok(Ok(_)), Some(e)) => Ok(Err(e)),
|
||||
(outcome, _) => outcome,
|
||||
};
|
||||
match outcome {
|
||||
Err(panic) => {
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
|
||||
@@ -2280,24 +2514,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;
|
||||
@@ -2617,6 +2862,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(|| {
|
||||
@@ -2624,7 +2870,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 {
|
||||
@@ -2638,6 +2891,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)]
|
||||
@@ -2654,6 +2918,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)]
|
||||
@@ -2680,6 +2953,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`].
|
||||
|
||||
@@ -0,0 +1,736 @@
|
||||
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
|
||||
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
|
||||
//! person or `script.run`'s `answers` give back.
|
||||
//!
|
||||
//! A description lists the dialog first and each control after the container that holds it. It is
|
||||
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
|
||||
//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than
|
||||
//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`],
|
||||
//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its
|
||||
//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's
|
||||
//! or progress bar's value to its range.
|
||||
//!
|
||||
//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`,
|
||||
//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`,
|
||||
//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of
|
||||
//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by
|
||||
//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out
|
||||
//! with loops over the list, from the last control to the first for sizes and from the first to the
|
||||
//! last for places, so a description's nesting takes no native stack.
|
||||
//!
|
||||
//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window",
|
||||
//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change",
|
||||
//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an
|
||||
//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog
|
||||
//! waits it takes the next step; a dialog that waits with no step left, a step for a control the
|
||||
//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run.
|
||||
//!
|
||||
//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`],
|
||||
//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`].
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
|
||||
|
||||
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
|
||||
|
||||
use super::Host;
|
||||
|
||||
/// The largest size or place, in pixels, of a dialog or a control in it.
|
||||
pub const MAX_EXTENT: f32 = 8192.0;
|
||||
/// A character's width and a line's height in VectorCraft's size estimates, in pixels.
|
||||
const CHAR: f32 = 7.0;
|
||||
const LINE: f32 = 16.0;
|
||||
|
||||
/// A dialog's element.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UiKind {
|
||||
Dialog,
|
||||
Group,
|
||||
Panel,
|
||||
StaticText,
|
||||
EditText,
|
||||
Button,
|
||||
CheckBox,
|
||||
RadioButton,
|
||||
DropDownList,
|
||||
ListBox,
|
||||
Slider,
|
||||
ProgressBar,
|
||||
}
|
||||
|
||||
impl UiKind {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
Some(match s {
|
||||
"dialog" => Self::Dialog,
|
||||
"group" => Self::Group,
|
||||
"panel" => Self::Panel,
|
||||
"statictext" => Self::StaticText,
|
||||
"edittext" => Self::EditText,
|
||||
"button" => Self::Button,
|
||||
"checkbox" => Self::CheckBox,
|
||||
"radiobutton" => Self::RadioButton,
|
||||
"dropdownlist" => Self::DropDownList,
|
||||
"listbox" => Self::ListBox,
|
||||
"slider" => Self::Slider,
|
||||
"progressbar" => Self::ProgressBar,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does it hold controls?
|
||||
pub fn container(self) -> bool {
|
||||
matches!(self, Self::Dialog | Self::Group | Self::Panel)
|
||||
}
|
||||
|
||||
/// Does a click reach it?
|
||||
pub fn clicks(self) -> bool {
|
||||
matches!(self, Self::Button | Self::CheckBox | Self::RadioButton)
|
||||
}
|
||||
}
|
||||
|
||||
/// How a container places its controls.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Orientation {
|
||||
Row,
|
||||
Column,
|
||||
Stack,
|
||||
}
|
||||
|
||||
/// Where a control goes across its container: left or top, right or bottom, the middle, or the
|
||||
/// whole width or height.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Align {
|
||||
Start,
|
||||
End,
|
||||
Center,
|
||||
Fill,
|
||||
}
|
||||
|
||||
/// A control's place and size in the dialog, from its top left corner.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct UiRect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
/// One element of a [`ScriptUiDialog`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UiNode {
|
||||
pub kind: UiKind,
|
||||
/// A number no other element of the run has, which stays with the element while the script
|
||||
/// adds and removes controls; its index in the description when the description gives none.
|
||||
pub id: u64,
|
||||
/// The index of its container; the dialog's own is 0.
|
||||
pub parent: usize,
|
||||
pub name: String,
|
||||
pub text: String,
|
||||
/// It and every container around it are enabled.
|
||||
pub enabled: bool,
|
||||
/// It and every container around it are visible.
|
||||
pub visible: bool,
|
||||
/// A check box's or radio button's value.
|
||||
pub checked: bool,
|
||||
/// A slider's or progress bar's value, within `min` to `max`.
|
||||
pub value: f64,
|
||||
pub min: f64,
|
||||
pub max: f64,
|
||||
pub items: Vec<String>,
|
||||
/// How many times the script replaced a list's items (removed or added some), which tells a
|
||||
/// list from one that holds the same texts again.
|
||||
pub items_revision: u64,
|
||||
pub selection: Option<usize>,
|
||||
pub multiline: bool,
|
||||
pub readonly: bool,
|
||||
pub rect: UiRect,
|
||||
orientation: Orientation,
|
||||
align_children: (Option<Align>, Option<Align>),
|
||||
alignment: (Option<Align>, Option<Align>),
|
||||
spacing: f32,
|
||||
margins: [f32; 4],
|
||||
size: [Option<f32>; 2],
|
||||
min_size: [Option<f32>; 2],
|
||||
max_size: [Option<f32>; 2],
|
||||
bounds: Option<UiRect>,
|
||||
/// The characters an edit field or static text reserves room for in its width.
|
||||
characters: Option<f32>,
|
||||
}
|
||||
|
||||
impl UiNode {
|
||||
/// How much of a progress bar is done, from 0 to 1.
|
||||
pub fn fraction(&self) -> f32 {
|
||||
if self.max <= self.min || self.value <= self.min {
|
||||
return 0.0;
|
||||
}
|
||||
if self.value >= self.max {
|
||||
return 1.0;
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
// A range wider than the largest number is measured at half scale.
|
||||
let part =
|
||||
if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) };
|
||||
part.clamp(0.0, 1.0) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a run shows, checked and laid out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptUiDialog {
|
||||
/// The dialog first, then each control after the container that holds it.
|
||||
pub nodes: Vec<UiNode>,
|
||||
/// The button Enter clicks and the one Escape clicks.
|
||||
pub default_element: Option<usize>,
|
||||
pub cancel_element: Option<usize>,
|
||||
/// Which `show()` of the run this is, counted from 1; 0 before it shows.
|
||||
pub shown: u64,
|
||||
}
|
||||
|
||||
impl ScriptUiDialog {
|
||||
/// The dialog's title.
|
||||
pub fn title(&self) -> &str {
|
||||
self.nodes.first().map_or("", |n| n.text.as_str())
|
||||
}
|
||||
|
||||
/// The size of the dialog's content.
|
||||
pub fn size(&self) -> (f32, f32) {
|
||||
self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h))
|
||||
}
|
||||
|
||||
/// The first control whose name is `control`, or else the first control without a name
|
||||
/// whose text is `control`.
|
||||
pub fn find(&self, control: &str) -> Option<usize> {
|
||||
let by = |name: bool| {
|
||||
let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control };
|
||||
self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i)
|
||||
};
|
||||
by(true).or_else(|| by(false))
|
||||
}
|
||||
}
|
||||
|
||||
/// A value a control takes in a change.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiValue {
|
||||
Text(String),
|
||||
Number(f64),
|
||||
Index(Option<usize>),
|
||||
}
|
||||
|
||||
/// What the person did with a dialog.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiEvent {
|
||||
/// A click on a button, check box or radio button.
|
||||
Click(usize),
|
||||
/// A new value for an edit field, a slider or a list.
|
||||
Change(usize, UiValue),
|
||||
/// The dialog's close box.
|
||||
Close,
|
||||
}
|
||||
|
||||
impl UiEvent {
|
||||
/// The event as `show()` takes it.
|
||||
pub(crate) fn data(&self) -> Data {
|
||||
let event = |e: &str| ("event".to_string(), Data::String(e.into()));
|
||||
let id = |i: usize| ("id".to_string(), Data::Number(i as f64));
|
||||
match self {
|
||||
Self::Click(i) => Data::Object(vec![event("click"), id(*i)]),
|
||||
Self::Change(i, v) => {
|
||||
let value = match v {
|
||||
UiValue::Text(t) => Data::String(t.clone()),
|
||||
UiValue::Number(n) => Data::Number(*n),
|
||||
UiValue::Index(Some(k)) => Data::Number(*k as f64),
|
||||
UiValue::Index(None) => Data::Null,
|
||||
};
|
||||
Data::Object(vec![event("change"), id(*i), ("value".into(), value)])
|
||||
}
|
||||
Self::Close => Data::Object(vec![event("close")]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped
|
||||
/// to its range.
|
||||
pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result<UiEvent, String> {
|
||||
let id = match &event {
|
||||
UiEvent::Close => return Ok(event),
|
||||
UiEvent::Click(i) | UiEvent::Change(i, _) => *i,
|
||||
};
|
||||
let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) };
|
||||
if !n.enabled || !n.visible {
|
||||
return Err(format!("the control {} is disabled or hidden", label(n)));
|
||||
}
|
||||
match event {
|
||||
UiEvent::Click(_) if n.kind.clicks() => Ok(event),
|
||||
UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))),
|
||||
UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => {
|
||||
if t.len() > MAX_TEXT_BYTES {
|
||||
return Err("the text is longer than 16 KiB".into());
|
||||
}
|
||||
Ok(UiEvent::Change(id, UiValue::Text(t)))
|
||||
}
|
||||
UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => {
|
||||
Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max))))
|
||||
}
|
||||
UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k {
|
||||
Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))),
|
||||
k => Ok(UiEvent::Change(id, UiValue::Index(k))),
|
||||
},
|
||||
UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))),
|
||||
UiEvent::Close => Ok(UiEvent::Close),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(n: &UiNode) -> String {
|
||||
let shown = if n.name.is_empty() { &n.text } else { &n.name };
|
||||
super::dialogs::cut_to(shown, 64).to_string()
|
||||
}
|
||||
|
||||
/// A step of a `window` answer in `script.run`'s `answers`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UiStep {
|
||||
/// The control's name or text; none for a close.
|
||||
pub control: Option<String>,
|
||||
pub event: String,
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value}
|
||||
/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a
|
||||
/// number or null.
|
||||
pub(crate) fn parse_steps(v: &Value) -> Result<Vec<UiStep>, String> {
|
||||
let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) };
|
||||
list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect()
|
||||
}
|
||||
|
||||
fn step(s: &Value) -> Option<UiStep> {
|
||||
let o = s.as_object()?;
|
||||
if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) {
|
||||
return None;
|
||||
}
|
||||
let control = match o.get("control") {
|
||||
None => None,
|
||||
Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()),
|
||||
Some(_) => return None,
|
||||
};
|
||||
let value = o.get("value").cloned();
|
||||
let event = o.get("event").and_then(Value::as_str)?;
|
||||
let fits = match event {
|
||||
"close" => control.is_none() && value.is_none(),
|
||||
"click" => control.is_some() && value.is_none(),
|
||||
"change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)),
|
||||
_ => false,
|
||||
};
|
||||
fits.then(|| UiStep { control, event: event.to_string(), value })
|
||||
}
|
||||
|
||||
/// The event `step` is for `dialog`.
|
||||
pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEvent, String> {
|
||||
let Some(control) = &step.control else { return Ok(UiEvent::Close) };
|
||||
let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) };
|
||||
let event = match (step.event.as_str(), &step.value) {
|
||||
("click", _) => UiEvent::Click(id),
|
||||
(_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
|
||||
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) {
|
||||
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
|
||||
None => return Err("a list's `value` must be an item index or null".into()),
|
||||
},
|
||||
(_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))),
|
||||
(_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)),
|
||||
_ => return Err("a change's `value` must be a string, a number or null".into()),
|
||||
};
|
||||
check_event(dialog, event)
|
||||
}
|
||||
|
||||
/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as
|
||||
/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative
|
||||
/// number.
|
||||
pub fn list_index(n: &serde_json::Number) -> Option<usize> {
|
||||
if let Some(k) = n.as_u64() {
|
||||
return Some(usize::try_from(k).unwrap_or(usize::MAX));
|
||||
}
|
||||
let f = n.as_f64()?;
|
||||
// `as` saturates a whole number too large for usize at usize::MAX.
|
||||
(f >= 0.0 && f.fract() == 0.0).then_some(f as usize)
|
||||
}
|
||||
|
||||
fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data {
|
||||
fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v)
|
||||
}
|
||||
|
||||
fn bad(what: &str) -> HostError {
|
||||
HostError::Type(format!("show: the dialog's description {what}"))
|
||||
}
|
||||
|
||||
/// A finite number.
|
||||
fn number(d: &Data) -> Option<f64> {
|
||||
match d {
|
||||
Data::Number(n) if n.is_finite() => Some(*n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(d: &Data, what: &str) -> Result<String, HostError> {
|
||||
match d {
|
||||
Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()),
|
||||
Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))),
|
||||
_ => Err(bad(&format!("has no {what}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn extent(n: f64) -> f32 {
|
||||
(n as f32).clamp(-MAX_EXTENT, MAX_EXTENT)
|
||||
}
|
||||
|
||||
fn align_name(s: &str, horizontal: Option<bool>) -> Result<(Option<Align>, Option<Align>), HostError> {
|
||||
let a = match (s, horizontal) {
|
||||
("left", Some(true) | None) => (Some(Align::Start), None),
|
||||
("right", Some(true) | None) => (Some(Align::End), None),
|
||||
("top", Some(false) | None) => (None, Some(Align::Start)),
|
||||
("bottom", Some(false) | None) => (None, Some(Align::End)),
|
||||
("center", _) => (Some(Align::Center), Some(Align::Center)),
|
||||
("fill", _) => (Some(Align::Fill), Some(Align::Fill)),
|
||||
_ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))),
|
||||
};
|
||||
Ok(match horizontal {
|
||||
Some(true) => (a.0, None),
|
||||
Some(false) => (None, a.1),
|
||||
None => a,
|
||||
})
|
||||
}
|
||||
|
||||
fn alignment(d: &Data) -> Result<(Option<Align>, Option<Align>), HostError> {
|
||||
match d {
|
||||
Data::Null | Data::Undefined => Ok((None, None)),
|
||||
Data::String(s) => align_name(s, None),
|
||||
Data::Array(a) if a.len() == 2 => {
|
||||
let part = |d: &Data, h: bool| match d {
|
||||
Data::String(s) => align_name(s, Some(h)),
|
||||
_ => Err(bad("has an alignment that is not a name")),
|
||||
};
|
||||
Ok((part(&a[0], true)?.0, part(&a[1], false)?.1))
|
||||
}
|
||||
_ => Err(bad("has an alignment that is not a name or a pair of names")),
|
||||
}
|
||||
}
|
||||
|
||||
fn numbers<const N: usize>(d: &Data) -> Result<Option<[f64; N]>, HostError> {
|
||||
match d {
|
||||
Data::Null | Data::Undefined => Ok(None),
|
||||
Data::Array(a) if a.len() == N => {
|
||||
let mut out = [0.0; N];
|
||||
for (o, v) in out.iter_mut().zip(a) {
|
||||
*o = number(v).ok_or_else(|| bad("has a size that is not a number"))?;
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
_ => Err(bad("has a size with the wrong count of numbers")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads, checks and lays out a dialog's description.
|
||||
pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
let Data::Object(top) = d else { return Err(bad("is not an object")) };
|
||||
let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) };
|
||||
if list.is_empty() {
|
||||
return Err(bad("has no dialog"));
|
||||
}
|
||||
if list.len() > MAX_CONTROLS + 1 {
|
||||
return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls")));
|
||||
}
|
||||
let mut nodes: Vec<UiNode> = Vec::with_capacity(list.len());
|
||||
let mut depth: Vec<usize> = Vec::with_capacity(list.len());
|
||||
let mut items_total = 0usize;
|
||||
for (i, n) in list.iter().enumerate() {
|
||||
let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) };
|
||||
let kind = match field(f, "kind") {
|
||||
Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?,
|
||||
_ => return Err(bad("has a control without a kind")),
|
||||
};
|
||||
let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?;
|
||||
let parent = if i == 0 {
|
||||
if kind != UiKind::Dialog || parent != -1.0 {
|
||||
return Err(bad("does not start with the dialog"));
|
||||
}
|
||||
0
|
||||
} else {
|
||||
let p = parent as usize;
|
||||
if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog {
|
||||
return Err(bad("has a control before its container"));
|
||||
}
|
||||
if !nodes[p].kind.container() {
|
||||
return Err(bad("has a control inside a control that holds none"));
|
||||
}
|
||||
p
|
||||
};
|
||||
let level = if i == 0 { 0 } else { depth[parent] + 1 };
|
||||
if level > MAX_DEPTH {
|
||||
return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep")));
|
||||
}
|
||||
depth.push(level);
|
||||
let flag = |name: &str| matches!(field(f, name), Data::Bool(true));
|
||||
let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) };
|
||||
let items = match field(f, "items") {
|
||||
Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::<Result<Vec<_>, _>>()?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
items_total = items_total.saturating_add(items.len());
|
||||
if items_total > MAX_ITEMS {
|
||||
return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all")));
|
||||
}
|
||||
let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len());
|
||||
let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0));
|
||||
if min > max {
|
||||
return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into()));
|
||||
}
|
||||
let orientation = match field(f, "orientation") {
|
||||
Data::String(s) if s == "row" => Orientation::Row,
|
||||
Data::String(s) if s == "column" => Orientation::Column,
|
||||
Data::String(s) if s == "stack" => Orientation::Stack,
|
||||
Data::Undefined => Orientation::Column,
|
||||
_ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())),
|
||||
};
|
||||
let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| {
|
||||
let (l, t) = (extent(l), extent(t));
|
||||
UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) }
|
||||
});
|
||||
// A width or height of 0 or less leaves that side to the layout.
|
||||
let sides = |name: &str| -> Result<[Option<f32>; 2], HostError> {
|
||||
Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]))
|
||||
};
|
||||
let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?);
|
||||
let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0)));
|
||||
nodes.push(UiNode {
|
||||
kind,
|
||||
id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64),
|
||||
parent,
|
||||
name: text(field(f, "name"), "a control's name")?,
|
||||
text: text(field(f, "text"), "a control's text")?,
|
||||
enabled: flag("enabled") && parent_enabled,
|
||||
visible: flag("visible") && parent_visible,
|
||||
checked: flag("value"),
|
||||
value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max),
|
||||
min,
|
||||
max,
|
||||
items,
|
||||
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
|
||||
selection,
|
||||
multiline: flag("multiline"),
|
||||
readonly: flag("readonly"),
|
||||
rect: UiRect::default(),
|
||||
orientation,
|
||||
align_children: alignment(field(f, "alignChildren"))?,
|
||||
alignment: alignment(field(f, "alignment"))?,
|
||||
spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)),
|
||||
margins,
|
||||
size,
|
||||
min_size,
|
||||
max_size,
|
||||
bounds,
|
||||
// At most as many characters as the longest text holds.
|
||||
characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)),
|
||||
});
|
||||
}
|
||||
let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button));
|
||||
let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement"));
|
||||
let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 };
|
||||
layout(&mut dialog);
|
||||
Ok(dialog)
|
||||
}
|
||||
|
||||
/// A control's own size, by VectorCraft's estimates.
|
||||
fn own_size(n: &UiNode) -> [f32; 2] {
|
||||
let chars = |s: &str| s.chars().count() as f32;
|
||||
let widest = |lines: &mut dyn Iterator<Item = &str>| lines.map(chars).fold(0.0, f32::max);
|
||||
let lines = |s: &str| s.lines().count().max(1) as f32;
|
||||
let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max);
|
||||
// `characters` reserves room for that many characters, however long the text is now.
|
||||
let reserved = n.characters.unwrap_or(0.0);
|
||||
match n.kind {
|
||||
UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0],
|
||||
UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0],
|
||||
UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0],
|
||||
UiKind::EditText if n.multiline => {
|
||||
[(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0]
|
||||
}
|
||||
UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0],
|
||||
UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0],
|
||||
UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0],
|
||||
UiKind::Slider => [160.0, 20.0],
|
||||
UiKind::ProgressBar => [160.0, 12.0],
|
||||
UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays the dialog out: each control's size from the last to the first, then each place from the
|
||||
/// first to the last.
|
||||
fn layout(d: &mut ScriptUiDialog) {
|
||||
let n = d.nodes.len();
|
||||
let mut kids: Vec<Vec<usize>> = vec![Vec::new(); n];
|
||||
for (i, node) in d.nodes.iter().enumerate().skip(1) {
|
||||
kids[node.parent].push(i);
|
||||
}
|
||||
let mut size = vec![[0.0f32; 2]; n];
|
||||
for i in (0..n).rev() {
|
||||
let node = &d.nodes[i];
|
||||
let mut s = if node.kind.container() {
|
||||
let [l, t, r, b] = node.margins;
|
||||
let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]);
|
||||
for &k in &kids[i] {
|
||||
// A hidden control, and everything in it, takes no room.
|
||||
if !d.nodes[k].visible {
|
||||
continue;
|
||||
}
|
||||
if let Some(bounds) = d.nodes[k].bounds {
|
||||
reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)];
|
||||
continue;
|
||||
}
|
||||
let [w, h] = size[k];
|
||||
count += 1;
|
||||
match node.orientation {
|
||||
Orientation::Row => (main, cross) = (main + w, cross.max(h)),
|
||||
Orientation::Column => (main, cross) = (main + h, cross.max(w)),
|
||||
Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)),
|
||||
}
|
||||
}
|
||||
if node.orientation != Orientation::Stack {
|
||||
main += node.spacing * count.saturating_sub(1) as f32;
|
||||
}
|
||||
let (w, h) = match node.orientation {
|
||||
Orientation::Row | Orientation::Stack => (main, cross),
|
||||
Orientation::Column => (cross, main),
|
||||
};
|
||||
[(w + l + r).max(reach[0]), (h + t + b).max(reach[1])]
|
||||
} else {
|
||||
own_size(node)
|
||||
};
|
||||
for axis in 0..2 {
|
||||
if let Some(v) = node.size[axis] {
|
||||
s[axis] = v;
|
||||
}
|
||||
if let Some(v) = node.min_size[axis] {
|
||||
s[axis] = s[axis].max(v);
|
||||
}
|
||||
if let Some(v) = node.max_size[axis] {
|
||||
s[axis] = s[axis].min(v);
|
||||
}
|
||||
}
|
||||
if let Some(b) = node.bounds {
|
||||
s = [b.w, b.h];
|
||||
}
|
||||
size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)];
|
||||
}
|
||||
d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] };
|
||||
for i in 0..n {
|
||||
if !d.nodes[i].kind.container() {
|
||||
continue;
|
||||
}
|
||||
let node = d.nodes[i].clone();
|
||||
let [l, t, r, b] = node.margins;
|
||||
let (x, y) = (node.rect.x + l, node.rect.y + t);
|
||||
let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0));
|
||||
let mut cursor = 0.0f32;
|
||||
for &k in &kids[i] {
|
||||
let kid = &d.nodes[k];
|
||||
let rect = if !kid.visible {
|
||||
UiRect { x, y, w: 0.0, h: 0.0 }
|
||||
} else if let Some(bounds) = kid.bounds {
|
||||
UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h }
|
||||
} else {
|
||||
let [w, h] = size[k];
|
||||
let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center);
|
||||
let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center);
|
||||
let max = kid.max_size;
|
||||
// A control that fills its container's room stays within its maximum.
|
||||
let place = |align: Align, own: f32, room: f32, axis: usize| match align {
|
||||
Align::Start => (0.0, own),
|
||||
Align::End => ((room - own).max(0.0), own),
|
||||
Align::Center => (((room - own) / 2.0).max(0.0), own),
|
||||
Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))),
|
||||
};
|
||||
match node.orientation {
|
||||
Orientation::Row => {
|
||||
let (dy, kh) = place(v_align, h, ch, 1);
|
||||
let r = UiRect { x: x + cursor, y: y + dy, w, h: kh };
|
||||
cursor += w + node.spacing;
|
||||
r
|
||||
}
|
||||
Orientation::Column => {
|
||||
let (dx, kw) = place(h_align, w, cw, 0);
|
||||
let r = UiRect { x: x + dx, y: y + cursor, w: kw, h };
|
||||
cursor += h + node.spacing;
|
||||
r
|
||||
}
|
||||
Orientation::Stack => {
|
||||
let (dx, kw) = place(h_align, w, cw, 0);
|
||||
let (dy, kh) = place(v_align, h, ch, 1);
|
||||
UiRect { x: x + dx, y: y + dy, w: kw, h: kh }
|
||||
}
|
||||
}
|
||||
};
|
||||
d.nodes[k].rect = UiRect {
|
||||
x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT),
|
||||
y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT),
|
||||
w: rect.w.clamp(0.0, MAX_EXTENT),
|
||||
h: rect.h.clamp(0.0, MAX_EXTENT),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it
|
||||
/// took.
|
||||
pub(crate) struct Showing {
|
||||
pub(crate) dialog: ScriptUiDialog,
|
||||
pub(crate) steps: Option<std::collections::VecDeque<UiStep>>,
|
||||
pub(crate) events: u64,
|
||||
}
|
||||
|
||||
impl Showing {
|
||||
/// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`,
|
||||
/// `"missing"` or `"error"`.
|
||||
pub(crate) fn record(&self, answer: Value) -> Value {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!("window"));
|
||||
r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES)));
|
||||
r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1)));
|
||||
r.insert("events".into(), json!(self.events));
|
||||
r.insert("answer".into(), answer);
|
||||
Value::Object(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The host function `name` of `Window`, for the run `link` holds.
|
||||
fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
|
||||
let l = link.clone();
|
||||
HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a)))
|
||||
}
|
||||
|
||||
/// Adds `Window` to the realm, for the run `link` holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
|
||||
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
|
||||
}
|
||||
|
||||
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
parse(args.first().unwrap_or(&Data::Undefined))
|
||||
}
|
||||
|
||||
fn open(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let dialog = described(host, args)?;
|
||||
host.dialogs.window_open(dialog)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn wait(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let dialog = described(host, args)?;
|
||||
host.dialogs.window_wait(dialog)
|
||||
}
|
||||
|
||||
fn end(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0);
|
||||
let normal = matches!(args.get(1), Some(Data::Bool(true)));
|
||||
host.dialogs.window_end(result, normal)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
Reference in new issue
Block a user