Merge main into fix/remove-all-image-frame-clip

This commit is contained in:
dotCooCoo committed 2026-12-04 12:23:45 -08:00
commit 07fb4c17ed
159 files changed
+10870 -715

No files matched your search

+151 -21
View File
@@ -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"));
+9
View File
@@ -117,6 +117,7 @@ mod tracing;
mod transform;
mod variables;
pub(super) use colors::of_color as color_data;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
@@ -1155,6 +1156,13 @@ 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.
@@ -3381,6 +3389,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", &[])),
+17 -2
View File
@@ -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)
+2 -1
View File
@@ -839,7 +839,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| {
+12 -11
View File
@@ -170,6 +170,8 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
/// 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 {
@@ -1949,18 +1951,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();
@@ -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()));
+3
View File
@@ -3188,6 +3188,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`].
+34 -3
View File
@@ -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()