Merge main into feat/scripts-api-d3-layers-artboards

This commit is contained in:
dotCooCoo committed 2026-12-01 15:07:13 -08:00
commit 9cff79a9ec
91 files changed
+5866 -272

No files matched your search

+20 -3
View File
@@ -95,10 +95,11 @@ use vectorcraft_js::{
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
pub(super) mod layers;
mod print;
mod save_open;
mod tags;
mod text;
@@ -234,6 +235,8 @@ pub(super) struct State {
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
/// The print option objects ([`print`]).
printing: print::State,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
@@ -253,6 +256,17 @@ impl State {
self.saving.get()
}
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
/// whether jobs an earlier run prepared still wait.
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
self.printing.start(printers, waiting);
}
/// The jobs the run prepared for a printer, which the run no longer holds.
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
self.printing.take_jobs()
}
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
/// when the run ends without an error.
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
@@ -3033,7 +3047,7 @@ const ENUMS: &[(&str, &[&str])] = &[
/// holds.
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
@@ -3072,6 +3086,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(save_open::application_members(l));
application.extend(print::application_members(l));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
@@ -3152,8 +3167,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
document.extend(text::styles::doc_members(l));
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
document.extend(layers::document_members(l));
document.extend(save_open::document_members(l));
document.extend(variables::document_members(l));
document.extend(save_open::document_members(l));
document.extend(print::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(
@@ -3266,6 +3282,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(variables::classes(l));
classes.extend(layers::classes(l));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.extend(tags::classes(l));
classes
}
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -717,18 +717,18 @@ fn typename(d: &Data) -> Option<&str> {
// ---- Files ----
/// The path of the `File` argument `d`, or a `TypeError` naming the method.
fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File")))
}
/// The error a refused path throws: the `File` error and the path.
fn refused(message: &str, path: &str) -> HostError {
pub(super) fn refused(message: &str, path: &str) -> HostError {
HostError::Error(format!("{message}: {path}"))
}
/// Runs `f` with the commands' reads and writes held to the script's own grants
/// ([`super::super::files::Disk::exact`]).
fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
h.disk.borrow_mut().exact = true;
let r = f();
h.disk.borrow_mut().exact = false;
@@ -747,7 +747,7 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
}
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
}
+49 -1
View File
@@ -47,6 +47,10 @@
//! run. An engine keeps no document and no run: its host functions reach the run through a link
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
//!
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
//! only after the run's changes are kept, for the frontend to send once the person approves them
//! ([`printing`]).
pub mod actions;
pub mod console;
@@ -54,6 +58,7 @@ pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod printing;
pub mod scriptui;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
@@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
}
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
command_crossing(host, id, params, false).map(|(_, value)| value)
}
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
// Point changes that wait in the object model are written before any command runs.
dom::flush(host)?;
let session = host.session.clone();
@@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
};
let mark = host.growth_mark();
let crossed = host.charge_growth(objects, added).and_then(|()| {
if !cross {
return Ok(None);
}
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
Ok(Some(data))
});
// A command whose result does not reach the script is put back, like one that failed, and so is
// the growth it was charged.
@@ -1985,6 +2004,22 @@ impl Session {
self.script_report.as_ref()
}
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
pub fn script_prints_waiting(&self) -> bool {
!self.script_prints.is_empty()
}
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
&self.script_prints
}
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
/// the frontend sends them or drops them ([`printing`]).
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
std::mem::take(&mut self.script_prints)
}
/// The Script Console: the lines of this session's runs, oldest first.
pub fn script_console(&self) -> &console::Console {
&self.script_console
@@ -2344,6 +2379,9 @@ impl Session {
),
linked: std::cell::OnceCell::new(),
});
// The printers the frontend listed are this run's alone, and a run may not print while
// jobs an earlier run prepared still wait for the person.
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
Ok(args) => args,
@@ -2645,6 +2683,12 @@ impl Session {
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
report["activeArtboards"] = boards;
}
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
let prints = host.dom.take_prints();
if !prints.is_empty() {
report["prints"] = json!(prints.len());
self.script_prints = prints;
}
let rejections = rejections_report(host, &job.realm);
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
o.insert("unhandledRejections".into(), Value::Array(rejections));
@@ -2898,6 +2942,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
}
std::mem::swap(s, &mut *cell.borrow_mut());
s.script_in_run = false;
// A panic in a member that opened the fence for one command skips its own reset.
s.script_unfenced = None;
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();
@@ -2964,6 +3010,8 @@ thread_local! {
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
/// Tests: makes the next slice panic.
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: makes the next command a member runs past the script fence panic before it runs.
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
+101
View File
@@ -0,0 +1,101 @@
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
//! prepares ([`PreparedPrint`]).
//!
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
//! for the frontend, which sends them only when the person at the computer approves them.
//!
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
//! a command line.
//!
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
/// The most printers a run lists.
pub const MAX_PRINTERS: usize = 256;
/// The longest printer name a run lists, in bytes.
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
/// The most printer jobs one run prepares.
pub const MAX_JOBS: usize = 4;
/// The most sheets of paper the jobs of one run hold together, every copy counted.
pub const MAX_SHEETS: u64 = 100;
/// The most bytes the jobs of one run hold together.
pub const MAX_JOB_BYTES: usize = 32 << 20;
/// The printers a frontend lists for a run, by name, with the system's default printer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Printers {
names: Vec<String>,
default: Option<usize>,
/// The printer turns no landscape page to fit its paper: jobs are written upright
/// (`file.print`'s `forPrinter`).
pub for_printer: bool,
}
impl Printers {
/// The printers of `list` (name, whether it is the default), in its order. A name that is
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and
/// so is a name that repeats an earlier one, though its default mark is kept. Every printer
/// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the
/// last place when it comes later.
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
let mut names: Vec<String> = Vec::new();
let mut default = None;
for (name, is_default) in list {
let full = names.len() >= MAX_PRINTERS;
if full && default.is_some() {
break;
}
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) {
continue;
}
if let Some(i) = names.iter().position(|n| *n == name) {
if is_default && default.is_none() {
default = Some(i);
}
continue;
}
if full {
if is_default && let Some(last) = names.last_mut() {
*last = name;
default = Some(MAX_PRINTERS - 1);
}
continue;
}
if is_default && default.is_none() {
default = Some(names.len());
}
names.push(name);
}
Self { names, default, for_printer }
}
/// The printers' names.
pub fn names(&self) -> &[String] {
&self.names
}
/// The system's default printer, when the list holds it.
pub fn default_name(&self) -> Option<&str> {
self.default.map(|i| self.names[i].as_str())
}
/// Whether the list holds a printer named exactly `name`.
pub fn has(&self, name: &str) -> bool {
self.names.iter().any(|n| n == name)
}
}
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
#[derive(Clone, Debug, PartialEq)]
pub struct PreparedPrint {
/// The printer, by the name the run's list gave it.
pub printer: String,
/// The title of the document it prints, the job's name in the print queue.
pub title: String,
pub pdf: Vec<u8>,
/// The sheets of paper it prints, every copy counted.
pub sheets: u64,
}