mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main into feat/scripts-api-d9-do-script
This commit is contained in:
commit
e2c4d0bbbe
335 files changed
+27813
-1674
No files matched your search
@@ -21,8 +21,9 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
use super::{Host, console};
|
||||
|
||||
/// The most bytes (UTF-8) of a dialog's message.
|
||||
@@ -48,6 +49,8 @@ pub enum DialogKind {
|
||||
Alert,
|
||||
Confirm,
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
@@ -57,6 +60,7 @@ impl DialogKind {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +89,8 @@ pub enum DialogAnswer {
|
||||
Confirm(bool),
|
||||
/// OK with the field's text, or Cancel (`None`), for `prompt`.
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -93,13 +99,14 @@ impl DialogAnswer {
|
||||
Self::Ok => DialogKind::Alert,
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
match self {
|
||||
Self::Ok => Data::Undefined,
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
@@ -112,6 +119,7 @@ impl DialogAnswer {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
|
||||
/// took before dialogs existed, is an empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, Stri
|
||||
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
|
||||
}
|
||||
|
||||
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
|
||||
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
|
||||
fn answer(a: &Value) -> Result<DialogAnswer, String> {
|
||||
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) };
|
||||
if o.len() != 2 || !o.contains_key("value") {
|
||||
return Err("must have exactly `kind` and `value`");
|
||||
return Err("must have exactly `kind` and `value`".into());
|
||||
}
|
||||
if o.get("kind").and_then(Value::as_str) == Some("window") {
|
||||
return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window);
|
||||
}
|
||||
known_answer(o).map_err(String::from)
|
||||
}
|
||||
|
||||
fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
|
||||
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
|
||||
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
|
||||
@@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm or prompt"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +215,15 @@ pub(crate) struct Dialogs {
|
||||
record_bytes: Cell<usize>,
|
||||
count: Cell<u64>,
|
||||
truncated: Cell<bool>,
|
||||
/// The ScriptUI dialog whose `show()` is running.
|
||||
window: RefCell<Option<Showing>>,
|
||||
/// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler
|
||||
/// opens is listed after it; `None` when the list had stopped at its limit.
|
||||
window_slot: Cell<Option<usize>>,
|
||||
/// That dialog waits for what the person does.
|
||||
window_waiting: Cell<bool>,
|
||||
/// The `show()` calls the run has made.
|
||||
shows: Cell<u64>,
|
||||
}
|
||||
|
||||
impl Dialogs {
|
||||
@@ -213,6 +238,10 @@ impl Dialogs {
|
||||
record_bytes: Cell::new(0),
|
||||
count: Cell::new(0),
|
||||
truncated: Cell::new(false),
|
||||
window: RefCell::default(),
|
||||
window_slot: Cell::new(None),
|
||||
window_waiting: Cell::new(false),
|
||||
shows: Cell::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +251,176 @@ impl Dialogs {
|
||||
}
|
||||
|
||||
pub(crate) fn is_waiting(&self) -> bool {
|
||||
self.waiting.borrow().is_some()
|
||||
self.waiting.borrow().is_some() || self.window_waiting.get()
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog that waits for what the person does.
|
||||
pub(crate) fn waiting_window(&self) -> Option<ScriptUiDialog> {
|
||||
if !self.window_waiting.get() {
|
||||
return None;
|
||||
}
|
||||
self.window.borrow().as_ref().map(|s| s.dialog.clone())
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs.
|
||||
pub(crate) fn showing_window(&self) -> Option<ScriptUiDialog> {
|
||||
self.window.borrow().as_ref().map(|s| s.dialog.clone())
|
||||
}
|
||||
|
||||
/// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog.
|
||||
pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> {
|
||||
if !self.window_waiting.get() {
|
||||
return Err("no script dialog waits".into());
|
||||
}
|
||||
let event = {
|
||||
let mut window = self.window.borrow_mut();
|
||||
let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) };
|
||||
let event = scriptui::check_event(&showing.dialog, event)?;
|
||||
showing.events = showing.events.saturating_add(1);
|
||||
event
|
||||
};
|
||||
self.window_waiting.set(false);
|
||||
if let Err(e) = realm.answer(event.data()) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cannot_wait(&self) -> Result<(), HostError> {
|
||||
if self.framed && !self.can_wait.get() {
|
||||
return Err(HostError::Error(
|
||||
"show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a
|
||||
/// `window` answer.
|
||||
pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> {
|
||||
self.cannot_wait()?;
|
||||
self.shows.set(self.shows.get().saturating_add(1));
|
||||
dialog.shown = self.shows.get();
|
||||
let mut showing = Showing { dialog, steps: None, events: 0 };
|
||||
if !self.framed {
|
||||
let next = self.answers.borrow_mut().pop_front();
|
||||
match next {
|
||||
Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()),
|
||||
Some(a) => {
|
||||
self.push_record(showing.record(json!("missing")));
|
||||
return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id())));
|
||||
}
|
||||
None => {
|
||||
self.push_record(showing.record(json!("missing")));
|
||||
return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.window_slot.set(self.reserve_record());
|
||||
*self.window.borrow_mut() = Some(showing);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count
|
||||
/// once the dialog ends. → the place, or `None` when the list stopped at its limit.
|
||||
fn reserve_record(&self) -> Option<usize> {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let mut records = self.records.borrow_mut();
|
||||
if self.truncated.get() || records.len() >= MAX_RECORDS {
|
||||
self.truncated.set(true);
|
||||
return None;
|
||||
}
|
||||
records.push(Value::Null);
|
||||
Some(records.len() - 1)
|
||||
}
|
||||
|
||||
/// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took
|
||||
/// in the list when it opened. When the dialogs a handler opened left no room for it, the list
|
||||
/// drops the last of them until it fits, or stops before the dialog when it does not fit
|
||||
/// alone, so it still holds the first dialogs in the order they opened, and is marked as
|
||||
/// stopped at its limit.
|
||||
fn end_record(&self, showing: &Showing, answer: Value) {
|
||||
let Some(i) = self.window_slot.take() else { return };
|
||||
let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len());
|
||||
let r = showing.record(answer);
|
||||
let bytes = size(&r);
|
||||
let mut records = self.records.borrow_mut();
|
||||
if i >= records.len() {
|
||||
return;
|
||||
}
|
||||
while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 {
|
||||
let last = records.pop().map_or(0, |r| size(&r));
|
||||
self.record_bytes.set(self.record_bytes.get().saturating_sub(last));
|
||||
self.truncated.set(true);
|
||||
}
|
||||
if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
|
||||
records.truncate(i);
|
||||
self.truncated.set(true);
|
||||
return;
|
||||
}
|
||||
self.record_bytes.set(self.record_bytes.get() + bytes);
|
||||
if let Some(slot) = records.get_mut(i) {
|
||||
*slot = r;
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the
|
||||
/// next step of its answer.
|
||||
pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result<Data, HostError> {
|
||||
self.cannot_wait()?;
|
||||
let mut window = self.window.borrow_mut();
|
||||
let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) };
|
||||
dialog.shown = showing.dialog.shown;
|
||||
showing.dialog = dialog;
|
||||
let Some(steps) = showing.steps.as_mut() else {
|
||||
drop(window);
|
||||
self.window_waiting.set(true);
|
||||
return Err(HostError::Wait);
|
||||
};
|
||||
let failure = match steps.pop_front() {
|
||||
None => "show: the dialog's answer in `answers` has no step left".to_string(),
|
||||
Some(step) => match scriptui::step_event(&showing.dialog, &step) {
|
||||
Ok(event) => {
|
||||
showing.events = showing.events.saturating_add(1);
|
||||
return Ok(event.data());
|
||||
}
|
||||
Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"),
|
||||
},
|
||||
};
|
||||
if let Some(showing) = window.take() {
|
||||
self.end_record(&showing, json!("missing"));
|
||||
}
|
||||
Err(HostError::Abort(failure))
|
||||
}
|
||||
|
||||
/// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask
|
||||
/// must have used every step of the dialog's answer.
|
||||
pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> {
|
||||
self.window_waiting.set(false);
|
||||
let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) };
|
||||
let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len);
|
||||
let steps = if left == 1 { "step" } else { "steps" };
|
||||
let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use");
|
||||
if normal && left > 0 {
|
||||
self.end_record(&showing, json!("missing"));
|
||||
return Err(HostError::Abort(unused));
|
||||
}
|
||||
// A show that a handler's error ended still ends the run when steps are left: the script
|
||||
// can catch that error, and the run must not finish as if it took every step.
|
||||
if left > 0 {
|
||||
let mut failed = self.failed.borrow_mut();
|
||||
if failed.is_none() {
|
||||
*failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false });
|
||||
}
|
||||
}
|
||||
let answer = match result {
|
||||
_ if !normal => json!("error"),
|
||||
r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64),
|
||||
r => json!(r),
|
||||
};
|
||||
self.end_record(&showing, answer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error that ended the run when its answer could not reach the script.
|
||||
@@ -257,10 +455,13 @@ impl Dialogs {
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
}
|
||||
self.window_waiting.set(false);
|
||||
if let Some(showing) = self.window.borrow_mut().take() {
|
||||
self.end_record(&showing, json!("stop"));
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
@@ -269,9 +470,14 @@ impl Dialogs {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
let r = Value::Object(r);
|
||||
self.push_record(Value::Object(r));
|
||||
}
|
||||
|
||||
fn push_record(&self, r: Value) {
|
||||
self.count.set(self.count.get().saturating_add(1));
|
||||
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
|
||||
let mut records = self.records.borrow_mut();
|
||||
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
|
||||
@@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
(text(args, 2), false, false, preset)
|
||||
}
|
||||
DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())),
|
||||
};
|
||||
if message.len() > MAX_MESSAGE_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//! them, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Application/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Documents/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describe them.
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Views/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/View/> describe them.
|
||||
//!
|
||||
//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the
|
||||
//! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's
|
||||
@@ -46,6 +48,15 @@
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
//! in view-number order, and none without one. View objects keep their window's identity when
|
||||
//! windows are renumbered. The screen mode is the app's:
|
||||
//! setting it on one view sets it on every view. Its `zoom` is 1 at the window's displayed 100%;
|
||||
//! the physical camera scale ranges from 0.0313 to 640, and the allowed zoom ratios account for
|
||||
//! the window's display density with Display Print Size at 100% Zoom enabled. `screenMode` reads
|
||||
//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not
|
||||
//! undoable and stays when the run fails.
|
||||
//! A center outside the canvas after coordinate conversion throws a `RangeError`.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
@@ -76,7 +87,7 @@ use vectorcraft_js::{
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod tags;
|
||||
mod variables;
|
||||
@@ -102,6 +113,8 @@ pub const STALE_ITEM: &str = "Stale page item";
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
pub const NOT_FOUND: &str = "Not found";
|
||||
/// The error for a view whose document no longer has a window, or that came from an earlier run.
|
||||
pub const STALE_VIEW: &str = "Stale view";
|
||||
/// The most objects one read of a selection gives, and the most a selection assignment takes.
|
||||
pub const MAX_LISTED: usize = 10_000;
|
||||
/// The longest name an object or a path query may have, in bytes.
|
||||
@@ -835,6 +848,13 @@ fn path_key(p: &str) -> String {
|
||||
if windows { p.to_lowercase() } else { p }
|
||||
}
|
||||
|
||||
/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's
|
||||
/// slices on its own, and it draws the documents as they were before the run until the run ends,
|
||||
/// so there is nothing for the call to draw. It adds no undo step.
|
||||
fn app_redraw(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is
|
||||
/// compared as text with the documents' files and is not resolved; a document whose file the
|
||||
/// automation read roots do not allow does not count, and that check can look the file up on disk.
|
||||
@@ -1481,6 +1501,179 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
|
||||
selection_of(h, doc.uid)
|
||||
}
|
||||
|
||||
fn doc_views(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Views", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
// ---- Views and View ----
|
||||
|
||||
fn views_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Views")
|
||||
}
|
||||
|
||||
fn window_of(h: &Host, doc: Doc, id: u64) -> Option<WindowView> {
|
||||
h.session.borrow().window_views.iter().find(|((uid, window), _)| *uid == doc.uid && *window == id).map(|(_, v)| *v)
|
||||
}
|
||||
|
||||
fn views_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
Ok(num(h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).count() as f64))
|
||||
}
|
||||
|
||||
fn views_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
views_doc(h, a)?;
|
||||
Ok(text("Views"))
|
||||
}
|
||||
|
||||
fn views_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn views_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
views_doc(h, a)?;
|
||||
Ok(text("[Views]"))
|
||||
}
|
||||
|
||||
fn views_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
let index = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|n| usize::try_from(n).ok()),
|
||||
_ => None,
|
||||
};
|
||||
let Some(index) = index else { return Ok(Data::Undefined) };
|
||||
let key = h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).nth(index).map(|(key, _)| *key);
|
||||
Ok(key.map_or(Data::Undefined, |(uid, id)| host_ref("View", &[float(h.run), float(uid), float(id)])))
|
||||
}
|
||||
|
||||
/// `views.index(key)`: the view at index `key`. A view has no name, so a name finds nothing.
|
||||
fn views_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => {
|
||||
views_doc(h, a)?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match views_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a `View` and its window, which must still be shown.
|
||||
fn this_view(h: &Host, a: &[Data]) -> std::result::Result<(Doc, u64, WindowView), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "View") else { return Err(HostError::Type("this is not a View".into())) };
|
||||
let &[run, uid, id] = handle.as_slice() else { return Err(HostError::Type("this is not a View".into())) };
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let id = whole(id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
let v = window_of(h, doc, id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
Ok((doc, id, v))
|
||||
}
|
||||
|
||||
/// Reads the view with `f`, given the document's script coordinates.
|
||||
fn read_view(h: &Host, a: &[Data], f: impl FnOnce(&Frame, Coords, &WindowView) -> Data) -> Answer {
|
||||
let (doc, _, v) = this_view(h, a)?;
|
||||
with_doc(h, doc, |_, st| Ok(f(&frame(st)?, h.dom.coords.get(), &v)))
|
||||
}
|
||||
|
||||
/// Changes the window of `doc` with `f`. No command runs: the change is not undoable, does not
|
||||
/// join the run's undo step and stays when the run fails.
|
||||
fn set_window(h: &Host, doc: Doc, id: u64, f: impl FnOnce(&mut WindowView)) -> Answer {
|
||||
let mut s = h.session.borrow_mut();
|
||||
let v = s
|
||||
.window_views
|
||||
.iter_mut()
|
||||
.find(|((uid, window), _)| *uid == doc.uid && *window == id)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
f(v);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn view_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_view(h, a)?;
|
||||
Ok(text("View"))
|
||||
}
|
||||
|
||||
fn view_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, _, _) = this_view(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn view_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
this_view(h, a)?;
|
||||
Ok(text("[View]"))
|
||||
}
|
||||
|
||||
/// `bounds`: `[left, top, right, bottom]` of the part of the document the canvas shows.
|
||||
fn view_bounds(h: &Host, a: &[Data]) -> Answer {
|
||||
read_view(h, a, |f, c, v| f.bounds(c, v.visible()))
|
||||
}
|
||||
|
||||
fn view_center(h: &Host, a: &[Data]) -> Answer {
|
||||
read_view(h, a, |f, c, v| pair(f.to_script(c, v.center)))
|
||||
}
|
||||
|
||||
fn view_set_center(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id, _) = this_view(h, a)?;
|
||||
let p = point(arg(a, 1), "centerPoint")?;
|
||||
let to = with_doc(h, doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), p)))?;
|
||||
if to.x.abs() > crate::MAX_COORD || to.y.abs() > crate::MAX_COORD {
|
||||
return Err(HostError::Range("centerPoint is outside the canvas".into()));
|
||||
}
|
||||
set_window(h, doc, id, |v| v.center = to)
|
||||
}
|
||||
|
||||
fn view_zoom(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
Ok(num(v.zoom))
|
||||
}
|
||||
|
||||
fn view_set_zoom(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id, v) = this_view(h, a)?;
|
||||
let z = number(arg(a, 1), "zoom")?;
|
||||
let (min, max) = v.zoom_range();
|
||||
if !(min..=max).contains(&z) {
|
||||
return Err(HostError::Range(format!("zoom must be from {min} to {max}")));
|
||||
}
|
||||
set_window(h, doc, id, |v| v.zoom = z)
|
||||
}
|
||||
|
||||
/// The `ScreenMode` value of each of the app's screen modes: Presentation Mode reads as
|
||||
/// `FULLSCREEN`.
|
||||
fn screen_mode_name(mode: u8) -> &'static str {
|
||||
match mode {
|
||||
0 => "ScreenMode.MULTIWINDOW",
|
||||
1 => "ScreenMode.DESKTOP",
|
||||
_ => "ScreenMode.FULLSCREEN",
|
||||
}
|
||||
}
|
||||
|
||||
fn view_screen_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
Ok(text(screen_mode_name(v.screen_mode)))
|
||||
}
|
||||
|
||||
fn view_set_screen_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) if s == "ScreenMode.MULTIWINDOW" => 0,
|
||||
Data::String(s) if s == "ScreenMode.DESKTOP" => 1,
|
||||
Data::String(s) if s == "ScreenMode.FULLSCREEN" => 2,
|
||||
_ => return Err(HostError::Type("give a ScreenMode value".into())),
|
||||
};
|
||||
if screen_mode_name(v.screen_mode) == screen_mode_name(mode) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// The screen mode is the app's, so every view shows the new one.
|
||||
for (_, v) in &mut h.session.borrow_mut().window_views {
|
||||
v.screen_mode = mode;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
|
||||
/// `pageItems` lists them, empty when nothing is selected.
|
||||
fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
@@ -2329,6 +2522,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
|
||||
("DocumentColorSpace", &["CMYK", "RGB"]),
|
||||
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
|
||||
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
|
||||
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
|
||||
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
|
||||
("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]),
|
||||
@@ -2378,6 +2572,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")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
@@ -2451,16 +2646,43 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"Views",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, views_typename), typed("string")),
|
||||
("length", get(l, views_length), typed("number")),
|
||||
("parent", get(l, views_parent), typed("Document")),
|
||||
("index", method(l, views_index), returns("View", &[("itemKey", "*")])),
|
||||
("toString", method(l, views_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, views_at)),
|
||||
));
|
||||
classes.push(class(
|
||||
"View",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, view_typename), typed("string")),
|
||||
("parent", get(l, view_parent), typed("Views")),
|
||||
("bounds", get(l, view_bounds), typed("Array")),
|
||||
("centerPoint", property(l, view_center, view_set_center), typed("Array")),
|
||||
("zoom", property(l, view_zoom, view_set_zoom), typed("number")),
|
||||
("screenMode", property(l, view_screen_mode, view_set_screen_mode), typed("ScreenMode")),
|
||||
("toString", method(l, view_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
None,
|
||||
|
||||
@@ -54,8 +54,10 @@ pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
@@ -136,7 +138,7 @@ impl Written {
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
/// The features `vc.api.has` knows.
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
|
||||
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"];
|
||||
/// The most commands a run's report lists in `slowestCommands`.
|
||||
pub const SLOWEST_COMMANDS: usize = 5;
|
||||
|
||||
@@ -1654,7 +1656,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
/// `e`'s message, with what to do about a failure that comes from a script written for another
|
||||
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
|
||||
fn explained(e: &RunError) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
|
||||
const HOST_OBJECTS: &[&str] = &["BridgeTalk"];
|
||||
let message = &e.message;
|
||||
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
|
||||
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
|
||||
@@ -1920,6 +1922,32 @@ impl Session {
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run
|
||||
/// asked to stop no longer waits: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_window(&self) -> Option<ScriptUiDialog> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten()
|
||||
}
|
||||
|
||||
/// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs
|
||||
/// one of its handlers. A run asked to stop is in none.
|
||||
pub fn script_window_showing(&self) -> Option<ScriptUiDialog> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten()
|
||||
}
|
||||
|
||||
/// Gives the ScriptUI dialog the running script waits at `event`; the next
|
||||
/// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still
|
||||
/// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]).
|
||||
pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) };
|
||||
with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into()))
|
||||
}
|
||||
|
||||
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
|
||||
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
|
||||
/// longer waits.
|
||||
@@ -2218,6 +2246,7 @@ impl Session {
|
||||
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
@@ -2306,6 +2335,12 @@ impl Session {
|
||||
}
|
||||
job.host.calls_this_slice.set(0);
|
||||
let outcome = run_slice(self, &mut job);
|
||||
// A failure a dialog recorded in the slice (steps a show left unused) ends the run, even
|
||||
// when the script went on.
|
||||
let outcome = match (outcome, job.host.dialogs.take_failure()) {
|
||||
(Ok(Ok(_)), Some(e)) => Ok(Err(e)),
|
||||
(outcome, _) => outcome,
|
||||
};
|
||||
match outcome {
|
||||
Err(panic) => {
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
|
||||
|
||||
@@ -0,0 +1,736 @@
|
||||
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
|
||||
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
|
||||
//! person or `script.run`'s `answers` give back.
|
||||
//!
|
||||
//! A description lists the dialog first and each control after the container that holds it. It is
|
||||
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
|
||||
//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than
|
||||
//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`],
|
||||
//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its
|
||||
//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's
|
||||
//! or progress bar's value to its range.
|
||||
//!
|
||||
//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`,
|
||||
//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`,
|
||||
//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of
|
||||
//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by
|
||||
//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out
|
||||
//! with loops over the list, from the last control to the first for sizes and from the first to the
|
||||
//! last for places, so a description's nesting takes no native stack.
|
||||
//!
|
||||
//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window",
|
||||
//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change",
|
||||
//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an
|
||||
//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog
|
||||
//! waits it takes the next step; a dialog that waits with no step left, a step for a control the
|
||||
//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run.
|
||||
//!
|
||||
//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`],
|
||||
//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`].
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
|
||||
|
||||
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
|
||||
|
||||
use super::Host;
|
||||
|
||||
/// The largest size or place, in pixels, of a dialog or a control in it.
|
||||
pub const MAX_EXTENT: f32 = 8192.0;
|
||||
/// A character's width and a line's height in VectorCraft's size estimates, in pixels.
|
||||
const CHAR: f32 = 7.0;
|
||||
const LINE: f32 = 16.0;
|
||||
|
||||
/// A dialog's element.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UiKind {
|
||||
Dialog,
|
||||
Group,
|
||||
Panel,
|
||||
StaticText,
|
||||
EditText,
|
||||
Button,
|
||||
CheckBox,
|
||||
RadioButton,
|
||||
DropDownList,
|
||||
ListBox,
|
||||
Slider,
|
||||
ProgressBar,
|
||||
}
|
||||
|
||||
impl UiKind {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
Some(match s {
|
||||
"dialog" => Self::Dialog,
|
||||
"group" => Self::Group,
|
||||
"panel" => Self::Panel,
|
||||
"statictext" => Self::StaticText,
|
||||
"edittext" => Self::EditText,
|
||||
"button" => Self::Button,
|
||||
"checkbox" => Self::CheckBox,
|
||||
"radiobutton" => Self::RadioButton,
|
||||
"dropdownlist" => Self::DropDownList,
|
||||
"listbox" => Self::ListBox,
|
||||
"slider" => Self::Slider,
|
||||
"progressbar" => Self::ProgressBar,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does it hold controls?
|
||||
pub fn container(self) -> bool {
|
||||
matches!(self, Self::Dialog | Self::Group | Self::Panel)
|
||||
}
|
||||
|
||||
/// Does a click reach it?
|
||||
pub fn clicks(self) -> bool {
|
||||
matches!(self, Self::Button | Self::CheckBox | Self::RadioButton)
|
||||
}
|
||||
}
|
||||
|
||||
/// How a container places its controls.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Orientation {
|
||||
Row,
|
||||
Column,
|
||||
Stack,
|
||||
}
|
||||
|
||||
/// Where a control goes across its container: left or top, right or bottom, the middle, or the
|
||||
/// whole width or height.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Align {
|
||||
Start,
|
||||
End,
|
||||
Center,
|
||||
Fill,
|
||||
}
|
||||
|
||||
/// A control's place and size in the dialog, from its top left corner.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct UiRect {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
}
|
||||
|
||||
/// One element of a [`ScriptUiDialog`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UiNode {
|
||||
pub kind: UiKind,
|
||||
/// A number no other element of the run has, which stays with the element while the script
|
||||
/// adds and removes controls; its index in the description when the description gives none.
|
||||
pub id: u64,
|
||||
/// The index of its container; the dialog's own is 0.
|
||||
pub parent: usize,
|
||||
pub name: String,
|
||||
pub text: String,
|
||||
/// It and every container around it are enabled.
|
||||
pub enabled: bool,
|
||||
/// It and every container around it are visible.
|
||||
pub visible: bool,
|
||||
/// A check box's or radio button's value.
|
||||
pub checked: bool,
|
||||
/// A slider's or progress bar's value, within `min` to `max`.
|
||||
pub value: f64,
|
||||
pub min: f64,
|
||||
pub max: f64,
|
||||
pub items: Vec<String>,
|
||||
/// How many times the script replaced a list's items (removed or added some), which tells a
|
||||
/// list from one that holds the same texts again.
|
||||
pub items_revision: u64,
|
||||
pub selection: Option<usize>,
|
||||
pub multiline: bool,
|
||||
pub readonly: bool,
|
||||
pub rect: UiRect,
|
||||
orientation: Orientation,
|
||||
align_children: (Option<Align>, Option<Align>),
|
||||
alignment: (Option<Align>, Option<Align>),
|
||||
spacing: f32,
|
||||
margins: [f32; 4],
|
||||
size: [Option<f32>; 2],
|
||||
min_size: [Option<f32>; 2],
|
||||
max_size: [Option<f32>; 2],
|
||||
bounds: Option<UiRect>,
|
||||
/// The characters an edit field or static text reserves room for in its width.
|
||||
characters: Option<f32>,
|
||||
}
|
||||
|
||||
impl UiNode {
|
||||
/// How much of a progress bar is done, from 0 to 1.
|
||||
pub fn fraction(&self) -> f32 {
|
||||
if self.max <= self.min || self.value <= self.min {
|
||||
return 0.0;
|
||||
}
|
||||
if self.value >= self.max {
|
||||
return 1.0;
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
// A range wider than the largest number is measured at half scale.
|
||||
let part =
|
||||
if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) };
|
||||
part.clamp(0.0, 1.0) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a run shows, checked and laid out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptUiDialog {
|
||||
/// The dialog first, then each control after the container that holds it.
|
||||
pub nodes: Vec<UiNode>,
|
||||
/// The button Enter clicks and the one Escape clicks.
|
||||
pub default_element: Option<usize>,
|
||||
pub cancel_element: Option<usize>,
|
||||
/// Which `show()` of the run this is, counted from 1; 0 before it shows.
|
||||
pub shown: u64,
|
||||
}
|
||||
|
||||
impl ScriptUiDialog {
|
||||
/// The dialog's title.
|
||||
pub fn title(&self) -> &str {
|
||||
self.nodes.first().map_or("", |n| n.text.as_str())
|
||||
}
|
||||
|
||||
/// The size of the dialog's content.
|
||||
pub fn size(&self) -> (f32, f32) {
|
||||
self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h))
|
||||
}
|
||||
|
||||
/// The first control whose name is `control`, or else the first control without a name
|
||||
/// whose text is `control`.
|
||||
pub fn find(&self, control: &str) -> Option<usize> {
|
||||
let by = |name: bool| {
|
||||
let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control };
|
||||
self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i)
|
||||
};
|
||||
by(true).or_else(|| by(false))
|
||||
}
|
||||
}
|
||||
|
||||
/// A value a control takes in a change.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiValue {
|
||||
Text(String),
|
||||
Number(f64),
|
||||
Index(Option<usize>),
|
||||
}
|
||||
|
||||
/// What the person did with a dialog.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiEvent {
|
||||
/// A click on a button, check box or radio button.
|
||||
Click(usize),
|
||||
/// A new value for an edit field, a slider or a list.
|
||||
Change(usize, UiValue),
|
||||
/// The dialog's close box.
|
||||
Close,
|
||||
}
|
||||
|
||||
impl UiEvent {
|
||||
/// The event as `show()` takes it.
|
||||
pub(crate) fn data(&self) -> Data {
|
||||
let event = |e: &str| ("event".to_string(), Data::String(e.into()));
|
||||
let id = |i: usize| ("id".to_string(), Data::Number(i as f64));
|
||||
match self {
|
||||
Self::Click(i) => Data::Object(vec![event("click"), id(*i)]),
|
||||
Self::Change(i, v) => {
|
||||
let value = match v {
|
||||
UiValue::Text(t) => Data::String(t.clone()),
|
||||
UiValue::Number(n) => Data::Number(*n),
|
||||
UiValue::Index(Some(k)) => Data::Number(*k as f64),
|
||||
UiValue::Index(None) => Data::Null,
|
||||
};
|
||||
Data::Object(vec![event("change"), id(*i), ("value".into(), value)])
|
||||
}
|
||||
Self::Close => Data::Object(vec![event("close")]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped
|
||||
/// to its range.
|
||||
pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result<UiEvent, String> {
|
||||
let id = match &event {
|
||||
UiEvent::Close => return Ok(event),
|
||||
UiEvent::Click(i) | UiEvent::Change(i, _) => *i,
|
||||
};
|
||||
let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) };
|
||||
if !n.enabled || !n.visible {
|
||||
return Err(format!("the control {} is disabled or hidden", label(n)));
|
||||
}
|
||||
match event {
|
||||
UiEvent::Click(_) if n.kind.clicks() => Ok(event),
|
||||
UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))),
|
||||
UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => {
|
||||
if t.len() > MAX_TEXT_BYTES {
|
||||
return Err("the text is longer than 16 KiB".into());
|
||||
}
|
||||
Ok(UiEvent::Change(id, UiValue::Text(t)))
|
||||
}
|
||||
UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => {
|
||||
Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max))))
|
||||
}
|
||||
UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k {
|
||||
Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))),
|
||||
k => Ok(UiEvent::Change(id, UiValue::Index(k))),
|
||||
},
|
||||
UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))),
|
||||
UiEvent::Close => Ok(UiEvent::Close),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(n: &UiNode) -> String {
|
||||
let shown = if n.name.is_empty() { &n.text } else { &n.name };
|
||||
super::dialogs::cut_to(shown, 64).to_string()
|
||||
}
|
||||
|
||||
/// A step of a `window` answer in `script.run`'s `answers`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct UiStep {
|
||||
/// The control's name or text; none for a close.
|
||||
pub control: Option<String>,
|
||||
pub event: String,
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value}
|
||||
/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a
|
||||
/// number or null.
|
||||
pub(crate) fn parse_steps(v: &Value) -> Result<Vec<UiStep>, String> {
|
||||
let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) };
|
||||
list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect()
|
||||
}
|
||||
|
||||
fn step(s: &Value) -> Option<UiStep> {
|
||||
let o = s.as_object()?;
|
||||
if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) {
|
||||
return None;
|
||||
}
|
||||
let control = match o.get("control") {
|
||||
None => None,
|
||||
Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()),
|
||||
Some(_) => return None,
|
||||
};
|
||||
let value = o.get("value").cloned();
|
||||
let event = o.get("event").and_then(Value::as_str)?;
|
||||
let fits = match event {
|
||||
"close" => control.is_none() && value.is_none(),
|
||||
"click" => control.is_some() && value.is_none(),
|
||||
"change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)),
|
||||
_ => false,
|
||||
};
|
||||
fits.then(|| UiStep { control, event: event.to_string(), value })
|
||||
}
|
||||
|
||||
/// The event `step` is for `dialog`.
|
||||
pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEvent, String> {
|
||||
let Some(control) = &step.control else { return Ok(UiEvent::Close) };
|
||||
let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) };
|
||||
let event = match (step.event.as_str(), &step.value) {
|
||||
("click", _) => UiEvent::Click(id),
|
||||
(_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
|
||||
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) {
|
||||
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
|
||||
None => return Err("a list's `value` must be an item index or null".into()),
|
||||
},
|
||||
(_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))),
|
||||
(_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)),
|
||||
_ => return Err("a change's `value` must be a string, a number or null".into()),
|
||||
};
|
||||
check_event(dialog, event)
|
||||
}
|
||||
|
||||
/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as
|
||||
/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative
|
||||
/// number.
|
||||
pub fn list_index(n: &serde_json::Number) -> Option<usize> {
|
||||
if let Some(k) = n.as_u64() {
|
||||
return Some(usize::try_from(k).unwrap_or(usize::MAX));
|
||||
}
|
||||
let f = n.as_f64()?;
|
||||
// `as` saturates a whole number too large for usize at usize::MAX.
|
||||
(f >= 0.0 && f.fract() == 0.0).then_some(f as usize)
|
||||
}
|
||||
|
||||
fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data {
|
||||
fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v)
|
||||
}
|
||||
|
||||
fn bad(what: &str) -> HostError {
|
||||
HostError::Type(format!("show: the dialog's description {what}"))
|
||||
}
|
||||
|
||||
/// A finite number.
|
||||
fn number(d: &Data) -> Option<f64> {
|
||||
match d {
|
||||
Data::Number(n) if n.is_finite() => Some(*n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(d: &Data, what: &str) -> Result<String, HostError> {
|
||||
match d {
|
||||
Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()),
|
||||
Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))),
|
||||
_ => Err(bad(&format!("has no {what}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn extent(n: f64) -> f32 {
|
||||
(n as f32).clamp(-MAX_EXTENT, MAX_EXTENT)
|
||||
}
|
||||
|
||||
fn align_name(s: &str, horizontal: Option<bool>) -> Result<(Option<Align>, Option<Align>), HostError> {
|
||||
let a = match (s, horizontal) {
|
||||
("left", Some(true) | None) => (Some(Align::Start), None),
|
||||
("right", Some(true) | None) => (Some(Align::End), None),
|
||||
("top", Some(false) | None) => (None, Some(Align::Start)),
|
||||
("bottom", Some(false) | None) => (None, Some(Align::End)),
|
||||
("center", _) => (Some(Align::Center), Some(Align::Center)),
|
||||
("fill", _) => (Some(Align::Fill), Some(Align::Fill)),
|
||||
_ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))),
|
||||
};
|
||||
Ok(match horizontal {
|
||||
Some(true) => (a.0, None),
|
||||
Some(false) => (None, a.1),
|
||||
None => a,
|
||||
})
|
||||
}
|
||||
|
||||
fn alignment(d: &Data) -> Result<(Option<Align>, Option<Align>), HostError> {
|
||||
match d {
|
||||
Data::Null | Data::Undefined => Ok((None, None)),
|
||||
Data::String(s) => align_name(s, None),
|
||||
Data::Array(a) if a.len() == 2 => {
|
||||
let part = |d: &Data, h: bool| match d {
|
||||
Data::String(s) => align_name(s, Some(h)),
|
||||
_ => Err(bad("has an alignment that is not a name")),
|
||||
};
|
||||
Ok((part(&a[0], true)?.0, part(&a[1], false)?.1))
|
||||
}
|
||||
_ => Err(bad("has an alignment that is not a name or a pair of names")),
|
||||
}
|
||||
}
|
||||
|
||||
fn numbers<const N: usize>(d: &Data) -> Result<Option<[f64; N]>, HostError> {
|
||||
match d {
|
||||
Data::Null | Data::Undefined => Ok(None),
|
||||
Data::Array(a) if a.len() == N => {
|
||||
let mut out = [0.0; N];
|
||||
for (o, v) in out.iter_mut().zip(a) {
|
||||
*o = number(v).ok_or_else(|| bad("has a size that is not a number"))?;
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
_ => Err(bad("has a size with the wrong count of numbers")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads, checks and lays out a dialog's description.
|
||||
pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
let Data::Object(top) = d else { return Err(bad("is not an object")) };
|
||||
let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) };
|
||||
if list.is_empty() {
|
||||
return Err(bad("has no dialog"));
|
||||
}
|
||||
if list.len() > MAX_CONTROLS + 1 {
|
||||
return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls")));
|
||||
}
|
||||
let mut nodes: Vec<UiNode> = Vec::with_capacity(list.len());
|
||||
let mut depth: Vec<usize> = Vec::with_capacity(list.len());
|
||||
let mut items_total = 0usize;
|
||||
for (i, n) in list.iter().enumerate() {
|
||||
let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) };
|
||||
let kind = match field(f, "kind") {
|
||||
Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?,
|
||||
_ => return Err(bad("has a control without a kind")),
|
||||
};
|
||||
let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?;
|
||||
let parent = if i == 0 {
|
||||
if kind != UiKind::Dialog || parent != -1.0 {
|
||||
return Err(bad("does not start with the dialog"));
|
||||
}
|
||||
0
|
||||
} else {
|
||||
let p = parent as usize;
|
||||
if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog {
|
||||
return Err(bad("has a control before its container"));
|
||||
}
|
||||
if !nodes[p].kind.container() {
|
||||
return Err(bad("has a control inside a control that holds none"));
|
||||
}
|
||||
p
|
||||
};
|
||||
let level = if i == 0 { 0 } else { depth[parent] + 1 };
|
||||
if level > MAX_DEPTH {
|
||||
return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep")));
|
||||
}
|
||||
depth.push(level);
|
||||
let flag = |name: &str| matches!(field(f, name), Data::Bool(true));
|
||||
let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) };
|
||||
let items = match field(f, "items") {
|
||||
Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::<Result<Vec<_>, _>>()?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
items_total = items_total.saturating_add(items.len());
|
||||
if items_total > MAX_ITEMS {
|
||||
return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all")));
|
||||
}
|
||||
let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len());
|
||||
let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0));
|
||||
if min > max {
|
||||
return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into()));
|
||||
}
|
||||
let orientation = match field(f, "orientation") {
|
||||
Data::String(s) if s == "row" => Orientation::Row,
|
||||
Data::String(s) if s == "column" => Orientation::Column,
|
||||
Data::String(s) if s == "stack" => Orientation::Stack,
|
||||
Data::Undefined => Orientation::Column,
|
||||
_ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())),
|
||||
};
|
||||
let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| {
|
||||
let (l, t) = (extent(l), extent(t));
|
||||
UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) }
|
||||
});
|
||||
// A width or height of 0 or less leaves that side to the layout.
|
||||
let sides = |name: &str| -> Result<[Option<f32>; 2], HostError> {
|
||||
Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]))
|
||||
};
|
||||
let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?);
|
||||
let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0)));
|
||||
nodes.push(UiNode {
|
||||
kind,
|
||||
id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64),
|
||||
parent,
|
||||
name: text(field(f, "name"), "a control's name")?,
|
||||
text: text(field(f, "text"), "a control's text")?,
|
||||
enabled: flag("enabled") && parent_enabled,
|
||||
visible: flag("visible") && parent_visible,
|
||||
checked: flag("value"),
|
||||
value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max),
|
||||
min,
|
||||
max,
|
||||
items,
|
||||
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
|
||||
selection,
|
||||
multiline: flag("multiline"),
|
||||
readonly: flag("readonly"),
|
||||
rect: UiRect::default(),
|
||||
orientation,
|
||||
align_children: alignment(field(f, "alignChildren"))?,
|
||||
alignment: alignment(field(f, "alignment"))?,
|
||||
spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)),
|
||||
margins,
|
||||
size,
|
||||
min_size,
|
||||
max_size,
|
||||
bounds,
|
||||
// At most as many characters as the longest text holds.
|
||||
characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)),
|
||||
});
|
||||
}
|
||||
let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button));
|
||||
let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement"));
|
||||
let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 };
|
||||
layout(&mut dialog);
|
||||
Ok(dialog)
|
||||
}
|
||||
|
||||
/// A control's own size, by VectorCraft's estimates.
|
||||
fn own_size(n: &UiNode) -> [f32; 2] {
|
||||
let chars = |s: &str| s.chars().count() as f32;
|
||||
let widest = |lines: &mut dyn Iterator<Item = &str>| lines.map(chars).fold(0.0, f32::max);
|
||||
let lines = |s: &str| s.lines().count().max(1) as f32;
|
||||
let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max);
|
||||
// `characters` reserves room for that many characters, however long the text is now.
|
||||
let reserved = n.characters.unwrap_or(0.0);
|
||||
match n.kind {
|
||||
UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0],
|
||||
UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0],
|
||||
UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0],
|
||||
UiKind::EditText if n.multiline => {
|
||||
[(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0]
|
||||
}
|
||||
UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0],
|
||||
UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0],
|
||||
UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0],
|
||||
UiKind::Slider => [160.0, 20.0],
|
||||
UiKind::ProgressBar => [160.0, 12.0],
|
||||
UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays the dialog out: each control's size from the last to the first, then each place from the
|
||||
/// first to the last.
|
||||
fn layout(d: &mut ScriptUiDialog) {
|
||||
let n = d.nodes.len();
|
||||
let mut kids: Vec<Vec<usize>> = vec![Vec::new(); n];
|
||||
for (i, node) in d.nodes.iter().enumerate().skip(1) {
|
||||
kids[node.parent].push(i);
|
||||
}
|
||||
let mut size = vec![[0.0f32; 2]; n];
|
||||
for i in (0..n).rev() {
|
||||
let node = &d.nodes[i];
|
||||
let mut s = if node.kind.container() {
|
||||
let [l, t, r, b] = node.margins;
|
||||
let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]);
|
||||
for &k in &kids[i] {
|
||||
// A hidden control, and everything in it, takes no room.
|
||||
if !d.nodes[k].visible {
|
||||
continue;
|
||||
}
|
||||
if let Some(bounds) = d.nodes[k].bounds {
|
||||
reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)];
|
||||
continue;
|
||||
}
|
||||
let [w, h] = size[k];
|
||||
count += 1;
|
||||
match node.orientation {
|
||||
Orientation::Row => (main, cross) = (main + w, cross.max(h)),
|
||||
Orientation::Column => (main, cross) = (main + h, cross.max(w)),
|
||||
Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)),
|
||||
}
|
||||
}
|
||||
if node.orientation != Orientation::Stack {
|
||||
main += node.spacing * count.saturating_sub(1) as f32;
|
||||
}
|
||||
let (w, h) = match node.orientation {
|
||||
Orientation::Row | Orientation::Stack => (main, cross),
|
||||
Orientation::Column => (cross, main),
|
||||
};
|
||||
[(w + l + r).max(reach[0]), (h + t + b).max(reach[1])]
|
||||
} else {
|
||||
own_size(node)
|
||||
};
|
||||
for axis in 0..2 {
|
||||
if let Some(v) = node.size[axis] {
|
||||
s[axis] = v;
|
||||
}
|
||||
if let Some(v) = node.min_size[axis] {
|
||||
s[axis] = s[axis].max(v);
|
||||
}
|
||||
if let Some(v) = node.max_size[axis] {
|
||||
s[axis] = s[axis].min(v);
|
||||
}
|
||||
}
|
||||
if let Some(b) = node.bounds {
|
||||
s = [b.w, b.h];
|
||||
}
|
||||
size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)];
|
||||
}
|
||||
d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] };
|
||||
for i in 0..n {
|
||||
if !d.nodes[i].kind.container() {
|
||||
continue;
|
||||
}
|
||||
let node = d.nodes[i].clone();
|
||||
let [l, t, r, b] = node.margins;
|
||||
let (x, y) = (node.rect.x + l, node.rect.y + t);
|
||||
let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0));
|
||||
let mut cursor = 0.0f32;
|
||||
for &k in &kids[i] {
|
||||
let kid = &d.nodes[k];
|
||||
let rect = if !kid.visible {
|
||||
UiRect { x, y, w: 0.0, h: 0.0 }
|
||||
} else if let Some(bounds) = kid.bounds {
|
||||
UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h }
|
||||
} else {
|
||||
let [w, h] = size[k];
|
||||
let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center);
|
||||
let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center);
|
||||
let max = kid.max_size;
|
||||
// A control that fills its container's room stays within its maximum.
|
||||
let place = |align: Align, own: f32, room: f32, axis: usize| match align {
|
||||
Align::Start => (0.0, own),
|
||||
Align::End => ((room - own).max(0.0), own),
|
||||
Align::Center => (((room - own) / 2.0).max(0.0), own),
|
||||
Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))),
|
||||
};
|
||||
match node.orientation {
|
||||
Orientation::Row => {
|
||||
let (dy, kh) = place(v_align, h, ch, 1);
|
||||
let r = UiRect { x: x + cursor, y: y + dy, w, h: kh };
|
||||
cursor += w + node.spacing;
|
||||
r
|
||||
}
|
||||
Orientation::Column => {
|
||||
let (dx, kw) = place(h_align, w, cw, 0);
|
||||
let r = UiRect { x: x + dx, y: y + cursor, w: kw, h };
|
||||
cursor += h + node.spacing;
|
||||
r
|
||||
}
|
||||
Orientation::Stack => {
|
||||
let (dx, kw) = place(h_align, w, cw, 0);
|
||||
let (dy, kh) = place(v_align, h, ch, 1);
|
||||
UiRect { x: x + dx, y: y + dy, w: kw, h: kh }
|
||||
}
|
||||
}
|
||||
};
|
||||
d.nodes[k].rect = UiRect {
|
||||
x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT),
|
||||
y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT),
|
||||
w: rect.w.clamp(0.0, MAX_EXTENT),
|
||||
h: rect.h.clamp(0.0, MAX_EXTENT),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it
|
||||
/// took.
|
||||
pub(crate) struct Showing {
|
||||
pub(crate) dialog: ScriptUiDialog,
|
||||
pub(crate) steps: Option<std::collections::VecDeque<UiStep>>,
|
||||
pub(crate) events: u64,
|
||||
}
|
||||
|
||||
impl Showing {
|
||||
/// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`,
|
||||
/// `"missing"` or `"error"`.
|
||||
pub(crate) fn record(&self, answer: Value) -> Value {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!("window"));
|
||||
r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES)));
|
||||
r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1)));
|
||||
r.insert("events".into(), json!(self.events));
|
||||
r.insert("answer".into(), answer);
|
||||
Value::Object(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The host function `name` of `Window`, for the run `link` holds.
|
||||
fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
|
||||
let l = link.clone();
|
||||
HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a)))
|
||||
}
|
||||
|
||||
/// Adds `Window` to the realm, for the run `link` holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
|
||||
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
|
||||
}
|
||||
|
||||
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
parse(args.first().unwrap_or(&Data::Undefined))
|
||||
}
|
||||
|
||||
fn open(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let dialog = described(host, args)?;
|
||||
host.dialogs.window_open(dialog)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn wait(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let dialog = described(host, args)?;
|
||||
host.dialogs.window_wait(dialog)
|
||||
}
|
||||
|
||||
fn end(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0);
|
||||
let normal = matches!(args.get(1), Some(Data::Bool(true)));
|
||||
host.dialogs.window_end(result, normal)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
Reference in new issue
Block a user