mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main into fix/appearance-well-spacing
This commit is contained in:
commit
33748616bc
23 files changed
+2727
-58
No files matched your search
@@ -855,7 +855,7 @@ pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, s
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
|
||||
@@ -682,6 +682,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"text.thread.info",
|
||||
"text.thread.releaseSelection",
|
||||
"text.thread.remove",
|
||||
"text.thread.setNeighbor",
|
||||
"text.touchType",
|
||||
"threeD.addGraphic",
|
||||
"threeD.mapArt",
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul
Line truncated
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
if s.script_frames && !answers.is_empty() {
|
||||
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
|
||||
}
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let mut checked_real = None;
|
||||
@@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -442,6 +444,7 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
|
||||
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.setNeighbor",
|
||||
"Thread Text",
|
||||
[],
|
||||
None,
|
||||
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
|
||||
has_doc,
|
||||
set_neighbor
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
|
||||
/// a path, each once, or `id` alone when it is in no thread.
|
||||
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(d, id);
|
||||
let mut seen = Ids::default();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
fn chain_ids(chains: &[&[NodeId]]) -> Value {
|
||||
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
|
||||
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.setNeighbor";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let next = match p.get("side").and_then(Value::as_str) {
|
||||
Some("next") => true,
|
||||
Some("previous") => false,
|
||||
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
|
||||
};
|
||||
let neighbor = match p.get("neighbor") {
|
||||
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(checked_id(s, v, C)?),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if text_of(d, id).is_none() {
|
||||
return Err(bad(C, "`id` must be area type or type on a path"));
|
||||
}
|
||||
let locked = |frames: &[NodeId]| {
|
||||
let editable = d.editable();
|
||||
frames.iter().any(|f| !editable(*f))
|
||||
};
|
||||
let chain = chain_of(d, id);
|
||||
let Some(n) = neighbor else {
|
||||
// Break the link on that side: the frames before it and the frames after it.
|
||||
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
|
||||
let at = if next { i + 1 } else { i };
|
||||
if at == 0 || at >= chain.len() {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
|
||||
}
|
||||
if locked(&chain) {
|
||||
return Err(bad(C, "a frame of the story is hidden or locked"));
|
||||
}
|
||||
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
|
||||
let cut: Ids = chain.iter().copied().collect();
|
||||
s.edit("Break Thread", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
|
||||
for part in [&head, &tail] {
|
||||
if part.len() >= 2 {
|
||||
d.text_threads.push(part.clone());
|
||||
}
|
||||
}
|
||||
// The first frame after the break starts its story, which flows again on this edit so
|
||||
// that its numbered paragraphs count from 1.
|
||||
if let Some(f) = tail.first() {
|
||||
touch(d, *f);
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
|
||||
};
|
||||
if n == id {
|
||||
return Err(bad(C, "a frame cannot be linked to itself"));
|
||||
}
|
||||
if text_of(d, n).is_none() {
|
||||
return Err(bad(C, "`neighbor` must be area type or type on a path"));
|
||||
}
|
||||
// `first` is to flow into `second`.
|
||||
let (first, second) = if next { (id, n) } else { (n, id) };
|
||||
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
|
||||
if a.contains(&second) {
|
||||
if a.windows(2).any(|w| w == [first, second]) {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
|
||||
}
|
||||
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
|
||||
}
|
||||
if a.last() != Some(&first) {
|
||||
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
|
||||
}
|
||||
if b.first() != Some(&second) {
|
||||
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
|
||||
}
|
||||
if locked(&a) || locked(&b) {
|
||||
return Err(bad(C, "a frame of either story is hidden or locked"));
|
||||
}
|
||||
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
|
||||
let affected: Ids = joined.iter().copied().collect();
|
||||
s.edit("Thread Text", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
|
||||
d.text_threads.push(joined.clone());
|
||||
// Force a re-flow of the joined story on this edit.
|
||||
touch(d, first);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -293,7 +293,7 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
@@ -301,7 +301,7 @@ fn typed(data_type: &str) -> MemberInfo {
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
@@ -309,7 +309,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -571,7 +571,7 @@ struct Frame {
|
||||
}
|
||||
|
||||
/// The index of the active artboard of `st`, as the view keeps it.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
pub(super) fn active_artboard(st: &DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
@@ -2672,6 +2672,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
@@ -2740,6 +2741,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
|
||||
@@ -50,6 +50,8 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod threads;
|
||||
|
||||
/// The error of a text range, or of a collection of one, whose frame's text changed other than
|
||||
/// through the object model.
|
||||
pub const STALE_RANGE: &str = "Stale text range";
|
||||
@@ -194,6 +196,7 @@ pub(in crate::script) struct TextState {
|
||||
/// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character
|
||||
/// names that is not installed is added at the end.
|
||||
fonts: RefCell<Option<Vec<(String, String)>>>,
|
||||
stories: threads::StoryState,
|
||||
/// The number of text range objects made, which numbers the next one.
|
||||
made: Cell<u64>,
|
||||
/// The span of each range object, by its number, whose `length` the script set.
|
||||
@@ -609,7 +612,10 @@ fn range_set_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(n) = usize_of(n).filter(|n| *n <= left) else {
|
||||
return Err(HostError::Range(format!("length must be a whole number from 0 to {left}")));
|
||||
};
|
||||
h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp));
|
||||
// An end inside a surrogate pair moves out to the end of its character.
|
||||
let end = s + n;
|
||||
let end = index.chars.get(index.chars.partition_point(|&c| c < end)).copied().unwrap_or(end);
|
||||
h.dom.text.resized.borrow_mut().insert(number, (s, end, stamp));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1322,39 +1328,54 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
|
||||
return Err(HostError::Error(super::CROSS_DOCUMENT.into()));
|
||||
}
|
||||
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
|
||||
return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into()));
|
||||
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
|
||||
}
|
||||
let orientation = if on_path { 4 } else { 2 };
|
||||
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
|
||||
let vertical = vertical_of(arg(a, orientation))?;
|
||||
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
|
||||
if base.is_some() {
|
||||
threads::check_base_path(h, path)?;
|
||||
}
|
||||
let mode = if on_path { "onPath" } else { "area" };
|
||||
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
|
||||
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?;
|
||||
new_ref(h, doc, result_id(&r))
|
||||
let id = result_id(&r);
|
||||
if let (Some((base, postfix)), Some(id)) = (base, id) {
|
||||
threads::thread_new(h, base, id, postfix)?;
|
||||
}
|
||||
new_ref(h, doc, id)
|
||||
}
|
||||
|
||||
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
|
||||
fn frames_area_text(h: &Host, a: &[Data]) -> Answer {
|
||||
in_path(h, a, false, &[3, 4])
|
||||
in_path(h, a, false, &[])
|
||||
}
|
||||
|
||||
/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`.
|
||||
fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
in_path(h, a, true, &[2, 3, 5, 6])
|
||||
in_path(h, a, true, &[2, 3])
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first.
|
||||
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
|
||||
/// locked artboard, stops it first, as `PageItems.removeAll()` does.
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused)
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused, on_locked)
|
||||
});
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
@@ -1525,6 +1546,23 @@ fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for character attribute `attr`.
|
||||
fn attr_type(attr: Attr) -> &'static str {
|
||||
match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for paragraph attribute `attr`.
|
||||
fn para_type(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "Justification",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
fn attr_members(link: &Link) -> Vec<Described> {
|
||||
let mut out = Vec::new();
|
||||
for (name, attr) in ATTRS {
|
||||
@@ -1540,12 +1578,7 @@ fn attr_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_attr(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(attr_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1565,8 +1598,7 @@ fn para_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_para(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(para_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1592,27 +1624,26 @@ pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunErr
|
||||
|
||||
/// The classes of type, `TextFrame` among them, which inherits from `PageItem`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut frame = named(vec![
|
||||
("kind", get(l, frame_kind), typed("TextType")),
|
||||
("contents", property(l, frame_contents, frame_set_contents), typed("string")),
|
||||
("textRange", get(l, frame_range), typed("TextRange")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")),
|
||||
("createOutline", method(l, frame_outline), returns("GroupItem", &[])),
|
||||
("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])),
|
||||
("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])),
|
||||
]);
|
||||
frame.extend(super::variables::item_members(l, "TextFrame"));
|
||||
frame.extend(threads::frame_members(l));
|
||||
frame.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"nextFrame",
|
||||
"previousFrame",
|
||||
"textPath",
|
||||
"anchor",
|
||||
"antialias",
|
||||
@@ -1637,9 +1668,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("end", read_only(l, range_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", property(l, range_length, range_set_length), typed("number")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")),
|
||||
("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")),
|
||||
("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])),
|
||||
@@ -1647,13 +1678,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, range_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(attr_members(l));
|
||||
range.push(threads::range_member(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
@@ -1676,8 +1707,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("*")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])),
|
||||
("parent", get(l, part_parent), typed("TextRange")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string"), ("relativeObject", "TextRange")])),
|
||||
("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
@@ -1687,7 +1718,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
chars.extend(attr_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
let stories = threads::classes(l);
|
||||
let mut out = vec![
|
||||
class("TextFrame", Some("PageItem"), frame, None),
|
||||
class("TextRange", None, range, None),
|
||||
part("Characters"),
|
||||
@@ -1702,12 +1734,29 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", get(l, frames_typename), typed("string")),
|
||||
("length", get(l, frames_length), typed("number")),
|
||||
("parent", get(l, frames_parent), typed("Document")),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
|
||||
("add", method(l, frames_add), returns("TextFrame", &[])),
|
||||
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
|
||||
("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])),
|
||||
("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])),
|
||||
(
|
||||
"areaText",
|
||||
method(l, frames_area_text),
|
||||
returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation"), ("baseFrame", "TextFrame")]),
|
||||
),
|
||||
(
|
||||
"pathText",
|
||||
method(l, frames_path_text),
|
||||
returns(
|
||||
"TextFrame",
|
||||
&[
|
||||
("textPath", "PathItem"),
|
||||
("startTValue", "number"),
|
||||
("endTValue", "number"),
|
||||
("orientation", "TextOrientation"),
|
||||
("baseFrame", "TextFrame"),
|
||||
],
|
||||
),
|
||||
),
|
||||
("removeAll", method(l, frames_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, frames_at)),
|
||||
@@ -1719,7 +1768,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", typename_of("TextFonts"), typed("string")),
|
||||
("length", get(l, fonts_length), typed("number")),
|
||||
("parent", get(l, app_ref), typed("Application")),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])),
|
||||
]),
|
||||
Some(function(l, fonts_at)),
|
||||
@@ -1736,7 +1785,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
]),
|
||||
None,
|
||||
),
|
||||
]
|
||||
];
|
||||
out.extend(stories);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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)),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -48,6 +48,7 @@
|
||||
//! 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;
|
||||
@@ -206,6 +207,8 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -806,6 +809,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
|
||||
@@ -2063,6 +2075,9 @@ 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));
|
||||
@@ -2182,6 +2197,9 @@ impl Session {
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
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()
|
||||
|
||||
@@ -175,6 +175,7 @@ mod repeat_edit;
|
||||
mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_actions;
|
||||
mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
@@ -187,6 +188,7 @@ mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_tags;
|
||||
mod script_text;
|
||||
mod script_threads;
|
||||
mod script_variables;
|
||||
mod script_xmp;
|
||||
mod scripts;
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
|
||||
}
|
||||
|
||||
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
|
||||
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error message a `try` around `call` logs, or `"ok"`.
|
||||
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
|
||||
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
|
||||
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn objects(s: &Session) -> usize {
|
||||
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
|
||||
}
|
||||
|
||||
fn undo_labels(s: &Session) -> Vec<String> {
|
||||
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
|
||||
}
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
|
||||
}
|
||||
|
||||
/// One set, `Set`, with the actions given as (name, steps).
|
||||
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
|
||||
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
|
||||
let mut s = doc();
|
||||
let before = undo_labels(&s);
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
|
||||
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
|
||||
assert_eq!(objects(&s), 3);
|
||||
let after = undo_labels(&s);
|
||||
assert_eq!(after.len(), before.len() + 1, "{after:?}");
|
||||
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
|
||||
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
|
||||
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
|
||||
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
|
||||
assert_eq!(objects(&s), 6);
|
||||
let r0 = run_with(&mut s, "1;", &batch).unwrap();
|
||||
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_throw_puts_back_what_the_action_did() {
|
||||
let mut s = doc();
|
||||
let before = (objects(&s), undo_labels(&s));
|
||||
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
|
||||
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains("late"), "{e}");
|
||||
assert_eq!((objects(&s), undo_labels(&s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
|
||||
let mut s = doc();
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
|
||||
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
|
||||
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_matched_exactly_and_must_be_one_action() {
|
||||
let mut s = doc();
|
||||
let actions = json!([
|
||||
{"set": "Set", "name": "One", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
|
||||
{"set": "Set", "name": "Empty", "steps": []},
|
||||
]);
|
||||
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
|
||||
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
|
||||
assert_eq!(objects(&s), 0);
|
||||
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
|
||||
assert_eq!(objects(&s), 1);
|
||||
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
|
||||
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let mut s = doc();
|
||||
let actions = set(&[("One", vec![rect(0)])]);
|
||||
for (call, want) in [
|
||||
("app.doScript()", "TypeError"),
|
||||
("app.doScript(1, 'Set')", "TypeError"),
|
||||
("app.doScript('One', {})", "TypeError"),
|
||||
("app.doScript('One', 'Set', 'yes')", "TypeError"),
|
||||
("app.doScript('One', 'Set', 1)", "TypeError"),
|
||||
("app.doScript('One', 'Set', false, 4)", "TypeError"),
|
||||
("app.doScript('', 'Set')", "Error"),
|
||||
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
|
||||
] {
|
||||
let m = caught(&mut s, call, &actions);
|
||||
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
|
||||
}
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
|
||||
let mut s = doc();
|
||||
s.prefs.show_external_script_warning = true;
|
||||
let steps = [
|
||||
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
|
||||
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
|
||||
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
|
||||
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
|
||||
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
|
||||
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
|
||||
];
|
||||
for (bad, want) in steps {
|
||||
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
|
||||
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
|
||||
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
|
||||
assert_eq!(objects(&s), 0, "{bad}: no step ran");
|
||||
}
|
||||
assert!(s.prefs.show_external_script_warning);
|
||||
// A refused command inside a recorded batch is refused too.
|
||||
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
|
||||
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
|
||||
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
|
||||
let batch = set(&[("F", vec![rect(0), files])]);
|
||||
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
|
||||
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
|
||||
assert_eq!(objects(&s), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_step_keeps_the_scripts_file_gate() {
|
||||
let mut s = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
|
||||
let actions = set(&[("Export", vec![export])]);
|
||||
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
|
||||
assert!(m.contains("Script file access denied"), "{m}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_action_is_held_to_the_host_call_limit() {
|
||||
let mut s = doc();
|
||||
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
|
||||
// steps of one call cannot pass the limit.
|
||||
let calls = |s: &mut Session, steps: usize| {
|
||||
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
|
||||
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
|
||||
};
|
||||
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
|
||||
assert!(many >= one + 2000, "{one} {many}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_action_lists_are_refused_before_the_script_runs() {
|
||||
let mut s = doc();
|
||||
let step = || json!({"command": "select.none"});
|
||||
let cases = [
|
||||
(json!({}), "`actions` must be a list"),
|
||||
(json!([1]), "`actions[0]` must be an object"),
|
||||
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
|
||||
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
|
||||
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
|
||||
(
|
||||
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
|
||||
"a command.batch inside a command.batch",
|
||||
),
|
||||
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
|
||||
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
|
||||
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
|
||||
];
|
||||
for (actions, want) in cases {
|
||||
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{want}: {e}");
|
||||
}
|
||||
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
|
||||
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 100000 steps in all"), "{e}");
|
||||
assert_eq!(objects(&s), 0, "no run started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
|
||||
let mut s = doc();
|
||||
let first = set(&[("One", vec![rect(0)])]);
|
||||
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
|
||||
assert_eq!(objects(&s), 0);
|
||||
// The next run has no actions: the function kept from the first run finds none.
|
||||
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
|
||||
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
|
||||
let two = set(&[("One", vec![rect(0), rect(30)])]);
|
||||
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
|
||||
assert_eq!(objects(&s), 2);
|
||||
}
|
||||
|
||||
/// Makes artboard `index` of the active document the view's active one, as the app does before each
|
||||
/// command.
|
||||
fn make_active(s: &mut Session, index: usize) {
|
||||
let id = s.active().unwrap().doc.artboards[index].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(id);
|
||||
}
|
||||
|
||||
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
|
||||
/// Art, acts on the active artboard's index as the run started; after the script deletes that
|
||||
/// artboard, the last one. A step that names its artboard keeps it.
|
||||
#[test]
|
||||
fn steps_act_on_the_artboard_active_as_they_run() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&s);
|
||||
make_active(&mut s, 2);
|
||||
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
|
||||
let mut first = align(json!(0));
|
||||
first["params"].as_object_mut().unwrap().remove("artboard");
|
||||
let actions = set(&[
|
||||
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
|
||||
("Align 1", vec![align(json!(0))]),
|
||||
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
|
||||
]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
|
||||
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
|
||||
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
|
||||
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
make_active(&mut s, 1);
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let mut own = align.clone();
|
||||
own["params"]["artboard"] = json!(1);
|
||||
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
|
||||
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
|
||||
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
|
||||
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
|
||||
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
|
||||
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
|
||||
}
|
||||
|
||||
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
|
||||
/// artboard before it, the artboard now at that index, as the view shows it.
|
||||
#[test]
|
||||
fn steps_keep_the_active_artboards_index() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
|
||||
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
|
||||
assert_eq!(add(&s), json!({"artboard": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
|
||||
/// `indices` fits those.
|
||||
#[test]
|
||||
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
make_active(&mut s, 1);
|
||||
let actions = set(&[
|
||||
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
|
||||
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
|
||||
]);
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
|
||||
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
|
||||
assert_eq!(boards(&s), art, "the step's own indices");
|
||||
}
|
||||
|
||||
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
|
||||
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
|
||||
/// still get the active one.
|
||||
#[test]
|
||||
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
let start = script::actions::Start { active: &[], picks: None, batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
assert_eq!(add(&s, id), json!({}), "{id}");
|
||||
}
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
|
||||
assert_eq!(add(&s, "shape.rectangle"), json!({}));
|
||||
}
|
||||
|
||||
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
|
||||
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
|
||||
/// Artwork Bounds step fits them.
|
||||
#[test]
|
||||
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
|
||||
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
|
||||
let setup = || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let mut art = Vec::new();
|
||||
for b in &was {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
|
||||
}
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
make_active(&mut s, 1);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
(s, was, art)
|
||||
};
|
||||
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
|
||||
let (mut s, ..) = setup();
|
||||
let before = objects(&s);
|
||||
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
|
||||
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
|
||||
let (mut s, was, art) = setup();
|
||||
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
|
||||
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
|
||||
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
|
||||
let (mut s, ..) = setup();
|
||||
s.reset_tool();
|
||||
let uid = s.active().unwrap().uid;
|
||||
let kept = (uid, vec![0, 2]);
|
||||
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
|
||||
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
|
||||
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
|
||||
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
|
||||
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
|
||||
}
|
||||
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
|
||||
|
||||
@@ -489,6 +489,30 @@ fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() {
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
/// A length that ends inside a surrogate pair moves the range's end out to the end of the character.
|
||||
#[test]
|
||||
fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() {
|
||||
let (mut s, _) = doc_with("a\u{1F600}b");
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);");
|
||||
assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]);
|
||||
}
|
||||
|
||||
/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard.
|
||||
#[test]
|
||||
fn remove_all_type_refuses_type_on_a_locked_artboard() {
|
||||
let (mut s, id) = doc_with("kept");
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}");
|
||||
assert!(s.active().unwrap().doc.node(id).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
let cases = [
|
||||
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`,
|
||||
//! `document.stories`, and the text of a story of several frames.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Area type `width` × `height` at `x` holding `text`.
|
||||
fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn threads(s: &Session) -> Vec<Vec<NodeId>> {
|
||||
s.active().unwrap().doc.text_threads.clone()
|
||||
}
|
||||
|
||||
/// The text of every frame of the document's threads, in thread order.
|
||||
fn story(s: &Session, frames: &[NodeId]) -> String {
|
||||
frames.iter().map(|f| plain(s, *f)).collect()
|
||||
}
|
||||
|
||||
/// Two area frames threaded into one story whose text starts in the first, one line high, and
|
||||
/// flows on into the second.
|
||||
fn threaded(text: &str) -> (Session, NodeId, NodeId) {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 90.0, 18.0, text);
|
||||
let b = area(&mut s, 150.0, 200.0, 200.0, "");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
const STORY: &str = "alpha beta gamma\ndelta \u{1F600}";
|
||||
|
||||
#[test]
|
||||
fn stories_list_one_story_for_each_thread_and_each_frame_in_none() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
area(&mut s, 400.0, 120.0, 40.0, "Alone");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, st = d.stories[1];\
|
||||
vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\
|
||||
vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\
|
||||
vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\
|
||||
vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\
|
||||
d.textFrames.add(); vc.log(d.stories.length);\
|
||||
vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\
|
||||
vc.log(d.textFrames[1].story.textFrames[0].contents);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Story"),
|
||||
json!(2),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!("Alone"),
|
||||
json!(1),
|
||||
json!(3),
|
||||
json!("Document"),
|
||||
json!("Document"),
|
||||
json!("Stories"),
|
||||
json!("Alone")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_counts_utf16_units_across_its_frames() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}");
|
||||
assert_eq!(first.clone() + &second, STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, r = st.textRange;\
|
||||
vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\
|
||||
vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\
|
||||
vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\
|
||||
vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\
|
||||
vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(25),
|
||||
json!(25),
|
||||
json!("alpha beta gamma\rdelta \u{1F600}"),
|
||||
json!("TextRange"),
|
||||
json!(24),
|
||||
json!(5),
|
||||
json!(2),
|
||||
json!("alpha beta gamma\r"),
|
||||
json!("\u{1F600}"),
|
||||
json!(23),
|
||||
json!(8),
|
||||
json!(25),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The members a long story's range does not have yet throw that they are not available, and
|
||||
/// first that a range that went stale is stale.
|
||||
#[test]
|
||||
fn a_story_range_names_the_members_it_does_not_have_yet() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange;\
|
||||
try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!("TextRange.characterAttributes is not available yet"),
|
||||
json!("TextRange.size is not available yet"),
|
||||
json!("Story.lines is not available yet")
|
||||
]
|
||||
);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
/// Ranges of one story read from different frames keep their places through each other's edits.
|
||||
#[test]
|
||||
fn story_ranges_read_from_different_frames_follow_each_others_edits() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\
|
||||
x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\
|
||||
vc.log(t[1].story.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]);
|
||||
}
|
||||
|
||||
/// A story range that an edit covers holds the edit's new text, as a frame's range does.
|
||||
#[test]
|
||||
fn a_story_range_an_edit_covers_holds_the_new_text() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\
|
||||
st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_edit_across_frames_reflows_in_one_undo_step() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\
|
||||
var p = st.paragraphs[0], tail = st.paragraphs[1];\
|
||||
p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\
|
||||
try { frame.contents; } catch (e) { vc.log(String(e.message)); }\
|
||||
st.words[2].remove(); vc.log(st.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]);
|
||||
assert_eq!(story(&s, &[a, b]), "X\ndelta ");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(story(&s, &[a, b]), STORY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_is_stale_after_another_change_to_the_story() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.words[1];\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
var st = app.activeDocument.textFrames[0].story;\
|
||||
vc.log(st.textFrames.length); vc.log(st.textRange.contents);\
|
||||
try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(st.words[1].contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(out[0], json!(2), "the reverted file keeps the thread");
|
||||
assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "First story.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Second.");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\
|
||||
t[2].nextFrame = t[1];",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]);
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
assert_eq!(story(&s, &[a, b]), "First story.Second.");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]);
|
||||
// previousFrame links the other way.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into()));
|
||||
log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];");
|
||||
assert_eq!(threads(&s), vec![vec![b, a]]);
|
||||
assert_eq!(story(&s, &[b, a]), "Second.First story.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_breaks_the_link_and_each_frame_keeps_its_text() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\
|
||||
t[1].nextFrame = null;",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(1), json!(null)]);
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), (first, second));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_and_path_text_thread_the_new_frame_to_a_base_frame() {
|
||||
let mut s = new_doc();
|
||||
let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it.");
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\
|
||||
var after = d.textFrames.areaText(p[2], undefined, base);\
|
||||
var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\
|
||||
var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\
|
||||
vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]);
|
||||
let t = threads(&s);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_base_frame_is_refused_before_a_frame_is_made() {
|
||||
let mut s = new_doc();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
let count = |s: &Session| s.active().unwrap().doc.node_count();
|
||||
let (n, before) = (count(&s), undo_steps(&s));
|
||||
let d = "var d = app.activeDocument, p = d.pageItems;";
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix"));
|
||||
assert_eq!((count(&s), undo_steps(&s)), (n, before));
|
||||
}
|
||||
|
||||
/// A base frame given with a path inside a compound path is refused before the path is turned
|
||||
/// into type, so a script that catches the error finds the path as it was.
|
||||
#[test]
|
||||
fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() {
|
||||
let mut s = new_doc();
|
||||
area(&mut s, 10.0, 120.0, 60.0, "Base.");
|
||||
let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = null;\
|
||||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\
|
||||
try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds
|
||||
/// now, to check that a refused change left it alone.
|
||||
fn three() -> (Session, [NodeId; 4]) {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let c = area(&mut s, 400.0, 120.0, 40.0, "Third");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
(s, [a, b, c, p])
|
||||
}
|
||||
|
||||
fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec<Vec<NodeId>>, Vec<String>, usize)) {
|
||||
assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::<Vec<_>>(), undo_steps(s)), *before);
|
||||
}
|
||||
|
||||
fn state(s: &Session, ids: &[NodeId]) -> (Vec<Vec<NodeId>>, Vec<String>, usize) {
|
||||
(threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_to_the_frame_itself_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];");
|
||||
assert!(m.contains("nextFrame") && m.contains("itself"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_that_makes_a_loop_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_into_the_middle_of_a_story_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];");
|
||||
assert!(m.contains("already has a previous frame"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];");
|
||||
assert!(m.contains("already has a next frame"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_other_values_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;");
|
||||
assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;");
|
||||
assert!(m.contains("TextFrame or null"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_or_locked_frame_in_either_story_stops_a_link() {
|
||||
let (mut s, ids) = three();
|
||||
log(&mut s, "app.activeDocument.textFrames[2].locked = true;");
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
// A script that catches the error goes on, and the links stay as they were.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\
|
||||
vc.log(t[2].nextFrame === null);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Error", true]), json!(true)]);
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// Reading a story whose text is larger than what one run may pass to and from the host stops
|
||||
/// the run when the story's text is joined.
|
||||
#[test]
|
||||
fn joining_a_storys_text_counts_toward_the_runs_data_limit() {
|
||||
let text = "word ".repeat(40_000);
|
||||
let (mut s, _, _) = threaded(&text);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000)));
|
||||
let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("more data to and from commands"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_of_another_document_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
area(&mut s, 10.0, 100.0, 40.0, "Elsewhere");
|
||||
s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap();
|
||||
let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];");
|
||||
assert!(m.contains("different documents"), "{m}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.documents[0], p = d.pageItems[0];\
|
||||
try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_frame_makes_its_story_and_links_stale() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;");
|
||||
assert!(m.contains("Stale page item"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;");
|
||||
assert!(m.contains("Stale text range"), "{m}");
|
||||
// A story read from a frame that stays follows it when its link is broken.
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stories_refuse_bad_keys_and_huge_numbers() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!(true)]);
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError"));
|
||||
log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_story_walks_to_its_end_and_refuses_a_loop() {
|
||||
let mut s = new_doc();
|
||||
let ids: Vec<NodeId> = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect();
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![ids.clone()]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(120), json!(120), json!(1)]);
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame
|
||||
/// once, so a walk along `nextFrame` ends.
|
||||
#[test]
|
||||
fn a_thread_listing_a_frame_twice_is_walked_once() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]];
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2), json!(1)]);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
assert!(threads(&s).is_empty());
|
||||
}
|
||||
|
||||
/// When a frame is listed in two threads, a story read from a frame of the second thread reads
|
||||
/// that thread's text, not the text of the story read before it from a shared frame.
|
||||
#[test]
|
||||
fn stories_of_threads_that_share_a_frame_keep_their_own_text() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
let c = area(&mut s, 300.0, 120.0, 60.0, "Three!");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]];
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);");
|
||||
let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count());
|
||||
assert_ne!(ab, bc);
|
||||
assert_eq!(out, vec![json!(ab), json!(bc)]);
|
||||
}
|
||||
|
||||
/// A story and its range keep the exact id of the frame they were read from, also past 2^53.
|
||||
#[test]
|
||||
fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() {
|
||||
let mut s = new_doc();
|
||||
// The second frame's id, 2^53 + 1, is not exact as a number.
|
||||
let big = 1u64 << 53;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
assert_eq!((a.0, b.0), (big, big + 1));
|
||||
s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\
|
||||
st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);",
|
||||
);
|
||||
// The whole story flows into the first frame, so the second is empty once the link is broken.
|
||||
assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
for bad in [
|
||||
json!({"id": a.0, "side": "up", "neighbor": b.0}),
|
||||
json!({"id": a.0, "side": "next"}),
|
||||
json!({"id": a.0, "side": "next", "neighbor": 999_999}),
|
||||
] {
|
||||
assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
}
|
||||
|
||||
/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered
|
||||
/// paragraphs count from 1, also when that story keeps two frames.
|
||||
#[test]
|
||||
fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() {
|
||||
let mut s = new_doc();
|
||||
let items = (1..=12).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "list": "number"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let numbers = |s: &Session, id: NodeId| {
|
||||
let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(!t.first_para_continues, "every frame starts a paragraph");
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let first = numbers(&s, ids[0]);
|
||||
assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items");
|
||||
assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1."));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]}));
|
||||
let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat();
|
||||
let expected: Vec<String> = (1..=later.len()).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!(later, expected, "the later story counts from 1");
|
||||
assert_eq!(numbers(&s, ids[0]), first);
|
||||
}
|
||||
@@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
|
||||
getIsFileOpen redraw selection selection= textFonts toString typename",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
|
||||
unloadAction unloadAction=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -107,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
|
||||
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
|
||||
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames toString \
|
||||
rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \
|
||||
typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -166,7 +167,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \
|
||||
insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \
|
||||
opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \
|
||||
rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \
|
||||
rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \
|
||||
textSelection= words",
|
||||
),
|
||||
("TextRange.", "prototype"),
|
||||
@@ -179,7 +180,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||||
spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||||
verticalScale= words",
|
||||
),
|
||||
@@ -209,6 +210,34 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"),
|
||||
("TextOrientation.", "HORIZONTAL VERTICAL"),
|
||||
("TextType.", "AREATEXT PATHTEXT POINTTEXT"),
|
||||
("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"),
|
||||
("Stories.", "prototype"),
|
||||
("Stories.prototype.", "constructor index length parent typename"),
|
||||
("Story.", "prototype"),
|
||||
(
|
||||
"Story.prototype.",
|
||||
"characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \
|
||||
textRanges textRanges= textSelection textSelection= typename words",
|
||||
),
|
||||
("StoryRange.", "prototype"),
|
||||
(
|
||||
"StoryRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
|
||||
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
|
||||
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
|
||||
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
|
||||
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
|
||||
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
|
||||
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||||
underline underline= verticalScale verticalScale= words",
|
||||
),
|
||||
("StoryCharacters.", "prototype"),
|
||||
("StoryCharacters.prototype.", "constructor length parent typename"),
|
||||
("StoryWords.", "prototype"),
|
||||
("StoryWords.prototype.", "constructor length parent typename"),
|
||||
("StoryParagraphs.", "prototype"),
|
||||
("StoryParagraphs.prototype.", "constructor length parent typename"),
|
||||
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
|
||||
// `visibilityVariable` is in its row above.
|
||||
("", "Dataset Datasets Variable VariableKind Variables"),
|
||||
|
||||
@@ -166,6 +166,8 @@ impl VectorcraftApp {
|
||||
}
|
||||
let mut params = params;
|
||||
self.add_active_artboard(id, &mut params);
|
||||
// A script's `app.doScript` plays the Actions panel's actions.
|
||||
panels::actions::add_script_actions(self, id, &mut params);
|
||||
// Edit Symbol from the Symbols panel in a document without artboards centers the symbol's
|
||||
// art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit
|
||||
// steps too.
|
||||
|
||||
@@ -58,7 +58,7 @@ pub use playback::{
|
||||
deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback,
|
||||
waiting_at_stop,
|
||||
};
|
||||
pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
|
||||
pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
|
||||
pub use recording::{START_RECORDING, STOP_RECORDING, record, stop};
|
||||
pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command};
|
||||
|
||||
|
||||
@@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec<PlayStep> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its
|
||||
/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the
|
||||
/// caller gave them: every action of every set, in panel order, with its steps as playback runs
|
||||
/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot
|
||||
/// hold (a step that is not a command, a name that is too long, or one past the limits of
|
||||
/// [`vectorcraft_engine::script::actions`]) is left out.
|
||||
pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) {
|
||||
use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse};
|
||||
let target = match id {
|
||||
"script.run" => Some(params),
|
||||
"script.startup.run" => params.get_mut("then"),
|
||||
_ => None,
|
||||
};
|
||||
let Some(p) = target.and_then(Value::as_object_mut) else { return };
|
||||
if p.contains_key("actions") {
|
||||
return;
|
||||
}
|
||||
let list = &app.ui.actions;
|
||||
let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize);
|
||||
for set in list.sets() {
|
||||
for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) {
|
||||
if held.len() >= MAX_ACTIONS {
|
||||
break;
|
||||
}
|
||||
// The commands of a recorded `command.batch` step go back into one batch step, so that an
|
||||
// error names a failing command by the batch's place and its own (`3.2`).
|
||||
let mut played: Vec<Value> = Vec::new();
|
||||
for s in playback_steps(a) {
|
||||
let params = match s.command.get("params") {
|
||||
None | Some(Value::Null) => json!({}),
|
||||
Some(p) => p.clone(),
|
||||
};
|
||||
let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params});
|
||||
let place = s.row + 1;
|
||||
if a.steps.get(s.row).is_none_or(|step| step.command != "command.batch") {
|
||||
let mut one = one;
|
||||
one["step"] = json!(place);
|
||||
played.push(one);
|
||||
continue;
|
||||
}
|
||||
match played.last_mut() {
|
||||
Some(last) if last["command"] == "command.batch" && last["step"] == place => {
|
||||
if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") {
|
||||
inner.push(one);
|
||||
}
|
||||
}
|
||||
_ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})),
|
||||
}
|
||||
}
|
||||
let one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]);
|
||||
let Ok(parsed) = parse(Some(&one)) else { continue };
|
||||
let count = parsed.first().map_or(0, Playable::len);
|
||||
let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len());
|
||||
if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES {
|
||||
continue;
|
||||
}
|
||||
steps += count;
|
||||
bytes += size;
|
||||
if let Value::Array(mut one) = one {
|
||||
held.append(&mut one);
|
||||
}
|
||||
}
|
||||
}
|
||||
p.insert("actions".into(), Value::Array(held));
|
||||
}
|
||||
|
||||
/// The steps of `action` whose command `known` does not hold, in order, as (step index, the index
|
||||
/// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are
|
||||
/// checked one by one, as playback runs them ([`included_commands`]); a command of one with no
|
||||
|
||||
@@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() {
|
||||
assert_eq!(x(&app), 0.0, "the failing batch changes nothing");
|
||||
}
|
||||
|
||||
/// A script's `app.doScript` plays the panel's actions with their included steps; an action whose
|
||||
/// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept.
|
||||
#[test]
|
||||
fn a_script_plays_the_panels_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let rect = |x: i64| ("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}));
|
||||
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
|
||||
let batch = json!({"commands": [{"command": "select.none"}, bad]});
|
||||
let actions = vec![
|
||||
action("Draw", &[rect(0), rect(20), rect(40)]),
|
||||
action("Odd", &[rect(0), ("select.none", json!(5))]),
|
||||
action("Batched", &[("select.none", json!({})), ("command.batch", batch)]),
|
||||
];
|
||||
push_set(&mut app, "Mine", actions);
|
||||
let draw = model::members(&app.ui.actions, "Mine")[0];
|
||||
app.ui.actions.set_step(draw, 1, false).unwrap();
|
||||
let objects =
|
||||
|app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::<usize>());
|
||||
let undo = app.session.active().map_or(0, |d| d.history.undo.len());
|
||||
app.session.script_frames = false;
|
||||
let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }";
|
||||
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"]));
|
||||
assert_eq!(objects(&app), 2, "the excluded step does not run");
|
||||
assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1);
|
||||
// A failing command of a recorded batch is named by the batch's place and its own.
|
||||
let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }";
|
||||
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let m = r["log"][0].as_str().unwrap_or_default();
|
||||
assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}");
|
||||
let r =
|
||||
app.run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})).unwrap();
|
||||
assert_eq!(r["log"], json!(["there is no action set “Mine”"]));
|
||||
assert_eq!(objects(&app), 2);
|
||||
}
|
||||
|
||||
/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the
|
||||
/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on.
|
||||
#[test]
|
||||
fn the_script_after_the_startup_scripts_plays_the_panels_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]);
|
||||
app.session.script_frames = false;
|
||||
let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"});
|
||||
let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap();
|
||||
assert_eq!(r["then"]["log"], json!(["ok"]), "{r}");
|
||||
}
|
||||
|
||||
/// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's
|
||||
/// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art.
|
||||
#[test]
|
||||
fn a_script_plays_the_actions_on_the_active_artboard() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setStroke", json!({"none": true})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
|
||||
let batch = json!({"commands": [align]});
|
||||
push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]);
|
||||
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let was = boards(&app);
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
app.session.script_frames = false;
|
||||
let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');";
|
||||
app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
|
||||
let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one");
|
||||
assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1");
|
||||
}
|
||||
|
||||
/// A step of a recorded `command.batch` that fails is named by the batch's place in the action
|
||||
/// and its own command.
|
||||
#[test]
|
||||
|
||||
+4
-4
@@ -846,11 +846,11 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G6 Automation and scripting
|
||||
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads
|
||||
of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes)
|
||||
and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
documents, new documents, each document's selection and its page items, its text frames with their text ranges and
|
||||
character and paragraph attributes, the installed fonts, and each document's variables, data sets and variable
|
||||
libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
character and paragraph attributes, their links to each other and the stories they form, the installed fonts, and
|
||||
each document's variables, data sets and variable libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
runs a script in a named engine whose globals last between runs,
|
||||
File › Scripts lists the scripts of the Scripts folder, and
|
||||
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
|
||||
|
||||
+67
-5
@@ -3005,8 +3005,8 @@ other files through `$`:
|
||||
`removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both
|
||||
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
|
||||
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`
|
||||
value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not
|
||||
available yet. A `TextFrame`
|
||||
value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and
|
||||
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
|
||||
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
|
||||
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
|
||||
@@ -3058,9 +3058,36 @@ other files through `$`:
|
||||
`addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and
|
||||
`PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is
|
||||
kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty
|
||||
string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story`
|
||||
and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`,
|
||||
`characterOffset` and `orientation` cannot be set yet.
|
||||
string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`,
|
||||
`TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`,
|
||||
`end`, `characterOffset` and `orientation` cannot be set yet.
|
||||
- Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a
|
||||
`TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end),
|
||||
and `story`; a `TextRange` has `story` too. Assigning `nextFrame` or `previousFrame` runs `text.thread.setNeighbor`:
|
||||
a frame links the last frame of one story to the first frame of another, whose text flows on after the first story's
|
||||
text, and `null` breaks that link, no text moving across it. `areaText(path, orientation?, baseFrame?,
|
||||
postFix?)` and `pathText(path, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)` thread the new frame
|
||||
after `baseFrame`, or before it when `postFix` is false, with `text.thread.add`; `startTValue` and `endTValue` are
|
||||
not available yet. `Document.stories` lists the stories with `length`, `[i]` and `index(key)`. A `Story` has
|
||||
`parent` (its document), `length`, `textFrames` (an array of its frames in thread order), `textRange`, `characters`,
|
||||
`words` and `paragraphs`; `lines`, `insertionPoints`, `textRanges` and `textSelection` are not available yet.
|
||||
VectorCraft's own rules: point type, a frame of another document, the frame itself, a frame inside a story, a link
|
||||
that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the
|
||||
link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out,
|
||||
and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type.
|
||||
`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, and `index` with a string finds the first story whose first frame has that name. A frame that
|
||||
a stored thread lists twice is in its story once. A `Story` is
|
||||
the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is
|
||||
deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its
|
||||
frames' text in thread order, counted in UTF-16 units: its `textRange` reads and writes across the frames, and
|
||||
writing it edits the frames from the last one it reaches back to the first, inside the run's one undo step, and the
|
||||
story then flows through its frames again. Such a range has `contents`, `start`, `end`, `characterOffset`,
|
||||
`length`, `parent` and `story` (its story), `characters`, `words`, `paragraphs`, `getParagraphLength()` and
|
||||
`remove()`; its character and paragraph attributes and the other members are not available yet. It keeps its place
|
||||
through edits made through the story's ranges and throws `Stale text range` after any other change to the story's
|
||||
text and after `file.revert`.
|
||||
- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and
|
||||
`exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets`
|
||||
@@ -3084,6 +3111,29 @@ other files through `$`:
|
||||
`importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or
|
||||
write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs
|
||||
no command.
|
||||
- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method
|
||||
of the scripting reference
|
||||
https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf
|
||||
describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the
|
||||
app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own
|
||||
steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and
|
||||
Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to
|
||||
Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run
|
||||
started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one
|
||||
past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
|
||||
Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that
|
||||
names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's
|
||||
own rules: the action and its set are matched by their exact names, and a name that matches no action or more than
|
||||
one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have
|
||||
(a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any
|
||||
step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an
|
||||
action cannot play itself.
|
||||
Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts
|
||||
as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an
|
||||
error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an
|
||||
uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default
|
||||
`false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error
|
||||
that says they are not available yet when they are read or assigned.
|
||||
- `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/)
|
||||
with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each
|
||||
`Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page
|
||||
@@ -13026,6 +13076,18 @@ after it (`out`). The whole story flows into the frames before the break; the fr
|
||||
threaded with each other when two or more remain, and the first of them starts a paragraph. It refuses an `id` that
|
||||
doesn't exist, a `port` other than `in` or `out`, and a side where no frame of a thread comes before or after `id`.
|
||||
|
||||
`text.thread.setNeighbor {id, side: "next" | "previous", neighbor: id | null}` is what a script's `nextFrame` and
|
||||
`previousFrame` assignments run, and needs no selection. With an id it links area type or type on a path `id` to
|
||||
`neighbor` after it (`next`) or before it (`previous`): `id` must be the last frame of its story for `next` (the first
|
||||
for `previous`) and `neighbor` the first (the last) frame of another story, and the second story's text flows on after
|
||||
the first's (one undo step, Thread Text). With `null` it breaks the link on that side, and the frames on each side
|
||||
form a story of their own (one undo step, Break Thread): no text moves across the break, and the frames after it flow
|
||||
their own text again from their first frame, which now starts a paragraph. It refuses point type and
|
||||
other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a story with a
|
||||
hidden or locked frame, with nothing changed. A link that is already there, or a break where there is no link, changes
|
||||
nothing and records no undo step. The selection is kept. It returns `{changed, threads}`, `threads` listing the
|
||||
stories of the frames involved after the change, a story of one frame as `[id]`.
|
||||
|
||||
`select.same.linkBlockSeries` (Select › Same › Link Block Series) selects every frame of the threads that the selected
|
||||
type objects, and the type inside selected groups, are in, in thread order, and returns `{count}`. Type in no thread
|
||||
selects itself, and other selected objects are left out. With frames of several threads selected, it selects the frames
|
||||
|
||||
+1
-1
@@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1115,12 +1115,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, 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; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
|
||||
|
||||
Reference in new issue
Block a user