mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into feat/print-per-job-settings
This commit is contained in:
commit
a8d0ac7caf
369 files changed
+29739
-2161
No files matched your search
@@ -5,12 +5,14 @@
|
||||
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
|
||||
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
|
||||
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
|
||||
//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and
|
||||
//! returns the color picked for OK, or a new object of the color it was given for Cancel.
|
||||
//!
|
||||
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
|
||||
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
|
||||
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
|
||||
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
|
||||
//! `dialogs` lists each dialog and its answer.
|
||||
//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts
|
||||
//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s
|
||||
//! `answers`; a call with no answer left, or with the next answer for another kind of dialog,
|
||||
//! ends the run. The report's `dialogs` lists each dialog and its answer.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
|
||||
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
|
||||
@@ -21,6 +23,7 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
@@ -51,22 +54,34 @@ pub enum DialogKind {
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
/// `app.showColorPicker`.
|
||||
ColorPicker,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
|
||||
/// The `kind` of an answer and of a report's dialog, which is also the function's name for
|
||||
/// `alert`, `confirm` and `prompt`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
Self::ColorPicker => "colorPicker",
|
||||
}
|
||||
}
|
||||
|
||||
/// The function's name, as its errors give it.
|
||||
fn function(self) -> &'static str {
|
||||
match self {
|
||||
Self::ColorPicker => "showColorPicker",
|
||||
k => k.id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a script opened, which waits for its answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptDialog {
|
||||
pub kind: DialogKind,
|
||||
pub message: String,
|
||||
@@ -78,10 +93,15 @@ pub struct ScriptDialog {
|
||||
pub no_as_default: bool,
|
||||
/// `prompt`: the text its field starts with.
|
||||
pub preset: String,
|
||||
/// `showColorPicker`: the color the picker starts with. `None` for the other dialogs.
|
||||
pub color: Option<Color>,
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogAnswer {
|
||||
/// OK, for `alert`.
|
||||
Ok,
|
||||
@@ -91,6 +111,8 @@ pub enum DialogAnswer {
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
/// OK with the color picked, or Cancel (`None`), for `showColorPicker`.
|
||||
ColorPicker(Option<Color>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -100,30 +122,101 @@ impl DialogAnswer {
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
Self::ColorPicker(_) => DialogKind::ColorPicker,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
/// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it
|
||||
/// started with.
|
||||
fn data(&self, d: &ScriptDialog) -> Data {
|
||||
match self {
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands
|
||||
/// take it, or `null`.
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the paint commands take it.
|
||||
fn color_json(c: &Color) -> Value {
|
||||
serde_json::to_value(c).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from
|
||||
/// -128 to 128, as a script's `LabColor` takes them?
|
||||
fn in_range(c: &Color) -> bool {
|
||||
let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => unit(&[r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]),
|
||||
Color::Gray { k } => unit(&[k]),
|
||||
Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key
|
||||
/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components
|
||||
/// into their ranges. An array or object is checked as written too, in f64 and with the scale
|
||||
/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded
|
||||
/// onto it when it narrows to f32.
|
||||
fn answer_color(v: &Value) -> Option<Color> {
|
||||
// Parsed as f64, so that a value just past a limit is not rounded onto it.
|
||||
let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x));
|
||||
let num = |o: &serde_json::Map<String, Value>, key: &str| o.get(key).and_then(Value::as_f64);
|
||||
let written_in_range = match v {
|
||||
Value::String(s) if Color::from_hex(s).is_none() => {
|
||||
let mut it = s.split_whitespace();
|
||||
let model = it.next()?.to_ascii_lowercase();
|
||||
let n: Vec<f64> = it.map(|t| t.parse::<f64>().ok().filter(|x| x.is_finite())).collect::<Option<_>>()?;
|
||||
match (model.as_str(), n.as_slice()) {
|
||||
("rgb", [_, _, _]) => within(&n, 0.0, 255.0),
|
||||
("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0),
|
||||
("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0),
|
||||
Value::Object(o) => {
|
||||
if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) {
|
||||
let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 };
|
||||
within(&[c, m, y, k], 0.0, scale)
|
||||
} else if let Some(g) = o.get("gray") {
|
||||
let g = g.as_f64()?;
|
||||
within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0)
|
||||
} else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) {
|
||||
within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0)
|
||||
} else {
|
||||
match o.get("model").and_then(Value::as_str) {
|
||||
Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0),
|
||||
Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0),
|
||||
Some("gray") => within(&[num(o, "k")?], 0.0, 1.0),
|
||||
Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
if !written_in_range {
|
||||
return None;
|
||||
}
|
||||
crate::cmd::color_value(v).filter(in_range)
|
||||
}
|
||||
|
||||
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
|
||||
/// is a line break; every other control character, and with `lines` false every line break too,
|
||||
/// shows as its Unicode Control Picture, as the Script Console shows it.
|
||||
@@ -156,9 +249,10 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}`, `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]) and `{kind: "colorPicker", value: color | null}`, the color in any form
|
||||
/// the paint commands take. An empty object, which the parameter took before dialogs existed, is
|
||||
/// an empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -196,7 +290,12 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
(Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)),
|
||||
(Some("colorPicker"), v) => match answer_color(v) {
|
||||
Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))),
|
||||
None => Err("is a color picker's answer, whose `value` must be a color or null"),
|
||||
},
|
||||
_ => Err("must have `kind` alert, confirm, prompt, window or colorPicker"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +564,10 @@ impl Dialogs {
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let data = answer.data(&d);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { data };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
@@ -523,13 +623,16 @@ impl Dialogs {
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
if d.kind != DialogKind::ColorPicker {
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
}
|
||||
match d.kind {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)),
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
self.push_record(Value::Object(r));
|
||||
@@ -584,7 +687,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
|
||||
let (title, error_icon, no_as_default, preset) = match kind {
|
||||
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
// `showColorPicker` opens through `show_color_picker`, not here.
|
||||
DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
|
||||
DialogKind::Prompt => {
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
@@ -601,7 +705,33 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
/// and a new object of `color` for Cancel.
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: false,
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of
|
||||
/// `answers`.
|
||||
fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result<Data, HostError> {
|
||||
let kind = dialog.kind;
|
||||
let name = kind.function();
|
||||
let d = &host.dialogs;
|
||||
if d.framed {
|
||||
if !d.can_wait.get() {
|
||||
@@ -616,11 +746,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
match next {
|
||||
Some(a) if a.kind() == kind => {
|
||||
d.record(&dialog, a.json());
|
||||
Ok(a.data())
|
||||
Ok(a.data(&dialog))
|
||||
}
|
||||
Some(a) => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id())))
|
||||
}
|
||||
None => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
|
||||
+116
-53
@@ -38,7 +38,8 @@
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
|
||||
//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the
|
||||
//! order of a layer's, a group's and a compound path's lists. An index out of range gives
|
||||
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
|
||||
//! - Script coordinates are points with Y up from the bottom of the first artboard
|
||||
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
|
||||
@@ -117,9 +118,12 @@ mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use print::postscript_name;
|
||||
#[cfg(test)]
|
||||
pub(crate) use save_open::with_extension;
|
||||
@@ -146,6 +150,8 @@ pub const STALE_ITEM: &str = "Stale page item";
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error of `move` and `remove()` for a tracing's source image.
|
||||
const SOURCE_STAYS: &str = "a tracing's source image cannot leave its tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -205,14 +211,18 @@ thread_local! {
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and
|
||||
/// layers its layers and groups gave, the active artboard of each document, and the tool
|
||||
/// `app.selectTool` chose last.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
/// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's
|
||||
/// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is
|
||||
/// unchanged.
|
||||
paths: RefCell<Vec<paths::PathList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
@@ -231,14 +241,13 @@ pub(super) struct State {
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first,
|
||||
/// each kept while its document is unchanged.
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
@@ -328,24 +337,6 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -627,6 +618,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
|
||||
[float(h.run), float(st.uid), high, low, float(st.reverts)]
|
||||
}
|
||||
|
||||
/// The handle of a collection that lists the art of the layer, group or compound path `id` in the
|
||||
/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a
|
||||
/// collection read before File > Revert is stale.
|
||||
fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
[float(h.run), float(uid), high, low, float(reverts)]
|
||||
}
|
||||
|
||||
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
let &[run, uid, high, low, reverts] = handle else { return None };
|
||||
let doc = find_doc(h, run, uid)?;
|
||||
@@ -695,7 +695,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
None => layers::layer_ref(h, st.uid, id),
|
||||
},
|
||||
None => Data::Null,
|
||||
}
|
||||
@@ -870,7 +870,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
} else {
|
||||
// One `select.anchorsMany` selects every object in its order: a partly selected path with
|
||||
// its anchors, a whole path with all of them and any other object with none.
|
||||
// its anchors, a whole path with all of them and any other object with none. A path with
|
||||
// only segments selected gets no anchors here, so `select.segments` below selects it with
|
||||
// just those segments.
|
||||
let items: Vec<Value> = kept
|
||||
.iter()
|
||||
.map(|i| {
|
||||
@@ -1159,12 +1161,25 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`,
|
||||
/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]).
|
||||
fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
let color = colors::solid(arg(a, 1), "showColorPicker's color")?;
|
||||
super::dialogs::show_color_picker(h, color)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
fn path_key(p: &str) -> String {
|
||||
path_key_on(p, cfg!(windows))
|
||||
}
|
||||
|
||||
/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts
|
||||
/// with a drive letter.
|
||||
pub(crate) fn path_key_on(p: &str, windows: bool) -> String {
|
||||
let b = p.as_bytes();
|
||||
let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
@@ -1618,9 +1633,17 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
let mut shadowed_by = None;
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim()));
|
||||
if shadowed {
|
||||
// `file.new` would find the saved preset of that name first, so the name is left out
|
||||
// and the built-in preset's settings, with `presetSettings` over them, go as params.
|
||||
shadowed_by = Some(first.clone());
|
||||
} else {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
@@ -1639,6 +1662,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
let reason = e["reason"].as_str().unwrap_or_default();
|
||||
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
|
||||
}
|
||||
// The built-in preset's settings went as params: Recent keeps its name, as `file.new`
|
||||
// keeps a preset's name, unless its size changed (turning it doesn't count).
|
||||
if let Some(first) = &shadowed_by {
|
||||
let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) {
|
||||
r.name.clone_from(&first.name);
|
||||
}
|
||||
}
|
||||
// Each warning from reading the profile's file goes to the console.
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut));
|
||||
@@ -2226,7 +2258,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2235,7 +2267,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
@@ -2243,7 +2275,7 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
@@ -2252,7 +2284,7 @@ fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2265,30 +2297,55 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a
|
||||
/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise.
|
||||
fn by_name_or_probe(a: &[Data], found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
|
||||
fn position(n: f64) -> Option<usize> {
|
||||
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// The arguments of an indexer called with a number that is not an array index, such as `-1` or
|
||||
/// `1.5`, with that key given as the text of the number, the name it is looked up by: a key such
|
||||
/// as `"-1"` reaches an indexer as a number.
|
||||
fn number_named(a: &[Data]) -> Option<Vec<Data>> {
|
||||
let Data::Number(n) = arg(a, 1) else { return None };
|
||||
if position(*n).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut named = a.to_vec();
|
||||
named[1] = text(vectorcraft_js::number_to_string(*n));
|
||||
Some(named)
|
||||
}
|
||||
|
||||
/// The answer of an indexer for a number key looked up as a name ([`number_named`]), from `found`,
|
||||
/// the collection's `getByName`: `undefined` when nothing has the name.
|
||||
fn named_or_undefined(found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::String(_) => by_name_or_probe(a, items_by_name(h, a)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
None => named_or_undefined(items_named(h, doc, &vectorcraft_js::number_to_string(*n))),
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
@@ -2300,7 +2357,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2319,7 +2376,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
@@ -2339,7 +2396,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2671,8 +2728,8 @@ fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
|
||||
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
|
||||
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
|
||||
/// path's.
|
||||
/// the visible bounds leave them out, a clip group or clipping layer gives only its clipping
|
||||
/// path's, and the source art a Shaper Group or a tracing keeps is left out.
|
||||
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
|
||||
@@ -2682,7 +2739,7 @@ fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
|
||||
}
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let children = n.editing_children();
|
||||
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
|
||||
for c in children {
|
||||
r = take_in_handles(c, r, steps);
|
||||
@@ -2844,7 +2901,8 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
|
||||
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
|
||||
/// refuses it. A compound path whose last path this is stays, empty.
|
||||
/// refuses it. A tracing's source image is refused when it is shown as well. A compound path whose
|
||||
/// last path this is stays, empty.
|
||||
fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -2856,6 +2914,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// A tracing keeps its source image when a script has shown it, as `move` keeps it there.
|
||||
if with_doc(h, item.doc, |_, st| crate::cmd::is_trace_source(&st.doc, item.id)) {
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
@@ -3082,7 +3144,7 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
// The clipping path itself, put back where it is, stays the clipping path.
|
||||
@@ -3285,7 +3347,7 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `toString()` of an object without a name: `[Class]`.
|
||||
fn class_text(name: &'static str) -> HostMember {
|
||||
pub(super) fn class_text(name: &'static str) -> HostMember {
|
||||
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
|
||||
}
|
||||
|
||||
@@ -3385,6 +3447,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("showColorPicker", method(l, app_show_color_picker), returns("Color", &[("color", "Color")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
|
||||
@@ -13,7 +13,10 @@
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -66,7 +69,7 @@ fn shown(v: f32, scale: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
pub(in crate::script) fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
@@ -149,6 +152,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color
|
||||
}))
|
||||
}
|
||||
|
||||
/// The solid color a script gave `what`, checked as [`assigned`] checks it: a `NoColor`, a
|
||||
/// `GradientColor`, a `SpotColor` or a `PatternColor` throws a `TypeError`.
|
||||
pub(super) fn solid(d: &Data, what: &str) -> std::result::Result<Color, HostError> {
|
||||
let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor"));
|
||||
match assigned(d, what) {
|
||||
Ok(Some(c)) => Ok(c),
|
||||
// A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error.
|
||||
Ok(None) | Err(HostError::Error(_)) => Err(not_solid()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems`, `pathItems` and `textFrames`, and a compound path's
|
||||
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
|
||||
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
|
||||
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
|
||||
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref,
|
||||
later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity,
|
||||
returns, text, typed, typename, whole, with_doc,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method,
|
||||
named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename,
|
||||
whole, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
@@ -66,8 +66,6 @@ enum Kind {
|
||||
Group,
|
||||
/// Compound paths (`CompoundPathItem`).
|
||||
Compound,
|
||||
/// Paths (`PathItem`).
|
||||
Path,
|
||||
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
|
||||
Text,
|
||||
}
|
||||
@@ -78,7 +76,6 @@ impl Kind {
|
||||
Kind::Any => "PageItems",
|
||||
Kind::Group => "GroupItems",
|
||||
Kind::Compound => "CompoundPathItems",
|
||||
Kind::Path => "PathItems",
|
||||
Kind::Text => "TextFrames",
|
||||
}
|
||||
}
|
||||
@@ -88,7 +85,6 @@ impl Kind {
|
||||
Kind::Any => typename(n).is_some(),
|
||||
Kind::Group => typename(n) == Some("GroupItem"),
|
||||
Kind::Compound => typename(n) == Some("CompoundPathItem"),
|
||||
Kind::Path => typename(n) == Some("PathItem"),
|
||||
Kind::Text => typename(n) == Some("TextFrame"),
|
||||
}
|
||||
}
|
||||
@@ -109,14 +105,16 @@ fn result_id(v: &Value, key: &str) -> Option<u64> {
|
||||
/// The layer `d` names, which must still be a layer of its document.
|
||||
pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> {
|
||||
let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) };
|
||||
if handle.len() != 5 {
|
||||
return Err(type_error("Layer"));
|
||||
}
|
||||
// A layer read before File › Revert is stale like the page items read with it.
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| {
|
||||
let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some());
|
||||
HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into())
|
||||
})?;
|
||||
let [run, uid, high, low, _] = handle.as_slice() else { return Err(type_error("Layer")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
// A layer read before its document was reverted is stale as the page items read then are.
|
||||
let (doc, id) = super::node_of(h, &handle).filter(|(d, _)| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
held_layer(h, doc, id)
|
||||
}
|
||||
|
||||
/// The layer `id` of `doc`, which must still be a layer of the document.
|
||||
fn held_layer(h: &Host, doc: Doc, id: NodeId) -> Result<(Doc, NodeId)> {
|
||||
let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer));
|
||||
if !ok {
|
||||
return Err(HostError::Error(STALE_LAYER.into()));
|
||||
@@ -128,14 +126,12 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> {
|
||||
layer_of(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("Layer", &layer_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
|
||||
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
|
||||
pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
let s = h.session.borrow();
|
||||
match s.documents().iter().find(|d| d.uid == uid) {
|
||||
Some(st) => host_ref("Layer", &super::node_handle(h, st, id)),
|
||||
None => Data::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the layer `this` names with `f`.
|
||||
@@ -285,22 +281,23 @@ fn layer_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
}))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_layer(h, a)?;
|
||||
Ok(text("Layer"))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is
|
||||
/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop
|
||||
/// not counted. The list comes from [`layer_ids`], so reading it for each layer of a loop
|
||||
/// lists the layers once. Each read is still charged for the search through the list.
|
||||
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let at = with_doc(h, doc, |_, st| {
|
||||
let list = layers_listed(h, st, st.doc.parent_of(id))?;
|
||||
let list = layer_ids(h, st, st.doc.parent_of(id))?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
|
||||
})?;
|
||||
@@ -535,8 +532,9 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?;
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its layer is.
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?;
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(type_error("Layers")),
|
||||
@@ -554,33 +552,33 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
|
||||
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
|
||||
/// level) and the layers it listed then.
|
||||
/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers.
|
||||
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
|
||||
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
|
||||
/// is charged by the objects it looks at.
|
||||
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
/// How many lists of layers [`super::State`] keeps at once.
|
||||
pub(super) const LAYER_LISTS: usize = 4;
|
||||
|
||||
/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a
|
||||
/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at.
|
||||
fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
{
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
|
||||
if let Some(at) = at {
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let looked_at = match parent {
|
||||
let looked = match parent {
|
||||
None => st.doc.layers.len(),
|
||||
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
|
||||
};
|
||||
h.charge_call(looked_at as u64)?;
|
||||
h.charge_call(looked as u64)?;
|
||||
let ids = Rc::new(layer_list(&st.doc, parent));
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= ART_LISTS {
|
||||
if lists.len() >= LAYER_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
|
||||
@@ -589,12 +587,12 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<V
|
||||
|
||||
fn layers_of(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
|
||||
Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id)))
|
||||
}
|
||||
|
||||
fn layers_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -607,30 +605,26 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Layers"))
|
||||
}
|
||||
|
||||
/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when
|
||||
/// nothing has the name, as the document's `pageItems` does.
|
||||
fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer {
|
||||
match by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `layers[i]`, and `layers["name"]` as `getByName` reads it. A number key that is not an array
|
||||
/// index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn layers_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, layers_by_name);
|
||||
return super::by_name_or_probe(a, layers_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(layers_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
}
|
||||
|
||||
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = layers_listed(h, st, parent)?;
|
||||
let ids = layer_ids(h, st, parent)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -640,6 +634,8 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn layers_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => layers_by_name(h, a),
|
||||
// A number is a position here, never a name ([`layers_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Data::Number(_) => match layers_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -673,7 +669,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if parent.is_none() {
|
||||
return Err(HostError::Error("a document needs at least one layer".into()));
|
||||
}
|
||||
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
|
||||
let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?;
|
||||
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
|
||||
if ids.len() > crate::cmd::layer::MAX_ROWS {
|
||||
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
|
||||
@@ -692,13 +688,11 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
// A collection read before File › Revert is stale like its container.
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
whole(*reverts) == Some(st.reverts)
|
||||
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -755,23 +749,15 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Whether a `PageItems` or `PathItems` object's handle names its container.
|
||||
pub(super) fn is_scoped(a: &[Data], class: &str) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn scoped_kind(a: &[Data]) -> Kind {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any }
|
||||
}
|
||||
|
||||
/// How many times File › Revert has reloaded the document with uid `uid`.
|
||||
fn reverts_of(h: &Host, uid: u64) -> u64 {
|
||||
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
|
||||
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
|
||||
/// names the container.
|
||||
pub(super) fn is_scoped(a: &[Data]) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
|
||||
match container {
|
||||
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
|
||||
Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)),
|
||||
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
|
||||
}
|
||||
}
|
||||
@@ -787,26 +773,19 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
|
||||
}
|
||||
|
||||
/// `collection[i]`, and `collection["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as the document's `pageItems` looks it up.
|
||||
fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match art_by_name(h, a, kind) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
};
|
||||
return super::by_name_or_probe(a, art_by_name(h, a, kind));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(art_by_name(h, &named, kind));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
|
||||
// The text of a number that is not an array index is looked up as a name.
|
||||
None => with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}),
|
||||
}
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
@@ -814,6 +793,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -823,8 +803,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => art_by_name(h, a, kind),
|
||||
// A number is a position only. A stale collection throws its stale error first.
|
||||
Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => {
|
||||
// A number is a position here, never a name ([`art_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
art_scope(h, arg(a, 0), kind.class())?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
@@ -839,7 +820,8 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
/// `removeAll()`: deletes every object the collection lists (those inside another listed one go
|
||||
/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or
|
||||
/// one on a locked artboard stops it before anything is deleted, as the document's
|
||||
/// `pageItems.removeAll()` is stopped.
|
||||
/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an
|
||||
/// ordinary group named as a tracing.
|
||||
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
@@ -852,21 +834,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect();
|
||||
let masks = kept_clipping_paths(d, &ids);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
@@ -877,12 +845,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
}
|
||||
refuse_kept_clipping_paths(&masks)?;
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
@@ -893,29 +856,75 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]).
|
||||
/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other
|
||||
/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest.
|
||||
/// Deleting every path of a compound path would leave it empty, so a compound path that clips
|
||||
/// counts as deleted too.
|
||||
pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec<u64> {
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
ids.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The error of a `removeAll()` that would delete the clipping paths `masks`, or `Ok` when there
|
||||
/// are none.
|
||||
pub(super) fn refuse_kept_clipping_paths(masks: &[u64]) -> std::result::Result<(), HostError> {
|
||||
if masks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)))
|
||||
}
|
||||
|
||||
/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their
|
||||
/// handle names one ([`is_scoped`]).
|
||||
pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer {
|
||||
art_length(h, a, scoped_kind(a))
|
||||
art_length(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
art_parent(h, a, scoped_kind(a))
|
||||
art_parent(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer {
|
||||
art_at(h, a, scoped_kind(a))
|
||||
art_at(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
art_by_name(h, a, scoped_kind(a))
|
||||
art_by_name(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
|
||||
art_index(h, a, scoped_kind(a))
|
||||
art_index(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
art_remove_all(h, a, scoped_kind(a))
|
||||
art_remove_all(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn groups_length(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -961,7 +970,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
}
|
||||
|
||||
pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, scoped_kind(a))
|
||||
art_typename(h, a, Kind::Any)
|
||||
}
|
||||
fn groups_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, Kind::Group)
|
||||
@@ -971,15 +980,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`.
|
||||
/// → the new object.
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A
|
||||
/// Live Paint group takes none. → the new object.
|
||||
fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Some(c) = c {
|
||||
let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let (compound, live) = with_doc(h, doc, |_, st| {
|
||||
(st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c))
|
||||
});
|
||||
if compound {
|
||||
return Err(HostError::Error("a compound path holds only paths".into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0}));
|
||||
if kind == Kind::Compound
|
||||
@@ -1024,10 +1038,6 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Path)
|
||||
}
|
||||
|
||||
fn held_groups(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Group)
|
||||
}
|
||||
@@ -1036,6 +1046,24 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Compound)
|
||||
}
|
||||
|
||||
/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]).
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let this = arg(a, 0);
|
||||
if handle_of(this, "Layer").is_some() {
|
||||
let (doc, id) = layer_of(h, this)?;
|
||||
return Ok(super::paths::held_path_items(h, doc.uid, id));
|
||||
}
|
||||
let item = this_item_of(h, a, "GroupItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it
|
||||
/// ([`super::paths`]).
|
||||
fn compound_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item_of(h, a, "CompoundPathItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
fn held_text(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Text)
|
||||
}
|
||||
@@ -1111,12 +1139,13 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
]);
|
||||
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m.extend(["symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m
|
||||
}
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths), listed("PathItems"))]),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -1180,19 +1209,22 @@ fn board_index(st: &DocState, id: u32) -> Option<usize> {
|
||||
st.doc.artboards.iter().position(|a| a.id == id)
|
||||
}
|
||||
|
||||
/// The artboard `d` names. An artboard read before its document was reverted is stale, as a page
|
||||
/// item is: the loaded document's artboard with the same id is another artboard.
|
||||
fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
|
||||
let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) };
|
||||
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
// An artboard read before File › Revert is stale, as the page items read with it are.
|
||||
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
|
||||
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
Ok((Board { doc }, index))
|
||||
}
|
||||
|
||||
/// An `Artboard` for the artboard `id` of the document `uid`, with the document's revert count.
|
||||
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)])
|
||||
}
|
||||
|
||||
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
|
||||
@@ -1419,13 +1451,18 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
|
||||
.ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1))))
|
||||
}
|
||||
|
||||
/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn boards_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, boards_by_name);
|
||||
return super::by_name_or_probe(a, boards_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(boards_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id))))
|
||||
}
|
||||
|
||||
@@ -1442,6 +1479,8 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn boards_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => boards_by_name(h, a),
|
||||
// A number is a position here, never a name ([`boards_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Data::Number(_) => match boards_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -1527,7 +1566,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = reverts_of(h, doc.uid);
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
@@ -1585,13 +1624,14 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("printable", property(l, layer_printable, layer_set_printable), typed("boolean")),
|
||||
("preview", property(l, layer_preview, layer_set_preview), typed("boolean")),
|
||||
("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("color", property(l, layer_color, layer_set_color), typed("RGBColor")),
|
||||
("parent", get(l, layer_parent), typed("*")),
|
||||
("layers", get(l, layers_of), listed("Layers")),
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
("zOrderPosition", get(l, layer_z_position), typed("number")),
|
||||
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")),
|
||||
@@ -1601,9 +1641,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]);
|
||||
layer.extend(
|
||||
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
|
||||
);
|
||||
layer.extend(["symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)));
|
||||
vec![
|
||||
class("Layer", None, layer, None),
|
||||
class(
|
||||
@@ -1664,7 +1702,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("name", property(l, board_name, board_set_name), typed("string")),
|
||||
("parent", get(l, board_parent), typed("Document")),
|
||||
("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), typed("number")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), MemberInfo { min: Some(0.1), max: Some(10.0), ..typed("number") }),
|
||||
("showCenter", property(l, board_center, board_set_center), typed("boolean")),
|
||||
("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")),
|
||||
("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")),
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in
|
||||
//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden
|
||||
//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`].
|
||||
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
|
||||
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
@@ -26,8 +28,8 @@
|
||||
//! fill or stroke only.
|
||||
//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes
|
||||
//! them all.
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever
|
||||
//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's
|
||||
//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds
|
||||
//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points.
|
||||
//! Removing the last points leaves the path, with no points.
|
||||
@@ -68,9 +70,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
|
||||
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
|
||||
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command,
|
||||
coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair,
|
||||
point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -168,8 +170,16 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
host_ref("PathItem", &handle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
static INDEX_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The index of the first point of each subpath of `subs`, followed by the number of points.
|
||||
fn starts(subs: &[SubPath]) -> Vec<usize> {
|
||||
#[cfg(test)]
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let mut out = Vec::with_capacity(subs.len() + 1);
|
||||
let mut n = 0;
|
||||
for sp in subs {
|
||||
@@ -206,6 +216,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(read_points(h, item, starts)?);
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone()));
|
||||
return Ok(counted);
|
||||
@@ -217,6 +229,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths));
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone()));
|
||||
Ok(counted)
|
||||
@@ -227,6 +241,12 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
|
||||
Ok(point_starts(h, item)?.last().copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn index_builds() -> u64 {
|
||||
INDEX_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
|
||||
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
|
||||
for (s, sp) in subs.iter().enumerate() {
|
||||
@@ -265,7 +285,20 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
|
||||
/// points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
edit_points_keeping(h, item, false, f)
|
||||
}
|
||||
|
||||
/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as
|
||||
/// they are, so the [`starts`] of the waiting changes stay kept.
|
||||
fn edit_points_keeping<T>(
|
||||
h: &super::Host,
|
||||
item: Item,
|
||||
counts_kept: bool,
|
||||
f: impl FnOnce(&mut Vec<SubPath>) -> T,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !counts_kept {
|
||||
forget_waiting_starts(h);
|
||||
}
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
&& same_path(*waiting, item)
|
||||
{
|
||||
@@ -306,7 +339,7 @@ fn forget_waiting_starts(h: &super::Host) {
|
||||
fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> {
|
||||
let counted = point_starts(h, item)?;
|
||||
let at = locate_at(&counted, i);
|
||||
edit_points(h, item, |subs| {
|
||||
edit_points_keeping(h, item, true, |subs| {
|
||||
if let Some((s, j)) = at
|
||||
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
|
||||
{
|
||||
@@ -394,6 +427,19 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
/// shown, unlocked layer otherwise. While an opacity mask, pattern or symbol is being edited,
|
||||
/// the path goes on the layer recorded by that edit mode. `create::on_layer` validates the layer.
|
||||
fn new_path_layer(st: &crate::DocState) -> Option<NodeId> {
|
||||
let d = &st.doc;
|
||||
if let Some(layer) =
|
||||
d.mask_edit.map(|e| e.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
|
||||
{
|
||||
return Some(layer);
|
||||
}
|
||||
st.current_layer().filter(|l| d.is_editable(*l)).or_else(|| d.default_layer())
|
||||
}
|
||||
|
||||
/// Runs a path creation command with its layer placement recorded.
|
||||
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let mut params = params.clone();
|
||||
@@ -439,19 +485,48 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
r
|
||||
}
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return Ok(ids);
|
||||
/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the
|
||||
/// document's), and the ids it listed then.
|
||||
pub(super) type PathList = (u64, Arc<crate::Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// How many lists of paths [`super::State`] keeps at once.
|
||||
pub(super) const PATH_LISTS: usize = 4;
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items, or of the paths directly in the
|
||||
/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their
|
||||
/// documents are unchanged, so a loop over a collection builds its list once. A new list is
|
||||
/// charged by the objects it looks at.
|
||||
fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
{
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
|
||||
let ids: Rc<Vec<NodeId>> = match container {
|
||||
Some(c) => {
|
||||
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
|
||||
h.charge_call(children.len() as u64)?;
|
||||
Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect())
|
||||
}
|
||||
None => {
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect())
|
||||
}
|
||||
};
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= PATH_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), container, ids.clone()));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
@@ -460,54 +535,66 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
|
||||
/// The `pathItems` of the layer or group `id` in the document `uid`.
|
||||
pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("PathItems", &super::scoped_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths
|
||||
/// of, if any.
|
||||
fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)),
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PathItems".into())),
|
||||
}
|
||||
doc_of(h, arg(a, 0), "PathItems")
|
||||
}
|
||||
|
||||
/// `typename` of the paths of a document that is still open.
|
||||
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
items_scope(h, a)?;
|
||||
Ok(Data::String("PathItems".into()))
|
||||
}
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(match c {
|
||||
None => host_ref("Document", &[float(h.run), float(doc.uid)]),
|
||||
Some(c) => with_doc(h, doc, |_, st| {
|
||||
if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) }
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Some(i) => item_at(h, doc, c, i),
|
||||
None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
@@ -517,23 +604,20 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
fn item_at(h: &super::Host, doc: Doc, c: Option<NodeId>, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
items_named(h, doc, c, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
fn items_named(h: &super::Host, doc: Doc, c: Option<NodeId>, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let ids = path_items(h, st, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -541,14 +625,11 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -557,25 +638,98 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
|
||||
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
|
||||
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
|
||||
/// or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st, c)?;
|
||||
let d = &st.doc;
|
||||
if h.session.borrow().menu.guides_locked
|
||||
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
{
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
|
||||
}
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
let mut next: Vec<_> = d.layers.iter().collect();
|
||||
let mut nodes = Vec::new();
|
||||
while let Some(n) = next.pop() {
|
||||
nodes.push(n);
|
||||
next.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut affected: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
for n in nodes.iter().rev() {
|
||||
if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) {
|
||||
affected.insert(n.id);
|
||||
}
|
||||
}
|
||||
// Type is laid out only inside a mask that loses a path; no other outline decides a refusal.
|
||||
let mut in_mask = std::collections::HashSet::new();
|
||||
for n in &nodes {
|
||||
if n.clips()
|
||||
&& let Some(mask) = n.children().and_then(|k| k.first())
|
||||
&& affected.contains(&mask.id)
|
||||
{
|
||||
let mut stack = vec![mask];
|
||||
while let Some(m) = stack.pop() {
|
||||
if in_mask.insert(m.id) {
|
||||
stack.extend(m.children().into_iter().flatten());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut geometry = std::collections::HashSet::new();
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths and the glyphs of visible type, as
|
||||
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
|
||||
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
|
||||
let shape = n.visible
|
||||
&& match &n.kind {
|
||||
NodeKind::Path { .. } => true,
|
||||
NodeKind::Text(t) => {
|
||||
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
// A clipping group's outline is its first member's alone.
|
||||
let inner =
|
||||
if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) };
|
||||
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
|
||||
geometry.insert(n.id);
|
||||
}
|
||||
if n.clips()
|
||||
&& let Some(mask) = kids.first()
|
||||
&& affected.contains(&mask.id)
|
||||
&& !geometry.contains(&mask.id)
|
||||
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
&& masks.len() < 20
|
||||
{
|
||||
masks.push(mask.id.0);
|
||||
}
|
||||
}
|
||||
let going: Vec<NodeId> = going.into_iter().collect();
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
let tracing = super::removal_makes_tracing(d, &going);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks, tracing))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
@@ -585,8 +739,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
super::layers::refuse_kept_clipping_paths(&masks)?;
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
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<_>>()})))?;
|
||||
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -597,24 +756,74 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
|
||||
/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path
|
||||
/// and putting the selection back load the selected objects' paint and stroke width into new art,
|
||||
/// so new art's paint from before, the defaults a script set included, is put back.
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or
|
||||
/// locked layer or group.
|
||||
pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group";
|
||||
|
||||
/// The error of an object made in a Live Paint group, which would join the group's paths instead
|
||||
/// of staying in the group's own list.
|
||||
pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group";
|
||||
|
||||
/// Whether `id` is a Live Paint group, which takes no new objects from the object model.
|
||||
pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool {
|
||||
st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint)
|
||||
}
|
||||
|
||||
/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the
|
||||
/// selection and the current layer kept. With a layer or group `container`, the container's layer
|
||||
/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made
|
||||
/// outside the container then moves on top of its contents in the same step; a container that is
|
||||
/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]
|
||||
/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path.
|
||||
fn make_in(
|
||||
h: &super::Host,
|
||||
doc: Doc,
|
||||
container: Option<NodeId>,
|
||||
make: impl FnOnce(&super::Host) -> std::result::Result<NodeId, HostError>,
|
||||
) -> Answer {
|
||||
if let Some(c) = container {
|
||||
let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c)));
|
||||
if !open {
|
||||
return Err(HostError::Error(CONTAINER_LOCKED.into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let made = match container {
|
||||
// Making a path can take more than one command (a stroke, a reversal): a failure of a later
|
||||
// one undoes the path too.
|
||||
None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?,
|
||||
Some(c) => super::atomically(h, |h| {
|
||||
let id = on_doc(h, doc.uid, true, |h| {
|
||||
command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?;
|
||||
make(h)
|
||||
})?;
|
||||
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
|
||||
Ok(id)
|
||||
})?,
|
||||
};
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s
|
||||
/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path.
|
||||
/// Selecting the new path and putting the selection back load the selected objects' paint and
|
||||
/// stroke width into new art, so new art's paint from before, the defaults a script set included,
|
||||
/// is put back.
|
||||
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, container, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
/// Argument `i`, or `default` when it is left out.
|
||||
@@ -655,13 +864,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result
|
||||
|
||||
/// `rectangle(top, left, width, height, reversed?)`.
|
||||
fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the
|
||||
@@ -701,7 +910,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec<Anchor> {
|
||||
/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20,
|
||||
/// reversed = false)`: a closed path with `path.create`.
|
||||
fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
@@ -709,12 +918,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let reversed = flag(a, 7, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
let anchors: Vec<Value> = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect();
|
||||
make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
}
|
||||
|
||||
/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`.
|
||||
fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?;
|
||||
let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?;
|
||||
let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?);
|
||||
@@ -723,7 +932,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("ellipse with inscribed true is not available yet".into()));
|
||||
}
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The center of a polygon or star, in document coordinates.
|
||||
@@ -735,52 +944,50 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result<Point, H
|
||||
|
||||
/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`.
|
||||
fn items_polygon(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r = size(a, 3, Some(50.0), "radius")?;
|
||||
let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?;
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
}
|
||||
|
||||
/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed =
|
||||
/// false)`.
|
||||
fn items_star(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r1 = size(a, 3, Some(50.0), "radius")?;
|
||||
let r2 = size(a, 4, Some(20.0), "innerRadius")?;
|
||||
let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?;
|
||||
let reversed = flag(a, 6, "reversed")?;
|
||||
make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
}
|
||||
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with
|
||||
/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open
|
||||
/// path is set back to none in the same step, and new art keeps the paint it had before.
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or
|
||||
/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art.
|
||||
/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set
|
||||
/// back to none in the same step, and new art keeps the paint it had before.
|
||||
fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
// New art's paint is read with the document active, since activating a document can load its
|
||||
// selection's appearance into new art. Selecting the new path loads its temporary stroke into
|
||||
// new art, and putting the selection back does not undo that, so new art's paint from before
|
||||
// the path is put back.
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, into, |h| {
|
||||
let unpainted = {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
|
||||
if unpainted {
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
// ---- PathItem geometry ----
|
||||
@@ -799,13 +1006,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let closed = boolean(arg(a, 1), "closed")?;
|
||||
let item = this_path(h, a)?;
|
||||
edit_points(h, item, |subs| {
|
||||
if subs.is_empty() && closed {
|
||||
subs.push(SubPath::new(Vec::new(), closed));
|
||||
} else {
|
||||
subs.iter_mut().for_each(|sp| sp.closed = closed);
|
||||
}
|
||||
})?;
|
||||
// A path with no subpath gets an empty closed one to keep the value in; any other change keeps
|
||||
// the number of points, so the kept starts of the waiting changes stay valid.
|
||||
if closed && read_points(h, item, |subs| subs.is_empty())? {
|
||||
edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?;
|
||||
} else {
|
||||
edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1814,18 +2021,17 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
|
||||
.flatten()
|
||||
.collect();
|
||||
let partial = sel.partial(item.id).filter(|_| !held);
|
||||
let mut picked = Vec::new();
|
||||
let mut offset = 0;
|
||||
for (s, sp) in pd.subpaths.iter().enumerate() {
|
||||
for j in 0..sp.anchors.len() {
|
||||
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
|
||||
picked.push(offset + j);
|
||||
}
|
||||
}
|
||||
offset += sp.anchors.len();
|
||||
let firsts = starts(&pd.subpaths);
|
||||
match sel.partial(item.id).filter(|_| !held) {
|
||||
// Direct-selected anchors that no selected segment ends at, in subpath and anchor
|
||||
// order, which is the order of `pathPoints`.
|
||||
Some(anchors) => anchors
|
||||
.iter()
|
||||
.filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j)))
|
||||
.filter_map(|(s, j)| firsts.get(*s).map(|first| first + j))
|
||||
.collect(),
|
||||
None => (0..firsts.last().copied().unwrap_or(0)).collect(),
|
||||
}
|
||||
picked
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
@@ -2036,6 +2242,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])),
|
||||
("add", point_method(l, points_add), returns("PathPoint", &[])),
|
||||
("removeAll", point_method(l, points_remove_all), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoints"), returns("string", &[])),
|
||||
]),
|
||||
Some(super::point_function(l, points_at)),
|
||||
),
|
||||
@@ -2055,6 +2262,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
typed("PathPointSelection"),
|
||||
),
|
||||
("remove", point_method(l, pt_remove), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoint"), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
|
||||
@@ -279,6 +279,8 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
@@ -2644,11 +2644,10 @@ impl Session {
|
||||
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// One more allowance may still leave the growth past it: the person is asked again
|
||||
// while they may be, and past that the run ends unkept.
|
||||
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
|
||||
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
// What the script added must fit the allowance the last answer gave: past it, the
|
||||
// person is asked again, as a running script is at its next charge.
|
||||
if let Err(e) = job.host.charge_growth(0, 0) {
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
if job.host.waiting.get() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
@@ -2682,14 +2681,24 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
// The point changes written as the script ended went past the growth allowance.
|
||||
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
// What the script added must fit the allowance the last answer gave, which one
|
||||
// answer can leave short of what the script had already added.
|
||||
if !job.host.waiting.get()
|
||||
&& let Err(e) = job.host.charge_growth(0, 0)
|
||||
{
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
// The point changes written as the script ended, or what it added before, went past
|
||||
// the growth allowance.
|
||||
if job.host.waiting.get() {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
Some(self.script_ended(job))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3188,6 +3197,9 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
@@ -236,6 +236,17 @@ impl Palettes {
|
||||
None
|
||||
}
|
||||
|
||||
/// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the
|
||||
/// line is empty or starts with an event that can still run.
|
||||
fn drop_stale(&mut self) {
|
||||
while let Some(q) = self.waiting.front() {
|
||||
if self.resolved(q.clone()).is_some() {
|
||||
break;
|
||||
}
|
||||
self.waiting.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other
|
||||
/// engines' palettes keep their places in line. Events whose file access scopes do not cover
|
||||
/// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest
|
||||
@@ -252,7 +263,13 @@ impl Palettes {
|
||||
|
||||
/// The taken event `q` given to its control in its palette, and that palette, or `None` when it
|
||||
/// is dropped ([`Palettes::next`]).
|
||||
fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
let (p, q) = self.resolved(q)?;
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// [`Palettes::checked`] without the copy of the palette.
|
||||
fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> {
|
||||
let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?;
|
||||
if let Some(c) = control_of(&mut q.event) {
|
||||
*c = p.dialog.index_of(q.element?)?;
|
||||
@@ -271,7 +288,7 @@ impl Palettes {
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
Some((p, q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
@@ -414,6 +431,12 @@ impl Session {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// The number of the last palette event put in line, which an event added, or merged into a
|
||||
/// waiting one, changes.
|
||||
pub fn script_palette_last_ticket(&self) -> u64 {
|
||||
self.script_palettes.last_ticket
|
||||
}
|
||||
|
||||
/// The changes that wait for a run, as (palette id, the id of the control they change).
|
||||
pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> {
|
||||
self.script_palettes
|
||||
@@ -456,7 +479,12 @@ impl Session {
|
||||
/// run is going or no event waits; otherwise the run's name, or the error that ended it before
|
||||
/// it began. An open edit that cannot be settled gives its error, and the events keep waiting.
|
||||
pub fn script_palette_start(&mut self) -> Option<Result<String>> {
|
||||
if self.script_running() || self.script_palettes.waiting.is_empty() {
|
||||
if self.script_running() {
|
||||
return None;
|
||||
}
|
||||
// Events that can no longer run do not settle the open edit.
|
||||
self.script_palettes.drop_stale();
|
||||
if self.script_palettes.waiting.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An event waits while a drag or an undo group is open, which a run cannot start in.
|
||||
@@ -507,6 +535,9 @@ impl Session {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running() {
|
||||
self.script_palettes.drop_stale();
|
||||
}
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
|
||||
Reference in new issue
Block a user