mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
Merge main into fix/print-paper-size-to-cups
This commit is contained in:
commit
ec8c564a6f
82 files changed
+8289
-569
No files matched your search
@@ -51,16 +51,28 @@ def run_smoke(results):
|
||||
time.sleep(1)
|
||||
channel.settimeout(30)
|
||||
with channel, channel.makefile("rwb") as stream:
|
||||
for request_id, method, params in (
|
||||
(0, "auth", {"token": token}),
|
||||
(1, "ui.inspect", {}),
|
||||
):
|
||||
def request(request_id, method, params):
|
||||
stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode())
|
||||
stream.flush()
|
||||
response = json.loads(stream.readline())
|
||||
(results / f"{method}.json").write_text(json.dumps(response, indent=2))
|
||||
if response.get("id") != request_id or response.get("ok") is not True:
|
||||
raise RuntimeError(f"GUI request failed: {method}")
|
||||
return response.get("result") or {}
|
||||
|
||||
request(0, "auth", {"token": token})
|
||||
# The fixture opens off the UI thread: inspect until it is listed as an open document.
|
||||
deadline = time.monotonic() + 90
|
||||
request_id = 1
|
||||
while True:
|
||||
state = request(request_id, "ui.inspect", {})
|
||||
titles = [d.get("title", "") for d in state.get("documents", [])]
|
||||
if not state.get("opening") and fixture.name in titles:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError(f"GUI did not open the fixture; open documents: {titles}")
|
||||
request_id += 1
|
||||
time.sleep(1)
|
||||
finally:
|
||||
app.terminate()
|
||||
try:
|
||||
|
||||
@@ -27,7 +27,7 @@ class SmokeLifecycleTests(unittest.TestCase):
|
||||
self.channel = MagicMock()
|
||||
self.stream = self.channel.makefile.return_value.__enter__.return_value
|
||||
self.stream.readline.side_effect = [
|
||||
b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n',
|
||||
b'{"id":0,"ok":true}\n', self.inspection(1, ["original-smoke.svg"]),
|
||||
]
|
||||
self.runtime = None
|
||||
|
||||
@@ -41,6 +41,11 @@ class SmokeLifecycleTests(unittest.TestCase):
|
||||
self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel)
|
||||
self.start_patch(smoke.time, "sleep")
|
||||
|
||||
@staticmethod
|
||||
def inspection(request_id, titles, opening=()):
|
||||
result = {"documents": [{"title": title, "dirty": False} for title in titles], "opening": list(opening)}
|
||||
return (json.dumps({"id": request_id, "ok": True, "result": result}) + "\n").encode()
|
||||
|
||||
def start_patch(self, owner, name, **kwargs):
|
||||
patcher = patch.object(owner, name, **kwargs)
|
||||
result = patcher.start()
|
||||
@@ -54,7 +59,7 @@ class SmokeLifecycleTests(unittest.TestCase):
|
||||
def test_success_records_inspection_and_removes_private_runtime(self):
|
||||
smoke.run_smoke(self.results)
|
||||
report = json.loads((self.results / "ui.inspect.json").read_text())
|
||||
self.assertEqual(report["result"], {"window": "fixture"})
|
||||
self.assertEqual(report["result"]["documents"][0]["title"], "original-smoke.svg")
|
||||
requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list]
|
||||
self.assertEqual(requests[0]["method"], "auth")
|
||||
self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"])
|
||||
@@ -99,6 +104,25 @@ class SmokeLifecycleTests(unittest.TestCase):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_inspection_is_repeated_while_the_fixture_is_opening(self):
|
||||
self.stream.readline.side_effect = [
|
||||
b'{"id":0,"ok":true}\n',
|
||||
self.inspection(1, [], opening=["/results/original-smoke.svg"]),
|
||||
self.inspection(2, ["original-smoke.svg"]),
|
||||
]
|
||||
smoke.run_smoke(self.results)
|
||||
requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list]
|
||||
self.assertEqual([r["method"] for r in requests], ["auth", "ui.inspect", "ui.inspect"])
|
||||
self.assertEqual([r["id"] for r in requests], [0, 1, 2])
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_fixture_that_never_opens_is_a_failure(self):
|
||||
self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', self.inspection(1, ["Untitled-1"])]
|
||||
self.start_patch(smoke.time, "monotonic", side_effect=[0, 0, 91])
|
||||
with self.assertRaisesRegex(RuntimeError, "did not open the fixture"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_malformed_response_still_stops_child(self):
|
||||
self.stream.readline.side_effect = [b'not json\n']
|
||||
with self.assertRaises(json.JSONDecodeError):
|
||||
|
||||
@@ -9,19 +9,23 @@ on:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "37 3 * * *"
|
||||
# `labeled` so adding the `full-ci` label starts a run of all six shards.
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a PR branch cancels its older run; every push to main runs to the end.
|
||||
# A newer push to a PR branch cancels its older run; every push to main runs to the end. Adding
|
||||
# any label other than `full-ci` gets a group of its own, so it never cancels a real run.
|
||||
concurrency:
|
||||
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
group: ci-${{ github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
@@ -47,6 +51,19 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# A pull request runs only the test shards whose crates its changes reach: the crates that
|
||||
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
|
||||
# crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the
|
||||
# shards left out and why; pushes to main, the nightly run and the `full-ci` label run all
|
||||
# six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
select-tests: true
|
||||
shard-members: |
|
||||
vectorcraft-ui-egui
|
||||
vectorcraft-ui-egui
|
||||
vectorcraft-engine
|
||||
vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask
|
||||
(rest)
|
||||
(always)
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
|
||||
@@ -40,32 +40,88 @@ impl PrintService for SystemPrint {
|
||||
true
|
||||
}
|
||||
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
|
||||
self.papers.poll(printer, fresh, |printer| installed_papers(&printer))
|
||||
self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer))
|
||||
}
|
||||
}
|
||||
|
||||
/// The paper-size lookup in flight: the printer it reads and its worker's channel.
|
||||
/// A paper-size read that waits for the worker before it.
|
||||
type PaperRead = Box<dyn FnOnce(String) -> Vec<Paper> + Send>;
|
||||
|
||||
/// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits
|
||||
/// when no worker may start before its printer is given no paper sizes.
|
||||
const PAPER_WAIT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
/// The most paper-size workers alive at once, stalled ones included.
|
||||
const PAPER_WORKERS: usize = 4;
|
||||
|
||||
/// The paper-size lookup: the printer it reads with its worker's channel, the read waiting to start with the time it
|
||||
/// began waiting, and the start times and completion flags of its workers. A read starts when no worker runs, or when
|
||||
/// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive.
|
||||
#[derive(Default)]
|
||||
struct PaperLookup(Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>);
|
||||
struct PaperLookup {
|
||||
current: Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>,
|
||||
waiting: Option<(String, PaperRead, std::time::Instant)>,
|
||||
started: Vec<(std::time::Instant, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
|
||||
workers: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
/// Marks a worker finished and counts it down when it ends, including when it panics.
|
||||
struct WorkerDone(std::sync::Arc<std::sync::atomic::AtomicUsize>, std::sync::Arc<std::sync::atomic::AtomicBool>);
|
||||
|
||||
impl Drop for WorkerDone {
|
||||
fn drop(&mut self) {
|
||||
self.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl PaperLookup {
|
||||
/// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight
|
||||
/// reads another printer, or when none is in flight; the earlier one's answer is dropped.
|
||||
fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
||||
if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) {
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
let name = printer.to_string();
|
||||
let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
||||
let _ = send.send(read(name));
|
||||
});
|
||||
self.0 = Some((printer.to_string(), receive));
|
||||
/// Poll the lookup of `printer`. A new lookup of `read` is wanted when `fresh` is set, when the one in flight or
|
||||
/// waiting reads another printer, or when none is in flight; the earlier one's answer is dropped. Only the newest
|
||||
/// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`.
|
||||
/// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while
|
||||
/// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes.
|
||||
fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
||||
let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p));
|
||||
if fresh || wanted.is_none_or(|p| p != printer) {
|
||||
self.current = None;
|
||||
self.waiting = Some((printer.to_string(), Box::new(read), now));
|
||||
}
|
||||
let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) {
|
||||
self.started.retain(|(_, running)| running.load(std::sync::atomic::Ordering::SeqCst));
|
||||
let alive = self.workers.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let may_start = alive == 0
|
||||
|| (alive < PAPER_WORKERS && self.started.last().is_none_or(|(started, _)| now.saturating_duration_since(*started) >= PAPER_WAIT));
|
||||
if may_start && let Some((name, read, _)) = self.waiting.take() {
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
self.workers.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let done = WorkerDone(self.workers.clone(), running.clone());
|
||||
let printer = name.clone();
|
||||
let spawned = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
||||
let worker = done;
|
||||
let papers = read(printer);
|
||||
worker.1.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = send.send(papers);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
return Papers::Ready(Vec::new());
|
||||
}
|
||||
self.started.push((now, running));
|
||||
self.current = Some((name, receive));
|
||||
}
|
||||
if let Some((.., since)) = &self.waiting {
|
||||
if now.saturating_duration_since(*since) < PAPER_WAIT {
|
||||
return Papers::Pending;
|
||||
}
|
||||
self.waiting = None;
|
||||
return Papers::Ready(Vec::new());
|
||||
}
|
||||
let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) {
|
||||
Some(Ok(papers)) => Papers::Ready(papers),
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending,
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()),
|
||||
};
|
||||
self.0 = None;
|
||||
self.current = None;
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -339,15 +395,27 @@ mod paper_lookup_tests {
|
||||
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
|
||||
}
|
||||
|
||||
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
||||
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
||||
let mut polled = lookup.poll(printer, true, move |_| paper(key));
|
||||
/// The test clock: `secs` seconds after a fixed start.
|
||||
fn at(secs: u64) -> std::time::Instant {
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
*START.get_or_init(std::time::Instant::now) + std::time::Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
/// Poll the lookup of `printer` at `now` until it answers.
|
||||
fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec<Paper> {
|
||||
loop {
|
||||
match polled {
|
||||
match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) {
|
||||
Papers::Ready(papers) => return papers,
|
||||
Papers::Pending => std::thread::yield_now(),
|
||||
}
|
||||
polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
||||
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
||||
match lookup.poll(printer, true, at(0), move |_| paper(key)) {
|
||||
Papers::Ready(papers) => papers,
|
||||
Papers::Pending => settle(lookup, printer, at(0)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,19 +432,110 @@ mod paper_lookup_tests {
|
||||
fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() {
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (open, read) = gated("Old");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let (other, read) = gated("Office");
|
||||
assert!(matches!(lookup.poll("Office", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Office", true, at(0), read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
let _ = other.send(());
|
||||
// Back on the card printer.
|
||||
assert_eq!(answer(&mut lookup, "Card", "New"), paper("New"));
|
||||
// The dialog opens again on the card printer while a lookup of it is still running.
|
||||
let (open, read) = gated("Stale");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_lookup_holds_the_only_worker_while_the_printer_changes() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (open, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let started = std::sync::Arc::new(AtomicUsize::new(0));
|
||||
for (i, printer) in ["Office", "Card", "Office", "Plotter"].into_iter().cycle().take(40).enumerate() {
|
||||
let count = started.clone();
|
||||
let polled = lookup.poll(printer, i % 3 == 0, at(1), move |_| {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
paper("Changed")
|
||||
});
|
||||
assert!(matches!(polled, Papers::Pending), "{printer}");
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "only the stalled worker runs");
|
||||
}
|
||||
let _ = open.send(());
|
||||
// Only the newest choice is read, once the stalled worker ends.
|
||||
assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed"));
|
||||
assert_eq!(started.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiting_read_starts_beside_a_worker_stalled_for_the_wait() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (card, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
let (office, read) = gated("Office");
|
||||
assert!(matches!(lookup.poll("Office", false, at(1), read), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Office", false, at(14), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 1, "the read waits while the worker is new");
|
||||
// The worker has stalled for the whole wait: the waiting read starts beside it.
|
||||
assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker");
|
||||
let _ = office.send(());
|
||||
assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office"));
|
||||
// The worker that answered counts itself down once its thread ends.
|
||||
while lookup.workers.load(Ordering::SeqCst) > 1 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// The older worker has stalled long enough for another read to start immediately.
|
||||
let (next, began) = std::sync::mpsc::channel();
|
||||
let (open, read) = gated("Next");
|
||||
assert!(matches!(
|
||||
lookup.poll("Next", false, at(16), move |printer| {
|
||||
let _ = next.send(());
|
||||
read(printer)
|
||||
}),
|
||||
Papers::Pending
|
||||
));
|
||||
assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait");
|
||||
began.recv().expect("the next read started");
|
||||
let _ = open.send(());
|
||||
assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next"));
|
||||
drop(card);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_waiting_on_stalled_workers_gets_no_sizes_after_the_wait() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (card, read) = gated("Stalled");
|
||||
assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending));
|
||||
// More stalls fill the workers up to the limit, one wait apart.
|
||||
let mut stalls = vec![card];
|
||||
for (i, printer) in ["Plotter", "Scanner", "Fax"].into_iter().enumerate() {
|
||||
let (gate, read) = gated("Stalled");
|
||||
stalls.push(gate);
|
||||
assert!(matches!(lookup.poll(printer, true, at(30 + 15 * i as u64), read), Papers::Pending), "{printer}");
|
||||
}
|
||||
assert!(matches!(lookup.poll("Label", true, at(61), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Label", false, at(75), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
// Reopening the same printer and choosing another printer each starts a new wait.
|
||||
assert!(matches!(lookup.poll("Label", true, at(76), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending));
|
||||
assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending));
|
||||
match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) {
|
||||
Papers::Ready(papers) => assert_eq!(papers, []),
|
||||
Papers::Pending => panic!("the wait for the stalled workers did not end"),
|
||||
}
|
||||
assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS);
|
||||
// Once the stalled workers end, the next choice is read again.
|
||||
drop(stalls);
|
||||
let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) {
|
||||
Papers::Ready(papers) => papers,
|
||||
Papers::Pending => settle(&mut lookup, "Photo", at(107)),
|
||||
};
|
||||
assert_eq!(papers, paper("Ready"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1521,6 +1521,13 @@ fn store_view(s: &mut Session, v: proof::ProofView) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn Overprint Preview on, as `view.overprintPreview` with `on` true does.
|
||||
pub(crate) fn turn_on_overprint_preview(s: &mut Session) {
|
||||
let mut v = proof::view();
|
||||
v.overprint = true;
|
||||
store_view(s, v);
|
||||
}
|
||||
|
||||
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
|
||||
let on = on_param(p, "on", cmd)?;
|
||||
let mut v = proof::view();
|
||||
|
||||
@@ -18,13 +18,16 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() && !s.previewing {
|
||||
let open = s.holds_interaction() || s.docs.iter().any(|d| d.interaction.is_some());
|
||||
super::super::edit::settle_interaction(s)?;
|
||||
s.plugin_events_batch_settled(open);
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let opens = s.plugin_events_mark();
|
||||
s.batch_stash = Some(vec![]);
|
||||
let mut grouped = Vec::with_capacity(cmds.len());
|
||||
// The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback.
|
||||
@@ -39,6 +42,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Err(e) => {
|
||||
roll_back(s, start, &stash);
|
||||
// The documents the steps opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(opens);
|
||||
s.notify_text_tool("batch.rollBack");
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
|
||||
@@ -1060,7 +1060,8 @@ fn open_loaded(
|
||||
st.import_losses = losses;
|
||||
st.links_from = read_from;
|
||||
let opened = &s.documents()[index];
|
||||
let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string());
|
||||
let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid);
|
||||
s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid);
|
||||
Ok(super::merge(
|
||||
json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }),
|
||||
links.to_json(),
|
||||
|
||||
@@ -1219,6 +1219,8 @@ impl SaveJob {
|
||||
}
|
||||
if saved {
|
||||
crate::cmd::recovery::forget(s, uid);
|
||||
// Also when the document closed while its file was being written.
|
||||
s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid);
|
||||
}
|
||||
if let Some(path) = written {
|
||||
if native {
|
||||
|
||||
@@ -911,9 +911,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::newart::reset(s);
|
||||
}
|
||||
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
|
||||
// are views of the whole app, so Default leaves them as they are.
|
||||
// are views of the whole app, so Default leaves them as they are. A script's run turns it on
|
||||
// when the run ends, and not at all when the run fails.
|
||||
if settings.preview_mode == PreviewMode::Overprint {
|
||||
s.execute("view.overprintPreview", &json!({ "on": true }))?;
|
||||
if s.script_in_run {
|
||||
s.overprint_after_run = true;
|
||||
} else {
|
||||
s.execute("view.overprintPreview", &json!({ "on": true }))?;
|
||||
}
|
||||
}
|
||||
remember(s, &settings);
|
||||
let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() });
|
||||
@@ -1103,8 +1108,11 @@ impl Session {
|
||||
// them, so the new document's assigned profiles draw and are saved with it.
|
||||
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
// Linked images in its symbols, patterns and brushes are read from their files, as placing
|
||||
// a document reads them.
|
||||
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
|
||||
// a document reads them. They are part of the profile, so a script's gate does not apply to
|
||||
// them either; the automation roots in force still do.
|
||||
crate::file_access::app_folder_read(|| {
|
||||
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
|
||||
});
|
||||
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
|
||||
Ok(Some(ReadProfile { doc, file, warnings }))
|
||||
}
|
||||
|
||||
@@ -134,6 +134,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if m.appearance_output {
|
||||
v["appearanceOutput"] = json!(true);
|
||||
}
|
||||
if !m.events.is_empty() {
|
||||
v["events"] = json!(m.events);
|
||||
}
|
||||
if let Some(script) = p.script() {
|
||||
v["runtime"] = json!(m.runtime.name());
|
||||
v["script"] = json!(script);
|
||||
@@ -1546,6 +1549,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
drop(turn);
|
||||
s.plugins_changed_for_events();
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -2313,12 +2317,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plugin = plugin_by_id("plugin.info", p)?;
|
||||
let mut v = describe_installed(&plugin);
|
||||
v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null);
|
||||
v["defaults"] = Value::Object(plugin.manifest().defaults());
|
||||
v["lastError"] = json!(effect::last_error(plugin.id()));
|
||||
if !plugin.manifest().events.is_empty() {
|
||||
let (off, last) = s.plugin_event_status(&plugin);
|
||||
v["eventsOff"] = json!(off);
|
||||
v["lastEventError"] = json!(last);
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
@@ -2389,6 +2398,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !stored && !module && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
s.plugins_changed_for_events();
|
||||
Ok(json!({"removed": id}))
|
||||
}
|
||||
|
||||
@@ -2418,7 +2428,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md; events: it reacts to the events it names, see events), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -2427,7 +2437,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Plug-in Info",
|
||||
[],
|
||||
None,
|
||||
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}",
|
||||
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or a module is installed with its id again, the same module included), lastEventError? (with events: its handler's last failure, null)}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
|
||||
@@ -463,6 +463,82 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std:
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads
|
||||
/// the document and returns what it found. Every other command is refused before it runs.
|
||||
pub(crate) const EVENT_READS: &[&str] = &[
|
||||
"dataset.list",
|
||||
"graphicStyle.list",
|
||||
"guide.list",
|
||||
"image.info",
|
||||
"object.blend.info",
|
||||
"swatch.list",
|
||||
"symbol.list",
|
||||
"text.getRange",
|
||||
"transparency.info",
|
||||
"variable.list",
|
||||
];
|
||||
|
||||
/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`])
|
||||
/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs,
|
||||
/// with an error that names the event. The call runs inside [`read_only`]: every document and the
|
||||
/// session state the commands a plug-in may call change go back to how they were afterwards, and a
|
||||
/// call that changed a document, its selection, current layer or layer rows, or which document is
|
||||
/// active, is refused.
|
||||
pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result<Value, CallFailure> {
|
||||
if super::find_command(id).is_none() {
|
||||
return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() });
|
||||
}
|
||||
if !EVENT_READS.contains(&id) {
|
||||
return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") });
|
||||
}
|
||||
let (r, changed) = read_only(s, |s| call(s, run, id, args));
|
||||
if changed {
|
||||
return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") });
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs `f` and then puts every open document (its art, selection, current layer, rows and
|
||||
/// history), which document is active and the session state the commands a plug-in may call change
|
||||
/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its
|
||||
/// selection, current layer or layer rows, opened or closed one, or changed which one is active.
|
||||
/// A document `f` changed is given a newer revision, so it redraws.
|
||||
fn read_only<R>(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) {
|
||||
let saved = Saved::of(s);
|
||||
let pending_paint = s.pending_paint.clone();
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
// A panic in `f` still puts everything back before it carries on.
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(s)));
|
||||
let now = std::mem::replace(&mut s.docs, start);
|
||||
let mut changed = s.active != active || now.len() != s.docs.len();
|
||||
for st in &mut s.docs {
|
||||
let Some(n) = now.iter().find(|d| d.uid == st.uid) else {
|
||||
changed = true;
|
||||
continue;
|
||||
};
|
||||
if n.revision != st.revision
|
||||
|| !Arc::ptr_eq(&n.doc, &st.doc)
|
||||
|| n.selection != st.selection
|
||||
|| n.active_layer != st.active_layer
|
||||
|| n.layer_rows != st.layer_rows
|
||||
{
|
||||
st.revision = st.revision.max(n.revision).saturating_add(1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
s.active = active;
|
||||
saved.restore(s);
|
||||
s.pending_paint = pending_paint;
|
||||
if changed {
|
||||
s.sync_front_profiles();
|
||||
}
|
||||
match r {
|
||||
Ok(r) => (r, changed),
|
||||
Err(payload) => std::panic::resume_unwind(payload),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the
|
||||
/// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever
|
||||
/// param carries it.
|
||||
@@ -952,4 +1028,50 @@ mod tests {
|
||||
assert!(!names_key("{pathData: 1}", "path"));
|
||||
assert!(names_key("path: x", "path"));
|
||||
}
|
||||
|
||||
/// Each command an event handler may call is one a plug-in may call and one the journal does
|
||||
/// not record, listed once, in order.
|
||||
#[test]
|
||||
fn event_reads_are_reviewed_reads() {
|
||||
for id in EVENT_READS {
|
||||
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
|
||||
assert_eq!(denied(spec), None, "{id} is refused to every plug-in");
|
||||
assert!(!spec.journal, "{id} is journaled");
|
||||
}
|
||||
assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each");
|
||||
}
|
||||
|
||||
/// [`read_only`] puts back what its function changed: the document, its selection, the
|
||||
/// preferences and the paint defaults, and says that the document changed; a function that
|
||||
/// changes nothing is no change.
|
||||
#[test]
|
||||
fn read_only_puts_everything_back() {
|
||||
use serde_json::json;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len());
|
||||
let (prefs, paint) = (s.prefs.history_states, s.paint.clone());
|
||||
let ((), changed) = read_only(&mut s, |s| {
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
s.prefs.history_states += 1;
|
||||
s.paint.stroke_width += 3.0;
|
||||
});
|
||||
assert!(changed);
|
||||
let st = s.doc().unwrap();
|
||||
assert!(Arc::ptr_eq(&st.doc, &doc), "the same document");
|
||||
assert!(st.selection.objects.is_empty(), "the selection as it was");
|
||||
assert_eq!(st.history.undo.len(), history, "no undo step");
|
||||
assert!(st.revision > revision, "a newer revision, so it redraws");
|
||||
assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint));
|
||||
let revision = st.revision;
|
||||
let ((), changed) = read_only(&mut s, |s| {
|
||||
s.execute("variable.list", &json!({})).unwrap();
|
||||
});
|
||||
assert!(!changed, "a read changes nothing");
|
||||
assert_eq!(s.doc().unwrap().revision, revision);
|
||||
}
|
||||
}
|
||||
@@ -240,15 +240,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The artboards' background colors print behind the art.
|
||||
let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(PRINT, e))?;
|
||||
let doc = &*filled;
|
||||
// Raster effects print as images at the document's raster effects resolution.
|
||||
let flat = super::rasterfx::flatten_raster_effects(doc);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite;
|
||||
// The flattener expands pattern fills whose tile images need flattening, in the layers that print.
|
||||
let tile_images = postscript
|
||||
&& !bitmap
|
||||
&& super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?
|
||||
.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
|
||||
let level = match p.get("level").filter(|v| postscript && !v.is_null()) {
|
||||
Some(v) => {
|
||||
let t = super::fileio::dxf::text(v);
|
||||
@@ -256,20 +248,32 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => Level::default(),
|
||||
};
|
||||
// A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it,
|
||||
// once the options are checked, when its pages follow from the artboards alone (composite, no
|
||||
// `skipBlank`, artboards not ignored); the pages are counted again on the prepared art.
|
||||
super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?;
|
||||
// A job past `maxPages` is turned away before its raster effects are flattened and before Print
|
||||
// as Bitmap or a flattener preset prepares it, once the options are checked, when its pages
|
||||
// follow from the artboards alone (composite, no `skipBlank`, artboards not ignored); the pages
|
||||
// are counted again on the prepared art.
|
||||
let flattener = super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?;
|
||||
let by_artboards = !set.skip_blank
|
||||
&& !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore)
|
||||
&& set.output.mode == vectorcraft_pdf::OutputMode::Composite;
|
||||
if max_pages.is_some()
|
||||
&& by_artboards
|
||||
&& let Ok(pv) = vectorcraft_pdf::preview(doc, &set)
|
||||
&& too_many(pv.pages)
|
||||
{
|
||||
return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } }));
|
||||
// Those pages are counted on the artboards with no art, which is not prepared for the count.
|
||||
if max_pages.is_some() && by_artboards {
|
||||
let mut bare = Document::new(0.0, 0.0);
|
||||
bare.artboards = doc.artboards.clone();
|
||||
bare.setup.bleed = doc.setup.bleed;
|
||||
bare.color_mode = doc.color_mode;
|
||||
bare.layers.clear();
|
||||
let pv = vectorcraft_pdf::preview(&bare, &set).map_err(|e| pdf_error(PRINT, e))?;
|
||||
if too_many(pv.pages) {
|
||||
return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } }));
|
||||
}
|
||||
}
|
||||
// Raster effects print as images at the document's raster effects resolution.
|
||||
let flat = super::rasterfx::flatten_raster_effects(doc);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
// The flattener expands pattern fills whose tile images need flattening, in the layers that print.
|
||||
let tile_images =
|
||||
postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
|
||||
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
|
||||
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
|
||||
let path = str_param(p, "path");
|
||||
|
||||
@@ -817,9 +817,17 @@ fn staged_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenRepor
|
||||
/// type, images, symbol instances, live objects) and on single fills and strokes, in the layers,
|
||||
/// opacity masks, symbol definitions and pattern tiles.
|
||||
pub fn flatten_raster_effects(doc: &Document) -> Option<Document> {
|
||||
#[cfg(test)]
|
||||
FLATTENED.with(|n| n.set(n.get() + 1));
|
||||
flatten(doc, &mut FlattenReport::new(Which::All, doc))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread called [`flatten_raster_effects`].
|
||||
pub(crate) static FLATTENED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A copy of `doc` in which the objects with Photoshop-style raster effects (Radial Blur, Unsharp
|
||||
/// Mask…) or Rasterize are images as [`flatten_raster_effects`] makes them (SVG export: its
|
||||
/// filters draw the other raster effects live), or `None` when there are none.
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Startup Scripts",
|
||||
[],
|
||||
None,
|
||||
"{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry",
|
||||
"{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry; in the app, a run lists the printers once when the runs are queued and each queued run may print to them, except with reason launch, whose runs list no printers and cannot print to a printer, and a queued run waits while the jobs the run before it prepared for a printer wait for Print or Cancel",
|
||||
always,
|
||||
startup_run
|
||||
),
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod journal;
|
||||
pub mod link_watch;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod packs;
|
||||
pub mod plugin_events;
|
||||
pub mod schemas;
|
||||
pub mod steps;
|
||||
pub mod store;
|
||||
@@ -384,6 +385,9 @@ pub struct Session {
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and
|
||||
/// is not turned on when the run fails.
|
||||
pub(crate) overprint_after_run: bool,
|
||||
/// The one command a member of the script object model runs past
|
||||
/// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the
|
||||
/// member checked its options and its file.
|
||||
@@ -404,6 +408,13 @@ pub struct Session {
|
||||
/// While the active tool's actions run: their commands aren't "a command from outside the
|
||||
/// tool" ([`Session::after_command`]).
|
||||
pub(crate) in_tool_actions: bool,
|
||||
/// The events plug-ins react to that wait for delivery, and how the documents were at the last
|
||||
/// check ([`plugin_events`]).
|
||||
pub(crate) plugin_events: plugin_events::PluginEvents,
|
||||
/// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off,
|
||||
/// each top-level command delivers them when it ends. When on, the frontend calls
|
||||
/// [`Session::begin_plugin_event_frame`] once before each frame's deliveries.
|
||||
pub plugin_event_frames: bool,
|
||||
/// The warnings of the previews that settling an interaction applied, while a top-level command
|
||||
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
|
||||
settled_warnings: Option<Vec<String>>,
|
||||
|
||||
@@ -0,0 +1,872 @@
|
||||
//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed
|
||||
//! selection, current layer or set of layers by comparing each open document with how it was at the
|
||||
//! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then
|
||||
//! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the
|
||||
//! change has finished and outside any undo step.
|
||||
//!
|
||||
//! - A check runs after each top-level command, or when a frontend that sets
|
||||
//! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame.
|
||||
//! Changes between two checks are one event: a burst of selection changes is one
|
||||
//! `selection.changed` with the final selection. No check or delivery runs while an interaction
|
||||
//! is open (a drag being previewed); waiting events wait for it to end. A document opened or
|
||||
//! created since the last check is compared with how it was when it was added
|
||||
//! ([`Session::plugin_events_see_new_documents`]).
|
||||
//! A check after commit or cancel records the settled state for plug-ins installed during the interaction.
|
||||
//! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a
|
||||
//! handler runs waits for the next delivery: handlers never run inside one another.
|
||||
//! A frontend frame runs at most [`MAX_FRAME_HANDLERS`] handlers across all its deliveries,
|
||||
//! after [`Session::begin_plugin_event_frame`] resets the budget. Runnable recipients still
|
||||
//! waiting request another frame through the delivery's return value.
|
||||
//! - A handler only reads. The host applies nothing it returns, and it may call only the commands
|
||||
//! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names
|
||||
//! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]).
|
||||
//! - A handler that fails is reported once a streak; after
|
||||
//! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop
|
||||
//! until the session ends, or until a module is installed under its id again.
|
||||
//! - When no installed plug-in reacts to events, a check returns before comparing anything.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS};
|
||||
use vectorcraft_plugins::permissions::Permission;
|
||||
use vectorcraft_plugins::{LogLevel, Plugin, registry};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Most events that wait for delivery.
|
||||
pub const MAX_PENDING: usize = 32;
|
||||
|
||||
/// Most events kept after the queue dropped them for room, until the next delivery, for a
|
||||
/// rollback to put back.
|
||||
const MAX_EVICTED: usize = 1024;
|
||||
|
||||
/// Most handlers called across all deliveries in one frontend frame.
|
||||
pub const MAX_FRAME_HANDLERS: usize = 4;
|
||||
|
||||
/// Most notices kept for the frontend to show; older ones are dropped.
|
||||
pub const MAX_NOTICES: usize = 64;
|
||||
|
||||
/// The reasons a `layer.changed` event gives, in the order it lists them.
|
||||
pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"];
|
||||
|
||||
/// A document as the last check saw it.
|
||||
struct Seen {
|
||||
uid: u64,
|
||||
doc: Arc<Document>,
|
||||
selection: Selection,
|
||||
layer: Option<NodeId>,
|
||||
}
|
||||
|
||||
/// A plug-in an event is for: its id, the hash of its module and its installation
|
||||
/// ([`Plugin::serial`]), so a module removed and installed again is another recipient.
|
||||
type Recipient = (String, String, u64);
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The recipient `p` is.
|
||||
fn recipient(p: &Plugin) -> Recipient {
|
||||
#[cfg(test)]
|
||||
RECIPIENT_IDENTITIES.with(|count| count.set(count.get() + 1));
|
||||
(p.id().to_string(), p.hash().to_string(), p.serial())
|
||||
}
|
||||
|
||||
/// An event waiting for delivery: what changed, in which document, and the plug-ins it is for
|
||||
/// (those installed when it happened), each with the reasons of a `layer.changed` it was given.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Pending {
|
||||
event: Event,
|
||||
document: u64,
|
||||
to: Vec<(Recipient, Vec<&'static str>)>,
|
||||
/// When it was queued ([`PluginEvents::queued`] then).
|
||||
seq: u64,
|
||||
/// The event this enqueue pushed out of the waiting queue.
|
||||
displaced: Option<u64>,
|
||||
/// Queued by a command of the running script, whose run has not ended yet
|
||||
/// ([`Session::plugin_events_script_ended`]).
|
||||
by_script: bool,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
/// Whether this event is for `r`.
|
||||
#[cfg(test)]
|
||||
fn is_for(&self, r: &Recipient) -> bool {
|
||||
self.to.iter().any(|(x, _)| x == r)
|
||||
}
|
||||
|
||||
/// The reasons of a `layer.changed` that `r` is given.
|
||||
#[cfg(test)]
|
||||
fn reasons_for(&self, r: &Recipient) -> &[&'static str] {
|
||||
self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice())
|
||||
}
|
||||
}
|
||||
|
||||
/// One plug-in's failed handlers in a row, for the installation `serial` of the module with `hash`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Failures {
|
||||
hash: String,
|
||||
serial: u64,
|
||||
count: u32,
|
||||
disabled: bool,
|
||||
last_error: Option<String>,
|
||||
}
|
||||
|
||||
/// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Notice {
|
||||
/// The plug-in's id and name.
|
||||
pub plugin: String,
|
||||
pub name: String,
|
||||
/// The event its handler was given.
|
||||
pub event: &'static str,
|
||||
pub level: LogLevel,
|
||||
/// The text, in English for a failure.
|
||||
pub text: String,
|
||||
/// For a failure, what failed, for the frontend to word in the interface language; `None` for
|
||||
/// a line the handler wrote.
|
||||
pub failure: Option<Failure>,
|
||||
}
|
||||
|
||||
/// A failure a [`Notice`] reports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Failure {
|
||||
/// A handler failed with `error`, the first time in a row.
|
||||
Handler { error: String },
|
||||
/// The plug-in's events stopped after `count` failed handlers in a row.
|
||||
EventsOff { count: u32 },
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// The English message with `{event}`, `{error}` and `{n}` placeholders, `one` or `other` by
|
||||
/// the count.
|
||||
pub const HANDLER: &'static str = "its {event} handler failed: {error}";
|
||||
pub const EVENTS_OFF_ONE: &'static str =
|
||||
"its events are off until it is installed again or VectorCraft starts again, after {n} failed handler in a row";
|
||||
pub const EVENTS_OFF_OTHER: &'static str =
|
||||
"its events are off until it is installed again or VectorCraft starts again, after {n} failed handlers in a row";
|
||||
}
|
||||
|
||||
/// The session's plug-in event state.
|
||||
#[derive(Default)]
|
||||
pub struct PluginEvents {
|
||||
seen: Vec<Seen>,
|
||||
/// The plug-ins that reacted to events when `seen` was taken.
|
||||
seen_by: Vec<Recipient>,
|
||||
pending: VecDeque<Pending>,
|
||||
/// The events dropped from `pending` since the last delivery, oldest first, which
|
||||
/// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room.
|
||||
evicted: VecDeque<Pending>,
|
||||
/// How many events have been queued as their own entry.
|
||||
queued: u64,
|
||||
dispatching: bool,
|
||||
frame_handlers: usize,
|
||||
interaction_ended: bool,
|
||||
failures: BTreeMap<String, Failures>,
|
||||
notices: VecDeque<Notice>,
|
||||
/// The installed plug-ins that react to events, as of a registry revision.
|
||||
subscribers: Option<(u64, Vec<Arc<Plugin>>)>,
|
||||
#[cfg(test)]
|
||||
pub(crate) test_subscribers: Option<Vec<Arc<Plugin>>>,
|
||||
}
|
||||
|
||||
impl PluginEvents {
|
||||
/// The installed plug-ins that react to events (none in Safe Mode).
|
||||
fn subscribers(&mut self) -> Vec<Arc<Plugin>> {
|
||||
#[cfg(test)]
|
||||
if let Some(subs) = &self.test_subscribers {
|
||||
return subs.clone();
|
||||
}
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
return Vec::new();
|
||||
}
|
||||
let revision = registry::revision();
|
||||
if let Some((at, subs)) = &self.subscribers
|
||||
&& *at == revision
|
||||
{
|
||||
return subs.clone();
|
||||
}
|
||||
let subs: Vec<Arc<Plugin>> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect();
|
||||
self.subscribers = Some((revision, subs.clone()));
|
||||
subs
|
||||
}
|
||||
|
||||
/// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a
|
||||
/// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document
|
||||
/// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given,
|
||||
/// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the
|
||||
/// oldest event is dropped.
|
||||
fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec<Recipient>) {
|
||||
if matches!(event, Event::SelectionChanged | Event::LayerChanged)
|
||||
&& let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid)
|
||||
{
|
||||
for r in to {
|
||||
let i = match p.to.iter().position(|(x, _)| *x == r) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
p.to.push((r, Vec::new()));
|
||||
p.to.len() - 1
|
||||
}
|
||||
};
|
||||
let given = &mut p.to[i].1;
|
||||
for reason in &reasons {
|
||||
if !given.contains(reason) {
|
||||
given.push(*reason);
|
||||
}
|
||||
}
|
||||
given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut displaced = None;
|
||||
if self.pending.len() >= MAX_PENDING
|
||||
&& let Some(dropped) = self.pending.pop_front()
|
||||
{
|
||||
displaced = Some(dropped.seq);
|
||||
log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name());
|
||||
// Kept until the next delivery, in case a rollback frees room for it again.
|
||||
// When that store is full, an open goes first, since only opens are rolled back.
|
||||
if self.evicted.len() >= MAX_EVICTED {
|
||||
let at = self.evicted.iter().position(|p| p.event == Event::DocumentOpened).unwrap_or(0);
|
||||
self.evicted.remove(at);
|
||||
}
|
||||
self.evicted.push_back(dropped);
|
||||
}
|
||||
let to = to.into_iter().map(|r| (r, reasons.clone())).collect();
|
||||
self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false });
|
||||
self.queued += 1;
|
||||
}
|
||||
|
||||
fn notice(&mut self, n: Notice) {
|
||||
if self.notices.len() >= MAX_NOTICES {
|
||||
self.notices.pop_front();
|
||||
}
|
||||
self.notices.push_back(n);
|
||||
}
|
||||
|
||||
/// The failures of plug-in `p`, started again when a module was installed under its id since
|
||||
/// they were recorded, the same module again included.
|
||||
fn failures_of(&mut self, p: &Plugin) -> &mut Failures {
|
||||
let f = self.failures.entry(p.id().to_string()).or_default();
|
||||
if !f.is_of(p) {
|
||||
*f = Failures { hash: p.hash().to_string(), serial: p.serial(), ..Failures::default() };
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
|
||||
impl Failures {
|
||||
/// Whether these are the failures of `p` as it is installed now.
|
||||
fn is_of(&self, p: &Plugin) -> bool {
|
||||
self.hash == p.hash() && self.serial == p.serial()
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its
|
||||
/// contents (for comparing its options) and the ids of the rows directly in it, in order.
|
||||
type LayerRow<Id = NodeId> = (Id, Option<Id>, vectorcraft_doc::Node, Vec<Id>);
|
||||
|
||||
/// Each layer and sublayer of `doc`, in order.
|
||||
fn layer_rows(doc: &Document) -> Vec<LayerRow> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack: Vec<(&Arc<vectorcraft_doc::Node>, Option<NodeId>)> = doc.layers.iter().rev().map(|l| (l, None)).collect();
|
||||
while let Some((n, parent)) = stack.pop() {
|
||||
let NodeKind::Layer { children, .. } = &n.kind else { continue };
|
||||
stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id))));
|
||||
let rows = children.iter().map(|c| c.id).collect();
|
||||
let mut bare = (**n).clone();
|
||||
if let Some(c) = bare.children_mut() {
|
||||
c.clear();
|
||||
}
|
||||
out.push((n.id, parent, bare, rows));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new`
|
||||
/// (of `after`), counting only the rows on both sides, so an object added or deleted next to a
|
||||
/// sublayer is not a move.
|
||||
fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
let layers: HashSet<NodeId> = old.iter().map(|r| r.0).collect();
|
||||
let lists = |doc: &Document, rows: &[LayerRow]| {
|
||||
let mut m: HashMap<Option<NodeId>, Vec<NodeId>> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect();
|
||||
m.insert(None, doc.layers.iter().map(|l| l.id).collect());
|
||||
m
|
||||
};
|
||||
let (a, b) = (lists(before, old), lists(after, new));
|
||||
a.iter().any(|(parent, xs)| {
|
||||
let Some(ys) = b.get(parent) else { return false };
|
||||
let (in_x, in_y): (HashSet<NodeId>, HashSet<NodeId>) = (xs.iter().copied().collect(), ys.iter().copied().collect());
|
||||
let places = |list: &[NodeId], other: &HashSet<NodeId>| {
|
||||
list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::<Vec<_>>()
|
||||
};
|
||||
places(xs, &in_y) != places(ys, &in_x)
|
||||
})
|
||||
}
|
||||
|
||||
/// Why the layers of `after` (with current layer `layer_after`) differ from those of `before`
|
||||
/// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't.
|
||||
fn layer_reasons(before: &Arc<Document>, layer_before: Option<NodeId>, after: &Arc<Document>, layer_after: Option<NodeId>) -> Vec<&'static str> {
|
||||
let mut reasons = Vec::new();
|
||||
if layer_before != layer_after {
|
||||
reasons.push("current");
|
||||
}
|
||||
if Arc::ptr_eq(before, after) {
|
||||
return reasons;
|
||||
}
|
||||
let (old, new) = (layer_rows(before), layer_rows(after));
|
||||
reasons.extend(layer_row_reasons(&old, &new, || layers_moved_among_rows(before, &old, after, &new)));
|
||||
reasons
|
||||
}
|
||||
|
||||
/// Compares layer membership, order and options by id.
|
||||
fn layer_row_reasons<Id: Copy + Eq + Hash>(old: &[LayerRow<Id>], new: &[LayerRow<Id>], moved: impl FnOnce() -> bool) -> Vec<&'static str> {
|
||||
let mut reasons = Vec::new();
|
||||
let old_by_id: HashMap<Id, &LayerRow<Id>> = old.iter().map(|r| (r.0, r)).collect();
|
||||
let new_by_id: HashMap<Id, &LayerRow<Id>> = new.iter().map(|r| (r.0, r)).collect();
|
||||
if new.iter().any(|r| !old_by_id.contains_key(&r.0)) {
|
||||
reasons.push("added");
|
||||
}
|
||||
if old.iter().any(|r| !new_by_id.contains_key(&r.0)) {
|
||||
reasons.push("deleted");
|
||||
}
|
||||
let kept = |rows: &[LayerRow<Id>], other: &HashMap<Id, &LayerRow<Id>>| {
|
||||
rows.iter().filter(|r| other.contains_key(&r.0)).map(|r| (r.0, r.1)).collect::<Vec<_>>()
|
||||
};
|
||||
if kept(old, &new_by_id) != kept(new, &old_by_id) || moved() {
|
||||
reasons.push("reordered");
|
||||
}
|
||||
if old.iter().any(|r| new_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) {
|
||||
reasons.push("options");
|
||||
}
|
||||
reasons
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which
|
||||
/// the next delivery hands the plug-ins that react to it. Nothing is kept when none does.
|
||||
pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) {
|
||||
let to: Vec<Recipient> = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect();
|
||||
if to.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.plugin_events.queue(event, uid, Vec::new(), to);
|
||||
// An open or a save is queued as its own entry, the newest.
|
||||
if self.script_in_run
|
||||
&& let Some(p) = self.plugin_events.pending.back_mut()
|
||||
{
|
||||
p.by_script = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// At the end of a script's run. The opens and saves its commands queued wait until then, also
|
||||
/// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run
|
||||
/// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since
|
||||
/// the documents they opened were discarded with its working copy. Its saves stay, since the
|
||||
/// files they wrote stay written, and so do the events of documents a frontend opened while the
|
||||
/// run was paused. The next delivery gives what is left in the order it was queued.
|
||||
pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) {
|
||||
let events = &mut self.plugin_events;
|
||||
if !kept {
|
||||
events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
|
||||
events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
|
||||
}
|
||||
for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) {
|
||||
p.by_script = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far.
|
||||
pub(crate) fn plugin_events_mark(&self) -> u64 {
|
||||
self.plugin_events.queued
|
||||
}
|
||||
|
||||
/// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback
|
||||
/// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The
|
||||
/// saves stay, since the files they wrote stay written.
|
||||
/// Events displaced by those opens return in their original order, ahead of the events still
|
||||
/// waiting, while there is room.
|
||||
pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) {
|
||||
let events = &mut self.plugin_events;
|
||||
let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark;
|
||||
let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect();
|
||||
events.pending.retain(|p| !undone(p));
|
||||
events.evicted.retain(|p| !undone(p));
|
||||
while events.pending.len() < MAX_PENDING
|
||||
&& let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq))
|
||||
&& let Some(p) = events.evicted.remove(at)
|
||||
{
|
||||
events.pending.push_front(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares each open document with how the last check saw it and queues the events its changes
|
||||
/// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the
|
||||
/// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in
|
||||
/// installed since the last check is given none: the
|
||||
/// change may have come before it. A waiting event is no longer for a plug-in that is not
|
||||
/// installed now, so a module removed and installed again is not given it. Nothing is compared
|
||||
/// while an interaction is open, nor when no plug-in reacts to events.
|
||||
fn check_plugin_events(&mut self, interaction_ended: bool) {
|
||||
if self.script_in_run {
|
||||
return;
|
||||
}
|
||||
let subs = self.plugin_events.subscribers();
|
||||
if subs.is_empty() {
|
||||
self.plugin_events.seen.clear();
|
||||
self.plugin_events.seen_by.clear();
|
||||
self.plugin_events.pending.clear();
|
||||
self.plugin_events.evicted.clear();
|
||||
return;
|
||||
}
|
||||
let installed: Vec<Recipient> = subs.iter().map(|p| recipient(p)).collect();
|
||||
self.plugin_events.pending.retain_mut(|p| {
|
||||
p.to.retain(|(r, _)| installed.contains(r));
|
||||
!p.to.is_empty()
|
||||
});
|
||||
if self.holds_interaction() || (self.in_tool_actions && !interaction_ended) || self.docs.iter().any(|d| d.interaction.is_some()) {
|
||||
return;
|
||||
}
|
||||
let mut events = std::mem::take(&mut self.plugin_events);
|
||||
let before = std::mem::take(&mut events.seen);
|
||||
let before_by = std::mem::take(&mut events.seen_by);
|
||||
let to = |e: Event| -> Vec<Recipient> {
|
||||
subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect()
|
||||
};
|
||||
let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged));
|
||||
let mut seen = Vec::with_capacity(self.docs.len());
|
||||
for st in &self.docs {
|
||||
if let Some(old) = before.iter().find(|s| s.uid == st.uid) {
|
||||
if !selection.is_empty() && old.selection != st.selection {
|
||||
events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone());
|
||||
}
|
||||
if !layers.is_empty() {
|
||||
let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer);
|
||||
if !reasons.is_empty() {
|
||||
events.queue(Event::LayerChanged, st.uid, reasons, layers.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer });
|
||||
}
|
||||
events.seen = seen;
|
||||
events.seen_by = subs.iter().map(|p| recipient(p)).collect();
|
||||
events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document));
|
||||
self.plugin_events = events;
|
||||
}
|
||||
|
||||
/// Resets the handler budget for a frontend frame. Call once before the frame's deliveries,
|
||||
/// including background work and all UI passes, when [`Session::plugin_event_frames`] is on.
|
||||
pub fn begin_plugin_event_frame(&mut self) {
|
||||
self.plugin_events.frame_handlers = 0;
|
||||
}
|
||||
|
||||
/// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the
|
||||
/// handlers of the events waiting, oldest first, one handler at a time. While a handler runs,
|
||||
/// this returns at once: what the handler's calls change waits for the next delivery. While an
|
||||
/// interaction is open, the events wait for the first delivery after it ends.
|
||||
/// A set-aside interaction also holds events. A frontend frame calls at most
|
||||
/// [`MAX_FRAME_HANDLERS`] handlers across all deliveries since [`Session::begin_plugin_event_frame`]
|
||||
/// and keeps the remaining recipients for later frames. Returns whether runnable handlers
|
||||
/// remain queued, so the frontend can request another frame even when no handler wrote a notice.
|
||||
pub fn deliver_plugin_events(&mut self) -> bool {
|
||||
if self.plugin_events.dispatching {
|
||||
return false;
|
||||
}
|
||||
self.check_plugin_events(false);
|
||||
if self.plugin_events.pending.is_empty()
|
||||
|| self.holds_interaction()
|
||||
|| self.in_tool_actions
|
||||
|| self.docs.iter().any(|d| d.interaction.is_some())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let subs: HashMap<Recipient, Arc<Plugin>> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect();
|
||||
self.plugin_events.dispatching = true;
|
||||
self.plugin_events.evicted.clear();
|
||||
// A handler's calls are checked as calls from outside, also when the command that ended
|
||||
// played saved steps ([`Session::replay`] puts its flag back only after this delivery).
|
||||
let replaying = self.set_replaying(false);
|
||||
// The commands a handler calls run nested, never journaled; a panic in one leaves the depth
|
||||
// as it was found.
|
||||
let depth = self.depth;
|
||||
self.depth += 1;
|
||||
// An open or a save a running script queued waits for the end of the run
|
||||
// ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its
|
||||
// slices: a run that fails discards the documents it opened.
|
||||
let mut held = VecDeque::new();
|
||||
let mut budget = if self.plugin_event_frames { MAX_FRAME_HANDLERS.saturating_sub(self.plugin_events.frame_handlers) } else { usize::MAX };
|
||||
let waiting = self.plugin_events.pending.len();
|
||||
for _ in 0..waiting {
|
||||
let Some(mut p) = self.plugin_events.pending.pop_front() else { break };
|
||||
if p.by_script {
|
||||
held.push_back(p);
|
||||
continue;
|
||||
}
|
||||
if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) {
|
||||
continue;
|
||||
}
|
||||
let mut served = 0;
|
||||
for (i, (r, reasons)) in p.to.iter().enumerate() {
|
||||
let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else {
|
||||
served = i + 1;
|
||||
continue;
|
||||
};
|
||||
if self.plugin_events.failures_of(plugin).disabled {
|
||||
served = i + 1;
|
||||
continue;
|
||||
}
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
self.run_handler(plugin, &p, reasons);
|
||||
served = i + 1;
|
||||
budget -= 1;
|
||||
if self.plugin_event_frames {
|
||||
self.plugin_events.frame_handlers += 1;
|
||||
}
|
||||
}
|
||||
p.to.drain(..served);
|
||||
if !p.to.is_empty() {
|
||||
held.push_back(p);
|
||||
}
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The held events are older than any a handler's calls queued meanwhile.
|
||||
while let Some(p) = held.pop_back() {
|
||||
self.plugin_events.pending.push_front(p);
|
||||
}
|
||||
self.depth = depth;
|
||||
self.set_replaying(replaying);
|
||||
self.plugin_events.dispatching = false;
|
||||
self.plugin_events.pending.iter().any(|p| {
|
||||
!p.by_script
|
||||
&& (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document))
|
||||
&& p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0))
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a
|
||||
/// `selection.changed` only with `doc.read`, and `reasons`, the reasons of a `layer.changed`
|
||||
/// it was given.
|
||||
fn event_json(&self, plugin: &Plugin, p: &Pending, reasons: &[&'static str]) -> Value {
|
||||
let mut v = json!({ "type": p.event.name(), "document": p.document });
|
||||
let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v };
|
||||
match p.event {
|
||||
Event::SelectionChanged => {
|
||||
let objects = &st.selection.objects;
|
||||
v["count"] = json!(objects.len());
|
||||
v["truncated"] = json!(false);
|
||||
v["ids"] = Value::Null;
|
||||
if plugin.manifest().permissions().contains(&Permission::DocRead) {
|
||||
v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::<Vec<_>>());
|
||||
v["truncated"] = json!(objects.len() > MAX_EVENT_IDS);
|
||||
}
|
||||
}
|
||||
Event::LayerChanged => {
|
||||
v["layer"] = json!(st.active_layer.map(|l| l.0));
|
||||
v["reasons"] = json!(reasons);
|
||||
}
|
||||
Event::DocumentOpened | Event::DocumentSaved => {}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Calls `plugin`'s handler with event `p`, given `reasons`, and records what it wrote and
|
||||
/// whether it failed.
|
||||
fn run_handler(&mut self, plugin: &Arc<Plugin>, p: &Pending, reasons: &[&'static str]) {
|
||||
let event = p.event.name();
|
||||
let text = serde_json::to_vec(&self.event_json(plugin, p, reasons)).unwrap_or_default();
|
||||
let m = plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() {
|
||||
let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false);
|
||||
let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args);
|
||||
plugin.run_event(&text, Some(&mut bridge))
|
||||
} else {
|
||||
plugin.run_event(&text, None)
|
||||
};
|
||||
let (id, name) = (plugin.id().to_string(), m.name.clone());
|
||||
for line in report.lines {
|
||||
self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text, failure: None });
|
||||
}
|
||||
let failures = self.plugin_events.failures_of(plugin);
|
||||
let e = match r {
|
||||
Ok(()) => {
|
||||
failures.count = 0;
|
||||
return;
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
failures.count += 1;
|
||||
failures.last_error = Some(e.clone());
|
||||
let (count, first) = (failures.count, failures.count == 1);
|
||||
log::warn!("plug-in {id}: its {event} handler failed: {e}");
|
||||
if first {
|
||||
let text = Failure::HANDLER.replace("{event}", event).replace("{error}", &e);
|
||||
let failure = Some(Failure::Handler { error: e });
|
||||
self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text, failure });
|
||||
}
|
||||
if count >= MAX_EVENT_FAILURES {
|
||||
self.plugin_events.failures_of(plugin).disabled = true;
|
||||
let text = if count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }.replace("{n}", &count.to_string());
|
||||
let failure = Some(Failure::EventsOff { count });
|
||||
self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text, failure });
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes each open document the last check didn't see, one opened or created since, as it is
|
||||
/// now, so the next check compares it with this state: a change made to it before the next
|
||||
/// delivery gives its event. Called when a document is added and after each top-level command.
|
||||
/// When no check has seen a plug-in that reacts to events, the first check runs now for the
|
||||
/// plug-ins installed. Nothing is kept when none is installed, nor for a document in an
|
||||
/// interaction.
|
||||
pub(crate) fn plugin_events_see_new_documents(&mut self) {
|
||||
if self.plugin_events.seen_by.is_empty() {
|
||||
// No check has run since plug-ins that react to events were installed: one now takes
|
||||
// every open document as it is, for the plug-ins installed now.
|
||||
if !self.plugin_events.subscribers().is_empty() {
|
||||
self.check_plugin_events(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for st in &self.docs {
|
||||
if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) {
|
||||
self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delivers the events of a top-level command that just ended, unless the frontend delivers
|
||||
/// them once a frame ([`Session::plugin_event_frames`]) or a script is running.
|
||||
pub(crate) fn plugin_events_after_command(&mut self) {
|
||||
self.plugin_events_see_new_documents();
|
||||
if std::mem::take(&mut self.plugin_events.interaction_ended) {
|
||||
self.plugin_events_interaction_ended();
|
||||
}
|
||||
if !self.plugin_event_frames && !self.script_in_run {
|
||||
self.deliver_plugin_events();
|
||||
}
|
||||
}
|
||||
|
||||
/// After a plug-in was installed or removed, compares the open documents with the last check
|
||||
/// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that
|
||||
/// were installed then, and what changes from now on to every plug-in installed now, also
|
||||
/// before the next delivery.
|
||||
pub(crate) fn plugins_changed_for_events(&mut self) {
|
||||
if !self.plugin_events.dispatching {
|
||||
self.check_plugin_events(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a batch's steps run: checks the documents when the batch settled an interaction
|
||||
/// (`settled`), or when the installed plug-ins differ from the last check's, so that a plug-in
|
||||
/// installed since then is given the batch's changes. Otherwise the last check stays the
|
||||
/// baseline.
|
||||
pub(crate) fn plugin_events_batch_settled(&mut self, settled: bool) {
|
||||
if self.plugin_events.dispatching || self.batch_stash.is_some() || self.script_in_run {
|
||||
return;
|
||||
}
|
||||
if !settled {
|
||||
let installed: Vec<Recipient> = self.plugin_events.subscribers().iter().map(|p| recipient(p)).collect();
|
||||
if installed == self.plugin_events.seen_by {
|
||||
// Events for plug-ins removed, or for documents closed, since then still leave the
|
||||
// queue first.
|
||||
let set: HashSet<&Recipient> = installed.iter().collect();
|
||||
let docs = &self.docs;
|
||||
self.plugin_events.pending.retain_mut(|p| {
|
||||
p.to.retain(|(r, _)| set.contains(r));
|
||||
!p.to.is_empty() && (p.event.outlives_document() || docs.iter().any(|d| d.uid == p.document))
|
||||
});
|
||||
self.plugin_events.seen.retain(|s| docs.iter().any(|d| d.uid == s.uid));
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.check_plugin_events(true);
|
||||
}
|
||||
|
||||
/// Records the settled document state after an interaction ends, including subscribers
|
||||
/// installed during its previews. Tool actions may still be finishing; handlers wait for them.
|
||||
pub(crate) fn plugin_events_interaction_ended(&mut self) {
|
||||
if !self.plugin_events.dispatching {
|
||||
if self.depth == 0 {
|
||||
self.check_plugin_events(true);
|
||||
} else {
|
||||
self.plugin_events.interaction_ended = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The handlers' log lines and failures since the last call, oldest first.
|
||||
pub fn take_plugin_event_notices(&mut self) -> Vec<Notice> {
|
||||
self.plugin_events.notices.drain(..).collect()
|
||||
}
|
||||
|
||||
/// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and
|
||||
/// the last failure's error.
|
||||
pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option<String>) {
|
||||
match self.plugin_events.failures.get(p.id()).filter(|f| f.is_of(p)) {
|
||||
Some(f) => (f.disabled, f.last_error.clone()),
|
||||
None => (false, None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_comparison_indexes_ids_instead_of_scanning_each_snapshot() {
|
||||
use std::cell::Cell;
|
||||
use std::hash::Hasher;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Counted<'a> {
|
||||
value: u64,
|
||||
comparisons: &'a Cell<usize>,
|
||||
}
|
||||
impl PartialEq for Counted<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.comparisons.set(self.comparisons.get() + 1);
|
||||
self.value == other.value
|
||||
}
|
||||
}
|
||||
impl Eq for Counted<'_> {}
|
||||
impl Hash for Counted<'_> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.value.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
let comparisons = Cell::new(0);
|
||||
let doc = Document::new(100.0, 100.0);
|
||||
let node = (*doc.layers[0]).clone();
|
||||
let old: Vec<LayerRow<Counted<'_>>> =
|
||||
(0..1024).map(|value| (Counted { value, comparisons: &comparisons }, None, node.clone(), Vec::new())).collect();
|
||||
let mut new = old.clone();
|
||||
new.last_mut().unwrap().2.name = Some("Notes".into());
|
||||
assert_eq!(layer_row_reasons(&old, &new, || false), ["options"]);
|
||||
assert!(comparisons.get() < old.len() * 32, "{} id comparisons for {} layers", comparisons.get(), old.len());
|
||||
}
|
||||
|
||||
/// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of
|
||||
/// the changes it was given.
|
||||
#[test]
|
||||
fn waiting_selection_and_layer_events_of_a_document_merge() {
|
||||
let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2));
|
||||
let mut e = PluginEvents::default();
|
||||
e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]);
|
||||
e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]);
|
||||
e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]);
|
||||
e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]);
|
||||
e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]);
|
||||
e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]);
|
||||
e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]);
|
||||
e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]);
|
||||
let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(Event::SelectionChanged, 1, vec![]),
|
||||
(Event::LayerChanged, 1, vec!["current", "deleted", "options"]),
|
||||
(Event::SelectionChanged, 2, vec![]),
|
||||
(Event::DocumentSaved, 1, vec![]),
|
||||
(Event::DocumentSaved, 1, vec![]),
|
||||
]
|
||||
);
|
||||
assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given");
|
||||
assert!(!e.pending[0].is_for(&b));
|
||||
}
|
||||
|
||||
/// While a handler runs, a delivery returns at once; the change waits for the next one, which
|
||||
/// hands it over once.
|
||||
#[test]
|
||||
fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() {
|
||||
use serde_json::json;
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let id = "test.events.nested";
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let manifest =
|
||||
format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#);
|
||||
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
|
||||
let grant = json!(["progress", "events"]);
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
|
||||
s.plugin_event_frames = true;
|
||||
let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count();
|
||||
s.plugin_events.dispatching = true;
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.deliver_plugin_events();
|
||||
assert_eq!(given(&mut s), 0, "not inside the running handler");
|
||||
s.plugin_events.dispatching = false;
|
||||
s.deliver_plugin_events();
|
||||
assert_eq!(given(&mut s), 1);
|
||||
s.deliver_plugin_events();
|
||||
assert_eq!(given(&mut s), 0, "once");
|
||||
s.execute("plugin.remove", &json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_most_32_events_wait() {
|
||||
let mut e = PluginEvents::default();
|
||||
for uid in 0..(MAX_PENDING as u64 + 5) {
|
||||
e.queue(Event::DocumentOpened, uid, vec![], vec![]);
|
||||
}
|
||||
assert_eq!(e.pending.len(), MAX_PENDING);
|
||||
assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rollback_of_opens_brings_back_the_events_they_pushed_out() {
|
||||
let mut s = Session::new();
|
||||
let r: Recipient = ("a".into(), "h".into(), 1);
|
||||
for uid in 1..=3 {
|
||||
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]);
|
||||
}
|
||||
let mark = s.plugin_events_mark();
|
||||
for uid in 0..(2 * MAX_PENDING) as u64 {
|
||||
s.plugin_events.queue(Event::DocumentOpened, 100 + uid, vec![], vec![r.clone()]);
|
||||
}
|
||||
assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the save was pushed out");
|
||||
s.plugin_events.queue(Event::DocumentSaved, 999, vec![], vec![r]);
|
||||
s.forget_plugin_opens_since(mark);
|
||||
let left: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event.name(), p.document)).collect();
|
||||
assert_eq!(
|
||||
left,
|
||||
[
|
||||
(Event::DocumentSaved.name(), 1),
|
||||
(Event::DocumentSaved.name(), 2),
|
||||
(Event::DocumentSaved.name(), 3),
|
||||
(Event::DocumentSaved.name(), 999)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() {
|
||||
let mut s = Session::new();
|
||||
for uid in 0..=MAX_PENDING as u64 {
|
||||
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![]);
|
||||
}
|
||||
assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0);
|
||||
s.plugin_events.pending.pop_front();
|
||||
let waiting = s.plugin_events.pending.clone();
|
||||
let mark = s.plugin_events_mark();
|
||||
s.plugin_events.queue(Event::DocumentOpened, 100, vec![], vec![]);
|
||||
s.forget_plugin_opens_since(mark);
|
||||
assert_eq!(s.plugin_events.pending, waiting);
|
||||
assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0);
|
||||
}
|
||||
}
|
||||
@@ -2477,8 +2477,12 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the
|
||||
/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path
|
||||
/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does
|
||||
/// nothing.
|
||||
/// nothing. Type in a document in the back that is not measured yet is measured first, as the
|
||||
/// switch to that document would measure it.
|
||||
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option<Rect>, Frame), HostError> {
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && rests_on_type(h, item) {
|
||||
h.session.borrow_mut().measure_back_type(item.doc.uid);
|
||||
}
|
||||
with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?)))
|
||||
}
|
||||
|
||||
@@ -2550,20 +2554,41 @@ fn item_height(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height())))
|
||||
}
|
||||
|
||||
/// Whether the item's bounds can rest on laid-out type: it holds type, a symbol instance or a
|
||||
/// placed document. Such bounds in a document in the back may be laid out in another document's
|
||||
/// composite fonts, so the setters measure them only after the switch to the document.
|
||||
fn rests_on_type(h: &Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).is_none_or(|n| {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_)));
|
||||
found
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one
|
||||
/// stays).
|
||||
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
// Measured once the document is active.
|
||||
edit_item_with(h, item, |h| {
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) };
|
||||
// The distance to move, or `None` when the item is already there or has no bounds.
|
||||
let delta = |h: &Host| -> std::result::Result<Option<(f64, f64)>, HostError> {
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(None) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
|
||||
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
|
||||
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
|
||||
Ok((dx.abs() > 1e-9 || dy.abs() > 1e-9).then_some((dx, dy)))
|
||||
};
|
||||
// An item already in place stays, and its document stays in the back.
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && delta(h)?.is_none() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Measured again once the document is active.
|
||||
edit_item_with(h, item, |h| {
|
||||
if let Some((dx, dy)) = delta(h)? {
|
||||
command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -2601,19 +2626,27 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
// Measured once the document is active, so the ratio applies to the bounds the scale works on.
|
||||
edit_item_with(h, item, |h| {
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) };
|
||||
// The bounds to scale and the percentage, or `None` when the item already has that size or has
|
||||
// no bounds.
|
||||
let scale = |h: &Host| -> std::result::Result<Option<(Rect, f64)>, HostError> {
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(None) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
return Err(HostError::Error(format!("the object has no {what} to scale")));
|
||||
}
|
||||
if (now - size).abs() < 1e-9 {
|
||||
return Ok(());
|
||||
Ok(((now - size).abs() >= 1e-9).then_some((r, size / now * 100.0)))
|
||||
};
|
||||
// An item already that size stays, and its document stays in the back.
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && scale(h)?.is_none() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Measured again once the document is active, so the ratio applies to the bounds the scale
|
||||
// works on.
|
||||
edit_item_with(h, item, |h| {
|
||||
if let Some((r, pct)) = scale(h)? {
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?;
|
||||
}
|
||||
let pct = size / now * 100.0;
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
|
||||
@@ -69,9 +69,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, doc_of,
|
||||
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number,
|
||||
on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method,
|
||||
named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -248,8 +248,9 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
|
||||
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
|
||||
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// that is, is written at once, so that its points read as the grid snaps them.
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
|
||||
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
|
||||
/// points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
@@ -415,20 +416,44 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -436,10 +461,13 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(_) => match items_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -462,7 +490,7 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
|
||||
@@ -545,6 +545,8 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile.
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
@@ -693,6 +695,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) {
|
||||
let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE");
|
||||
job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v));
|
||||
job.source = source;
|
||||
job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE");
|
||||
let g = job.group("color");
|
||||
for (k, v) in &set {
|
||||
if *k == "intent" {
|
||||
@@ -992,7 +995,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// each assigned name against the list it must come from, and puts the checked names into the
|
||||
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws.
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
@@ -1022,6 +1025,9 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
}
|
||||
job.group("advanced").insert("flattenerPreset".into(), json!(n));
|
||||
}
|
||||
if job.custom && job.profile.is_none() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.profile.take() {
|
||||
let what = "PrintColorManagementOptions.name";
|
||||
let n = plain_name(what, "color profile", &name)?;
|
||||
|
||||
@@ -1015,12 +1015,13 @@ const SAVES_SOME_ARTBOARDS: &str =
|
||||
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// Whether the file that saving `st` with its remembered options writes would omit artboards. A
|
||||
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai`
|
||||
/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its
|
||||
/// `range` names only the separate files. An EPS file embeds the whole document in its main file,
|
||||
/// so its `artboardRange` never omits an artboard from what reopens.
|
||||
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file holds every
|
||||
/// artboard, and its `range` names only the separate files of `separateArtboards`. A `.ai` file
|
||||
/// other than a legacy version 7 one with `separateArtboards` holds every artboard too. An EPS
|
||||
/// file embeds the whole document in its main file, so its `artboardRange` never omits an artboard
|
||||
/// from what reopens.
|
||||
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
if st.format == "eps" {
|
||||
if matches!(st.format, "eps" | "vectorcraft" | "template") {
|
||||
return false;
|
||||
}
|
||||
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
|
||||
@@ -1032,7 +1033,7 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
return true;
|
||||
}
|
||||
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
|
||||
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
|
||||
if matches!(st.format, "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
|
||||
return false;
|
||||
}
|
||||
let count = st.doc.artboards.len();
|
||||
|
||||
@@ -498,11 +498,13 @@ struct World {
|
||||
|
||||
/// The choices outside the documents that a script's commands can change: the preferences, the
|
||||
/// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state.
|
||||
/// item, the Eyedropper's sample, the envelope defaults, the Caps Lock state and whether Overprint
|
||||
/// Preview turns on when the run ends.
|
||||
#[derive(Clone)]
|
||||
struct Choices {
|
||||
prefs: crate::Prefs,
|
||||
caps_lock: bool,
|
||||
overprint_after_run: bool,
|
||||
eyedropper_sample: Option<Arc<vectorcraft_doc::Node>>,
|
||||
global_edit_options: cmd::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
@@ -518,6 +520,7 @@ impl Choices {
|
||||
Self {
|
||||
prefs: s.prefs.clone(),
|
||||
caps_lock: s.caps_lock,
|
||||
overprint_after_run: s.overprint_after_run,
|
||||
eyedropper_sample: s.eyedropper_sample.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
@@ -532,6 +535,7 @@ impl Choices {
|
||||
fn put(self, s: &mut Session) {
|
||||
s.prefs = self.prefs;
|
||||
s.caps_lock = self.caps_lock;
|
||||
s.overprint_after_run = self.overprint_after_run;
|
||||
s.eyedropper_sample = self.eyedropper_sample;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
@@ -546,6 +550,7 @@ impl Choices {
|
||||
use std::mem::swap;
|
||||
swap(&mut self.prefs, &mut s.prefs);
|
||||
swap(&mut self.caps_lock, &mut s.caps_lock);
|
||||
swap(&mut self.overprint_after_run, &mut s.overprint_after_run);
|
||||
swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample);
|
||||
swap(&mut self.global_edit_options, &mut s.global_edit_options);
|
||||
swap(&mut self.select_similar, &mut s.select_similar);
|
||||
@@ -659,6 +664,8 @@ pub(crate) struct Savepoint {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: usize,
|
||||
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
|
||||
plugin_events: u64,
|
||||
}
|
||||
|
||||
impl Savepoint {
|
||||
@@ -693,6 +700,7 @@ impl Savepoint {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: s.journal.len(),
|
||||
plugin_events: s.plugin_events_mark(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -745,6 +753,8 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
// The documents the command opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(self.plugin_events);
|
||||
s.sync_front_profiles();
|
||||
exact
|
||||
}
|
||||
@@ -2197,6 +2207,8 @@ impl Session {
|
||||
lost
|
||||
});
|
||||
drop(lost);
|
||||
// The job's working copy went with it, with the documents the run opened.
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
@@ -2592,6 +2604,7 @@ impl Session {
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
self.end_job(job, e.kind == RunErrorKind::Internal);
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
@@ -2668,6 +2681,9 @@ impl Session {
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
if std::mem::take(&mut self.overprint_after_run) {
|
||||
cmd::colormgmt::turn_on_overprint_preview(self);
|
||||
}
|
||||
let host = &job.host;
|
||||
let mut report = json!({
|
||||
"ok": true,
|
||||
@@ -2693,6 +2709,7 @@ impl Session {
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
let tool = host.dom.chosen_tool();
|
||||
self.end_job(job, false);
|
||||
self.plugin_events_script_ended(true);
|
||||
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
|
||||
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
|
||||
if let Some(id) = tool
|
||||
|
||||
@@ -151,6 +151,8 @@ impl Session {
|
||||
screens_hand_off: None,
|
||||
recovery: Default::default(),
|
||||
in_tool_actions: false,
|
||||
plugin_events: Default::default(),
|
||||
plugin_event_frames: false,
|
||||
settled_warnings: None,
|
||||
held_interaction: None,
|
||||
previewing: false,
|
||||
@@ -192,6 +194,7 @@ impl Session {
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
overprint_after_run: false,
|
||||
script_unfenced: None,
|
||||
script_printers: None,
|
||||
script_prints: Vec::new(),
|
||||
@@ -422,6 +425,7 @@ impl Session {
|
||||
{
|
||||
self.begin_named_undo_group(label);
|
||||
}
|
||||
self.plugin_events_see_new_documents();
|
||||
i
|
||||
}
|
||||
|
||||
@@ -496,6 +500,28 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Measure the type not measured yet in the open document with [`DocState::uid`] `uid` when it is
|
||||
/// in the back, as [`Session::measure_back_document`] does, so bounds read from it are the ones
|
||||
/// it has once it comes to the front. A document in front, or one with all its type measured,
|
||||
/// is left as it is. A document unchanged since it was last measured or checked here is not
|
||||
/// walked again ([`DocState::measured_in_own`]; with no composite font names kept, its coming
|
||||
/// to the front measures again what it would have measured without the check).
|
||||
pub(crate) fn measure_back_type(&mut self, uid: u64) {
|
||||
let Some(index) = self.docs.iter().position(|d| d.uid == uid) else { return };
|
||||
if self.active == Some(index) {
|
||||
return;
|
||||
}
|
||||
let st = &mut self.docs[index];
|
||||
if st.measured_in_own.as_ref().is_some_and(|(doc, _)| std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))) {
|
||||
return;
|
||||
}
|
||||
if text_trees(&st.doc).any(|n| has_text_where(n, &mut |t| t.cached_bounds.is_none())) {
|
||||
self.measure_back_document(index);
|
||||
} else {
|
||||
st.measured_in_own = Some((Arc::downgrade(&st.doc), HashSet::new()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the type not measured yet in open document `index`, which is in the back, in its own
|
||||
/// composite fonts, lent for the measuring, so its type has the bounds it will have when the
|
||||
/// document comes to the front: type naming a composite font the document does not define is
|
||||
|
||||
@@ -665,10 +665,15 @@ impl Session {
|
||||
// The interaction is taken below, so its starting state is read first: the commit is what
|
||||
// the previews that came before it changed.
|
||||
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
|
||||
// Plug-in events wait for an open interaction only: a commit with none open ends nothing.
|
||||
let open = self.in_interaction() || self.holds_interaction();
|
||||
let r = self.commit_interaction_unwatched();
|
||||
if let Some(before) = before {
|
||||
self.reveal_since(&before);
|
||||
}
|
||||
if r.is_ok() && open {
|
||||
self.plugin_events_interaction_ended();
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
@@ -774,6 +779,7 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn cancel_interaction(&mut self) -> Result<()> {
|
||||
let open = self.in_interaction() || self.holds_interaction();
|
||||
self.put_back_interaction();
|
||||
self.restore_preview_appearance_item();
|
||||
self.clear_deferred_overlay_cache();
|
||||
@@ -811,6 +817,9 @@ impl Session {
|
||||
if !used_defaults_only {
|
||||
self.inherit_new_art();
|
||||
}
|
||||
if open {
|
||||
self.plugin_events_interaction_ended();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -132,6 +132,9 @@ impl Session {
|
||||
if self.script_in_run && self.depth > 0 && r.is_ok() {
|
||||
crate::script::note_style_lists(self);
|
||||
}
|
||||
if self.depth == 0 {
|
||||
self.plugin_events_after_command();
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
|
||||
@@ -1319,11 +1319,13 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, without waiting, in `turn`.
|
||||
/// Records the installed plug-ins' event baseline now, or after an open interaction ends.
|
||||
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
|
||||
match load {
|
||||
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
|
||||
}
|
||||
self.plugins_changed_for_events();
|
||||
}
|
||||
|
||||
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report.
|
||||
|
||||
@@ -154,6 +154,7 @@ mod perspgrid;
|
||||
mod pixelalign;
|
||||
mod place;
|
||||
mod placed_document;
|
||||
mod plugin_events;
|
||||
mod plugins;
|
||||
mod prefs;
|
||||
mod prefs_file;
|
||||
|
||||
@@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
|
||||
let (_dir, root) = folder("relative");
|
||||
std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap();
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let up = "../".repeat(cwd.components().count().saturating_sub(1));
|
||||
let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display());
|
||||
let up: PathBuf = cwd.components().skip(1).map(|_| std::path::Component::ParentDir).collect();
|
||||
let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string();
|
||||
assert!(Path::new(&relative).is_relative());
|
||||
let mut s = session_for(&root);
|
||||
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -186,6 +186,58 @@ fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the
|
||||
assert_eq!(s.active().unwrap().uid, front, "the front document stays in front");
|
||||
}
|
||||
|
||||
/// The getters measure type in a document in the back as the setters do, so assigning an item's
|
||||
/// own width, height, left, top or position back to it changes nothing and makes no undo step,
|
||||
/// and for an object without type the document is not switched to.
|
||||
#[test]
|
||||
fn page_item_geometry_read_from_a_back_document_assigns_back_without_a_change() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
rect(&mut s, 200.0, 20.0, 30.0, 40.0);
|
||||
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let uid = s.active().unwrap().uid;
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let front = s.active().unwrap().uid;
|
||||
let back = |s: &Session| s.documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.history.undo.len());
|
||||
let steps = back(&s);
|
||||
let sets = ["t.width = t.width;", "t.height = t.height;", "t.left = t.left;", "t.top = t.top;", "t.position = t.position;"];
|
||||
for (kind, set) in sets.iter().flat_map(|set| [("TextFrame", set), ("PathItem", set)]) {
|
||||
let st = s.document_mut(uid).unwrap();
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) {
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
}
|
||||
// A switch to the back document and back again would stamp the front document anew.
|
||||
let stamp = s.active().unwrap().activated;
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.documents[1].pageItems, t = p[0].typename == '{kind}' ? p[0] : p[1];\
|
||||
var w = t.width, x = t.left; {set} vc.log(t.width - w); vc.log(t.left - x);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out.len(), 2, "{kind} {set}");
|
||||
for d in &out {
|
||||
assert!(d.as_f64().unwrap().abs() < 1e-6, "{kind} {set} moved or resized the item by {d}");
|
||||
}
|
||||
assert_eq!(back(&s), steps, "{kind} {set} made an undo step");
|
||||
if kind == "PathItem" {
|
||||
assert_eq!(s.active().unwrap().activated, stamp, "{set} switched documents");
|
||||
}
|
||||
}
|
||||
assert_eq!(s.active().unwrap().uid, front, "the front document stays in front");
|
||||
let st = s.document_mut(uid).unwrap();
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) {
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
}
|
||||
let in_back = log(&mut s, "vc.log(app.documents[1].pageItems[0].width);");
|
||||
let index = s.documents().iter().position(|d| d.uid == uid).unwrap();
|
||||
s.execute("document.activate", &json!({"index": index})).unwrap();
|
||||
let in_front = log(&mut s, "vc.log(app.activeDocument.pageItems[0].width);");
|
||||
assert_eq!(in_back, in_front, "the width read in the back is the width read in front");
|
||||
}
|
||||
|
||||
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
|
||||
/// visible bounds.
|
||||
#[test]
|
||||
@@ -1703,6 +1755,69 @@ fn headless_add_document_dialog_fails_without_creating() {
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
}
|
||||
|
||||
/// A run's `addDocument` with Overprint Preview turns the view on when the run ends; a run that
|
||||
/// fails leaves it off.
|
||||
#[test]
|
||||
fn add_document_with_overprint_preview_turns_it_on_when_the_run_ends() {
|
||||
if !super::in_own_process("tests::script_dom::add_document_with_overprint_preview_turns_it_on_when_the_run_ends") {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let overprint = |s: &mut Session| s.execute("view.proofSetup", &json!({})).unwrap()["overprintPreview"].clone();
|
||||
s.execute("view.overprintPreview", &json!({"on": false})).unwrap();
|
||||
let add = "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);";
|
||||
let e = failure(&mut s, &format!("{add} throw new Error('stopped here');"));
|
||||
assert!(e.contains("stopped here"), "{e}");
|
||||
assert_eq!(overprint(&mut s), false);
|
||||
assert!(s.documents().is_empty());
|
||||
assert_eq!(log(&mut s, &format!("{add} vc.log(app.documents.length);")), vec![json!(1)]);
|
||||
assert_eq!(overprint(&mut s), true);
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
s.execute("view.overprintPreview", &json!({"on": false})).unwrap();
|
||||
}
|
||||
|
||||
/// A run's `addDocument` reads the images the profile links to beside its file, as the person's
|
||||
/// File › New does.
|
||||
#[test]
|
||||
fn add_document_reads_the_images_the_profile_links_to() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-newdoc-links-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut s = Session::new();
|
||||
s.attach_new_doc_profiles(dir.clone());
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
600,
|
||||
300,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[200u8, 30, 30, 255].repeat(600 * 300),
|
||||
)
|
||||
.unwrap();
|
||||
let mut bytes = vec![];
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map(|b| bytes.extend_from_slice(&b))
|
||||
.unwrap();
|
||||
let pic = dir.join("logo.png");
|
||||
std::fs::write(&pic, &bytes).unwrap();
|
||||
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Logo"})).unwrap();
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
let read = |s: &Session| {
|
||||
let images = &s.doc().unwrap().doc.images;
|
||||
!images.is_empty() && images.values().all(|b| !b.is_proxy())
|
||||
};
|
||||
s.execute("file.new", &json!({"preset": "Letter"})).unwrap();
|
||||
assert!(read(&s), "the person's File › New reads the linked image");
|
||||
// No document open when the run begins links to the image, so the run's gate alone does not
|
||||
// let it be read.
|
||||
while !s.documents().is_empty() {
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
}
|
||||
log(&mut s, "app.documents.addDocument('Print');");
|
||||
assert!(read(&s), "a script's addDocument reads it too");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `addDocumentNoUI(startupPreset)` makes the document `addDocument(startupPreset)` makes, and
|
||||
/// ignores the arguments after the preset's name.
|
||||
#[test]
|
||||
|
||||
@@ -98,6 +98,64 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() {
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match,
|
||||
/// as `pageItems` does.
|
||||
#[test]
|
||||
fn path_items_read_with_a_name_give_the_named_path() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems, m = [];\
|
||||
vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\
|
||||
try { p['nosuch']; } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]);
|
||||
}
|
||||
|
||||
/// `pathItems` read with a name that is the text of a number but not an array index, such as `-1`
|
||||
/// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes
|
||||
/// a number as a position, as in `pageItems`.
|
||||
#[test]
|
||||
fn path_items_read_with_a_number_name_that_is_not_an_index_give_the_named_path() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems, m = [];\
|
||||
vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p['1.5'] === undefined, '1.5' in p]);\
|
||||
try { p.index(-1); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, true, true, true, false]), json!(["Not found"])]);
|
||||
}
|
||||
|
||||
/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes
|
||||
/// nothing, as `pageItems.removeAll()` and `remove()` do.
|
||||
#[test]
|
||||
fn path_items_remove_all_refuses_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.group", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let lock = |s: &mut Session, locked: bool| {
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = locked;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
lock(&mut s, true);
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
lock(&mut s, false);
|
||||
log(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_creators_use_documented_defaults_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -389,6 +389,39 @@ fn file_print_max_pages_composes_only_what_fits() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A job past `maxPages` is turned away before its raster effects are flattened.
|
||||
#[test]
|
||||
fn file_print_max_pages_turns_a_job_away_before_raster_effects_are_flattened() {
|
||||
use crate::cmd::rasterfx::FLATTENED;
|
||||
let base = folder("max-pages-raster");
|
||||
let mut s = session(&base);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap();
|
||||
let before = FLATTENED.with(std::cell::Cell::get);
|
||||
let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap();
|
||||
assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}");
|
||||
assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened");
|
||||
let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap();
|
||||
assert!(r["dataBase64"].is_string(), "{r}");
|
||||
assert!(FLATTENED.with(std::cell::Cell::get) > before, "a job that fits is flattened");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A job past the page limit throws before its raster effects are flattened.
|
||||
#[test]
|
||||
fn file_print_max_pages_returns_a_page_cap_error_before_raster_effects_are_flattened() {
|
||||
use crate::cmd::rasterfx::FLATTENED;
|
||||
let base = folder("max-pages-raster-cap");
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 3})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow"})).unwrap();
|
||||
let before = FLATTENED.with(std::cell::Cell::get);
|
||||
let e = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 700}})).unwrap_err().to_string();
|
||||
assert!(e.contains("more than 2000 pages"), "{e}");
|
||||
assert_eq!(FLATTENED.with(std::cell::Cell::get), before, "nothing was flattened");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad values throw when they are assigned, and nothing prints.
|
||||
#[test]
|
||||
fn print_options_refuse_bad_values() {
|
||||
@@ -661,6 +694,7 @@ fn print_refuses_profile_paper_and_blank_preset_names() {
|
||||
("c.name = 'No Such Profile';", profile),
|
||||
("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile),
|
||||
("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"),
|
||||
("c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE;", "PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE"),
|
||||
("p.name = '../letter';", paper),
|
||||
("p.name = 'let\\u0007ter';", paper),
|
||||
("p.name = '\\tA4\\n';", paper),
|
||||
|
||||
@@ -1271,9 +1271,9 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native
|
||||
/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves
|
||||
/// them; a `range` the save refuses still refuses.
|
||||
/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that
|
||||
/// carries the native document, keep every artboard whatever `range` names, so
|
||||
/// `close(SaveOptions.SAVECHANGES)` saves them; a `range` the save refuses still refuses.
|
||||
#[test]
|
||||
fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
|
||||
let base = folder("closekeepall");
|
||||
@@ -1281,7 +1281,11 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
|
||||
let mut s = session(&base);
|
||||
data_folder(&mut s, &base)
|
||||
};
|
||||
for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] {
|
||||
for (name, options) in [
|
||||
("whole.vectorcraft", json!({"range": "2"})),
|
||||
("whole.ai", json!({"range": "2"})),
|
||||
("native.svg", json!({"preserveEditing": true, "range": "1"})),
|
||||
] {
|
||||
let mut s = session(&base);
|
||||
data_folder(&mut s, &base);
|
||||
let file = dir.join(name);
|
||||
|
||||
@@ -1823,6 +1823,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
|
||||
/// Headless sessions deliver plug-in events after the outer actions finish.
|
||||
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
// The tool acts on its own interaction, which a command from outside it may have set aside.
|
||||
if !acts.is_empty() {
|
||||
@@ -1851,6 +1852,7 @@ impl Session {
|
||||
self.back_to_painter = outer_painter;
|
||||
if !outer && self.depth == 0 {
|
||||
self.trim_histories();
|
||||
self.plugin_events_after_command();
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
+350
-28
@@ -89,13 +89,15 @@ fn create_new(path: &Path) -> io::Result<File> {
|
||||
/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is
|
||||
/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at
|
||||
/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it;
|
||||
/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by
|
||||
/// a link put there later is replaced, never followed. A folder that moved after it was opened is
|
||||
/// checked with `allowed` again at its new path right before the file is put in place, and a folder
|
||||
/// whose new path the system does not report fails. Elsewhere this is `allowed(path)` followed by
|
||||
/// [`write_atomic_with`].
|
||||
#[cfg(unix)]
|
||||
pub fn write_atomic_checked(
|
||||
path: &Path,
|
||||
fill: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
allowed: impl FnOnce(&Path) -> io::Result<()>,
|
||||
allowed: impl Fn(&Path) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
use rustix::fs::{AtFlags, Mode, OFlags};
|
||||
// A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name`
|
||||
@@ -126,6 +128,24 @@ pub fn write_atomic_checked(
|
||||
};
|
||||
// The folder may have moved since it was opened: messages name it where it is now.
|
||||
let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file);
|
||||
// Right before the file is put in place: a folder that moved since it was opened is checked
|
||||
// again where it is now, so a move out of the allowed folders does not receive the file.
|
||||
let still_allowed = || -> io::Result<()> {
|
||||
let here = folder_now(&dir, &real);
|
||||
let open = rustix::fs::fstat(&dir)?;
|
||||
// The path itself, not a link that leads to the folder from elsewhere.
|
||||
let same = |p: &Path| {
|
||||
std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino))
|
||||
};
|
||||
if here == real && same(&real) {
|
||||
return Ok(());
|
||||
}
|
||||
if here == real || !same(&here) {
|
||||
return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display())));
|
||||
}
|
||||
allowed(&here.join(stored_name(&dir, &here, &name)))
|
||||
.map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display())))
|
||||
};
|
||||
let synced = || {
|
||||
// Opened for reading here: the folder handle above may allow name lookups only.
|
||||
let flushed =
|
||||
@@ -133,13 +153,21 @@ pub fn write_atomic_checked(
|
||||
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
|
||||
};
|
||||
let open_target = |write: bool| -> io::Result<File> {
|
||||
// A missing target is created by `create_target`, after the last check. An existing one is
|
||||
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
|
||||
if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) {
|
||||
return Err(io::ErrorKind::NotFound.into());
|
||||
}
|
||||
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
|
||||
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
|
||||
};
|
||||
let create_target = || -> io::Result<File> { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) };
|
||||
match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) {
|
||||
Ok(mut f) => {
|
||||
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
|
||||
if let Err(e) = filled {
|
||||
// Checked before the temporary file takes the old file's wider permissions, and again
|
||||
// right before the rename.
|
||||
if let Err(e) = filled.and_then(|()| still_allowed()) {
|
||||
drop(f);
|
||||
remove_tmp();
|
||||
return Err(e);
|
||||
@@ -151,6 +179,10 @@ pub fn write_atomic_checked(
|
||||
let _ = keep_permissions_at(&dir, &name, &old, &f);
|
||||
}
|
||||
drop(f);
|
||||
if let Err(e) = still_allowed() {
|
||||
remove_tmp();
|
||||
return Err(e);
|
||||
}
|
||||
#[cfg(test)]
|
||||
let refuse = RENAME_REFUSED.with(std::cell::Cell::get);
|
||||
#[cfg(not(test))]
|
||||
@@ -189,7 +221,9 @@ pub fn write_atomic_checked(
|
||||
},
|
||||
remove_tmp: &remove_tmp,
|
||||
open_target: &open_target,
|
||||
create_target: &create_target,
|
||||
synced: &synced,
|
||||
still_allowed: &still_allowed,
|
||||
};
|
||||
write_over_in(&over, refused.into())
|
||||
}
|
||||
@@ -207,7 +241,7 @@ pub fn write_atomic_checked(
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&elsewhere);
|
||||
};
|
||||
if let Err(e) = filled {
|
||||
if let Err(e) = filled.and_then(|()| still_allowed()) {
|
||||
remove();
|
||||
return Err(e);
|
||||
}
|
||||
@@ -222,7 +256,9 @@ pub fn write_atomic_checked(
|
||||
open_tmp: &|| File::open(&elsewhere),
|
||||
remove_tmp: &remove,
|
||||
open_target: &open_target,
|
||||
create_target: &create_target,
|
||||
synced: &synced,
|
||||
still_allowed: &still_allowed,
|
||||
};
|
||||
write_over_in(&over, refused.into())
|
||||
}
|
||||
@@ -422,7 +458,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) },
|
||||
#[cfg(unix)]
|
||||
create_target: &|| create_new(target),
|
||||
synced: &|| sync_written_parent(target),
|
||||
still_allowed: &|| Ok(()),
|
||||
};
|
||||
write_over_in(&over, refused)
|
||||
}
|
||||
@@ -441,38 +480,92 @@ struct Over<'a> {
|
||||
open_tmp: &'a dyn Fn() -> io::Result<File>,
|
||||
/// Best effort.
|
||||
remove_tmp: &'a dyn Fn(),
|
||||
/// The target for writing (created when missing, not truncated) when `true`, for reading when
|
||||
/// `false`.
|
||||
/// Opens the target without truncating it for writing when `true`, or for reading when `false`.
|
||||
/// Checked Unix writes defer creation of a missing target to `create_target`.
|
||||
open_target: &'a dyn Fn(bool) -> io::Result<File>,
|
||||
/// Creates a missing target after the final check and fails if its name is taken.
|
||||
#[cfg(unix)]
|
||||
create_target: &'a dyn Fn() -> io::Result<File>,
|
||||
/// The target's folder flushed, after the target is written.
|
||||
synced: &'a dyn Fn() -> io::Result<()>,
|
||||
/// Asked right before the target is overwritten: an error leaves it as it was.
|
||||
still_allowed: &'a dyn Fn() -> io::Result<()>,
|
||||
}
|
||||
|
||||
/// [`write_over`] through `over`.
|
||||
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
|
||||
let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?)));
|
||||
let Ok((mut from, mut to)) = opened else {
|
||||
// Checked Unix writes create a missing target only after the final check.
|
||||
if let Err(e) = (over.still_allowed)() {
|
||||
(over.remove_tmp)();
|
||||
return Err(e);
|
||||
}
|
||||
let opened = (over.open_tmp)().and_then(|from| {
|
||||
let to = match (over.open_target)(true) {
|
||||
Ok(to) => Some(to),
|
||||
#[cfg(unix)]
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
Ok((from, to))
|
||||
});
|
||||
let Ok((mut from, to)) = opened else {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
(over.remove_tmp)();
|
||||
return Err(refused);
|
||||
};
|
||||
// Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes
|
||||
// into: one put at its name meanwhile is not copied in its place.
|
||||
let kept = to.metadata().map_or(true, |m| m.len() > 0);
|
||||
let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0));
|
||||
if kept
|
||||
&& let Err(e) = (over.open_target)(false).and_then(|mut target| {
|
||||
if !same_file(&target, &to) {
|
||||
if !to.as_ref().is_some_and(|to| same_file(&target, to)) {
|
||||
return Err(io::Error::other("the file was replaced while it was opened"));
|
||||
}
|
||||
keep_old(&mut target, over)
|
||||
})
|
||||
{
|
||||
#[cfg(unix)]
|
||||
if let Err(e) = (over.still_allowed)() {
|
||||
drop((from, to));
|
||||
(over.remove_tmp)();
|
||||
return Err(e);
|
||||
}
|
||||
let why = format!(
|
||||
"{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}",
|
||||
(over.tmp)().display()
|
||||
);
|
||||
return Err(io::Error::new(refused.kind(), RecoveryError(why)));
|
||||
}
|
||||
if let Err(e) = (over.still_allowed)() {
|
||||
// Nothing was overwritten: neither copy is needed.
|
||||
drop((from, to));
|
||||
(over.remove_tmp)();
|
||||
if kept {
|
||||
(over.remove_old)();
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let mut to = match to {
|
||||
Some(to) => to,
|
||||
#[cfg(unix)]
|
||||
None => match (over.create_target)() {
|
||||
Ok(to) => to,
|
||||
// A file put at the name meanwhile is left alone, and reported as there.
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||
(over.remove_tmp)();
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
(over.remove_tmp)();
|
||||
return Err(refused);
|
||||
}
|
||||
},
|
||||
#[cfg(not(unix))]
|
||||
None => {
|
||||
(over.remove_tmp)();
|
||||
return Err(refused);
|
||||
}
|
||||
};
|
||||
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
|
||||
drop((from, to));
|
||||
match (copied, kept) {
|
||||
@@ -826,8 +919,18 @@ mod tests {
|
||||
(d, root, outside)
|
||||
}
|
||||
|
||||
/// Whether this system says where an open folder is now: macOS always, Linux and Android through
|
||||
/// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`.
|
||||
#[cfg(unix)]
|
||||
fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ {
|
||||
fn reports_open_folder_paths() -> bool {
|
||||
if cfg!(target_vendor = "apple") {
|
||||
return true;
|
||||
}
|
||||
cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ {
|
||||
move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) }
|
||||
}
|
||||
|
||||
@@ -851,22 +954,51 @@ mod tests {
|
||||
#[test]
|
||||
fn a_checked_write_stays_in_the_folder_it_opened() {
|
||||
let (d, root, outside) = checked_folders("checked-after");
|
||||
let check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
|f| {
|
||||
std::fs::rename(root.join("inside"), root.join("moved"))?;
|
||||
std::os::unix::fs::symlink(&outside, root.join("inside"))
|
||||
std::os::unix::fs::symlink(&outside, root.join("inside"))?;
|
||||
f.write_all(b"new")
|
||||
},
|
||||
under(&root),
|
||||
);
|
||||
if !reports_open_folder_paths() {
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}");
|
||||
assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists());
|
||||
assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
return;
|
||||
}
|
||||
r.unwrap();
|
||||
assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder");
|
||||
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A folder moved out of the allowed root while the file is written receives nothing: the move is
|
||||
/// caught before the file is put in place, and the temporary file is removed.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() {
|
||||
let (d, root, outside) = checked_folders("checked-moved-out");
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| {
|
||||
f.write_all(b"new")?;
|
||||
std::fs::rename(root.join("inside"), outside.join("inside"))
|
||||
},
|
||||
under(&root),
|
||||
);
|
||||
assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}");
|
||||
let message = r.unwrap_err().to_string();
|
||||
assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}");
|
||||
assert!(message.contains("the folder moved"), "{message}");
|
||||
assert!(!message.contains(&outside.display().to_string()), "{message}");
|
||||
assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A link put at the file's name after the check is replaced by the file, not followed.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -922,31 +1054,34 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A checked write whose folder moved after it was opened, refused the rename, and failed to
|
||||
/// copy into the file: the temporary file and the copy of the old content stay in that folder,
|
||||
/// and the error names them where they are now. (FreeBSD does not say where an open folder is
|
||||
/// now: there the error names them where the folder was opened.)
|
||||
/// A failed fallback names the recovery files in the folder's current location when available.
|
||||
/// A move is refused when the system cannot resolve the open folder's current path.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_names_the_kept_file_where_its_folder_moved() {
|
||||
let (d, root, _) = checked_folders("checked-moved");
|
||||
std::fs::write(root.join("inside/doc.txt"), b"original").unwrap();
|
||||
let check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
|f| {
|
||||
std::fs::rename(root.join("inside"), root.join("moved"))?;
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
// The temporary file's flush and the copy of the old content work, the next doesn't.
|
||||
FLUSHES_LEFT.with(|c| c.set(Some(2)));
|
||||
Ok(())
|
||||
f.write_all(b"new")
|
||||
},
|
||||
under(&root),
|
||||
);
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
FLUSHES_LEFT.with(|c| c.set(None));
|
||||
let message = r.unwrap_err().to_string();
|
||||
if !reports_open_folder_paths() {
|
||||
assert!(message.contains("the folder moved"), "{message}");
|
||||
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
return;
|
||||
}
|
||||
let kept = |ext: &str| -> PathBuf {
|
||||
let found: Vec<_> = std::fs::read_dir(root.join("moved"))
|
||||
.unwrap()
|
||||
@@ -958,15 +1093,200 @@ mod tests {
|
||||
};
|
||||
let (tmp, old) = (kept("tmp"), kept("old"));
|
||||
assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec()));
|
||||
let named_in =
|
||||
if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") };
|
||||
for file in [&tmp, &old] {
|
||||
let named = named_in.join(file.file_name().unwrap());
|
||||
let named = root.join("moved").join(file.file_name().unwrap());
|
||||
assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A refused rename whose folder is no longer allowed by the time the file would be overwritten
|
||||
/// leaves the file as it was, and neither copy stays behind.
|
||||
#[test]
|
||||
fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() {
|
||||
let d = dir("no-rename-disallowed");
|
||||
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
std::fs::write(&tmp, b"new").unwrap();
|
||||
let checks = std::cell::Cell::new(0);
|
||||
let over = Over {
|
||||
tmp: &|| tmp.clone(),
|
||||
create_old: &|| create_private(&old),
|
||||
old: &|| old.clone(),
|
||||
remove_old: &|| {
|
||||
let _ = std::fs::remove_file(&old);
|
||||
},
|
||||
open_tmp: &|| File::open(&tmp),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
|
||||
#[cfg(unix)]
|
||||
create_target: &|| create_new(&path),
|
||||
synced: &|| Ok(()),
|
||||
still_allowed: &|| {
|
||||
checks.set(checks.get() + 1);
|
||||
if checks.get() == 1 {
|
||||
Ok(())
|
||||
} else {
|
||||
assert_eq!(std::fs::read(&old).unwrap(), b"original");
|
||||
Err(io::Error::other("moved outside"))
|
||||
}
|
||||
},
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert_eq!(checks.get(), 2);
|
||||
assert!(e.to_string().contains("moved outside"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
assert!(!tmp.exists() && !old.exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A backup failure after a folder moves outside removes the new content and reports the refusal.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_refused_rename_rechecks_authorization_after_a_backup_error() {
|
||||
let (d, root, outside) = checked_folders("no-rename-backup-moved");
|
||||
let inside = root.join("inside");
|
||||
let moved = outside.join("inside");
|
||||
let path = inside.join("doc.txt");
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
std::fs::write(inside.join("doc.tmp"), b"new").unwrap();
|
||||
let checks = std::cell::Cell::new(0);
|
||||
let over = Over {
|
||||
tmp: &|| moved.join("doc.tmp"),
|
||||
create_old: &|| {
|
||||
std::fs::rename(&inside, &moved)?;
|
||||
Err(io::Error::other("backup failed"))
|
||||
},
|
||||
old: &|| moved.join("doc.old"),
|
||||
remove_old: &|| {},
|
||||
open_tmp: &|| File::open(inside.join("doc.tmp")),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(moved.join("doc.tmp"));
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
|
||||
create_target: &|| create_new(&path),
|
||||
synced: &|| Ok(()),
|
||||
still_allowed: &|| {
|
||||
checks.set(checks.get() + 1);
|
||||
if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) }
|
||||
},
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert_eq!(checks.get(), 2);
|
||||
assert!(e.to_string().contains("moved outside"), "{e}");
|
||||
assert!(!e.to_string().contains(&outside.display().to_string()), "{e}");
|
||||
assert!(!e.get_ref().is_some_and(|e| e.is::<RecoveryError>()));
|
||||
assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A refused fallback leaves a missing target absent when the final check fails.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() {
|
||||
let d = dir("no-rename-disallowed-new");
|
||||
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
|
||||
std::fs::write(&tmp, b"new").unwrap();
|
||||
let checks = std::cell::Cell::new(0);
|
||||
let created = std::cell::Cell::new(false);
|
||||
let over = Over {
|
||||
tmp: &|| tmp.clone(),
|
||||
create_old: &|| create_private(&old),
|
||||
old: &|| old.clone(),
|
||||
remove_old: &|| {
|
||||
let _ = std::fs::remove_file(&old);
|
||||
},
|
||||
open_tmp: &|| File::open(&tmp),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
},
|
||||
open_target: &|write| {
|
||||
if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }
|
||||
},
|
||||
create_target: &|| {
|
||||
created.set(true);
|
||||
create_new(&path)
|
||||
},
|
||||
synced: &|| Ok(()),
|
||||
still_allowed: &|| {
|
||||
checks.set(checks.get() + 1);
|
||||
if checks.get() == 1 {
|
||||
assert!(!path.exists());
|
||||
Ok(())
|
||||
} else {
|
||||
assert!(!created.get() && !path.exists());
|
||||
Err(io::Error::other("moved outside"))
|
||||
}
|
||||
},
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert_eq!(checks.get(), 2);
|
||||
assert!(e.to_string().contains("moved outside"), "{e}");
|
||||
assert!(!created.get());
|
||||
assert!(!path.exists());
|
||||
assert!(!tmp.exists() && !old.exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A checked fallback creates a missing target after authorization succeeds.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() {
|
||||
let (d, root, _) = checked_folders("checked-new-no-rename");
|
||||
let path = root.join("inside/doc.txt");
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
r.unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"new");
|
||||
assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A file created by another writer at the final check is preserved whether that check succeeds or fails.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_refused_rename_preserves_a_target_created_at_the_final_check() {
|
||||
for allowed in [false, true] {
|
||||
let d = dir("no-rename-new-target-taken");
|
||||
let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp"));
|
||||
std::fs::write(&tmp, b"new").unwrap();
|
||||
let checks = std::cell::Cell::new(0);
|
||||
let over = Over {
|
||||
tmp: &|| tmp.clone(),
|
||||
create_old: &|| Err(io::Error::other("no backup expected")),
|
||||
old: &|| d.join("doc.old"),
|
||||
remove_old: &|| {},
|
||||
open_tmp: &|| File::open(&tmp),
|
||||
remove_tmp: &|| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
|
||||
create_target: &|| create_new(&path),
|
||||
synced: &|| Ok(()),
|
||||
still_allowed: &|| {
|
||||
checks.set(checks.get() + 1);
|
||||
if checks.get() == 1 {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::write(&path, b"someone else's")?;
|
||||
if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) }
|
||||
},
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert_eq!(checks.get(), 2);
|
||||
if !allowed {
|
||||
assert!(e.to_string().contains("moved outside"), "{e}");
|
||||
}
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"someone else's");
|
||||
assert!(!tmp.exists() && !d.join("doc.old").exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// A refused rename copies the old content through the file handle it then overwrites: when a
|
||||
/// different file is at the name by the time it is opened for reading, nothing is overwritten and
|
||||
/// the new content stays in the temporary file.
|
||||
@@ -991,7 +1311,9 @@ mod tests {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) },
|
||||
create_target: &|| create_new(&path),
|
||||
synced: &|| Ok(()),
|
||||
still_allowed: &|| Ok(()),
|
||||
};
|
||||
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
|
||||
assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}");
|
||||
|
||||
@@ -389,8 +389,15 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult
|
||||
let mut n = 0u64;
|
||||
for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) {
|
||||
interp.use_fuel()?;
|
||||
// A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1).
|
||||
let spread = if interp.is_array(&e)? { e.as_object() } else { None };
|
||||
// Code run without the ECMAScript 2015 option reads no such Symbol, even in a realm
|
||||
// that has it from an earlier run.
|
||||
let spreadable = if interp.options.es2015 { interp.well_known(|w| &w.is_concat_spreadable) } else { None };
|
||||
let override_spread = match (e.as_object(), spreadable) {
|
||||
(Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?,
|
||||
_ => Value::Undefined,
|
||||
};
|
||||
let spread = if matches!(override_spread, Value::Undefined) { interp.is_array(&e)? } else { override_spread.truthy() };
|
||||
let spread = if spread { e.as_object() } else { None };
|
||||
let Some(e) = spread else {
|
||||
if n >= 9_007_199_254_740_991 {
|
||||
return Err(interp.type_error("concat exceeds the maximum safe length"));
|
||||
|
||||
@@ -824,6 +824,23 @@ fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult<Elem> {
|
||||
Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor")))
|
||||
}
|
||||
|
||||
fn typed_create(interp: &mut Interp, this: &Value, len: u64, name: &str) -> JsResult<ObjId> {
|
||||
if !this.as_object().is_some_and(|o| interp.is_proxy(o)) {
|
||||
let elem = ctor_elem(interp, this, name)?;
|
||||
return new_typed(interp, elem, len);
|
||||
}
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let result = interp.construct_value(this, &[Value::Number(len as f64)], this)?;
|
||||
interp.rooted(std::slice::from_ref(&result), |interp| {
|
||||
let Some(o) = result.as_object() else { return Err(interp.type_error("the constructor did not return a typed array")) };
|
||||
let Some(view) = view_of(interp, o) else { return Err(interp.type_error("the constructor did not return a typed array")) };
|
||||
if (view.length as u64) < len {
|
||||
return Err(interp.type_error(&format!("TypedArray.{name} constructor returned a typed array that is too short")));
|
||||
}
|
||||
Ok(o)
|
||||
})
|
||||
}
|
||||
|
||||
/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1).
|
||||
fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
if !interp.is_constructor(&this) {
|
||||
@@ -836,16 +853,15 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe
|
||||
}
|
||||
let this_arg = arg(args, 2);
|
||||
let map = mapping.then_some((&map_fn, &this_arg));
|
||||
typed_array_from(interp, &arg(args, 0), map, |interp, len| {
|
||||
let elem = ctor_elem(interp, &this, "from")?;
|
||||
new_typed(interp, elem, len)
|
||||
})
|
||||
typed_array_from(interp, &arg(args, 0), map, |interp, len| typed_create(interp, &this, len, "from"))
|
||||
}
|
||||
|
||||
/// `%TypedArray%.of(...items)` (section 22.2.2.2).
|
||||
fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let elem = ctor_elem(interp, &this, "of")?;
|
||||
let ta = new_typed(interp, elem, args.len() as u64)?;
|
||||
if !interp.is_constructor(&this) {
|
||||
return Err(interp.type_error("TypedArray.of must be called on a typed array constructor"));
|
||||
}
|
||||
let ta = typed_create(interp, &this, args.len() as u64, "of")?;
|
||||
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
|
||||
interp.rooted(&[Value::Object(ta)], |interp| {
|
||||
for (i, v) in args.iter().enumerate() {
|
||||
|
||||
@@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult<Value> {
|
||||
struct Settings {
|
||||
replacer: Option<Value>,
|
||||
properties: Option<Vec<Key>>,
|
||||
_held_properties: Option<crate::interp::HeldBytes>,
|
||||
gap: Vec<u16>,
|
||||
}
|
||||
|
||||
@@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult<Value> {
|
||||
|
||||
/// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8).
|
||||
fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult<Settings> {
|
||||
let mut s = Settings { replacer: None, properties: None, gap: Vec::new() };
|
||||
let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() };
|
||||
if let Value::Object(r) = replacer {
|
||||
if interp.is_callable(replacer) {
|
||||
s.replacer = Some(replacer.clone());
|
||||
} else if interp.is_array(replacer)? {
|
||||
s.properties = Some(property_list(interp, *r)?);
|
||||
let (keys, held) = property_list(interp, *r)?;
|
||||
s.properties = Some(keys);
|
||||
s._held_properties = Some(held);
|
||||
}
|
||||
}
|
||||
let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone());
|
||||
@@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult<Se
|
||||
}
|
||||
|
||||
/// The property names a replacer array lists, without repeats (section 15.12.3, step 4.b).
|
||||
fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<Vec<Key>> {
|
||||
/// Each name kept is charged to the heap for as long as the returned holder lives.
|
||||
fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec<Key>, crate::interp::HeldBytes)> {
|
||||
let len = super::collections::length_of(interp, r)?;
|
||||
if len > interp.fuel {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel));
|
||||
}
|
||||
interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?;
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
let mut list: Vec<Key> = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for i in 0..len {
|
||||
@@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<Vec<Key>> {
|
||||
}
|
||||
// The list lives until the call returns, so its names are rooted.
|
||||
interp.temp_roots.push(Value::String(s));
|
||||
held.add(interp, ELEMENT_BYTES)?;
|
||||
list.push(k);
|
||||
}
|
||||
}
|
||||
Ok(list)
|
||||
Ok((list, held))
|
||||
}
|
||||
|
||||
/// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the
|
||||
|
||||
@@ -18,6 +18,8 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> {
|
||||
("hasInstance", well_known.has_instance.clone()),
|
||||
("toPrimitive", well_known.to_primitive.clone()),
|
||||
("toStringTag", well_known.to_string_tag.clone()),
|
||||
("unscopables", well_known.unscopables.clone()),
|
||||
("isConcatSpreadable", well_known.is_concat_spreadable.clone()),
|
||||
];
|
||||
let (to_string_tag, to_primitive, has_instance) =
|
||||
(well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone());
|
||||
@@ -171,7 +173,7 @@ fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bo
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
// A proxy's list stays counted against the heap until the array holds its Symbols.
|
||||
let (syms, _held) = if interp.is_proxy(o) {
|
||||
let keys = interp.proxy_own_keys(o)?;
|
||||
let keys = interp.proxy_own_keys(o, false)?;
|
||||
(keys.syms, keys.held)
|
||||
} else {
|
||||
let syms = interp.own_symbols(o)?;
|
||||
|
||||
@@ -215,9 +215,8 @@ pub(crate) struct ArgMap {
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ForIn {
|
||||
pub(crate) keys: Vec<Key>,
|
||||
/// The proxies whose `ownKeys` trap returned a listed name, each with the positions in `keys`
|
||||
/// of the names it returned.
|
||||
pub(crate) listed: Vec<Listed>,
|
||||
/// Each proxy on the chain maps to the positions in `keys` of the names its `ownKeys` trap returned.
|
||||
pub(crate) listed: HashMap<ObjId, Listed>,
|
||||
pub(crate) pos: usize,
|
||||
pub(crate) object: Option<ObjId>,
|
||||
}
|
||||
@@ -227,7 +226,8 @@ pub(crate) struct ForIn {
|
||||
/// name's position is here.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Listed {
|
||||
pub(crate) proxy: ObjId,
|
||||
/// The proxy returned by this proxy's prototype lookup, if any.
|
||||
pub(crate) prototype: Option<ObjId>,
|
||||
pub(crate) positions: Vec<u32>,
|
||||
}
|
||||
|
||||
@@ -1191,7 +1191,8 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
Class::ForIn(state) => {
|
||||
work.extend(state.object.iter().map(|o| o.0));
|
||||
work.extend(state.listed.iter().map(|l| l.proxy.0));
|
||||
work.extend(state.listed.keys().map(|o| o.0));
|
||||
work.extend(state.listed.values().filter_map(|l| l.prototype.map(|o| o.0)));
|
||||
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
|
||||
strings.bytes += crate::interp::listed_bytes(&state.listed);
|
||||
}
|
||||
|
||||
+86
-40
@@ -18,6 +18,7 @@
|
||||
//! keeps its operands on the operand stack until it is done, so everything it holds is reachable
|
||||
//! from the roots when a nested run collects.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -575,11 +576,11 @@ pub(crate) const KEY_ENTRY_BYTES: usize = 32;
|
||||
pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::<u32>();
|
||||
|
||||
/// The bytes of a `for-in` loop's record of one proxy that listed names, without its positions.
|
||||
const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<Listed>();
|
||||
const LISTED_ENTRY_BYTES: usize = std::mem::size_of::<(ObjId, Listed)>() + KEY_ENTRY_BYTES;
|
||||
|
||||
/// The bytes of a `for-in` loop's records of the proxies that listed its names.
|
||||
pub(crate) fn listed_bytes(listed: &[Listed]) -> usize {
|
||||
listed.iter().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum()
|
||||
pub(crate) fn listed_bytes(listed: &HashMap<ObjId, Listed>) -> usize {
|
||||
listed.values().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum()
|
||||
}
|
||||
|
||||
/// The most units of a computed property name an error about a property of `null` or `undefined`
|
||||
@@ -1619,7 +1620,7 @@ impl Interp {
|
||||
cur = *outer;
|
||||
}
|
||||
Some(&Env::Obj { object, with_this, outer }) => {
|
||||
if self.scope_has(object, name)? {
|
||||
if self.scope_binding(object, name, with_this)? {
|
||||
return Ok(Resolved::Obj { object, with_this });
|
||||
}
|
||||
cur = outer;
|
||||
@@ -1630,6 +1631,23 @@ impl Interp {
|
||||
Ok(Resolved::Unresolved)
|
||||
}
|
||||
|
||||
fn scope_binding(&mut self, object: ObjId, name: &Key, with_this: bool) -> JsResult<bool> {
|
||||
if !self.scope_has(object, name)? {
|
||||
return Ok(false);
|
||||
}
|
||||
if with_this
|
||||
&& self.options.es2015
|
||||
&& let Some(sym) = self.well_known(|w| &w.unscopables)
|
||||
{
|
||||
let blocked = self.get_value_sym(&Value::Object(object), &sym)?;
|
||||
if let Value::Object(o) = blocked {
|
||||
let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?;
|
||||
return Ok(!value.truthy());
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult<Value> {
|
||||
match self.heap.env(env) {
|
||||
Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())),
|
||||
@@ -1673,7 +1691,7 @@ impl Interp {
|
||||
cur = *outer;
|
||||
}
|
||||
Some(&Env::Obj { object, with_this, outer }) => {
|
||||
if self.scope_has(object, name)? {
|
||||
if self.scope_binding(object, name, with_this)? {
|
||||
return self.get_resolved(Resolved::Obj { object, with_this }, name);
|
||||
}
|
||||
let this = Value::Object(object);
|
||||
@@ -2389,7 +2407,7 @@ impl Interp {
|
||||
/// list is checked first. A proxy's names come from its `ownKeys` trap.
|
||||
pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult<HeldKeys> {
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_own_keys(id);
|
||||
return self.proxy_own_keys(id, false);
|
||||
}
|
||||
let o = self.object(id)?;
|
||||
// A typed array's indices come first, as a String object's do (section 9.4.5.6).
|
||||
@@ -2422,14 +2440,15 @@ impl Interp {
|
||||
}
|
||||
|
||||
pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult<HeldKeys> {
|
||||
let mut keys = self.own_keys(id)?;
|
||||
if !self.is_proxy(id) {
|
||||
if matches!(self.object(id)?.class, Class::Array { .. }) {
|
||||
let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?;
|
||||
keys.insert(0, length);
|
||||
}
|
||||
keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n)));
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_own_keys(id, true);
|
||||
}
|
||||
let mut keys = self.own_keys(id)?;
|
||||
if matches!(self.object(id)?.class, Class::Array { .. }) {
|
||||
let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?;
|
||||
keys.insert(0, length);
|
||||
}
|
||||
keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n)));
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
@@ -3332,29 +3351,28 @@ impl Interp {
|
||||
/// For a String object, the heap budget for all its index names is checked before any is
|
||||
/// built. Each index name and each property visited takes a unit of fuel.
|
||||
///
|
||||
/// The second list holds each proxy whose `ownKeys` trap returned a listed name, with the
|
||||
/// positions of the names it returned.
|
||||
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec<Key>, Vec<Listed>)> {
|
||||
/// The map records each proxy's listed positions and the proxy returned by its prototype lookup.
|
||||
/// Listing roots remain until `op_for_in_start` installs the iterator.
|
||||
fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec<Key>, HashMap<ObjId, Listed>)> {
|
||||
if self.options.e4x && self.is_xml(&Value::Object(id)) {
|
||||
return Ok((self.xml_enumerate(id)?, Vec::new()));
|
||||
return Ok((self.xml_enumerate(id)?, HashMap::new()));
|
||||
}
|
||||
let slot = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Undefined);
|
||||
let r = self.enumerable_keys_from(id, slot);
|
||||
self.temp_roots.truncate(slot);
|
||||
r
|
||||
self.enumerable_keys_from(id, slot)
|
||||
}
|
||||
|
||||
/// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its
|
||||
/// `ownKeys` trap and the next object with its `getPrototypeOf` trap.
|
||||
/// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype.
|
||||
/// Descriptors are checked when iteration reaches each name.
|
||||
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec<Key>, Vec<Listed>)> {
|
||||
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec<Key>, HashMap<ObjId, Listed>)> {
|
||||
// Each name met on the chain, with its position in `out` when it is listed.
|
||||
let mut seen: std::collections::HashMap<Key, Option<u32>> = std::collections::HashMap::new();
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut out: Vec<Key> = Vec::new();
|
||||
let mut listed: Vec<Listed> = Vec::new();
|
||||
let mut listed = HashMap::new();
|
||||
let mut proxy_positions: std::collections::HashSet<(ObjId, u32)> = std::collections::HashSet::new();
|
||||
let next_pos = |out: &Vec<Key>| u32::try_from(out.len()).unwrap_or(u32::MAX);
|
||||
let mut cur = Some(id);
|
||||
while let Some(o) = cur {
|
||||
@@ -3362,6 +3380,7 @@ impl Interp {
|
||||
if let Some(root) = self.temp_roots.get_mut(slot) {
|
||||
*root = Value::Object(o);
|
||||
}
|
||||
self.temp_roots.push(Value::Object(o));
|
||||
let keys = self.own_keys(o)?;
|
||||
let mut positions = Vec::new();
|
||||
for k in keys {
|
||||
@@ -3377,18 +3396,20 @@ impl Interp {
|
||||
}
|
||||
};
|
||||
// A name an earlier object has but does not list is not listed again.
|
||||
if let Some(pos) = pos {
|
||||
held.add(self, SOURCE_ENTRY_BYTES)?;
|
||||
// A proxy met again on the chain records each position once.
|
||||
if let Some(pos) = pos.filter(|&pos| !proxy_positions.contains(&(o, pos))) {
|
||||
held.add(self, SOURCE_ENTRY_BYTES.saturating_add(KEY_ENTRY_BYTES))?;
|
||||
proxy_positions.insert((o, pos));
|
||||
positions.push(pos);
|
||||
}
|
||||
}
|
||||
if !positions.is_empty() {
|
||||
held.add(self, LISTED_ENTRY_BYTES)?;
|
||||
positions.sort_unstable();
|
||||
positions.dedup();
|
||||
listed.push(Listed { proxy: o, positions });
|
||||
}
|
||||
held.add(self, LISTED_ENTRY_BYTES)?;
|
||||
cur = self.get_prototype_of(o)?;
|
||||
let prototype = cur.filter(|&p| self.is_proxy(p));
|
||||
// A proxy met again on the chain keeps the names its earlier visits listed.
|
||||
let entry = listed.entry(o).or_insert_with(|| Listed { prototype, positions: Vec::new() });
|
||||
entry.prototype = prototype;
|
||||
entry.positions.append(&mut positions);
|
||||
if let Some(root) = self.temp_roots.get_mut(slot) {
|
||||
*root = cur.map_or(Value::Undefined, Value::Object);
|
||||
}
|
||||
@@ -3439,18 +3460,30 @@ impl Interp {
|
||||
}
|
||||
cur = obj.proto;
|
||||
}
|
||||
// Sorted once after the walk, for the iterator's binary search.
|
||||
for entry in listed.values_mut() {
|
||||
entry.positions.sort_unstable();
|
||||
entry.positions.dedup();
|
||||
entry.positions.shrink_to_fit();
|
||||
}
|
||||
Ok((out, listed))
|
||||
}
|
||||
|
||||
fn op_for_in_start(&mut self) -> JsResult<()> {
|
||||
let saved = self.temp_roots.len();
|
||||
let r = self.op_for_in_start_rooted();
|
||||
self.temp_roots.truncate(saved);
|
||||
r
|
||||
}
|
||||
|
||||
fn op_for_in_start_rooted(&mut self) -> JsResult<()> {
|
||||
let v = self.peek(0)?;
|
||||
let ((keys, listed), object) = if v.is_nullish() {
|
||||
((Vec::new(), Vec::new()), None)
|
||||
((Vec::new(), HashMap::new()), None)
|
||||
} else {
|
||||
let o = self.to_object(&v)?;
|
||||
// A wrapper made by ToObject is not on the stack; a collection while the names are
|
||||
// listed or their bytes reserved must not free it.
|
||||
let saved = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(o));
|
||||
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
|
||||
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
|
||||
@@ -3460,7 +3493,6 @@ impl Interp {
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
|
||||
Ok((keys, listed))
|
||||
});
|
||||
self.temp_roots.truncate(saved);
|
||||
(keys?, Some(o))
|
||||
};
|
||||
let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, listed, pos: 0, object })), None));
|
||||
@@ -3493,8 +3525,9 @@ impl Interp {
|
||||
///
|
||||
/// `pos` is the position of `k` in the names of the loop `iter`. A proxy is asked through its
|
||||
/// `getOwnPropertyDescriptor` trap only when its `ownKeys` trap returned `k` while the names
|
||||
/// were listed, wherever it sits on the chain now; any other proxy cannot hide an inherited
|
||||
/// name. A typed array without the element `k` names does not hide its prototypes' `k`.
|
||||
/// were listed, or when the same prototype lookup returns a fresh proxy of that target.
|
||||
/// Recorded proxies can move on the chain; any other proxy cannot hide an inherited name.
|
||||
/// A typed array without the element `k` names does not hide its prototypes' `k`.
|
||||
fn for_in_still_has(&mut self, iter: ObjId, o: ObjId, k: &Key, pos: u32) -> JsResult<bool> {
|
||||
// One root slot holds the proxy the walk has reached, then the prototype it gave.
|
||||
let mark = self.temp_roots.len();
|
||||
@@ -3506,13 +3539,18 @@ impl Interp {
|
||||
|
||||
fn for_in_still_has_rooted(&mut self, iter: ObjId, mut cur: ObjId, k: &Key, pos: u32, slot: usize) -> JsResult<bool> {
|
||||
let mut steps = 0usize;
|
||||
let mut candidate = None;
|
||||
loop {
|
||||
if self.is_proxy(cur) {
|
||||
if let Some(root) = self.temp_roots.get_mut(slot) {
|
||||
*root = Value::Object(cur);
|
||||
}
|
||||
self.use_fuel()?;
|
||||
if self.for_in_listed_by(iter, cur, pos)?
|
||||
let source = self.for_in_listing_proxy(iter, cur, candidate)?;
|
||||
let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") };
|
||||
let listed = source.and_then(|p| state.listed.get(&p));
|
||||
candidate = listed.and_then(|l| l.prototype);
|
||||
if listed.is_some_and(|l| l.positions.binary_search(&pos).is_ok())
|
||||
&& let Some(prop) = self.get_own_property(cur, k)?
|
||||
{
|
||||
return Ok(prop.enumerable());
|
||||
@@ -3524,6 +3562,7 @@ impl Interp {
|
||||
cur = next;
|
||||
continue;
|
||||
}
|
||||
candidate = None;
|
||||
if let Some(prop) = self.ordinary_own_property(cur, k)? {
|
||||
return Ok(prop.enumerable());
|
||||
}
|
||||
@@ -3536,11 +3575,18 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `ownKeys` trap of `proxy` returned the name at `pos` when the loop `iter`
|
||||
/// listed its names.
|
||||
fn for_in_listed_by(&self, iter: ObjId, proxy: ObjId, pos: u32) -> JsResult<bool> {
|
||||
/// Finds a recorded proxy by identity or by the preceding proxy's recorded prototype lookup.
|
||||
fn for_in_listing_proxy(&self, iter: ObjId, proxy: ObjId, candidate: Option<ObjId>) -> JsResult<Option<ObjId>> {
|
||||
let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") };
|
||||
Ok(state.listed.iter().any(|l| l.proxy == proxy && l.positions.binary_search(&pos).is_ok()))
|
||||
if state.listed.contains_key(&proxy) {
|
||||
return Ok(Some(proxy));
|
||||
}
|
||||
let target = |p: ObjId| match self.heap.object(p).map(|o| &o.class) {
|
||||
Some(Class::Proxy(d)) => d.target,
|
||||
_ => None,
|
||||
};
|
||||
let Some(own) = target(proxy) else { return Ok(None) };
|
||||
Ok(candidate.filter(|&p| target(p) == Some(own)))
|
||||
}
|
||||
|
||||
// ---- calls ----
|
||||
|
||||
@@ -421,11 +421,11 @@ impl Interp {
|
||||
/// non-configurable key of the target, and of a non-extensible target exactly its keys. Each
|
||||
/// key takes a unit of fuel and counts against the heap limit until the caller drops the list,
|
||||
/// which keeps the trap's order in [`HeldKeys::ordered`].
|
||||
pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult<HeldKeys> {
|
||||
pub(crate) fn proxy_own_keys(&mut self, p: ObjId, ecma_order: bool) -> JsResult<HeldKeys> {
|
||||
self.proxy_op(p, "list the properties of", &[], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "ownKeys")? else {
|
||||
// A target that is a proxy gives its Symbols with its names.
|
||||
let mut keys = i.ecma_own_keys(target)?;
|
||||
let mut keys = if ecma_order { i.ecma_own_keys(target)? } else { i.own_keys(target)? };
|
||||
if !i.is_proxy(target) {
|
||||
keys.syms = i.own_symbols(target)?;
|
||||
keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?;
|
||||
@@ -441,12 +441,15 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]:
|
||||
/// one `ownKeys` trap call for a proxy.
|
||||
/// one `ownKeys` trap call for a proxy. With [`crate::Options::es2015`] the names come in
|
||||
/// ECMAScript order (array indices ascending first), through proxies without an `ownKeys`
|
||||
/// trap too; without it they come in the order `for-in` visits them.
|
||||
pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult<HeldKeys> {
|
||||
let ecma_order = self.options.es2015;
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_own_keys(id);
|
||||
return self.proxy_own_keys(id, ecma_order);
|
||||
}
|
||||
let mut keys = self.own_keys(id)?;
|
||||
let mut keys = if ecma_order { self.ecma_own_keys(id)? } else { self.own_keys(id)? };
|
||||
keys.syms = self.own_symbols(id)?;
|
||||
keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?;
|
||||
Ok(keys)
|
||||
|
||||
+544
-24
@@ -626,6 +626,43 @@ fn reflect_methods_answer_with_booleans_and_receivers() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_keeps_symbol_keys_as_symbols() {
|
||||
truth(
|
||||
"var s = Symbol('x'), o = { a: 1 }; o[s] = 7;
|
||||
var read = Reflect.get(o, s) === 7 && Reflect.has(o, s) && !Reflect.has(o, Symbol('x'))
|
||||
&& Reflect.getOwnPropertyDescriptor(o, s).value === 7;
|
||||
var written = Reflect.set(o, s, 8) && o[s] === 8;
|
||||
var r = {}, base = {}; Object.defineProperty(base, s, { value: 1, writable: true });
|
||||
var received = Reflect.set(base, s, 2, r) && r[s] === 2 && base[s] === 1;
|
||||
var fixed = {}; Object.defineProperty(fixed, s, { value: 1 });
|
||||
var refused = !Reflect.set(fixed, s, 2) && !Reflect.deleteProperty(fixed, s);
|
||||
var t = Symbol('t'), defined = Reflect.defineProperty(o, t, { value: 3, configurable: true }) && o[t] === 3;
|
||||
var deleted = Reflect.deleteProperty(o, t) && !(t in o) && o['Symbol(t)'] === undefined;
|
||||
var keys = Reflect.ownKeys(o);
|
||||
read && written && received && refused && defined && deleted && keys.length === 2 && keys[0] === 'a' && keys[1] === s",
|
||||
);
|
||||
// A proxy's Symbol keys are its target's.
|
||||
truth(
|
||||
"var s = Symbol('x'), t = { a: 1 }; t[s] = 1;
|
||||
var keys = Reflect.ownKeys(new Proxy(t, {}));
|
||||
keys.length === 2 && keys[0] === 'a' && keys[1] === s",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subclassable_built_in_runs_the_outer_get_trap_of_a_new_target_whose_inner_proxy_is_revoked() {
|
||||
// The outer trap runs; its invariant check then reads the revoked target and throws
|
||||
// (ECMA-262 2020 section 9.5.8, step 9).
|
||||
truth(
|
||||
"class DerivedArray extends Array {}
|
||||
var P = {}, inner = Proxy.revocable(function () {}, {}), reads = 0;
|
||||
var outer = new Proxy(inner.proxy, { get: function (t, k) { if (k === 'prototype') { reads++; return P; } } });
|
||||
inner.revoke();
|
||||
type_error(function () { Reflect.construct(DerivedArray, [], outer); }) && reads === 1",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() {
|
||||
truth(
|
||||
@@ -707,6 +744,184 @@ fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() {
|
||||
|
||||
// ---- proxies elsewhere in the language ----
|
||||
|
||||
#[test]
|
||||
fn proxy_with_bindings_honor_unscopables() {
|
||||
truth_collecting(
|
||||
"var x = 'outer', result, log = [], scope, blocked;
|
||||
var p = new Proxy({ x: 'inner' }, {
|
||||
has: function (t, k) { if (k === 'x') log.push('has'); return Reflect.has(t, k); },
|
||||
get: function (t, k, r) {
|
||||
if (k === Symbol.unscopables) {
|
||||
scope = r;
|
||||
return new Proxy({ x: true }, { get: function (t, k, r) {
|
||||
log.push(k); blocked = r; return t[k];
|
||||
} });
|
||||
}
|
||||
throw 'unexpected binding read';
|
||||
}
|
||||
});
|
||||
with (p) { result = x; }
|
||||
result === 'outer' && scope === p && typeof blocked === 'object' && log.join() === 'has,x'",
|
||||
);
|
||||
for blocked in ["undefined", "null", "false", "1", "{}", "{ x: false }"] {
|
||||
truth(&format!(
|
||||
"var x = 'outer', result, t = {{ x: 'inner' }};
|
||||
t[Symbol.unscopables] = {blocked};
|
||||
with (new Proxy(t, {{}})) {{ result = x; }}
|
||||
result === 'inner'"
|
||||
));
|
||||
}
|
||||
truth(
|
||||
"var x = 'outer', kind, result, t = { x: 'inner' };
|
||||
t[Symbol.unscopables] = { x: true };
|
||||
with (new Proxy(t, {})) { x = 'changed'; kind = typeof x; result = delete x; }
|
||||
x === 'changed' && t.x === 'inner' && kind === 'string' && result === false",
|
||||
);
|
||||
for trap in ["return new Proxy({}, { get: function () { throw marker; } });", "throw marker;"] {
|
||||
truth(&format!(
|
||||
"var marker = {{}}, caught = false;
|
||||
var p = new Proxy({{ x: 1 }}, {{ get: function (t, k) {{
|
||||
if (k === Symbol.unscopables) {{ {trap} }} return t[k];
|
||||
}} }});
|
||||
try {{ with (p) {{ x; }} }} catch (e) {{ caught = e === marker; }}
|
||||
caught"
|
||||
));
|
||||
}
|
||||
let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
|
||||
assert_eq!(
|
||||
realm.run(
|
||||
"function method() { return 'outer'; }
|
||||
var t = { method: function () { return 'inner'; } }, result;
|
||||
t[Symbol.unscopables] = { method: true };
|
||||
with (new Proxy(t, {})) { result = method(); }
|
||||
result === 'outer'"
|
||||
),
|
||||
Ok(JsValue::Bool(true))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_proxies_preserve_object_key_order() {
|
||||
truth_collecting(
|
||||
"var o = { z: 0, 10: 10, 2: 2, a: 1 }, a = [1, 2]; a.label = 'a';
|
||||
[o, a].every(function (target) {
|
||||
var p = new Proxy(new Proxy(target, {}), {});
|
||||
return Object.keys(p).join() === Object.keys(target).join() &&
|
||||
Object.getOwnPropertyNames(p).join() === Object.getOwnPropertyNames(target).join() &&
|
||||
Reflect.ownKeys(p).join() === Reflect.ownKeys(target).join();
|
||||
})",
|
||||
);
|
||||
truth(
|
||||
"var calls = 0, p = new Proxy({ a: 1, b: 2 }, { ownKeys: function () { calls++; return ['b', 'a']; } });
|
||||
var q = new Proxy(p, {});
|
||||
Object.keys(q).join() === 'b,a' && Object.getOwnPropertyNames(q).join() === 'b,a' &&
|
||||
Reflect.ownKeys(q).join() === 'b,a' && calls === 3",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concat_honors_proxy_spreadability_overrides() {
|
||||
truth_collecting(
|
||||
"var reads = 0, receiver, p = new Proxy([1, 2], { get: function (t, k, r) {
|
||||
if (k === Symbol.isConcatSpreadable) { reads++; receiver = r; return false; }
|
||||
return Reflect.get(t, k, r);
|
||||
} });
|
||||
var a = [].concat(p), b = p.concat(3);
|
||||
a.length === 1 && a[0] === p && b.length === 2 && b[0] === p && b[1] === 3 && reads === 2 && receiver === p",
|
||||
);
|
||||
truth_collecting(
|
||||
"var reads = [], receiver;
|
||||
var p = new Proxy({ 0: 'a', 2: 'c', length: 3 }, { get: function (t, k, r) {
|
||||
if (k === Symbol.isConcatSpreadable) { reads.push('spread'); receiver = r; return true; }
|
||||
reads.push(k); return Reflect.get(t, k, r);
|
||||
} });
|
||||
var a = [].concat(p);
|
||||
a.length === 3 && a[0] === 'a' && !(1 in a) && a[2] === 'c' && receiver === p && reads.join() === 'spread,length,0,2'",
|
||||
);
|
||||
truth(
|
||||
"var p = new Proxy([1, 2], {}), t = [3, 4]; t[Symbol.isConcatSpreadable] = null;
|
||||
var q = new Proxy(t, {}), a = [].concat(p, q);
|
||||
a.length === 3 && a[0] === 1 && a[1] === 2 && a[2] === q",
|
||||
);
|
||||
truth(
|
||||
"var marker = {}, caught = false;
|
||||
var p = new Proxy([], { get: function (t, k) { if (k === Symbol.isConcatSpreadable) throw marker; return t[k]; } });
|
||||
try { [].concat(p); } catch (e) { caught = e === marker; }
|
||||
caught",
|
||||
);
|
||||
type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreadability_and_unscopables_kept_from_an_earlier_run_apply_only_with_the_option() {
|
||||
let mut realm = es();
|
||||
let setup = "var a = [1, 2]; a[Symbol.isConcatSpreadable] = false;
|
||||
var o = { x: 'own' }; o[Symbol.unscopables] = { x: true }; var x = 'outer'; true";
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
|
||||
realm.set_es2015(false);
|
||||
assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 2 && c[0] === 1 && w === 'own'"), Ok(JsValue::Bool(true)));
|
||||
realm.set_es2015(true);
|
||||
assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 1 && c[0] === a && w === 'outer'"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_properties_defines_array_index_keys_in_ascending_order() {
|
||||
truth(
|
||||
"var log = [], bag = {}; bag.b = { value: 0 }; bag[2] = { value: 2 }; bag[1] = { value: 1 };
|
||||
var p = new Proxy({}, { defineProperty: function (t, k, d) { log.push(k); return Reflect.defineProperty(t, k, d); } });
|
||||
Object.defineProperties(p, bag);
|
||||
var wrapped = [], q = new Proxy({}, { defineProperty: function (t, k, d) { wrapped.push(k); return Reflect.defineProperty(t, k, d); } });
|
||||
Object.defineProperties(q, new Proxy(bag, {}));
|
||||
log.join() === '1,2,b' && wrapped.join() === '1,2,b'",
|
||||
);
|
||||
// Without the option, descriptors are read in the order for-in visits the names.
|
||||
let mut realm = Realm::new();
|
||||
let src = "var order = [], bag = {}; bag.b = 0; bag[2] = 0; bag[1] = 0;
|
||||
var seen = [], descs = {};
|
||||
for (var k in bag) { order.push(k); (function (k) { Object.defineProperty(descs, k, { enumerable: true, get: function () { seen.push(k); return { value: 0 }; } }); })(k); }
|
||||
Object.defineProperties({}, descs);
|
||||
seen.join() === order.join()";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_array_statics_construct_through_proxy_receivers() {
|
||||
truth_collecting(
|
||||
"var p = new Proxy(Uint8Array, {}), a = p.of(257, 2), b = p.from([3, 260]);
|
||||
a instanceof Uint8Array && a.length === 2 && a[0] === 1 && a[1] === 2 &&
|
||||
b instanceof Uint8Array && b.length === 2 && b[0] === 3 && b[1] === 4",
|
||||
);
|
||||
truth_collecting(
|
||||
"var calls = [], receiver, context = { add: 1 };
|
||||
var p = new Proxy(Uint8Array, { construct: function (t, args, nt) {
|
||||
calls.push(t === Uint8Array, args.length, args[0], nt === p);
|
||||
return new Uint16Array(args[0]);
|
||||
} });
|
||||
var a = p.of(257, 2), b = p.from({ 0: 300, length: 1 }, function (v, i) { receiver = this; return v + i + this.add; }, context);
|
||||
a instanceof Uint16Array && a[0] === 257 && a[1] === 2 && b instanceof Uint16Array && b[0] === 301 &&
|
||||
receiver === context && calls.join() === 'true,1,2,true,true,1,1,true'",
|
||||
);
|
||||
for method in ["of(1, 2)", "from([1, 2])"] {
|
||||
for result in ["{}", "new Uint8Array(1)", "new Proxy(new Uint8Array(2), {})"] {
|
||||
truth(&format!(
|
||||
"var p = new Proxy(Uint8Array, {{ construct: function () {{ return {result}; }} }});
|
||||
type_error(function () {{ p.{method}; }})"
|
||||
));
|
||||
}
|
||||
truth(&format!(
|
||||
"var marker = {{}}, caught = false;
|
||||
var p = new Proxy(Uint8Array, {{ construct: function () {{ throw marker; }} }});
|
||||
try {{ p.{method}; }} catch (e) {{ caught = e === marker; }}
|
||||
caught"
|
||||
));
|
||||
}
|
||||
truth(
|
||||
"var pair = Proxy.revocable(Uint8Array, {}), p = pair.proxy;
|
||||
pair.revoke();
|
||||
type_error(function () { Uint8Array.of.call(p, 1); }) && type_error(function () { Uint8Array.from.call(p, [1]); })",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_works_as_a_prototype_and_a_with_scope() {
|
||||
truth(
|
||||
@@ -732,21 +947,27 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() {
|
||||
fn typeof_reads_the_binding_a_with_scope_reported_once() {
|
||||
// GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`.
|
||||
truth(
|
||||
"var asked = 0, got = 0;
|
||||
"var asked = 0, got = 0, unscopables = 0;
|
||||
var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; },
|
||||
get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } });
|
||||
get: function (t, k) {
|
||||
if (k === Symbol.unscopables) { unscopables++; return undefined; }
|
||||
got++; return k === 'x' ? function () {} : undefined;
|
||||
} });
|
||||
var r;
|
||||
with (p) { r = typeof x; }
|
||||
r === 'undefined' && asked === 2 && got === 0",
|
||||
r === 'undefined' && asked === 2 && got === 0 && unscopables === 1",
|
||||
);
|
||||
// A plain read of the same binding takes the same path.
|
||||
truth(
|
||||
"var asked = 0, got = 0;
|
||||
"var asked = 0, got = 0, unscopables = 0;
|
||||
var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; },
|
||||
get: function (t, k) { got++; return 1; } });
|
||||
get: function (t, k) {
|
||||
if (k === Symbol.unscopables) { unscopables++; return undefined; }
|
||||
got++; return 1;
|
||||
} });
|
||||
var r;
|
||||
with (p) { r = x; }
|
||||
r === undefined && asked === 2 && got === 0",
|
||||
r === undefined && asked === 2 && got === 0 && unscopables === 1",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -755,15 +976,19 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() {
|
||||
for present in ["asked++ < 2", "asked++ === 0", "false"] {
|
||||
let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
|
||||
let src = format!(
|
||||
"var asked = 0, got = 0, outer = 0, receiver;
|
||||
"var asked = 0, got = 0, outer = 0, unscopables = 0, receiver;
|
||||
function method() {{ outer++; return 'outer'; }}
|
||||
var p = new Proxy({{}}, {{
|
||||
has: function (t, k) {{ return k === 'method' && ({present}); }},
|
||||
get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }}
|
||||
get: function (t, k) {{
|
||||
if (k === Symbol.unscopables) {{ unscopables++; return undefined; }}
|
||||
got++; return function () {{ receiver = this; return 'proxy'; }};
|
||||
}}
|
||||
}});
|
||||
var result, caught = false;
|
||||
try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }}
|
||||
{expected}",
|
||||
({expected}) && unscopables === {unscopables}",
|
||||
unscopables = usize::from(present != "false"),
|
||||
expected = match present {
|
||||
"asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught",
|
||||
"asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0",
|
||||
@@ -779,16 +1004,21 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() {
|
||||
#[test]
|
||||
fn concat_proxy_array_lengths_use_to_length() {
|
||||
truth(
|
||||
"var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0;
|
||||
"var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0, spreadReads = 0;
|
||||
var empty = lengths.every(function (length) {
|
||||
var p = new Proxy([7], {
|
||||
get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; },
|
||||
get: function (t, k) {
|
||||
if (k === Symbol.isConcatSpreadable) { spreadReads++; return undefined; }
|
||||
if (k === 'length') return length;
|
||||
reads++; return t[k];
|
||||
},
|
||||
has: function () { reads++; return true; }
|
||||
});
|
||||
return [3].concat(new Proxy(p, {}), 9).join() === '3,9';
|
||||
});
|
||||
var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } });
|
||||
empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'",
|
||||
empty && reads === 0 && spreadReads === lengths.length &&
|
||||
[].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -818,7 +1048,11 @@ fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() {
|
||||
for length in ["4294967296", "Infinity"] {
|
||||
let setup = format!(
|
||||
"var p = new Proxy([], {{
|
||||
get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }},
|
||||
get: function (t, k) {{
|
||||
if (k === Symbol.isConcatSpreadable) return undefined;
|
||||
if (k === 'length') return {length};
|
||||
throw new Error('element read');
|
||||
}},
|
||||
has: function () {{ throw new Error('element checked'); }}
|
||||
}});"
|
||||
);
|
||||
@@ -1129,6 +1363,23 @@ fn a_typed_array_receiver_converts_the_value_for_an_index_it_lacks() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_keys_pass_through_a_proxy_to_its_target() {
|
||||
truth(
|
||||
"var s = Symbol('x'), t = {}, p = new Proxy(t, {});
|
||||
Object.defineProperty(p, s, { value: 7, writable: true, configurable: true });
|
||||
var defined = t[s] === 7 && p[s] === 7 && Object.getOwnPropertySymbols(p)[0] === s;
|
||||
p[s] = 8;
|
||||
var written = t[s] === 8;
|
||||
delete p[s];
|
||||
var self = null, u = {}; Object.defineProperty(u, s, { set: function () { self = this; } });
|
||||
var q = new Proxy(u, {}); q[s] = 1;
|
||||
defined && written && !(s in t) && self === q && type_error(function () {
|
||||
var pair = Proxy.revocable({}, {}); pair.revoke(); Object.defineProperty(pair.proxy, s, { value: 1 });
|
||||
})",
|
||||
);
|
||||
}
|
||||
|
||||
fn namespace_script(source: &str) -> Realm {
|
||||
let mut realm = es();
|
||||
assert!(realm.run("var out = false;").is_ok());
|
||||
@@ -1308,12 +1559,23 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() {
|
||||
}
|
||||
}
|
||||
assert!(seen.borrow().is_empty(), "the host function did not run");
|
||||
// The traps did not run either.
|
||||
// The same argument with a trap is refused too, before the host function or the trap runs.
|
||||
let mut realm = es();
|
||||
let f: HostFunction = Rc::new(|_| Ok(Data::Undefined));
|
||||
let calls = Rc::new(RefCell::new(0usize));
|
||||
let counter = calls.clone();
|
||||
let f: HostFunction = Rc::new(move |_| {
|
||||
*counter.borrow_mut() += 1;
|
||||
Ok(Data::Undefined)
|
||||
});
|
||||
realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap();
|
||||
let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran");
|
||||
assert_eq!(r, Ok(JsValue::Bool(false)));
|
||||
let r = realm.run(
|
||||
"var ran = false, threw = false;
|
||||
try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); }
|
||||
catch (e) { threw = e instanceof TypeError; }
|
||||
threw && !ran",
|
||||
);
|
||||
assert_eq!(r, Ok(JsValue::Bool(true)));
|
||||
assert_eq!(*calls.borrow(), 0, "the host function did not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1703,6 +1965,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() {
|
||||
assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() {
|
||||
let mut realm = es();
|
||||
realm.add_script_extensions().unwrap();
|
||||
let src = format!(
|
||||
"{PRELUDE}
|
||||
var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0;
|
||||
var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }});
|
||||
find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0"
|
||||
);
|
||||
assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_proxy_and_reflect_membership_use_host_indexers() {
|
||||
let index: HostFunction = Rc::new(|args| {
|
||||
@@ -1854,6 +2129,131 @@ fn for_in_asks_only_the_proxies_that_listed_a_name() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_visits_a_name_from_a_prototype_trap_that_returns_a_new_proxy_each_time() {
|
||||
// Each [[GetPrototypeOf]] gives a new proxy of `t`: the one asked before each name is not the
|
||||
// one whose ownKeys listed it.
|
||||
truth_collecting(
|
||||
"var t = { a: 1, b: 2 };
|
||||
var o = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return new Proxy(t, {}); } });
|
||||
var seen = [];
|
||||
for (var name in o) seen.push(name);
|
||||
seen.join() === 'a,b'",
|
||||
);
|
||||
// A non-enumerable descriptor from such a proxy still does not hide a name further on.
|
||||
truth(
|
||||
"var c = { x: 1 };
|
||||
var o = new Proxy({}, {
|
||||
ownKeys: function () { return []; },
|
||||
getPrototypeOf: function () {
|
||||
return new Proxy({}, {
|
||||
ownKeys: function () { return []; },
|
||||
getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; },
|
||||
getPrototypeOf: function () { return c; }
|
||||
});
|
||||
}
|
||||
});
|
||||
var seen = [];
|
||||
for (var name in o) seen.push(name);
|
||||
seen.join() === 'x'",
|
||||
);
|
||||
// Two proxies of one target on the chain: the one that listed nothing does not decide for the
|
||||
// one that listed `x`.
|
||||
truth(
|
||||
"var t = {};
|
||||
var b = new Proxy(t, {
|
||||
ownKeys: function () { return ['x']; },
|
||||
getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; }
|
||||
});
|
||||
var a = new Proxy(t, {
|
||||
ownKeys: function () { return []; },
|
||||
getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; },
|
||||
getPrototypeOf: function () { return b; }
|
||||
});
|
||||
var seen = [];
|
||||
for (var name in a) seen.push(name);
|
||||
seen.join() === 'x'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_keeps_the_names_a_proxy_listed_before_it_returns_itself_as_its_prototype() {
|
||||
// The first visit lists `x`; the proxy is its own prototype once, and the second visit lists
|
||||
// nothing. The name from the first visit is still visited.
|
||||
truth(
|
||||
"var keysCalls = 0, protoCalls = 0;
|
||||
var p = new Proxy({}, {
|
||||
ownKeys: function () { return keysCalls++ === 0 ? ['x'] : []; },
|
||||
getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; },
|
||||
getPrototypeOf: function () { return protoCalls++ === 0 ? p : null; }
|
||||
});
|
||||
var seen = [];
|
||||
for (var name in p) seen.push(name);
|
||||
seen.join() === 'x'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_matches_nested_fresh_wrappers_to_their_prototype_lookups() {
|
||||
truth_collecting(
|
||||
"var t = { a: 1, b: 2 }, middle = {};
|
||||
var handler = {
|
||||
ownKeys: function () { return []; },
|
||||
getPrototypeOf: function () { return new Proxy(t, {}); }
|
||||
};
|
||||
var o = new Proxy({}, {
|
||||
ownKeys: function () { return []; },
|
||||
getPrototypeOf: function () { return new Proxy(middle, handler); }
|
||||
});
|
||||
var seen = [];
|
||||
for (var name in o) seen.push(name);
|
||||
seen.join() === 'a,b'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_does_not_ask_an_inserted_proxy_of_a_listing_proxys_target() {
|
||||
truth_collecting(
|
||||
"var t = { a: 1, b: 2 }, reads = 0;
|
||||
var listed = new Proxy(t, {});
|
||||
var o = Object.create(listed), seen = [];
|
||||
for (var name in o) {
|
||||
seen.push(name);
|
||||
if (name === 'a') {
|
||||
Object.setPrototypeOf(o, new Proxy(t, {
|
||||
getOwnPropertyDescriptor: function () {
|
||||
reads++;
|
||||
return { value: 0, enumerable: false, configurable: true };
|
||||
},
|
||||
getPrototypeOf: function () { return listed; }
|
||||
}));
|
||||
}
|
||||
}
|
||||
seen.join() === 'a,b' && reads === 0",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_walks_many_empty_proxies_before_inherited_names() {
|
||||
truth(
|
||||
"var base = {}, depth = 256, count = 32, walks = 0, reads = 0;
|
||||
for (var i = 0; i < count; i++) base['key' + i] = i;
|
||||
function wrap(next) {
|
||||
return new Proxy({}, {
|
||||
ownKeys: function () { return []; },
|
||||
getOwnPropertyDescriptor: function () { reads++; return undefined; },
|
||||
getPrototypeOf: function () { walks++; return next; }
|
||||
});
|
||||
}
|
||||
var o = base;
|
||||
for (var j = 0; j < depth; j++) o = wrap(o);
|
||||
var seen = [];
|
||||
for (var name in o) seen.push(name);
|
||||
seen.length === count && seen.every(function (name, index) { return name === 'key' + index; }) &&
|
||||
reads === 0 && walks === depth * (count + 1)",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_in_reaches_a_name_past_a_typed_array_without_that_element() {
|
||||
truth(
|
||||
@@ -1982,6 +2382,14 @@ fn json_proxy_replacer_lengths_use_to_length() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_replacer_lists_charge_only_the_names_they_keep() {
|
||||
// A long, sparse replacer array keeps one name, so only that name counts against the heap.
|
||||
let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() };
|
||||
let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'";
|
||||
assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_proxy_lengths_check_limits_before_reading_elements() {
|
||||
for length in ["4294967296", "Infinity"] {
|
||||
@@ -2007,13 +2415,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() {
|
||||
),
|
||||
LimitKind::Fuel
|
||||
);
|
||||
// A replacer list's length alone is not charged to the heap; the names it keeps are.
|
||||
let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() };
|
||||
assert_eq!(
|
||||
Realm::with_options(es_options(), limits.clone()).run(
|
||||
"var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } });
|
||||
JSON.stringify({ a: 1 }, p) === '{}'"
|
||||
),
|
||||
Ok(JsValue::Bool(true))
|
||||
);
|
||||
assert_eq!(
|
||||
limit(
|
||||
"var p = new Proxy([], { get: function (t, k) {
|
||||
if (k === 'length') return 1000000;
|
||||
throw new Error('element read');
|
||||
} }); JSON.stringify({}, p)",
|
||||
"var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } });
|
||||
JSON.stringify({}, p)",
|
||||
limits,
|
||||
),
|
||||
LimitKind::Heap
|
||||
@@ -2023,17 +2437,123 @@ fn json_proxy_lengths_check_limits_before_reading_elements() {
|
||||
#[test]
|
||||
fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() {
|
||||
truth(
|
||||
"var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {});
|
||||
"var B = Map.bind(null, [[1, 7]]), proto = Object.create(Map.prototype);
|
||||
Object.defineProperty(B, 'prototype', { value: proto });
|
||||
var P = new Proxy(B, {}), Q = new Proxy(P, {});
|
||||
var a = new P(), b = new Q(), c = Reflect.construct(Q, []);
|
||||
var R = new Proxy(Q.bind(null), {}), d = new R();
|
||||
var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U();
|
||||
Object.defineProperty(B, 'prototype', { value: Map.prototype });
|
||||
a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 &&
|
||||
Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 &&
|
||||
Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(b) === proto && Object.getPrototypeOf(c) === proto &&
|
||||
Object.getPrototypeOf(d) === Map.prototype && u.length === 2 && u[1] === 8 &&
|
||||
type_error(function () { class Child extends P {} new Child(); })",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() {
|
||||
truth(
|
||||
"var s = Symbol('s'), hidden = Symbol('h'), t = {}; t[hidden] = 1;
|
||||
var calls = 0;
|
||||
var open = new Proxy(t, { ownKeys: function () { calls++; return ['a', s]; } });
|
||||
var listed = Reflect.ownKeys(open);
|
||||
var syms = Object.getOwnPropertySymbols(open);
|
||||
listed.length === 2 && listed[0] === 'a' && listed[1] === s && syms.length === 1 && syms[0] === s && calls === 2",
|
||||
);
|
||||
truth(
|
||||
"var s = Symbol('s');
|
||||
var mixed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, 'a', 'b']; } }));
|
||||
mixed.length === 3 && mixed[0] === s && mixed[1] === 'a' && mixed[2] === 'b'",
|
||||
);
|
||||
type_errors(&[
|
||||
"var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))",
|
||||
"var s = Symbol('s'); Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, s]; } }))",
|
||||
"var s = Symbol('s'); Reflect.ownKeys(new Proxy(Object.preventExtensions({}), { ownKeys: function () { return [s]; } }))",
|
||||
"Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [1]; } }))",
|
||||
]);
|
||||
truth(
|
||||
"var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return [s]; } })).length === 1",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_keys_checks_target_descriptors_in_combined_key_order() {
|
||||
truth(
|
||||
"var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 };
|
||||
t[s] = 3; t[u] = 4;
|
||||
var reads = [], extensible = 0;
|
||||
var target = new Proxy(t, {
|
||||
ownKeys: function () { return [s, 'a', u, 'b']; },
|
||||
isExtensible: function () { extensible++; return true; },
|
||||
getOwnPropertyDescriptor: function (t, k) {
|
||||
reads.push(String(k));
|
||||
if (k === s) Object.defineProperty(t, u, { configurable: false });
|
||||
return Object.getOwnPropertyDescriptor(t, k);
|
||||
}
|
||||
});
|
||||
// The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the
|
||||
// outer trap that leaves `u` out breaks the invariant.
|
||||
var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); });
|
||||
var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } }));
|
||||
threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3",
|
||||
);
|
||||
truth(
|
||||
"var s = Symbol('s'), t = { a: 1 }, marker = {};
|
||||
Object.defineProperty(t, s, { value: 2 });
|
||||
var target = new Proxy(t, {
|
||||
ownKeys: function () { return [s, 'a']; },
|
||||
getOwnPropertyDescriptor: function () { throw marker; }
|
||||
});
|
||||
var caught;
|
||||
try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); }
|
||||
catch (e) { caught = e; }
|
||||
caught === marker",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_keys_consumers_keep_interleaved_trap_keys() {
|
||||
truth(
|
||||
"var s = Symbol('s'), u = Symbol('u');
|
||||
var p = new Proxy({}, { ownKeys: function () { return ['a', s, 'b', u, 'c']; } });
|
||||
var keys = Reflect.ownKeys(p);
|
||||
keys.length === 5 && keys[0] === 'a' && keys[1] === s && keys[2] === 'b' && keys[3] === u && keys[4] === 'c'",
|
||||
);
|
||||
truth(
|
||||
"var s = Symbol('s'), t = { a: { value: 1 }, b: { value: 3 } };
|
||||
t[s] = { value: 2 };
|
||||
var order = [];
|
||||
var props = new Proxy(t, {
|
||||
ownKeys: function () { return ['a', s, 'b']; },
|
||||
get: function (t, k) { order.push(k); return t[k]; }
|
||||
});
|
||||
var o = Object.defineProperties({}, props);
|
||||
order.length === 3 && order[0] === 'a' && order[1] === s && order[2] === 'b' && o.a === 1 && o[s] === 2 && o.b === 3",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_reads_through_a_proxy_call_its_get_trap() {
|
||||
truth(
|
||||
"var s = Symbol('s'); var seen;
|
||||
var p = new Proxy({}, { get: function (t, k, r) { seen = [k, r]; return 5; } });
|
||||
var child = Object.create(p);
|
||||
p[s] === 5 && seen[0] === s && seen[1] === p && child[s] === 5 && seen[1] === child",
|
||||
);
|
||||
truth(
|
||||
"var s = Symbol('s'); var t = {}; t[s] = 3;
|
||||
new Proxy(t, {})[s] === 3 && Object.create(new Proxy(t, {}))[s] === 3",
|
||||
);
|
||||
type_errors(&["var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
new Proxy(t, { get: function () { return 2; } })[s]"]);
|
||||
truth(
|
||||
"var p = new Proxy({}, { get: function (t, k) { if (k === Symbol.toPrimitive) return function () { return 9; }; } });
|
||||
+p === 9",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() {
|
||||
let calls = Rc::new(RefCell::new(0));
|
||||
|
||||
@@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<V
|
||||
};
|
||||
let not_reflection = "reflect.find must be called on a reflection object";
|
||||
let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) };
|
||||
// Ordinary reads run no proxy traps, so the lists scanned are the ones the reflection object
|
||||
// holds and stay reachable from it.
|
||||
for list in ["properties", "methods"] {
|
||||
let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else {
|
||||
let Some(Prop::Data { value: Value::Object(a), .. }) = interp.ordinary_own_property(r, &key(list))? else {
|
||||
return Err(interp.type_error(not_reflection));
|
||||
};
|
||||
let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) };
|
||||
for i in 0..length {
|
||||
interp.use_fuel()?;
|
||||
let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue };
|
||||
let name = match interp.get_own_property(e, &key("name"))? {
|
||||
let Some(Prop::Data { value: Value::Object(e), .. }) = interp.ordinary_own_property(a, &index_key(i))? else { continue };
|
||||
let name = match interp.ordinary_own_property(e, &key("name"))? {
|
||||
Some(Prop::Data { value: Value::String(s), .. }) => flat_charged(interp, &s)?,
|
||||
Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?,
|
||||
_ => continue,
|
||||
|
||||
+12
-4
@@ -157,7 +157,9 @@ pub(crate) struct WellKnown {
|
||||
pub(crate) has_instance: Sym,
|
||||
pub(crate) to_primitive: Sym,
|
||||
pub(crate) to_string_tag: Sym,
|
||||
/// The five as values, for the collector.
|
||||
pub(crate) unscopables: Sym,
|
||||
pub(crate) is_concat_spreadable: Sym,
|
||||
/// The Symbols as values, for the collector.
|
||||
values: Vec<Value>,
|
||||
}
|
||||
|
||||
@@ -171,8 +173,14 @@ impl WellKnown {
|
||||
make("Symbol.toPrimitive"),
|
||||
make("Symbol.toStringTag"),
|
||||
);
|
||||
let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect();
|
||||
WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values }
|
||||
let unscopables = make("Symbol.unscopables");
|
||||
let is_concat_spreadable = make("Symbol.isConcatSpreadable");
|
||||
let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag, &unscopables, &is_concat_spreadable]
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.map(Value::Symbol)
|
||||
.collect();
|
||||
WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, unscopables, is_concat_spreadable, values }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,7 +551,7 @@ impl Interp {
|
||||
/// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap.
|
||||
pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult<Vec<Sym>> {
|
||||
if self.is_proxy(id) {
|
||||
return Ok(self.proxy_own_keys(id)?.syms);
|
||||
return Ok(self.proxy_own_keys(id, false)?.syms);
|
||||
}
|
||||
let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
|
||||
self.reserve_heap(count.saturating_mul(16))?;
|
||||
|
||||
@@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -44,7 +44,3 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] }
|
||||
[features]
|
||||
# `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only).
|
||||
test-steady = []
|
||||
|
||||
# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate.
|
||||
[package.metadata.craft]
|
||||
reads-every-member = true
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them
|
||||
//! ([`Event`]) and lists the `events` permission, and the module exports
|
||||
//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls
|
||||
//! `vc_event` in a fresh instance with a small JSON object that names the event and the document
|
||||
//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and
|
||||
//! a command call that would change a document is refused ([`crate::host`]).
|
||||
//!
|
||||
//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and
|
||||
//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and
|
||||
//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event.
|
||||
|
||||
/// The plug-in API level that adds `events`, the `events` permission and `vc_event`.
|
||||
pub const EVENTS_API: u32 = 2;
|
||||
|
||||
/// Instructions one handler may use, or the plug-in's own budget when that is smaller.
|
||||
pub const EVENT_FUEL: u64 = 5_000_000;
|
||||
|
||||
/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter.
|
||||
pub const EVENT_WALL_TIME_MS: u64 = 200;
|
||||
|
||||
/// Largest event JSON the host hands a handler, in bytes.
|
||||
pub const MAX_EVENT_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first
|
||||
/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit
|
||||
/// in [`MAX_EVENT_BYTES`].
|
||||
pub const MAX_EVENT_IDS: usize = 2048;
|
||||
|
||||
/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app
|
||||
/// starts again.
|
||||
pub const MAX_EVENT_FAILURES: u32 = 3;
|
||||
|
||||
/// One thing a plug-in may react to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Event {
|
||||
/// The selection in a document changed: other objects, anchors or segments, or nothing.
|
||||
SelectionChanged,
|
||||
/// A file opened as a document (File › Open, a recent file, New from Template).
|
||||
DocumentOpened,
|
||||
/// A document was saved to its own file (Save, Save As).
|
||||
DocumentSaved,
|
||||
/// The current layer changed, or a layer was added, deleted, moved or given other options.
|
||||
LayerChanged,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
/// Every event, in the order the docs list them.
|
||||
pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged];
|
||||
|
||||
/// Its name in a manifest's `events`, which is also the event's `type`.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Event::SelectionChanged => "selection.changed",
|
||||
Event::DocumentOpened => "document.opened",
|
||||
Event::DocumentSaved => "document.saved",
|
||||
Event::LayerChanged => "layer.changed",
|
||||
}
|
||||
}
|
||||
|
||||
/// The event named `name`.
|
||||
pub fn parse(name: &str) -> Option<Event> {
|
||||
Event::ALL.into_iter().find(|e| e.name() == name)
|
||||
}
|
||||
|
||||
/// Whether the event is still delivered when its document has closed before the delivery:
|
||||
/// an open or a save is, a selection or layer change is not.
|
||||
pub fn outlives_document(self) -> bool {
|
||||
matches!(self, Event::DocumentOpened | Event::DocumentSaved)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_round_trip() {
|
||||
for e in Event::ALL {
|
||||
assert_eq!(Event::parse(e.name()), Some(e));
|
||||
}
|
||||
assert_eq!(Event::parse("selection.change"), None);
|
||||
assert_eq!(Event::parse(""), None);
|
||||
}
|
||||
|
||||
/// A `selection.changed` event that lists the most ids, each of the largest value, fits in the
|
||||
/// largest event a handler is given.
|
||||
#[test]
|
||||
fn the_largest_selection_event_fits() {
|
||||
let ids = vec![u64::MAX; MAX_EVENT_IDS];
|
||||
let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true});
|
||||
let len = serde_json::to_vec(&event).unwrap().len();
|
||||
assert!(len <= MAX_EVENT_BYTES, "{len} bytes");
|
||||
}
|
||||
}
|
||||
@@ -460,6 +460,8 @@ mod tests {
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}");
|
||||
let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}");
|
||||
let e = refused(bundle("test.js.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{e:?}");
|
||||
let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}");
|
||||
let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"})));
|
||||
|
||||
@@ -34,8 +34,9 @@
|
||||
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
|
||||
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
|
||||
//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and
|
||||
//! parameter text may come in other languages too ([`translations`]). The web build checks modules and
|
||||
//! runs filters in a worker of its own ([`worker`]).
|
||||
//! parameter text may come in other languages too ([`translations`]). Any kind may also react to the
|
||||
//! [`events`] its manifest names, through `vc_event`, without changing the document. The web
|
||||
//! build checks modules and runs filters in a worker of its own ([`worker`]).
|
||||
//!
|
||||
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
|
||||
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
|
||||
@@ -45,6 +46,7 @@
|
||||
pub mod deferred;
|
||||
pub mod dialog;
|
||||
pub mod effect;
|
||||
pub mod events;
|
||||
pub mod export;
|
||||
pub mod generate;
|
||||
pub mod host;
|
||||
@@ -66,6 +68,7 @@ pub mod wat;
|
||||
pub mod worker;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use events::Event;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{
|
||||
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, OutputKind, Param, ParamSpec,
|
||||
|
||||
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::events::{EVENTS_API, Event};
|
||||
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::translations::Translations;
|
||||
use crate::{Error, Result};
|
||||
@@ -723,6 +724,11 @@ pub struct Manifest {
|
||||
/// lists any ([`Manifest::validate`]).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub command_allowlist: Vec<String>,
|
||||
/// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose
|
||||
/// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left
|
||||
/// out or empty, it reacts to none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")]
|
||||
pub events: Vec<String>,
|
||||
/// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter.
|
||||
#[serde(default, skip_serializing_if = "Runtime::is_wasm")]
|
||||
pub runtime: Runtime,
|
||||
@@ -783,6 +789,7 @@ impl Manifest {
|
||||
appearance_output: false,
|
||||
commands: Vec::new(),
|
||||
command_allowlist: Vec::new(),
|
||||
events: Vec::new(),
|
||||
runtime: Runtime::Wasm,
|
||||
translations: Translations::default(),
|
||||
}
|
||||
@@ -897,12 +904,47 @@ impl Manifest {
|
||||
self.validate_params()?;
|
||||
self.validate_commands()?;
|
||||
self.validate_allowlist()?;
|
||||
self.validate_events()?;
|
||||
self.validate_translations()?;
|
||||
self.validate_runtime()
|
||||
}
|
||||
|
||||
/// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the
|
||||
/// permission `events`, which needs a list.
|
||||
fn validate_events(&self) -> Result<()> {
|
||||
for (i, name) in self.events.iter().enumerate() {
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
if Event::parse(name).is_none() {
|
||||
return Err(Error::Manifest(format!(
|
||||
"`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed"
|
||||
)));
|
||||
}
|
||||
if self.events.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(format!("`events` lists `{shown}` twice")));
|
||||
}
|
||||
}
|
||||
let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name()));
|
||||
if self.events.is_empty() == listed {
|
||||
return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into()));
|
||||
}
|
||||
if listed && self.api < EVENTS_API {
|
||||
return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The events it reacts to (`events`).
|
||||
pub fn event_kinds(&self) -> Vec<Event> {
|
||||
self.events.iter().filter_map(|n| Event::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// Does it react to `event`?
|
||||
pub fn reacts_to(&self, event: Event) -> bool {
|
||||
self.events.iter().any(|n| n == event.name())
|
||||
}
|
||||
|
||||
/// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions
|
||||
/// it lists only `progress`: its realm has no settings, cache or command calls.
|
||||
/// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`.
|
||||
fn validate_runtime(&self) -> Result<()> {
|
||||
if self.runtime == Runtime::Wasm {
|
||||
return Ok(());
|
||||
@@ -912,7 +954,7 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\"")));
|
||||
}
|
||||
let listed = self.permissions.as_deref().unwrap_or_default();
|
||||
for p in [Permission::Settings, Permission::Cache, Permission::Commands] {
|
||||
for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] {
|
||||
if listed.iter().any(|n| n == p.name()) {
|
||||
let name = p.name();
|
||||
return Err(Error::Manifest(format!(
|
||||
@@ -1326,6 +1368,17 @@ fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `events`: a list of names (`null`: none). Anything else is an error that names the key, as
|
||||
/// [`Manifest::validate_events`] names a wrong entry.
|
||||
fn event_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed");
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `context`: a list of names (`null`: none). Anything else is the error
|
||||
/// [`Manifest::validate_context`] gives a wrong entry.
|
||||
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
@@ -2359,6 +2412,52 @@ mod tests {
|
||||
assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all");
|
||||
}
|
||||
|
||||
/// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an
|
||||
/// unknown or repeated name, a list without the permission or the permission without a list,
|
||||
/// and a list at `api` 1 are refused, and the error names the fault.
|
||||
#[test]
|
||||
fn events_are_listed_with_their_permission_at_api_2() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]);
|
||||
assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved));
|
||||
assert_eq!(m.permissions(), [Permission::Events]);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"]));
|
||||
let effect =
|
||||
br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#;
|
||||
assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]);
|
||||
let importer =
|
||||
br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#;
|
||||
assert!(Manifest::parse(importer).is_ok());
|
||||
let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap();
|
||||
assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none());
|
||||
for (bad, says) in [
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#,
|
||||
"unknown event `selection.change`",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#,
|
||||
"lists `layer.changed` twice",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#,
|
||||
"needs the permission `events`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_manifests() {
|
||||
for bad in [
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of
|
||||
//! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`,
|
||||
//! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a
|
||||
//! manifest lists them.
|
||||
//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its
|
||||
//! manifest names ([`crate::events`]).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -96,10 +97,14 @@ pub enum Permission {
|
||||
/// ([`crate::host::IMPORTS`]): a filter only.
|
||||
#[serde(rename = "commands")]
|
||||
Commands,
|
||||
/// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with
|
||||
/// `vc_event`: any kind.
|
||||
#[serde(rename = "events")]
|
||||
Events,
|
||||
}
|
||||
|
||||
/// Every permission this host grants, in the order prompts list them.
|
||||
pub const ALL: [Permission; 10] = [
|
||||
pub const ALL: [Permission; 11] = [
|
||||
Permission::DocRead,
|
||||
Permission::DocWrite,
|
||||
Permission::State,
|
||||
@@ -110,6 +115,7 @@ pub const ALL: [Permission; 10] = [
|
||||
Permission::Settings,
|
||||
Permission::Cache,
|
||||
Permission::Commands,
|
||||
Permission::Events,
|
||||
];
|
||||
|
||||
/// The permissions of the host imports, which any kind may list and none implies; each needs plug-in
|
||||
@@ -131,6 +137,7 @@ impl Permission {
|
||||
Permission::Settings => "settings",
|
||||
Permission::Cache => "cache",
|
||||
Permission::Commands => "commands",
|
||||
Permission::Events => "events",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,13 +159,14 @@ impl Permission {
|
||||
Permission::Settings => "Keep settings of its own",
|
||||
Permission::Cache => "Keep a cache of its own, which you can clear",
|
||||
Permission::Commands => "Run these commands",
|
||||
Permission::Events => "Run on its own when the selection, a document or a layer changes",
|
||||
}
|
||||
}
|
||||
|
||||
/// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`]
|
||||
/// gives it, or one of the host imports' ([`HOST`]), which any kind may list.
|
||||
/// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list.
|
||||
pub fn applies(self, kind: Kind, commands: bool) -> bool {
|
||||
HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self)
|
||||
self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self)
|
||||
}
|
||||
|
||||
/// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list
|
||||
@@ -301,7 +309,7 @@ impl Grant {
|
||||
|
||||
/// A [`Grant`] that [`crate::registry::grant`] records. The engine makes one where it records what
|
||||
/// a person approved and where it loads the grants kept in its plug-in folder; tests that set up a
|
||||
/// grant use the same constructors. `tests/grant_sites.rs` fails when other shipped code makes one.
|
||||
/// grant use the same constructors. `cargo xtask grant-sites` fails when other shipped code makes one.
|
||||
/// Native code linked into the app can still call these constructors, so the token does not
|
||||
/// protect against such code.
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -333,6 +333,9 @@ fn wasm_err(e: wasmi::Error) -> Error {
|
||||
/// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error).
|
||||
type RunArgs = (i32, i32, i32, i32);
|
||||
|
||||
/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed).
|
||||
type EventArgs = (i32, i32);
|
||||
|
||||
/// The manifest in the module's [`MANIFEST_SECTION`] custom section, or `None` when it has none.
|
||||
/// A module with more than one is refused, and so is a section longer than [`MAX_MANIFEST_BYTES`],
|
||||
/// which [`Manifest::parse`] checks before it decodes the bytes. The manifest in the section must
|
||||
@@ -395,8 +398,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose
|
||||
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types.
|
||||
fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
|
||||
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and
|
||||
/// `vc_event` with its type when `events` is set (the manifest lists events).
|
||||
fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> Result<()> {
|
||||
use ValType::{I32, I64};
|
||||
let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone());
|
||||
let Some(ExternType::Memory(memory)) = export("memory") else {
|
||||
@@ -414,6 +418,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
|
||||
return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}")));
|
||||
}
|
||||
}
|
||||
if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) {
|
||||
return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -449,6 +456,9 @@ impl Plugin {
|
||||
// The other exports must exist with the right types.
|
||||
live.func::<i32, i32>("vc_alloc")?;
|
||||
live.func::<RunArgs, i64>("vc_run")?;
|
||||
if !p.manifest.events.is_empty() {
|
||||
live.func::<EventArgs, i32>("vc_event")?;
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
@@ -475,6 +485,10 @@ impl Plugin {
|
||||
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
|
||||
}
|
||||
p.read(manifest.to_vec(), &imports)?;
|
||||
if !p.manifest.events.is_empty() {
|
||||
let Code::Wasm { module, .. } = &p.code else { return Ok(p) };
|
||||
exports_func(module, "vc_event", &[ValType::I32; 2], &[ValType::I32])?;
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
@@ -498,7 +512,7 @@ impl Plugin {
|
||||
return Ok(false);
|
||||
};
|
||||
self.take(manifest, text, imports)?;
|
||||
check_exports(&module, self.limits.max_memory_bytes)?;
|
||||
check_exports(&module, self.limits.max_memory_bytes, !self.manifest.events.is_empty())?;
|
||||
check_tables(bytes)?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -646,6 +660,12 @@ impl Plugin {
|
||||
/// A new instance for `run`, with the host imports of the permissions `granted` linked. When the
|
||||
/// module's start function fails, what it reported through the host imports goes to `report`.
|
||||
fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result<Live> {
|
||||
self.instantiate_with(run, granted, report, self.limits.fuel_base)
|
||||
}
|
||||
|
||||
/// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions;
|
||||
/// the instance's store holds what it left.
|
||||
fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result<Live> {
|
||||
let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) };
|
||||
let limits = StoreLimitsBuilder::new()
|
||||
.memory_size(self.limits.max_memory_bytes)
|
||||
@@ -658,7 +678,7 @@ impl Plugin {
|
||||
store.limiter(|h| &mut h.limits);
|
||||
// The start function (if any) runs on one slice of fuel: it runs before `call` can check
|
||||
// the deadline or a cancel between slices, so a heavy budget would let it run for minutes.
|
||||
store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?;
|
||||
store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?;
|
||||
let linker = host::linker(engine, granted);
|
||||
let instance = match linker.instantiate_and_start(&mut store, module) {
|
||||
Ok(instance) => instance,
|
||||
@@ -703,6 +723,37 @@ impl Plugin {
|
||||
slice(live, left, start)
|
||||
}
|
||||
|
||||
/// Calls `f` on at most `budget` instructions, which holds what the call left unused when it
|
||||
/// returns `Ok`, for the next call to share. With `bridge`, each command call `vc_call` asks
|
||||
/// for is made with it while the call waits ([`Plugin::answer`]); without it one fails the call.
|
||||
fn call_budget<P: WasmParams, R: WasmResults>(
|
||||
live: &mut Live,
|
||||
f: &TypedFunc<P, R>,
|
||||
params: P,
|
||||
budget: &mut u64,
|
||||
deadline: &Deadline,
|
||||
mut bridge: Option<&mut Bridge<'_>>,
|
||||
) -> Result<R> {
|
||||
let mut call = Self::first_slice(live, budget, |store| f.call_resumable(store, params))?;
|
||||
loop {
|
||||
match Self::drive(live, budget, deadline, call)? {
|
||||
Driven::Finished(r) => {
|
||||
*budget = budget.saturating_add(live.store.get_fuel().map_err(wasm_err)?);
|
||||
return Ok(r);
|
||||
}
|
||||
Driven::Call(command, args, paused) => {
|
||||
let Some(bridge) = bridge.as_deref_mut() else {
|
||||
return Err(Error::Trap("unexpected host trap".into()));
|
||||
};
|
||||
// A panic making the call fails the handler, as one in the runtime does.
|
||||
let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| bridge(&command, &args)))
|
||||
.map_err(|_| Error::Trap("the runtime panicked".into()))?;
|
||||
call = Self::answer(live, budget, deadline, &command, answer, paused)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Goes on with `call` slice by slice ([`Plugin::call`]) until it finishes or pauses for a
|
||||
/// command call that `vc_call` asked for ([`host::Run::pending`]). Each command call costs
|
||||
/// [`host::CALL_FUEL`] instructions and one for every 64 bytes of its arguments, and the deadline
|
||||
@@ -937,4 +988,75 @@ impl Plugin {
|
||||
}
|
||||
live.read_packed(packed, "the output", limits.max_output_bytes)
|
||||
}
|
||||
|
||||
/// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and
|
||||
/// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every
|
||||
/// other limit as it is.
|
||||
pub fn event_limits(&self) -> Limits {
|
||||
Limits {
|
||||
fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL),
|
||||
wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS),
|
||||
..self.limits.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `vc_event` with `event` (the event JSON) in a fresh instance under
|
||||
/// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host
|
||||
/// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with
|
||||
/// it; a failed call fails the handler. A module that doesn't react to events, an event past
|
||||
/// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing.
|
||||
pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) {
|
||||
let mut report = Report::default();
|
||||
if let Err(e) = crate::safe_mode::check() {
|
||||
return (Err(e), report);
|
||||
}
|
||||
if self.manifest.events.is_empty() {
|
||||
return (Err(Error::Abi("the module reacts to no events".into())), report);
|
||||
}
|
||||
if event.len() > crate::events::MAX_EVENT_BYTES {
|
||||
let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES);
|
||||
return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report);
|
||||
}
|
||||
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge)));
|
||||
(run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report)
|
||||
}
|
||||
|
||||
fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> {
|
||||
let limits = self.event_limits();
|
||||
let deadline = Deadline::new(limits.wall_time_ms);
|
||||
let m = &self.manifest;
|
||||
let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id));
|
||||
let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?;
|
||||
// The start function, `vc_alloc` and `vc_event` share the one budget.
|
||||
let mut budget = live.store.get_fuel().map_err(wasm_err)?;
|
||||
if bridge.is_some() {
|
||||
live.store.data_mut().run.allow_calls(m.command_allowlist.clone());
|
||||
}
|
||||
let out = (|| {
|
||||
let alloc: TypedFunc<i32, i32> = live.func("vc_alloc")?;
|
||||
let handler: TypedFunc<EventArgs, i32> = live.func("vc_event")?;
|
||||
// The start function may have used the time: neither call runs past it.
|
||||
deadline.check()?;
|
||||
let ptr = Self::call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize;
|
||||
if ptr == 0 {
|
||||
return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into()));
|
||||
}
|
||||
let outside = || Error::Abi("vc_alloc returned a block outside memory".into());
|
||||
let end = ptr.checked_add(event.len()).ok_or_else(outside)?;
|
||||
live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event);
|
||||
deadline.check()?;
|
||||
let code = Self::call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?;
|
||||
deadline.check()?;
|
||||
if code != 0 {
|
||||
return Err(Error::Failed(format!("vc_event returned {code}")));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let state = &mut live.store.data_mut().run;
|
||||
*report = std::mem::take(&mut state.report);
|
||||
match (state.call_failure.take(), out) {
|
||||
(Some(e), _) => Err(e),
|
||||
(None, out) => out,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,18 @@ pub fn with_field(module: &str, field: &str) -> Option<String> {
|
||||
/// A `vc_run` body returning the input unchanged.
|
||||
pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))";
|
||||
|
||||
/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the
|
||||
/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters
|
||||
/// `$ep $el`, result i32) and a `vc_run` that returns its input.
|
||||
pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String {
|
||||
let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#);
|
||||
module(manifest, ECHO, &extra, 1)
|
||||
}
|
||||
|
||||
/// A `vc_event` body that writes the event it is given as an information log line (with
|
||||
/// [`HOST_IMPORTS`]) and returns 0.
|
||||
pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)";
|
||||
|
||||
/// A plug-in that always returns `output` (whatever it is given).
|
||||
pub fn returning(manifest: &str, output: &str) -> String {
|
||||
then_returning(manifest, "", output)
|
||||
|
||||
@@ -1247,6 +1247,96 @@ fn a_plugin_reaches_only_its_own_storage() {
|
||||
registry::set_storage("test.storage.theirs", None);
|
||||
}
|
||||
|
||||
/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list).
|
||||
fn reacting_manifest(id: &str, events: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#)
|
||||
}
|
||||
|
||||
/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none
|
||||
/// may leave it out.
|
||||
#[test]
|
||||
fn an_event_plugin_exports_vc_event() {
|
||||
let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#);
|
||||
let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err();
|
||||
assert!(e.to_string().contains("vc_event"), "{e}");
|
||||
let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS);
|
||||
let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err();
|
||||
assert!(e.to_string().contains("vc_event"), "{e}");
|
||||
assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok());
|
||||
assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event");
|
||||
// A module whose manifest is in its custom section is checked without being instantiated.
|
||||
let section =
|
||||
r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#;
|
||||
let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err();
|
||||
assert!(e.to_string().contains("vc_event"), "{e}");
|
||||
let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#;
|
||||
let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err();
|
||||
assert!(e.to_string().contains("vc_event"), "{e}");
|
||||
let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#;
|
||||
assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok());
|
||||
}
|
||||
|
||||
/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a
|
||||
/// handler past its instruction budget fail it. A module without events runs no handler.
|
||||
#[test]
|
||||
fn vc_event_is_given_the_event_and_its_code_is_checked() {
|
||||
let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#);
|
||||
let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap();
|
||||
let event = br#"{"type":"layer.changed","document":7}"#;
|
||||
let (r, report) = p.run_event(event, None);
|
||||
r.unwrap();
|
||||
assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>(), [std::str::from_utf8(event).unwrap()]);
|
||||
for (handler, says) in [
|
||||
("(i32.const 3)", "vc_event returned 3"),
|
||||
("unreachable", "trapped"),
|
||||
// The instruction budget, or the time budget on a loaded machine.
|
||||
("(loop $l (br $l)) (i32.const 0)", "budget"),
|
||||
] {
|
||||
let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap();
|
||||
let e = p.run_event(event, None).0.unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{handler}: {e}");
|
||||
}
|
||||
let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err();
|
||||
assert!(e.to_string().contains("event size"), "{e}");
|
||||
let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap();
|
||||
assert!(plain.run_event(event, None).0.is_err());
|
||||
let limits = p.event_limits();
|
||||
assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS));
|
||||
}
|
||||
|
||||
/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the
|
||||
/// handler alone fits it no longer when the start function has done as much first. The budget is
|
||||
/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that
|
||||
/// fails is stopped by its instruction budget.
|
||||
#[test]
|
||||
fn a_handler_and_its_start_function_share_the_event_budget() {
|
||||
let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#);
|
||||
let burn = r#"(func $burn (param $k i32) (block $b (loop $l
|
||||
(br_if $b (i32.eqz (local.get $k)))
|
||||
(local.set $k (i32.sub (local.get $k) (i32.const 1)))
|
||||
(br $l))))"#;
|
||||
let plugin = |start: u32, handler: u32| {
|
||||
let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS);
|
||||
let body = format!("(call $burn (i32.const {handler})) (i32.const 0)");
|
||||
Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap()
|
||||
};
|
||||
let event = br#"{"type":"layer.changed","document":1}"#;
|
||||
// The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out
|
||||
// of instructions.
|
||||
let mut k = 1u32 << 8;
|
||||
let e = loop {
|
||||
match plugin(0, k * 2).run_event(event, None).0 {
|
||||
Ok(()) => k *= 2,
|
||||
Err(e) => break e.to_string(),
|
||||
}
|
||||
assert!(k < 1 << 30, "a handler that never runs out of its budget");
|
||||
};
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert!(plugin(0, k).run_event(event, None).0.is_ok());
|
||||
let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
}
|
||||
|
||||
/// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped
|
||||
/// and reported.
|
||||
#[test]
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
//! The shipped code that records a plug-in grant: only the engine's install approval and its load
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`,
|
||||
//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until
|
||||
//! it is added to the list. It checks the source, not what native code can do at run time.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `(text, file, how many times)` for every place shipped code may name it.
|
||||
const EXPECTED: &[(&str, &str, usize)] = &[
|
||||
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 1),
|
||||
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("registry::install_for_load", "crates/engine/src/store.rs", 2),
|
||||
];
|
||||
|
||||
/// The names the audit counts.
|
||||
const NAMES: [&str; 5] = [
|
||||
"GrantToken::after_engine_approval",
|
||||
"GrantToken::from_engine_grants_file",
|
||||
"registry::grant",
|
||||
"registry::install_checked",
|
||||
"registry::install_for_load",
|
||||
];
|
||||
|
||||
/// Every `.rs` file under `dir`, without test files and folders.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if path.is_dir() {
|
||||
if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") {
|
||||
sources(&path, out);
|
||||
}
|
||||
} else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {`
|
||||
/// on.
|
||||
fn shipped(text: &str) -> Vec<&str> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let opens_test_module = |i: usize| {
|
||||
lines[i] == "#[cfg(test)]"
|
||||
&& lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{'))
|
||||
};
|
||||
let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len());
|
||||
lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect()
|
||||
}
|
||||
|
||||
/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`).
|
||||
fn count(line: &str, name: &str) -> usize {
|
||||
line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grant_token_call_sites_are_limited() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let mut files = Vec::new();
|
||||
for top in ["crates", "apps", "xtask"] {
|
||||
sources(&root.join(top), &mut files);
|
||||
}
|
||||
assert!(files.len() > 100, "found only {} source files under {}", files.len(), root.display());
|
||||
let mut found: BTreeMap<(&str, String), usize> = BTreeMap::new();
|
||||
for file in &files {
|
||||
let text = std::fs::read_to_string(file).unwrap();
|
||||
let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
for line in shipped(&text) {
|
||||
for name in NAMES {
|
||||
let n = count(line, name);
|
||||
if n > 0 {
|
||||
*found.entry((name, rel.clone())).or_default() += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect();
|
||||
assert_eq!(found, expected, "shipped code that makes a grant token or records a grant");
|
||||
}
|
||||
|
||||
/// The audit's own filters: a test module and comments are left out, a longer name isn't counted.
|
||||
#[test]
|
||||
fn the_audit_skips_test_code_and_comments() {
|
||||
let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n";
|
||||
let lines = shipped(text);
|
||||
assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::<usize>(), 1, "{lines:?}");
|
||||
}
|
||||
@@ -103,7 +103,8 @@ fn from_workspace(dir: PathBuf) -> PathBuf {
|
||||
return dir;
|
||||
}
|
||||
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
crate_dir.join("../..").join(dir)
|
||||
// The workspace root is two levels above `crates/text`.
|
||||
crate_dir.ancestors().nth(2).unwrap_or(&crate_dir).join(dir)
|
||||
}
|
||||
|
||||
/// The one craft-fonts face web builds embed (family, style).
|
||||
|
||||
@@ -61,6 +61,12 @@ fn now_secs() -> f64 {
|
||||
monotonic_ms() / 1000.0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The notices [`VectorcraftApp::deliver_plugin_events`] took on this thread.
|
||||
static TAKEN_EVENT_NOTICES: std::cell::RefCell<Vec<vectorcraft_engine::plugin_events::Notice>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
impl VectorcraftApp {
|
||||
/// The app around `session`, reaching the platform through `services` (the clipboard, files
|
||||
/// and the like). It registers the app's icon sets, starts cataloguing the installed fonts at
|
||||
@@ -79,6 +85,9 @@ impl VectorcraftApp {
|
||||
session.place_cursor_requests = true;
|
||||
// A script runs a slice per frame, so the window keeps drawing and Stop can be pressed.
|
||||
session.script_frames = true;
|
||||
// Plug-in events are delivered by the frame: after the work that finished in the
|
||||
// background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]).
|
||||
session.plugin_event_frames = true;
|
||||
let views = session.documents().iter().map(View::of).collect();
|
||||
let view_uids = session.documents().iter().map(|d| d.uid).collect();
|
||||
let known = session.documents().iter().map(|d| d.uid).collect();
|
||||
@@ -194,6 +203,7 @@ impl VectorcraftApp {
|
||||
titlebar_inset: 0.0,
|
||||
last_effect: None,
|
||||
last_pathfinder: None,
|
||||
queued_script_printers: None,
|
||||
last_filters: Default::default(),
|
||||
character_focus: None,
|
||||
run_count: 0,
|
||||
@@ -361,10 +371,11 @@ impl VectorcraftApp {
|
||||
/// Applies the work that finished off the UI thread. It stays pending while a script runs, since
|
||||
/// every change to the documents ends in a busy error until the script ends. Plug-in worker runs
|
||||
/// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]).
|
||||
pub(crate) fn poll_finished_work(&mut self) {
|
||||
/// Returns whether plug-in event delivery needs a repaint.
|
||||
pub(crate) fn poll_finished_work(&mut self) -> bool {
|
||||
if self.session.script_running() {
|
||||
plugin_runs::poll(self);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
background::poll(self);
|
||||
opening::poll(self);
|
||||
@@ -372,6 +383,46 @@ impl VectorcraftApp {
|
||||
trace_runs::poll(self);
|
||||
placing::poll(self);
|
||||
retype_runs::poll(self);
|
||||
// The handlers' time counts toward the frame-time sample, as the delivery after the UI
|
||||
// pass does.
|
||||
let t0 = monotonic_ms();
|
||||
let pending = self.deliver_plugin_events();
|
||||
self.perf.early_events_ms += monotonic_ms() - t0;
|
||||
pending
|
||||
}
|
||||
|
||||
/// The plug-in event notices this thread's apps took, for tests that check a handler ran in a
|
||||
/// pass ([`Self::deliver_plugin_events`] takes them from the session).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn take_event_notices_taken() -> Vec<vectorcraft_engine::plugin_events::Notice> {
|
||||
TAKEN_EVENT_NOTICES.with(|taken| std::mem::take(&mut *taken.borrow_mut()))
|
||||
}
|
||||
|
||||
/// Hands the plug-ins that react to events the changes of this frame
|
||||
/// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler
|
||||
/// wrote, or the last handler failure, shows in the status bar after the plug-in's name.
|
||||
/// Returns whether the status bar changed or runnable handlers remain queued.
|
||||
fn deliver_plugin_events(&mut self) -> bool {
|
||||
let pending = self.session.deliver_plugin_events();
|
||||
let notices = self.session.take_plugin_event_notices();
|
||||
#[cfg(test)]
|
||||
TAKEN_EVENT_NOTICES.with(|taken| taken.borrow_mut().extend(notices.iter().cloned()));
|
||||
let shown = notices.into_iter().rev().find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn));
|
||||
let Some(mut n) = shown else { return pending };
|
||||
let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
|
||||
// The status is kept in English and translated when the status bar shows it, with the
|
||||
// plug-in's name kept as it is; a line the handler wrote is kept whole.
|
||||
let status = format!("{name}: {}", n.text);
|
||||
self.status(status.clone());
|
||||
if n.failure.is_some() {
|
||||
n.name = name;
|
||||
self.ui.status_plugin_event = Some((status, n));
|
||||
self.ui.status_kept = None;
|
||||
} else {
|
||||
self.ui.status_plugin_event = None;
|
||||
self.ui.status_kept = Some((String::new(), status, String::new()));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The language the UI is drawn in: the Preferences window's choice while it is open (so a
|
||||
@@ -466,6 +517,10 @@ impl VectorcraftApp {
|
||||
/// [`Self::tick`]'s work.
|
||||
fn tick_frame(&mut self, ctx: &egui::Context) {
|
||||
self.ticked_pass = Some(ctx.cumulative_pass_nr());
|
||||
if ctx.current_pass_index() == 0 {
|
||||
self.perf.early_events_ms = 0.0;
|
||||
self.session.begin_plugin_event_frame();
|
||||
}
|
||||
let lang = self.ui_language();
|
||||
i18n::set_current(lang);
|
||||
// The engine gives new type the Japanese defaults while the UI is in Japanese.
|
||||
@@ -514,16 +569,22 @@ impl VectorcraftApp {
|
||||
// them, even if the worker below finishes them during this same tick.
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending()));
|
||||
screen_color::tick(self, ctx);
|
||||
let script_was_running = self.session.script_running();
|
||||
// Once a frame: work that finishes during a frame's first pass is applied in the next frame, not in a second
|
||||
// pass of this one.
|
||||
if ctx.current_pass_index() == 0 {
|
||||
self.poll_finished_work();
|
||||
if ctx.current_pass_index() == 0 && self.poll_finished_work() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
crate::script_runs::poll(self);
|
||||
// Apply the work that waited for the script in the frame it ended in.
|
||||
if script_was_running && !self.session.script_running() && self.poll_finished_work() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
// A panel's, a dialog's or the text input's commit journaled in the frame before.
|
||||
crate::panels::actions::after_journaled_edit(self);
|
||||
crate::scripts_menu::poll(self, ctx);
|
||||
if self.session.script_running()
|
||||
&& !crate::script_runs::waiting_for_print(self)
|
||||
&& !self.session.script_waiting()
|
||||
&& self.session.script_dialog().is_none()
|
||||
&& self.session.script_picker().is_none()
|
||||
@@ -650,6 +711,9 @@ impl VectorcraftApp {
|
||||
/// input to the automation roots and turns a panic into an error message.
|
||||
pub fn ui(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if ctx.current_pass_index() == 0 && self.ticked_pass != Some(ctx.cumulative_pass_nr()) {
|
||||
self.perf.early_events_ms = 0.0;
|
||||
}
|
||||
self.adopt_context(&ctx);
|
||||
let confined = self.automation_scope(&ctx);
|
||||
if let Err(msg) = file_access::confine(confined.as_ref(), || {
|
||||
@@ -657,6 +721,19 @@ impl VectorcraftApp {
|
||||
self.handle_input(&ctx);
|
||||
self.ui_frame(ui);
|
||||
self.window_keys(&ctx);
|
||||
// What the canvas, a panel, a dialog or a window key changed in this pass reaches
|
||||
// the plug-ins that react to it now, since an idle app draws no further frame; a
|
||||
// line a handler wrote shows in the next one. The handlers' time counts toward the
|
||||
// frame-time sample of a pass egui presents.
|
||||
let t0 = monotonic_ms();
|
||||
if !self.session.script_running() && self.deliver_plugin_events() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if !ctx.will_discard() {
|
||||
self.perf.frame_ms += monotonic_ms() - t0;
|
||||
} else {
|
||||
self.perf.early_events_ms += monotonic_ms() - t0;
|
||||
}
|
||||
})
|
||||
}) {
|
||||
self.session.set_replaying(false);
|
||||
@@ -751,7 +828,7 @@ impl VectorcraftApp {
|
||||
// A pass egui will discard and rerun is not a presented frame: it must not become the
|
||||
// frame-time sample, and it must not issue a capture of what it drew.
|
||||
if !ctx.will_discard() {
|
||||
self.perf.frame_ms = monotonic_ms() - t0;
|
||||
self.perf.frame_ms = monotonic_ms() - t0 + std::mem::take(&mut self.perf.early_events_ms);
|
||||
self.issue_captures(&ctx);
|
||||
// A hidden window's pass shows nothing, so the step waits for a pass the user sees.
|
||||
if step_held && !self.viewport_hidden(&ctx) {
|
||||
|
||||
@@ -409,4 +409,6 @@ pub struct Perf {
|
||||
pub frame_ms: f64,
|
||||
pub render_ms: f64,
|
||||
pub fps: f64,
|
||||
/// Time plug-in event handlers took before the frame's UI pass, added to its `frame_ms`.
|
||||
pub early_events_ms: f64,
|
||||
}
|
||||
@@ -771,6 +771,20 @@ fn date_time_now() -> (String, u64) {
|
||||
/// it are translated.
|
||||
pub(crate) fn status_message(app: &VectorcraftApp) -> String {
|
||||
let status = app.ui.status.as_str();
|
||||
if let Some((original, notice)) = &app.ui.status_plugin_event
|
||||
&& original == status
|
||||
{
|
||||
use vectorcraft_engine::plugin_events::Failure;
|
||||
let text = match ¬ice.failure {
|
||||
Some(Failure::Handler { error }) => crate::i18n::fmt(&crate::i18n::msg(Failure::HANDLER), &[("event", notice.event), ("error", error)]),
|
||||
Some(Failure::EventsOff { count }) => {
|
||||
let template = if *count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER };
|
||||
crate::i18n::fmt(&crate::i18n::msg(template), &[("n", &count.to_string())])
|
||||
}
|
||||
None => notice.text.clone(),
|
||||
};
|
||||
return format!("{}: {text}", notice.name);
|
||||
}
|
||||
let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept);
|
||||
if let Some((before, kept, after)) = app.session.script_authored_failure()
|
||||
&& is(&before, kept, &after)
|
||||
|
||||
@@ -631,7 +631,7 @@ fn the_status_bar_stands_still_while_its_readouts_change() {
|
||||
] {
|
||||
let (x_value, y_value) = {
|
||||
let mut app = bar.app();
|
||||
app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps };
|
||||
app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps, ..Default::default() };
|
||||
app.hover_doc = Some(vectorcraft_geom::Point::new(x, y));
|
||||
(app.session.general_unit().readout(x), app.session.general_unit().readout(y))
|
||||
};
|
||||
|
||||
@@ -181,7 +181,7 @@ fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> {
|
||||
} else {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for p in papers {
|
||||
let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string());
|
||||
let id = own_media_choice(p, papers).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string());
|
||||
if out.iter().all(|(i, _)| *i != id) {
|
||||
out.push((id, p.label.clone()));
|
||||
}
|
||||
@@ -203,6 +203,13 @@ fn own_media_of(p: &Paper) -> Option<Media> {
|
||||
Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5))
|
||||
}
|
||||
|
||||
/// [`own_media_of`] `p`, unless another of `papers` with a different size matches the same size: both then stay
|
||||
/// the printer's own papers.
|
||||
fn own_media_choice(p: &Paper, papers: &[Paper]) -> Option<Media> {
|
||||
let own = own_media_of(p)?;
|
||||
(!papers.iter().any(|q| own_media_of(q) == Some(own) && (q.width, q.height) != (p.width, p.height))).then_some(own)
|
||||
}
|
||||
|
||||
/// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`.
|
||||
fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> {
|
||||
let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?;
|
||||
@@ -533,7 +540,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
if let Some(new) = printer_paper(fields, &open.papers.1)
|
||||
&& chosen.as_ref().is_none_or(|old| same_size(old, new))
|
||||
{
|
||||
let own = own_media_of(new)?;
|
||||
let own = own_media_choice(new, &open.papers.1)?;
|
||||
fields.set("media", own.id());
|
||||
return Some((own.id().to_string(), settings(fields)));
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@
|
||||
//! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder.
|
||||
//!
|
||||
//! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of
|
||||
//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other
|
||||
//! dialog is open and no text field or text being typed on the canvas has the keyboard. Its fields
|
||||
//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no question
|
||||
//! or popup is open and no text field or text being typed on the canvas has the keyboard. Its fields
|
||||
//! are `jobs` (each job's `document`, `printer` and `pages`, read from the jobs when it opens; no
|
||||
//! field sets them) and `answer`. Only the person at the keyboard prints them, with a click on its
|
||||
//! Print button or Space once Tab gave it the focus: the button takes no click for
|
||||
@@ -508,6 +508,11 @@ pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool {
|
||||
with_host(app, |host, _| host.is_open::<CloseQuestion>()).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the question before a script's print jobs are sent is open.
|
||||
pub(crate) fn asking_to_print(app: &VectorcraftApp) -> bool {
|
||||
with_host(app, |host, _| host.is_open::<ScriptPrint>()).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether a dialog is open or waits to open: a script's dialog opens only over nothing.
|
||||
pub(crate) fn busy(app: &VectorcraftApp) -> bool {
|
||||
app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false)
|
||||
@@ -991,10 +996,13 @@ fn choose(app: &mut VectorcraftApp) {
|
||||
pub(crate) const PRINT_ENABLE_DELAY_SECS: f64 = 1.0;
|
||||
|
||||
/// Opens the question before the jobs a script prepared for a printer are sent, once the run has
|
||||
/// ended, no other dialog is open and nothing is being typed: while a text field or text on the
|
||||
/// ended, no question or popup is open and nothing is being typed: while a text field or text on the
|
||||
/// canvas has the keyboard it waits, and a later poll opens it.
|
||||
pub(crate) fn ask_print(app: &mut VectorcraftApp) {
|
||||
if app.session.script_running() || !app.session.script_prints_waiting() || busy(app) {
|
||||
// Between two queued runs, the jobs the ended run prepared are asked about before the next starts.
|
||||
let between_runs = app.session.script_name().is_none();
|
||||
let blocked = app.asking_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false);
|
||||
if (app.session.script_running() && !between_runs) || !app.session.script_prints_waiting() || blocked {
|
||||
return;
|
||||
}
|
||||
let typing = app.ui_ctx.as_ref().is_some_and(egui::Context::text_edit_focused) || app.session.tool_wants_text();
|
||||
|
||||
@@ -751,6 +751,40 @@ impl PrintService for KeywordPrint {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_paper_sizes_that_share_a_name_are_all_listed() {
|
||||
// A driver form whose name looks like a size suffix is a size of its own.
|
||||
let out = "256\tCustom\t400\t600\r\n256\tCustom\t500\t1181\r\n256\tCustom\t400\t600\r\n256\tCustom 500x1181\t520\t720\r\n\
|
||||
256\tCustom (4 x 6 in)\t300\t300\r\n";
|
||||
let papers = crate::print::windows_papers(out);
|
||||
let labels: Vec<&str> = papers.iter().map(|p| p.label.as_str()).collect();
|
||||
// Both sizes named Custom are listed, with their sizes; the repeat of the first size is left out,
|
||||
// and a shown name another form already has gets a number.
|
||||
assert_eq!(labels, ["Custom (4 x 6 in) 2", "Custom (5 x 11.81 in)", "Custom 500x1181", "Custom (4 x 6 in)"]);
|
||||
let mut keys: Vec<&str> = papers.iter().map(|p| p.key.as_str()).collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
assert_eq!(keys.len(), 4, "{keys:?}");
|
||||
assert!((papers[1].width - 360.0).abs() < 1e-9 && (papers[1].height - 850.32).abs() < 1e-9);
|
||||
}
|
||||
|
||||
struct WindowsForms(&'static str);
|
||||
|
||||
impl PrintService for WindowsForms {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
vec![Printer::new("Forward").is_default(true), Printer::new("Reverse")]
|
||||
}
|
||||
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
MockPrint(Jobs::default()).print(job)
|
||||
}
|
||||
|
||||
fn papers(&mut self, printer: &str, _fresh: bool) -> Papers {
|
||||
let out = if printer == "Reverse" { self.0.lines().rev().collect::<Vec<_>>().join("\n") } else { self.0.to_string() };
|
||||
Papers::Ready(crate::print::windows_papers(&out))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_job_asks_the_queue_for_the_driver_paper_chosen() {
|
||||
let sent = SentPapers::default();
|
||||
@@ -822,6 +856,28 @@ impl PrintService for PendingKeywordPrint {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() {
|
||||
let out = "11\tA5\t582\t827\n11\tA5\t583\t827\n";
|
||||
let papers = crate::print::windows_papers(out);
|
||||
assert_eq!(papers.len(), 2);
|
||||
assert!(papers[0].width < papers[1].width);
|
||||
assert_eq!(papers[0].height, papers[1].height);
|
||||
let services = Services { print: Some(Box::new(WindowsForms(out))), ..Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
|
||||
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
for paper in &papers {
|
||||
let media = format!("printer:{}", paper.key);
|
||||
set(&mut app, "media", json!(media));
|
||||
pump(&mut app);
|
||||
let f = fields(&app);
|
||||
assert_eq!(f["media"], media);
|
||||
assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_print_keeps_the_paper_keyword_when_the_lookup_finishes() {
|
||||
let ready = Rc::new(Cell::new(false));
|
||||
@@ -857,6 +913,54 @@ fn an_explicit_paper_is_refused_when_the_print_path_cannot_apply_it() {
|
||||
assert!(sent.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_forms_stay_selected_when_queue_enumeration_order_changes() {
|
||||
for out in ["256\tCustom\t400\t600\n256\tCustom\t500\t700\n", "11\tA5\t582\t827\n11\tA5\t583\t827\n"] {
|
||||
let papers = crate::print::windows_papers(out);
|
||||
let reverse = crate::print::windows_papers(&out.lines().rev().collect::<Vec<_>>().join("\n"));
|
||||
for paper in &papers {
|
||||
let other = reverse.iter().find(|p| (p.width, p.height) == (paper.width, paper.height)).unwrap();
|
||||
assert_eq!(paper.key, other.key);
|
||||
}
|
||||
let services = Services { print: Some(Box::new(WindowsForms(out))), ..Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
|
||||
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
for paper in &papers {
|
||||
set(&mut app, "printer", json!("Forward"));
|
||||
pump(&mut app);
|
||||
let media = format!("printer:{}", paper.key);
|
||||
set(&mut app, "media", json!(media));
|
||||
pump(&mut app);
|
||||
set(&mut app, "printer", json!("Reverse"));
|
||||
pump(&mut app);
|
||||
pump(&mut app);
|
||||
let f = fields(&app);
|
||||
assert_eq!(f["media"], media);
|
||||
assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_windows_paper_labels_keep_dimensions_and_collision_numbers() {
|
||||
let name = "é".repeat(128);
|
||||
let suffix = " (4 x 6 in)";
|
||||
let prefix: String = name.chars().take(128 - suffix.chars().count()).collect();
|
||||
let collision = format!("{prefix}{suffix}");
|
||||
let out = format!("256\t{name}\t400\t600\n256\t{name}\t500\t700\n256\t{collision}\t300\t300\n");
|
||||
let papers = crate::print::windows_papers(&out);
|
||||
assert_eq!(papers.len(), 3);
|
||||
assert!(papers.iter().all(|p| p.label.chars().count() <= 128));
|
||||
assert!(papers[0].label.ends_with(" (4 x 6 in) 2"), "{:?}", papers[0]);
|
||||
assert!(papers[1].label.ends_with(" (5 x 7 in)"), "{:?}", papers[1]);
|
||||
assert_eq!(papers[2].label, collision);
|
||||
for (i, paper) in papers.iter().enumerate() {
|
||||
assert!(papers[i + 1..].iter().all(|p| p.label != paper.label));
|
||||
}
|
||||
}
|
||||
|
||||
/// A print queue that puts each page on the paper as it is, as `lp` does.
|
||||
struct UprightQueue(Jobs);
|
||||
|
||||
@@ -1243,3 +1347,29 @@ fn every_number_and_length_field_is_named() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_past_max_pages_neither_prints_nor_saves() {
|
||||
// Three artboards × 2 copies is 6 pages: a limit of 5 sends no job.
|
||||
let (mut app, jobs) = app();
|
||||
let r = app.run("file.print", json!({"settings": {"copies": 2}, "maxPages": 5})).unwrap();
|
||||
assert_eq!(r, json!({"pages": 6, "format": "pdf"}));
|
||||
assert!(jobs.borrow().is_empty(), "nothing is sent");
|
||||
// Within the limit the job prints as before.
|
||||
let r = app.run("file.print", json!({"settings": {"copies": 2}, "maxPages": 6})).unwrap();
|
||||
assert_eq!((r["pages"].clone(), r["printed"].clone()), (json!(6), json!(true)));
|
||||
assert_eq!(jobs.borrow().len(), 1);
|
||||
// Saved to a path, a job past the limit writes nothing.
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |p: &str, b: &[u8]| {
|
||||
w.borrow_mut().push((p.to_string(), b.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
let r = app.run("file.print", json!({"path": "/tmp/job.pdf", "settings": {"copies": 2}, "maxPages": 5})).unwrap();
|
||||
assert_eq!(r, json!({"pages": 6, "format": "pdf"}));
|
||||
assert!(written.borrow().is_empty(), "nothing is written");
|
||||
// A null limit is an error, not "no limit".
|
||||
assert!(app.run("file.print", json!({"maxPages": null})).is_err());
|
||||
assert_eq!(jobs.borrow().len(), 1, "nothing more is sent");
|
||||
}
|
||||
@@ -351,6 +351,11 @@ fn write_output(
|
||||
then: impl FnOnce(&mut VectorcraftApp, String, Value) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
let mut v = app.session.execute(id, ¶ms).map_err(|e| e.to_string())?;
|
||||
// `file.print` past its `maxPages` composes nothing: its `{pages, format}` is the answer and no
|
||||
// file is written.
|
||||
if params.get("maxPages").is_some() && v.get("dataBase64").is_none() {
|
||||
return Ok(v);
|
||||
}
|
||||
let bytes = take_output(&mut v)?;
|
||||
let write = move |app: &mut VectorcraftApp, path: String| {
|
||||
write_reporting(app, &path, &bytes)?;
|
||||
|
||||
@@ -294,6 +294,7 @@ fn permission_words(name: &str, commands: &[String], context: bool) -> String {
|
||||
Some(permissions::Permission::Progress) => tl!("Show its progress, see Cancel and write log lines"),
|
||||
Some(permissions::Permission::Settings) => tl!("Keep settings of its own"),
|
||||
Some(permissions::Permission::Cache) => tl!("Keep a cache of its own, which you can clear"),
|
||||
Some(permissions::Permission::Events) => tl!("Run on its own when the selection, a document or a layer changes"),
|
||||
None => return permissions::display_text(name, permissions::MAX_SHOWN_FIELD),
|
||||
};
|
||||
words.to_string()
|
||||
|
||||
@@ -164,6 +164,9 @@ pub struct VectorcraftApp {
|
||||
pub last_effect: Option<(String, serde_json::Value)>,
|
||||
/// Last successful destructive Pathfinder operation, repeated on the current selection.
|
||||
pub last_pathfinder: Option<String>,
|
||||
/// The printers listed when `script.startup.run` queued its runs: each queued run lists them
|
||||
/// as it starts, without asking the print service again.
|
||||
pub(crate) queued_script_printers: Option<vectorcraft_engine::script::printing::Printers>,
|
||||
/// The parameters each object filter plug-in last ran with (Object › Plug-ins › Apply Last Filter).
|
||||
pub last_filters: dialogs::plugin::LastFilters,
|
||||
/// The Character panel field that takes the keyboard focus when the panel next draws it
|
||||
|
||||
@@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
+71
-11
@@ -149,7 +149,9 @@ pub fn ppd_papers(ppd: &str) -> Vec<Paper> {
|
||||
}
|
||||
|
||||
/// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows'
|
||||
/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply.
|
||||
/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. A name
|
||||
/// listed again with another size stays in the list, keyed by its name and size, and every size of that name
|
||||
/// shows its size in inches after the name; one listed again with the same size is left out.
|
||||
pub fn windows_papers(out: &str) -> Vec<Paper> {
|
||||
let mut papers: Vec<Paper> = Vec::new();
|
||||
for line in out.lines() {
|
||||
@@ -158,9 +160,37 @@ pub fn windows_papers(out: &str) -> Vec<Paper> {
|
||||
let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>()) else { continue };
|
||||
if !key.is_empty() {
|
||||
let label = if label.is_empty() { key } else { label };
|
||||
push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 });
|
||||
let (width, height) = (w * 0.72, h * 0.72);
|
||||
let key = format!("{label}\t{w}x{h}");
|
||||
push_paper(&mut papers, Paper { key, label: label.into(), width, height });
|
||||
}
|
||||
}
|
||||
// Sizes that share a name show their size in inches after it.
|
||||
// A shown name that is still another paper's gets a number after it.
|
||||
let names: Vec<String> = papers.iter().map(|p| p.key.split('\t').next().unwrap_or_default().to_string()).collect();
|
||||
let inches = |pt: f64| (pt / 0.72).round() / 100.0;
|
||||
for i in 0..papers.len() {
|
||||
if names.iter().filter(|n| **n == names[i]).count() < 2 {
|
||||
papers[i].key = names[i].clone();
|
||||
continue;
|
||||
}
|
||||
let p = &papers[i];
|
||||
let suffix = format!(" ({} x {} {})", inches(p.width), inches(p.height), tl!("in"));
|
||||
let with_suffix = |suffix: &str| {
|
||||
let name: String = names[i].chars().take(MAX_PAPER_LABEL.saturating_sub(suffix.chars().count())).collect();
|
||||
format!("{name}{suffix}")
|
||||
};
|
||||
let shown = |label: &str| {
|
||||
papers.iter().enumerate().any(|(j, q)| j != i && q.label.chars().take(MAX_PAPER_LABEL).eq(label.chars().take(MAX_PAPER_LABEL)))
|
||||
};
|
||||
let mut label = with_suffix(&suffix);
|
||||
let mut n = 2;
|
||||
while shown(&label) && n < MAX_PAPERS + 2 {
|
||||
label = with_suffix(&format!("{suffix} {n}"));
|
||||
n += 1;
|
||||
}
|
||||
papers[i].label = label.chars().take(MAX_PAPER_LABEL).collect();
|
||||
}
|
||||
papers
|
||||
}
|
||||
|
||||
@@ -291,20 +321,29 @@ pub fn script_printers(app: &mut VectorcraftApp) -> Option<Printers> {
|
||||
Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer))
|
||||
}
|
||||
|
||||
/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to
|
||||
/// ([`script_printers`]), and only that run lists them.
|
||||
/// Runs the engine command `id`. A `script.run`, or a `script.startup.run` whose reason is not
|
||||
/// `launch`, started here lists the printers its first run may print to ([`script_printers`]), and
|
||||
/// only that run lists them; the runs `script.startup.run` queues list the same printers as they
|
||||
/// start ([`crate::script_runs::poll`]). The startup scripts run at launch list no printers, so the
|
||||
/// first window does not wait on the print service.
|
||||
pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result<Value, String> {
|
||||
if id == "script.run" {
|
||||
app.session.script_printers = script_printers(app);
|
||||
}
|
||||
let lists = id == "script.run" || (id == "script.startup.run" && params.get("reason").and_then(Value::as_str) != Some("launch"));
|
||||
let listed = if lists { script_printers(app) } else { None };
|
||||
app.session.script_printers = listed.clone();
|
||||
let r = app.session.execute(id, params).map_err(|e| e.to_string());
|
||||
app.session.script_printers = None;
|
||||
if id == "script.startup.run" && r.is_ok() {
|
||||
app.queued_script_printers = listed.filter(|_| app.session.script_running());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The error for a script's jobs when the print service does not let scripts print.
|
||||
const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent";
|
||||
|
||||
/// The start of the status line for a script's print jobs that the desktop's worker failed to send.
|
||||
const SCRIPT_PRINT_FAILED: &str = "Printing from a script failed";
|
||||
|
||||
/// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer
|
||||
/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or
|
||||
/// `{background: true}` while the desktop's worker sends them.
|
||||
@@ -323,8 +362,24 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPri
|
||||
None,
|
||||
move |_| send_each(&mut |job| submit(job), &jobs).map(|notes| json!({ "notes": notes })),
|
||||
move |app, result| {
|
||||
let notes = result?;
|
||||
app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default());
|
||||
let notes = result.inspect_err(|e| {
|
||||
let failure = format!("{SCRIPT_PRINT_FAILED}: {e}");
|
||||
let mut kept = app
|
||||
.ui
|
||||
.status_notes
|
||||
.take()
|
||||
.filter(|(status, notes)| *status == app.ui.status || notes.iter().any(|n| n.starts_with(SCRIPT_PRINT_FAILED)))
|
||||
.map(|(_, notes)| notes)
|
||||
.unwrap_or_default();
|
||||
kept.insert(0, failure.clone());
|
||||
io::show_with_notes(app, failure, kept);
|
||||
})?;
|
||||
let failed = app.ui.status_notes.clone().filter(|(_, notes)| notes.iter().any(|n| n.starts_with(SCRIPT_PRINT_FAILED)));
|
||||
if let Some((status, kept)) = failed {
|
||||
io::show_with_notes(app, status, kept);
|
||||
} else if !app.ui.status.starts_with(SCRIPT_PRINT_FAILED) {
|
||||
app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default());
|
||||
}
|
||||
Ok(json!({ "sent": count }))
|
||||
},
|
||||
);
|
||||
@@ -379,8 +434,9 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
return Err("The print service cannot apply a paper keyword for this job.".into());
|
||||
}
|
||||
let mut q = json!({});
|
||||
for k in ["preset", "settings", "format", "level", "flattenerPreset"] {
|
||||
if let Some(v) = p.get(k).filter(|v| !v.is_null()) {
|
||||
for k in ["preset", "settings", "format", "level", "flattenerPreset", "maxPages"] {
|
||||
// An explicit null `maxPages` goes on, so the engine rejects it instead of printing every page.
|
||||
if let Some(v) = p.get(k).filter(|v| !v.is_null() || k == "maxPages") {
|
||||
q[k] = v.clone();
|
||||
}
|
||||
}
|
||||
@@ -406,6 +462,10 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
q["forPrinter"] = json!(true);
|
||||
}
|
||||
let mut v = app.session.execute("file.print", &q).map_err(|e| e.to_string())?;
|
||||
// A job past `maxPages` is not composed: the reply is `{pages, format}` and nothing is sent.
|
||||
if q.get("maxPages").is_some() && v.get("dataBase64").is_none() {
|
||||
return Ok(v);
|
||||
}
|
||||
let data = v.as_object_mut().and_then(|o| o.remove("dataBase64"));
|
||||
let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?;
|
||||
let title = app.session.active().map(|d| d.title()).unwrap_or_default();
|
||||
|
||||
@@ -12,6 +12,11 @@ use crate::VectorcraftApp;
|
||||
use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice};
|
||||
use crate::dialogs::script_window;
|
||||
|
||||
/// Between two queued runs, the next one waits until the last run's print jobs are approved or canceled.
|
||||
pub(crate) fn waiting_for_print(app: &VectorcraftApp) -> bool {
|
||||
app.session.script_name().is_none() && (app.session.script_prints_waiting() || script_run::asking_to_print(app))
|
||||
}
|
||||
|
||||
/// Advances the running script by one slice, or asks what its growth needs asked.
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
startup_failures(app);
|
||||
@@ -27,10 +32,22 @@ pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.session.script_name().is_none() && (script_run::asking_to_close(app) || script_run::answer_close_between_runs(app)) {
|
||||
return;
|
||||
}
|
||||
if waiting_for_print(app) {
|
||||
return;
|
||||
}
|
||||
let name = app.session.script_name().unwrap_or_default();
|
||||
let startup = app.session.startup_script_running();
|
||||
let shared = share_views(app);
|
||||
// Between two queued runs, this pump starts the next one: it lists the printers listed when the
|
||||
// runs were queued.
|
||||
if app.session.script_name().is_none() {
|
||||
app.session.script_printers = app.queued_script_printers.clone();
|
||||
}
|
||||
let pumped = app.session.script_pump();
|
||||
app.session.script_printers = None;
|
||||
if !app.session.script_running() {
|
||||
app.queued_script_printers = None;
|
||||
}
|
||||
take_views(app, &shared);
|
||||
let Some(result) = pumped else {
|
||||
// A pump that started the next queued run shows the runs before it that could not start
|
||||
|
||||
@@ -747,6 +747,9 @@ pub struct UiState {
|
||||
/// as they are ([`crate::plugin_runs::show_notice`]). Not saved.
|
||||
#[serde(skip)]
|
||||
pub status_kept: Option<(String, String, String)>,
|
||||
/// The status and structured plug-in event failure translated when shown. Not saved.
|
||||
#[serde(skip)]
|
||||
pub status_plugin_event: Option<(String, vectorcraft_engine::plugin_events::Notice)>,
|
||||
pub palette_open: bool,
|
||||
pub palette_query: String,
|
||||
/// Set when the palette's shortcut, its command or the search icon opens or closes the palette,
|
||||
@@ -1530,6 +1533,7 @@ impl Default for UiState {
|
||||
status_notes: None,
|
||||
startup_notes: Vec::new(),
|
||||
status_kept: None,
|
||||
status_plugin_event: None,
|
||||
palette_open: false,
|
||||
palette_query: String::new(),
|
||||
palette_toggled: false,
|
||||
|
||||
@@ -1055,6 +1055,83 @@ fn opening_a_javascript_manifest_by_path_does_not_read_it_first() {
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// A selection made in the UI pass, after the frame's background work (as a click on the canvas or
|
||||
/// a panel makes it), reaches a plug-in that reacts to `selection.changed` before that pass ends:
|
||||
/// nothing is left for a later delivery.
|
||||
#[test]
|
||||
fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() {
|
||||
let mut app = app();
|
||||
app.session.allow_plugin_grants_from_requests();
|
||||
let id = "test.UI.ui_pass_events";
|
||||
let grant = json!(["progress", "events"]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Pass Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
|
||||
// The handler writes the event as an information line, which the status bar does not show, so
|
||||
// the plug-in leaves the status bar of other tests' sessions alone.
|
||||
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
|
||||
let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));
|
||||
let pass = |app: &mut VectorcraftApp, select: bool| {
|
||||
crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |app, ui| {
|
||||
app.tick(ui.ctx());
|
||||
if select {
|
||||
app.session.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
}
|
||||
app.ui(ui);
|
||||
});
|
||||
};
|
||||
// The window lays itself out in the first two passes.
|
||||
pass(&mut app, false);
|
||||
pass(&mut app, false);
|
||||
let _ = VectorcraftApp::take_event_notices_taken();
|
||||
pass(&mut app, true);
|
||||
let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count();
|
||||
assert_eq!(ran, 1, "the handler ran in the pass that made the change");
|
||||
app.session.deliver_plugin_events();
|
||||
let left: Vec<String> = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
|
||||
assert!(left.is_empty(), "delivered in the pass that made the change, not later: {left:?}");
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the selection was made");
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// Escape leaving isolation mode restores the selection from before entry after the window's
|
||||
/// panels and dialogs are drawn; the plug-in that reacts to `selection.changed` is still given the
|
||||
/// change in that pass.
|
||||
#[test]
|
||||
fn a_selection_a_window_key_changes_is_delivered_in_that_pass() {
|
||||
let mut app = app();
|
||||
app.session.allow_plugin_grants_from_requests();
|
||||
let id = "test.UI.window_key_events";
|
||||
let grant = json!(["progress", "events"]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Key Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
|
||||
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
|
||||
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let b = app.run("shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
let g = app.run("object.group", json!({})).unwrap()["id"].clone();
|
||||
app.run("object.isolate", json!({"id": g})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
super::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
super::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
app.session.deliver_plugin_events();
|
||||
let _ = app.session.take_plugin_event_notices();
|
||||
let _ = VectorcraftApp::take_event_notices_taken();
|
||||
let before = app.session.doc().unwrap().selection.objects.clone();
|
||||
let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
super::synthetic::key_frame(&mut app, &ctx, vec![esc]);
|
||||
assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection");
|
||||
let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count();
|
||||
assert_eq!(ran, 1, "the handler ran in the pass of the key");
|
||||
app.session.deliver_plugin_events();
|
||||
let left: Vec<String> = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
|
||||
assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}");
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// The approval names a plug-in whose manifest translates its name in the UI language and also
|
||||
/// gives the manifest's own name, both escaped; a language without a translation shows the
|
||||
/// manifest's name alone. What OK installs stays bound to the id and hash shown.
|
||||
|
||||
@@ -24,10 +24,16 @@ struct Spool {
|
||||
sent: Sent,
|
||||
names: Rc<RefCell<Vec<String>>>,
|
||||
scripts: bool,
|
||||
/// When set, jobs go to the desktop's worker, which fails to spool them with this message, or
|
||||
/// sends them when it is empty.
|
||||
spool_error: Option<&'static str>,
|
||||
/// How many times the printers were listed.
|
||||
lists: Rc<std::cell::Cell<usize>>,
|
||||
}
|
||||
|
||||
impl PrintService for Spool {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
self.lists.set(self.lists.get() + 1);
|
||||
self.names.borrow().iter().enumerate().map(|(i, name)| Printer::new(name.clone()).is_default(i == 0)).collect()
|
||||
}
|
||||
|
||||
@@ -39,6 +45,11 @@ impl PrintService for Spool {
|
||||
fn scripts_may_print(&self) -> bool {
|
||||
self.scripts
|
||||
}
|
||||
|
||||
fn shared_print(&self) -> Option<crate::print::SharedPrintFn> {
|
||||
let error = self.spool_error?;
|
||||
Some(std::sync::Arc::new(move |_| if error.is_empty() { Ok("Sent".to_string()) } else { Err(error.to_string()) }))
|
||||
}
|
||||
}
|
||||
|
||||
/// An app in a window, with a document, a print service listing Office (the default) and Lab, and
|
||||
@@ -46,7 +57,7 @@ impl PrintService for Spool {
|
||||
fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc<RefCell<Vec<String>>>) {
|
||||
let sent = Sent::default();
|
||||
let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()]));
|
||||
let spool = Spool { sent: sent.clone(), names: names.clone(), scripts };
|
||||
let spool = Spool { sent: sent.clone(), names: names.clone(), scripts, spool_error: None, lists: Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() }));
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
@@ -303,6 +314,111 @@ fn a_failed_run_or_a_printer_that_went_away_sends_nothing() {
|
||||
assert!(!asking(&app));
|
||||
}
|
||||
|
||||
/// An app whose script print jobs go to the desktop's worker, which fails with `error` (or sends
|
||||
/// them when it is empty).
|
||||
fn worker_print_app(error: &'static str) -> VectorcraftApp {
|
||||
let spool = Spool {
|
||||
sent: Sent::default(),
|
||||
names: Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()])),
|
||||
scripts: true,
|
||||
spool_error: Some(error),
|
||||
lists: Default::default(),
|
||||
};
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() }));
|
||||
app.services.write_shared = Some(std::sync::Arc::new(|_, _| Ok(())));
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
app
|
||||
}
|
||||
|
||||
/// A job the desktop's worker fails to spool is reported even when another line, such as the next
|
||||
/// queued script's, took the status bar while the worker ran.
|
||||
#[test]
|
||||
fn a_spool_failure_shows_after_a_later_status_line() {
|
||||
let mut app = worker_print_app("The printer Lab is offline");
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
assert!(asking(&app));
|
||||
click_after_delay(&mut app, 10.0, "Print");
|
||||
app.status("The next script ran");
|
||||
crate::background::wait_all(&mut app);
|
||||
assert!(app.ui.status.contains("The printer Lab is offline"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
/// A later batch the worker sent does not replace an earlier batch's failure in the status bar.
|
||||
#[test]
|
||||
fn a_sent_batch_does_not_hide_an_earlier_spool_failure() {
|
||||
let mut app = worker_print_app("");
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
assert!(asking(&app));
|
||||
click_after_delay(&mut app, 10.0, "Print");
|
||||
app.status("Printing from a script failed: The printer Office is offline");
|
||||
crate::background::wait_all(&mut app);
|
||||
assert!(app.ui.status.contains("The printer Office is offline"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
/// A spool failure stays visible after the next batch is approved and sent.
|
||||
#[test]
|
||||
fn a_batch_submitted_after_a_spool_failure_does_not_hide_it() {
|
||||
let mut app = worker_print_app("The printer Lab is offline");
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
click_after_delay(&mut app, 10.0, "Print");
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
assert!(asking(&app));
|
||||
crate::background::wait_all(&mut app);
|
||||
let failure = app.ui.status.clone();
|
||||
assert!(failure.contains("The printer Lab is offline"), "{failure}");
|
||||
assert!(asking(&app));
|
||||
app.services.print = worker_print_app("").services.print;
|
||||
click_after_delay(&mut app, 20.0, "Print");
|
||||
assert!(!asking(&app));
|
||||
assert!(!app.background.jobs.is_empty(), "the next batch was submitted");
|
||||
assert_eq!(app.ui.status, "Printing from a script…");
|
||||
crate::background::wait_all(&mut app);
|
||||
assert_eq!(app.ui.status, failure);
|
||||
assert_eq!(app.ui.status_notes, Some((failure.clone(), vec![failure])));
|
||||
}
|
||||
|
||||
/// A spool failure keeps the startup scripts' errors in the status bar's hover notes.
|
||||
#[test]
|
||||
fn a_spool_failure_does_not_hide_a_later_startup_script_failure() {
|
||||
let mut app = worker_print_app("The printer Lab is offline");
|
||||
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO));
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-print-startup-failure-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.jsx"), PRINT_TO_LAB).unwrap();
|
||||
std::fs::write(dir.join("b.jsx"), "throw new Error('The later startup script failed');").unwrap();
|
||||
app.session.attach_startup_scripts_dir(dir.clone());
|
||||
app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(1);", "name": "chosen" })).unwrap().unwrap();
|
||||
for _ in 0..10_000 {
|
||||
script_runs::poll(&mut app);
|
||||
if asking(&app) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(asking(&app));
|
||||
click_after_delay(&mut app, 10.0, "Print");
|
||||
for _ in 0..10_000 {
|
||||
script_runs::poll(&mut app);
|
||||
if !app.session.script_running() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!app.session.script_running());
|
||||
assert!(app.ui.startup_notes.is_empty(), "the startup round ended");
|
||||
assert!(app.ui.status.contains("The later startup script failed"), "{}", app.ui.status);
|
||||
let startup_notes = app.ui.status_notes.as_ref().unwrap().1.clone();
|
||||
crate::background::wait_all(&mut app);
|
||||
assert!(app.ui.status.contains("The printer Lab is offline"), "{}", app.ui.status);
|
||||
let (status, notes) = app.ui.status_notes.as_ref().unwrap();
|
||||
assert_eq!(status, &app.ui.status, "the hover notes match the displayed status");
|
||||
assert!(notes.len() > 1, "the hover lists both failures");
|
||||
assert!(notes.contains(status));
|
||||
assert!(startup_notes.iter().all(|note| notes.contains(note)), "{notes:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Without a service that lets scripts print (the web's), or without any, printing to a printer
|
||||
/// from a script throws and nothing is asked or sent.
|
||||
#[test]
|
||||
@@ -327,6 +443,107 @@ fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() {
|
||||
assert!(app.session.script_printers.is_none());
|
||||
}
|
||||
|
||||
/// With startup scripts on, the chosen script starts after them, in a later frame, and still lists
|
||||
/// the service's printers: its job asks the person as it does without startup scripts.
|
||||
#[test]
|
||||
fn a_script_chosen_after_startup_scripts_may_print() {
|
||||
let (mut app, sent, _) = print_app(true);
|
||||
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO));
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-print-startup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap();
|
||||
app.session.attach_startup_scripts_dir(dir.clone());
|
||||
app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap();
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
assert!(!app.ui.status.contains("not available here"), "{}", app.ui.status);
|
||||
assert_eq!(objects(&app), 1, "the chosen script ran");
|
||||
assert!(asking(&app), "its job waits for the person");
|
||||
assert!(app.session.script_printers.is_none());
|
||||
assert!(sent.borrow().is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The startup scripts run at launch do not list the printers, so the first window does not wait
|
||||
/// on the print service.
|
||||
#[test]
|
||||
fn the_startup_scripts_at_launch_list_no_printers() {
|
||||
let lists: Rc<std::cell::Cell<usize>> = Default::default();
|
||||
let spool = Spool {
|
||||
sent: Sent::default(),
|
||||
names: Rc::new(RefCell::new(vec!["Office".to_string()])),
|
||||
scripts: true,
|
||||
spool_error: None,
|
||||
lists: lists.clone(),
|
||||
};
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() }));
|
||||
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO));
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-print-launch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.jsx"), "vc.log(1);").unwrap();
|
||||
app.session.attach_startup_scripts_dir(dir.clone());
|
||||
app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap();
|
||||
script_runs::run_at_launch(&mut app);
|
||||
assert!(app.session.script_running(), "the startup script started: {}", app.ui.status);
|
||||
assert_eq!(lists.get(), 0, "the printers were not listed");
|
||||
assert!(app.queued_script_printers.is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A startup script's jobs are asked about before the chosen script starts, so that script may
|
||||
/// print too.
|
||||
#[test]
|
||||
fn a_startup_scripts_jobs_are_asked_about_before_the_chosen_script_starts() {
|
||||
let (mut app, sent, _) = print_app(true);
|
||||
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO));
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-print-startup-jobs-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.jsx"), "var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);").unwrap();
|
||||
app.session.attach_startup_scripts_dir(dir.clone());
|
||||
app.run("prefs.set", json!({"key": "runStartupScripts", "value": true})).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": PRINT_TO_LAB, "name": "p.js" })).unwrap().unwrap();
|
||||
script_run::with_host(&app, |host, _| host.open(script_run::RunQuestion(craft::ui::dialog::StandardPrompt::custom("Blocked")))).unwrap();
|
||||
for _ in 0..10_000 {
|
||||
script_runs::poll(&mut app);
|
||||
if app.session.script_prints_waiting() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(app.session.script_prints_waiting());
|
||||
assert!(!asking(&app), "the print question waits for the other dialog");
|
||||
script_runs::poll(&mut app);
|
||||
assert!(script_runs::waiting_for_print(&app));
|
||||
assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits under another dialog");
|
||||
assert_eq!(objects(&app), 0);
|
||||
script_run::forget::<script_run::RunQuestion>(&app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let _ = craft::ui::dialog::JobProgress::new("Placing", "Reading").show(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert!(app.any_dialog_open());
|
||||
assert!(!app.asking_dialog_open());
|
||||
script_runs::poll(&mut app);
|
||||
assert!(asking(&app), "the startup script's job is asked about");
|
||||
assert!(app.session.script_running() && app.session.script_name().is_none(), "the chosen script waits");
|
||||
click_after_delay(&mut app, 10.0, "Print");
|
||||
assert_eq!(sent.borrow().iter().map(|(p, ..)| p.clone()).collect::<Vec<_>>(), [Some("Office".to_string())]);
|
||||
for _ in 0..10_000 {
|
||||
script_runs::poll(&mut app);
|
||||
if !app.session.script_running() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!app.session.script_running());
|
||||
assert_eq!(objects(&app), 1, "the chosen script ran: {}", app.ui.status);
|
||||
script_runs::poll(&mut app);
|
||||
assert!(asking(&app), "the chosen script's job is asked about");
|
||||
assert!(app.queued_script_printers.is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Space on Print, once Tab gave it the keyboard focus after [`PRINT_ENABLE_DELAY_SECS`], prints:
|
||||
/// a keyboard user can approve the jobs without a mouse.
|
||||
#[test]
|
||||
|
||||
@@ -321,6 +321,51 @@ fn finished_background_work_waits_for_the_run_to_end() {
|
||||
assert!(app.opening.activate.is_empty());
|
||||
}
|
||||
|
||||
/// The selection a script changes reaches a plug-in that reacts to `selection.changed` in the
|
||||
/// frame the script ends in: once it has ended, nothing asks for another frame.
|
||||
#[test]
|
||||
fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
|
||||
/// Removes the plug-in when the test ends, failed or not: the registry serves every session in
|
||||
/// the process.
|
||||
struct Remove(&'static str);
|
||||
impl Drop for Remove {
|
||||
fn drop(&mut self) {
|
||||
vectorcraft_plugins::registry::remove(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let mut app = app();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
app.session.allow_plugin_grants_from_requests();
|
||||
let id = "test.UI.script_run_events";
|
||||
let _remove = Remove(id);
|
||||
let grant = json!(["progress", "events"]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
|
||||
// The handler writes the event as an information line, which the status bar does not show, so
|
||||
// the plug-in leaves the status bar of other tests' sessions alone; this thread's app keeps
|
||||
// what it took ([`VectorcraftApp::take_event_notices_taken`]).
|
||||
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
|
||||
app.poll_finished_work();
|
||||
let _ = crate::VectorcraftApp::take_event_notices_taken();
|
||||
let source = format!("{DRAW} vc.run('select.all', {{}});");
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
break;
|
||||
}
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert!(!app.session.script_running(), "the script did not end");
|
||||
let ran: Vec<String> = crate::VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
|
||||
assert_eq!(ran.len(), 1, "{ran:?}");
|
||||
assert!(ran[0].contains("selection.changed"), "{ran:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_asks_to_stop_and_stop_undoes_the_run() {
|
||||
let mut app = app();
|
||||
|
||||
+1
-1
@@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For
|
||||
|
||||
## Test lint
|
||||
|
||||
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
|
||||
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a hit of any of its rules: an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`), a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status (`exit-status-only`), a test with no assertion and no asserting helper (`no-assertion`), a silent early `return` on a value from the code under test (`early-return`), an environment variable that no CI leg sets (`env-gate-unset`), and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+49
-15
@@ -2882,6 +2882,8 @@ Existing globals with either name are preserved. If a missing global cannot be a
|
||||
is nonextensible, sealed or frozen, the run fails with an installation error before the script executes.
|
||||
An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)`
|
||||
and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object.
|
||||
Typed-array `from` and `of` accept proxy constructors and run their `construct` traps.
|
||||
A proxy constructor must return a typed array with at least the requested length; otherwise the method throws `TypeError`.
|
||||
`Reflect.construct` also accepts a distinct constructor
|
||||
as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object.
|
||||
`Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's
|
||||
@@ -2902,20 +2904,25 @@ A conversion or syntax error throws before that prototype getter runs.
|
||||
membership checks use host collection indexers, including numeric indices and named items.
|
||||
`JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths
|
||||
become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys
|
||||
or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped.
|
||||
or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped,
|
||||
and each distinct name a replacer array keeps counts against it until the call returns.
|
||||
Its `toJSON` lookup skips host collection indexers through empty-handler proxies
|
||||
and calls an explicit `get` trap when present.
|
||||
`concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before
|
||||
walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds
|
||||
the maximum safe integer. Reviver traversal keys count against the heap limit until their traversal frame is dropped.
|
||||
`concat` reads `Symbol.isConcatSpreadable` through proxy `get` traps. A defined value controls whether the object
|
||||
is spread; an undefined value uses the array check.
|
||||
In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again
|
||||
when reading its value; a binding removed between those checks does not select an outer function.
|
||||
The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating
|
||||
its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations
|
||||
its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without
|
||||
calling proxy traps, so a proxy receiver throws `TypeError`. Symbol property reads, writes, deletion, descriptor operations
|
||||
and symbol enumeration on a revoked proxy also throw `TypeError`.
|
||||
A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`,
|
||||
`defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation
|
||||
reaches the target. `Reflect`'s functions take Symbol keys too.
|
||||
`Object.keys` and `Object.getOwnPropertyNames` keep the target's key order through empty-handler proxies.
|
||||
For an ordinary object, `Reflect.ownKeys` returns the string keys, then the Symbols in insertion order. Ordinary
|
||||
targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes
|
||||
its other non-index strings. A proxy's `ownKeys` trap determines its key order, with strings and Symbols mixed as the
|
||||
@@ -2924,12 +2931,15 @@ the same key twice (two Symbols are the same key only when they are the same Sym
|
||||
result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable
|
||||
through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain.
|
||||
A `for-in` loop checks each proxy candidate's descriptor
|
||||
when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, wherever they sit
|
||||
on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate
|
||||
when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, or a new proxy of
|
||||
the same target that the same `getPrototypeOf` trap returns in its place (such a trap may return a new proxy on each call), wherever they sit on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate
|
||||
names are rejected; a later getter's exception takes precedence over the duplicate-name error.
|
||||
Deleting a binding in a `with` scope calls the proxy's `deleteProperty`
|
||||
trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay
|
||||
reachable during proxy callbacks, including callbacks that revoke a nested target proxy.
|
||||
A `with` scope checks `Symbol.unscopables` after finding a property. If that lookup returns an object whose
|
||||
property for the binding name is truthy, resolution continues in the outer scope. Each read calls a proxy's `get` trap
|
||||
when its receiver is a proxy.
|
||||
`Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype
|
||||
without creating a property on the receiver; when that typed array is the receiver, the value is converted to a
|
||||
number first. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` include a proxy's Symbol
|
||||
@@ -3070,10 +3080,12 @@ through `$`:
|
||||
`transparencyGrid` also take `null` and can be assigned, but `addDocument` throws an error that says they are not available yet when
|
||||
the preset it is given holds one of them with a value other than `null`, and makes no document. A
|
||||
`presetSettings` that is omitted, `undefined` or `null` gives the preset's settings unchanged; any other value
|
||||
that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the
|
||||
that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder, and the files its symbols, patterns and brushes link to, as the person's does, under the
|
||||
automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the
|
||||
profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it
|
||||
that cannot be used, for example) goes to the Script Console as a line `addDocument: <warning>`. A `previewMode` of
|
||||
`DocumentPreviewMode.OverprintPreview` turns Overprint Preview on when the run ends; a run that fails does not turn
|
||||
it on. A `previewMode` of
|
||||
`DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made.
|
||||
`showOptionsDialog` true throws `Dialog unavailable` with no document made. `addDocumentNoUI(startupPreset)`
|
||||
makes the document `addDocument(startupPreset)` makes and ignores any further arguments. A `DocumentPreset` kept
|
||||
@@ -3106,7 +3118,10 @@ through `$`:
|
||||
100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value
|
||||
throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
|
||||
visible bounds, widened to take in the direction points of every path in the object), `editable` (false for an
|
||||
visible bounds, widened to take in the direction points of every path in the object; in a document in the back, type
|
||||
not measured yet is measured first, as the switch to that document would measure it; a valid
|
||||
`position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance
|
||||
or placed document already has is not applied, and its document stays in the back), `editable` (false for an
|
||||
object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`,
|
||||
`duplicate(relativeObject?, insertionLocation?)`,
|
||||
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`
|
||||
@@ -3283,7 +3298,7 @@ through `$`:
|
||||
and leaves the document open when the document has no file (a converted or recovered document included) or when
|
||||
the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several
|
||||
artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with
|
||||
`useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other
|
||||
`useArtboards: false` omits artboards; a native file (its `range` names only the separate files of `separateArtboards`) and a `.ai` or `.ait` file other
|
||||
than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve
|
||||
Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not
|
||||
refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with
|
||||
@@ -3354,7 +3369,7 @@ through `$`:
|
||||
`print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an
|
||||
artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset`
|
||||
is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any
|
||||
case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom`
|
||||
case) or `colorProfileMode` is assigned `CUSTOMPROFILE` without a `name`, when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom`
|
||||
and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or
|
||||
a control character (also at either end), throws too, and each checked name is sent without the spaces around it.
|
||||
`PPDName` takes only `""`. A listed option that is not mapped, or a value that is not mapped such as
|
||||
@@ -3365,8 +3380,11 @@ through `$`:
|
||||
the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or
|
||||
`print.*`.
|
||||
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
|
||||
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as
|
||||
`pageItems["name"]` is read), `index(key)`,
|
||||
`getByName(name)`, `removeAll()` (it deletes nothing and throws `cannot delete hidden or locked paths` when any path is
|
||||
hidden or locked or is inside a hidden or locked object, and otherwise `cannot delete objects on a locked artboard`
|
||||
when any path is on a locked artboard; each message is followed by a colon and the ids of up to 20 of those paths), `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
art has no fill and no stroke, the path has neither), and the shape creators
|
||||
`rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15,
|
||||
verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`,
|
||||
@@ -3442,8 +3460,10 @@ through `$`:
|
||||
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with
|
||||
`inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
|
||||
that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws
|
||||
`Cannot edit` with nothing changed, and `pathItems.removeAll()` when any path is on a locked artboard throws
|
||||
`cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
`Cannot edit` with nothing changed. `pathItems.removeAll()` deletes nothing and throws an error when any path is
|
||||
hidden or locked or is inside a hidden or locked layer, group, compound path or other object (`cannot delete hidden or locked paths`), and otherwise
|
||||
when any path is on a locked artboard (`cannot delete objects on a locked artboard`), each followed by a colon and
|
||||
the ids of up to 20 of those paths. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new
|
||||
art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops
|
||||
are not available yet.
|
||||
@@ -4523,7 +4543,11 @@ disabled, truncated, unreadable}`, with `then` holding `script.run`'s reply. In
|
||||
reply is `{reason, skipped: false, running, queued, failed, disabled, truncated, unreadable}`, with `failed` naming
|
||||
the runs that could not start before the first one did. Each run then reports as a `script.run` in the app does, the
|
||||
next one starts at the frame after, and a later run that cannot start, the chosen script included, is named in the
|
||||
status bar. Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from
|
||||
status bar. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel.
|
||||
Each queued run lists the printers listed when the runs were queued; the runs with reason `launch` list no
|
||||
printers, so they cannot print to a printer. A job that fails to spool is reported in the status bar even when a
|
||||
later run or a later job's note took it.
|
||||
Stop (`script.stop`) asked for between two runs stops the run that starts next. In the app, stopping the runs from
|
||||
the prompt shown on quitting, between two runs, drops the runs not yet started, and the status bar says so. While that prompt is open, the next run does not start. Under `--automation-read-root` it reads the folder only when the folder lies inside a
|
||||
read root. With the preference on, `ui.runScript` and `ui.runInstalledScript` still return `script.run`'s reply,
|
||||
or its error when the chosen script cannot start, and add `startup` holding the `script.startup.run` reply. While a
|
||||
@@ -13221,7 +13245,8 @@ and, with copies per sheet, each copy's artboard on the page (`copies`), plus `t
|
||||
`inks` of a separation and `warnings`. `file.print {settings?, path?}` writes the job as a print-ready PDF (one page per
|
||||
sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, the job is composed only when it
|
||||
prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers
|
||||
`{pages, format}`. In the app, `file.print` with no params opens the Print
|
||||
`{pages, format}`. A composite job without `skipBlank` that prints its artboards is counted on the artboards before
|
||||
its raster effects are rendered. In the app, `file.print` with no params opens the Print
|
||||
dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's
|
||||
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer
|
||||
driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its
|
||||
@@ -15569,7 +15594,16 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an
|
||||
fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that
|
||||
reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in,
|
||||
switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as
|
||||
`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with
|
||||
`refusedCommands` and ids no command has as `unknownCommands`; `plugin.install` also lists the `unknownCommands`. A plug-in
|
||||
at API level 2 whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given the events
|
||||
of the kinds its `events` list names, from `selection.changed`, `document.opened`, `document.saved` and `layer.changed`,
|
||||
through `vc_event` once the change has finished. Headless tool gestures deliver events after their actions finish.
|
||||
An open drag, including one temporarily set aside by a command, holds events until it ends. Documents created or
|
||||
opened in a batch are compared with their state when added, and background plug-in loads record the event baseline
|
||||
when they install, or after the drag ends if one is open. Each UI frame calls at most four event handlers across
|
||||
background delivery and all UI passes; runnable recipients still queued request another frame, even without notices.
|
||||
The handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`).
|
||||
Both reset when a module is installed under the plug-in's id again, including the same module. A live-effect plug-in is an effect with
|
||||
id `plugin.<id>`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and
|
||||
`effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api`
|
||||
and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them
|
||||
|
||||
+70
-6
@@ -439,6 +439,7 @@ capability model proposed for PhotoCraft plug-ins
|
||||
| `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. |
|
||||
| `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. |
|
||||
| `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. |
|
||||
| `events` | all | Run on its own when the selection, a document or a layer changes, for the `events` it names ([events](#events-api-level-2)). Needs `api` 2. |
|
||||
|
||||
- A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter
|
||||
`doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state`
|
||||
@@ -448,9 +449,9 @@ capability model proposed for PhotoCraft plug-ins
|
||||
- An effect, an exporter, an importer or a generator that lists permissions lists all of its implied ones (`doc.read`
|
||||
and `effect.render`; `doc.read` and `export.write`; `import.read`; `doc.write`). An effect with commands may add `doc.write` and
|
||||
`state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`.
|
||||
Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a
|
||||
name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api`
|
||||
below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is
|
||||
Any kind may add `progress`, `settings`, `cache` and `events`, which no kind implies. An unknown name, a name listed
|
||||
twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache`, `commands` or
|
||||
`events` with an `api` below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is
|
||||
installed, and the error names it.
|
||||
- **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of
|
||||
the file and each permission in plain words, and install it once the user clicks OK, if the file still has the
|
||||
@@ -672,6 +673,7 @@ pointers are offsets into the module's memory.
|
||||
| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). Needed only by a module without a `vc_manifest` custom section. |
|
||||
| `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. |
|
||||
| `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. |
|
||||
| `vc_event` | `(event, event_len) -> i32` | Only in a module whose manifest lists [`events`](#events-api-level-2): reacts to the event JSON; returns `0` when it handled it, anything else when it failed. |
|
||||
|
||||
### Manifest section
|
||||
|
||||
@@ -812,7 +814,8 @@ arguments as a JSON object, the params the command takes from any request:
|
||||
`-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command
|
||||
has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected),
|
||||
`-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from
|
||||
the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed).
|
||||
the module's start function, in a run that isn't a filter's run on a document or an [event](#events-api-level-2)
|
||||
handler, or after a call in the run failed).
|
||||
|
||||
- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The
|
||||
run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs
|
||||
@@ -844,6 +847,62 @@ the module's start function, in a run that isn't a filter's run on a document, o
|
||||
`commandAllowlist` and `budget: "heavy"` is refused. On the web it runs in a worker, and the page makes each call
|
||||
([The web build](#the-web-build)).
|
||||
|
||||
### Events (API level 2)
|
||||
|
||||
A plug-in of any kind whose manifest gives `"api": 2`, lists the `events` permission and names events in `events`
|
||||
exports `vc_event`, and VectorCraft calls it after each change of those kinds:
|
||||
|
||||
```json
|
||||
{"id": "org.example.watch", "name": "Watch", "kind": "filter", "api": 2,
|
||||
"permissions": ["doc.read", "events"], "events": ["selection.changed", "document.saved"]}
|
||||
```
|
||||
|
||||
| Event | When | The event JSON |
|
||||
|---|---|---|
|
||||
| `selection.changed` | The selection in a document changed: other objects, anchors or segments, or nothing (`count` 0). | `{"type", "document", "count", "ids", "truncated"}`: `ids` lists the selected objects, at most 2,048 of them (`truncated` is then `true`), and is `null` without `doc.read`. |
|
||||
| `document.opened` | A file opened as a document (File › Open, Open Recent, New from Template). A new blank document is not one. | `{"type", "document"}` |
|
||||
| `document.saved` | Save or Save As wrote the document's own file. Save a Copy, a template and an export are not. | `{"type", "document"}` |
|
||||
| `layer.changed` | The current layer changed, or a layer or sublayer was added, deleted, moved or given other options. | `{"type", "document", "layer", "reasons"}`: `layer` is the current layer's id (`null` when there is none), `reasons` lists any of `current`, `added`, `deleted`, `reordered` and `options`. `reordered` means a layer's or sublayer's place among the rows beside it changed, also when an object moved past it. |
|
||||
|
||||
`document` is a number that names the open document for the rest of the session. No event carries a path, a file name
|
||||
or the document's contents.
|
||||
|
||||
- VectorCraft calls `vc_event(event, event_len)` in a fresh instance with the UTF-8 event JSON in a block from
|
||||
`vc_alloc`, after the change has finished: after the command, after Undo or Redo, after the file was written or the
|
||||
document opened. Nothing happens while a drag is still being previewed, for a failed command, or for a command that
|
||||
leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past
|
||||
events, also none that were waiting for the next delivery when it was installed. A change made to a document opened
|
||||
or created since the last delivery is an event at the next one, after that document's `document.opened`.
|
||||
- The selection changes of one document between two deliveries are one `selection.changed` with the state they ended
|
||||
with, and its layer changes are one `layer.changed`; each document's events are separate. The desktop app delivers
|
||||
in each frame, after the work that finished in the background and again at the end of the frame, after the canvas,
|
||||
panels, dialogs and window keys have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does
|
||||
not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app
|
||||
and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP
|
||||
deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its
|
||||
`document.saved`. Opens and saves are each their own event, in order, and are delivered even when the
|
||||
document closed before the delivery. The opens and saves of a running script wait until its run ends, also
|
||||
through any delivery between its slices. The desktop app does not deliver while a script runs; a frontend that
|
||||
does can give its own opens and saves made while the run was paused before the script's earlier ones. A run that fails gives its saves and none of its opens. At most 32
|
||||
events wait; past that the oldest is dropped.
|
||||
- A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a
|
||||
`commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active
|
||||
document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`,
|
||||
`symbol.list`, `text.getRange`, `transparency.info` and `variable.list`. A call of any other command fails with `-6`
|
||||
before it runs, the error names the event (`a selection.changed handler only reads: …`), and the handler fails.
|
||||
Afterwards VectorCraft puts back every document, its selection, current layer and undo history, which document is
|
||||
active, and the session state a command call can change (paint defaults, the Appearance panel's active row,
|
||||
preferences); a call that changed a document is refused the same way. An event raised while a handler runs waits
|
||||
for the next delivery: handlers never run inside one another.
|
||||
- A handler gets at most 5,000,000 instructions and 200 ms, or its plug-in's own budget when that is smaller, for the
|
||||
module's start function, `vc_alloc` and `vc_event` together; its settings, cache and log lines work as in a run.
|
||||
These limits are VectorCraft's own values. A handler that returns anything but `0`, traps or runs out of budget
|
||||
leaves the change it was told of as it is. Every failure goes to the log, and the first failure in a row also shows
|
||||
in the status bar; after 3 failures in a row, the plug-in gets no more events until VectorCraft
|
||||
starts again or a module is installed with its id again, the same module included. A warning or error line a handler writes with `vc_log`
|
||||
shows in the status bar after the plug-in's name. `plugin.info` gives `eventsOff` and `lastEventError`.
|
||||
- In Safe Mode no handler runs. When no installed plug-in names an event, VectorCraft does not compare anything.
|
||||
|
||||
### Manifest
|
||||
|
||||
```json
|
||||
@@ -929,6 +988,11 @@ the module's start function, in a run that isn't a filter's run on a document, o
|
||||
it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist":
|
||||
["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with
|
||||
no empty part between dots. A malformed list is refused when the module is installed, and the error names the id.
|
||||
- `events` (any kind at `api` 2, and only with the `events` permission, which needs it): the
|
||||
[events](#events-api-level-2) the plug-in reacts to, any of `"selection.changed"`, `"document.opened"`,
|
||||
`"document.saved"` and `"layer.changed"`, each at most once. The module then exports `vc_event`. An unknown or
|
||||
repeated name, an entry that isn't a string, `api` 1, a list without the permission, the permission without a list,
|
||||
and a missing or wrongly typed `vc_event` are refused when the module is installed, and the error names the fault.
|
||||
- `translations`: the plug-in's text in other languages ([Translations](#translations)).
|
||||
- `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or
|
||||
`preview`. The host validates the user's values before calling: missing values take the default, numbers are
|
||||
@@ -1541,8 +1605,8 @@ function run(input, params) {
|
||||
The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to
|
||||
128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so
|
||||
existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind`
|
||||
`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or
|
||||
`commands`, so it has no `commandAllowlist`.
|
||||
`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache`,
|
||||
`commands` or `events`, so it has no `commandAllowlist` and no `events`.
|
||||
|
||||
`plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload`
|
||||
install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other
|
||||
|
||||
@@ -1114,14 +1114,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
@@ -1155,7 +1155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `new ExternalObject("lib:AdobeXMPScript")` gives `XMPMeta`, `XMPFile` and `XMPConst` ([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)): properties, arrays, language alternatives and namespaces read from a packet, changed and serialized, and a `.xmp` sidecar read and written with `getXMP`, `putXMP` and `closeFile`. VectorCraft's own rules: `XMPFile` reads and writes only where `File` may; other files are scanned for their packet and read only; a packet over 8 MiB or not well-formed throws; members not built yet (iterators, structure fields, qualifiers, aliases) throw that they are not available yet. `crates/js/src/xmp_tests.rs`, `crates/engine/src/tests/script_xmp.rs`.
|
||||
- Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`).
|
||||
- Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`.
|
||||
- Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/tests/safe_mode.rs`.
|
||||
- Startup scripts: with Preferences › General › Run Startup Scripts on, the `.jsx` files of the `Startup Scripts` folder next to the preferences run when VectorCraft starts and before each script chosen from File › Scripts ([the scripting guide](https://web.archive.org/web/20210515232518/https://www.adobe.com/content/dam/acom/en/devnet/illustrator/pdf/Illustrator_Scripting_Guide_cc.pdf), page 11). VectorCraft's own rules: the preference is off by default; only the folder's own `.jsx` files run, sorted by name without regard to case, each with the limits of any script and its own undo step; one that fails is named in the Script Console and the next one runs, then the chosen script; nothing runs in Safe Mode, the launch marker names the running startup script so a launch that stops there offers to disable it, and a startup script cannot start another round. `script.startup.run` runs the folder. A queued run also waits while the jobs the previous run prepared for a printer wait for Print or Cancel, and each queued run lists the printers listed when the runs were queued; the startup scripts run at launch list no printers. `crates/engine/tests/script_startup.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`, `crates/ui-egui/src/tests/script_print.rs`, `crates/ui-egui/tests/safe_mode.rs`.
|
||||
- Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`.
|
||||
- Plug-in run notices: a filter or plug-in command's output may report a `notice`, which needs no permission; once the output is applied, `plugin.run` and the command return it and the status bar shows it as `Plug-in “name”: notice`, escaped, cut at 200 characters and never translated, and a run that fails or is refused shows none. VectorCraft's own API and limits. Tests: `objects::tests::notice_is_escaped_capped_and_checked` in `vectorcraft-plugins`, `a_filter_s_notice_is_returned_once_its_output_is_applied` and `a_plugin_command_returns_its_run_s_notice` in `vectorcraft-engine`, `plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated` in `vectorcraft-ui-egui`.
|
||||
- Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`.
|
||||
@@ -2844,6 +2844,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged.
|
||||
- **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged.
|
||||
- **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged.
|
||||
- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two checks are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. At most 32 events wait for delivery; past that the oldest waiting event is dropped. The desktop app checks after background work and at the end of each UI pass; `vectorcraft-cli` and headless MCP check after each top-level command. Each UI frame runs at most four handlers across background delivery and all UI passes, and requests another frame while runnable handlers remain queued, even without notices. An open drag holds events until it ends. A plug-in loaded during a drag records its baseline after commit or cancel, before the next edit, without recording temporary previews. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session or until the plug-in is installed again, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
|
||||
- **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged.
|
||||
- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged.
|
||||
- **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode <subcommand>` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged.
|
||||
@@ -2858,7 +2859,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged.
|
||||
- **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `<kind>` dialog cannot set protected field `<field>`"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged.
|
||||
- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `xtask/src/grant_sites.rs` (`cargo xtask grant-sites`), `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged.
|
||||
- **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
|
||||
@@ -107,7 +107,14 @@ try {
|
||||
$file = Join-Path $root 'owned-sentinel.exe'
|
||||
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
|
||||
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
|
||||
& $sign -Files $file
|
||||
# With GITHUB_ACTIONS set, sign.ps1 prints its unsigned-files warning as a workflow annotation.
|
||||
# The test clears it for this call, reads the warning from the warning stream and restores it.
|
||||
$actions = $env:GITHUB_ACTIONS
|
||||
$env:GITHUB_ACTIONS = $null
|
||||
try { $signOutput = @(& $sign -Files $file 3>&1) } finally { $env:GITHUB_ACTIONS = $actions }
|
||||
$warnings = @($signOutput | Where-Object { $_ -is [Management.Automation.WarningRecord] })
|
||||
Assert-Policy ($warnings.Count -eq 1 -and $warnings[0].Message.Contains('Windows signing secrets not set')) 'optional stable policy did not warn about unsigned files'
|
||||
Assert-Policy (-not ($signOutput | Where-Object { "$_".StartsWith('::') })) 'optional stable policy printed a workflow command'
|
||||
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
|
||||
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! `cargo xtask grant-sites`: the shipped code that records a plug-in grant. Only the engine's
|
||||
//! install approval and its load of the plug-in folder's grants file make a `GrantToken` and call
|
||||
//! `registry::grant`, `registry::install_checked` or `registry::install_for_load`. A new call site
|
||||
//! fails this check until it is added to the list. It checks the source, not what native code can
|
||||
//! do at run time.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `(text, file, how many times)` for every place shipped code may name it.
|
||||
const EXPECTED: &[(&str, &str, usize)] = &[
|
||||
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 1),
|
||||
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("registry::install_for_load", "crates/engine/src/store.rs", 2),
|
||||
];
|
||||
|
||||
/// This file lists the names it counts.
|
||||
const SELF: &str = "xtask/src/grant_sites.rs";
|
||||
|
||||
/// The names the audit counts.
|
||||
const NAMES: [&str; 5] = [
|
||||
"GrantToken::after_engine_approval",
|
||||
"GrantToken::from_engine_grants_file",
|
||||
"registry::grant",
|
||||
"registry::install_checked",
|
||||
"registry::install_for_load",
|
||||
];
|
||||
|
||||
pub fn run(root: &Path) -> Result<(), String> {
|
||||
let mut files = Vec::new();
|
||||
for top in ["crates", "apps", "xtask"] {
|
||||
sources(&root.join(top), &mut files);
|
||||
}
|
||||
if files.len() <= 100 {
|
||||
return Err(format!("grant-sites: found only {} source files under {}", files.len(), root.display()));
|
||||
}
|
||||
let found = scan(root, &files)?;
|
||||
let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect();
|
||||
if found == expected {
|
||||
println!("grant-sites: only the listed shipped code makes a grant token or records a grant");
|
||||
return Ok(());
|
||||
}
|
||||
let list =
|
||||
|m: &BTreeMap<(&str, String), usize>| m.iter().map(|((name, file), n)| format!("{file}: {name} x{n}")).collect::<Vec<_>>().join("\n ");
|
||||
Err(format!(
|
||||
"shipped code that makes a grant token or records a grant differs from EXPECTED in xtask/src/grant_sites.rs\nfound:\n {}\nexpected:\n {}",
|
||||
list(&found),
|
||||
list(&expected)
|
||||
))
|
||||
}
|
||||
|
||||
/// How many times each name occurs in the shipped lines of each of `files`, keyed by the file's
|
||||
/// path relative to `root`. This file is left out.
|
||||
fn scan(root: &Path, files: &[PathBuf]) -> Result<BTreeMap<(&'static str, String), usize>, String> {
|
||||
let mut found = BTreeMap::new();
|
||||
for file in files {
|
||||
let rel = file.strip_prefix(root).unwrap_or(file).to_string_lossy().replace('\\', "/");
|
||||
if rel == SELF {
|
||||
continue;
|
||||
}
|
||||
let text = std::fs::read_to_string(file).map_err(|e| format!("grant-sites: {}: {e}", file.display()))?;
|
||||
for line in shipped(&text) {
|
||||
for name in NAMES {
|
||||
let n = count(line, name);
|
||||
if n > 0 {
|
||||
*found.entry((name, rel.clone())).or_default() += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Every `.rs` file under `dir`, without test files and folders.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if path.is_dir() {
|
||||
if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") {
|
||||
sources(&path, out);
|
||||
}
|
||||
} else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {`
|
||||
/// on.
|
||||
fn shipped(text: &str) -> Vec<&str> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let opens_test_module = |i: usize| {
|
||||
lines[i] == "#[cfg(test)]"
|
||||
&& lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{'))
|
||||
};
|
||||
let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len());
|
||||
lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect()
|
||||
}
|
||||
|
||||
/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`).
|
||||
fn count(line: &str, name: &str) -> usize {
|
||||
line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The audit's own filters: a test module and comments are left out, a longer name isn't counted.
|
||||
#[test]
|
||||
fn the_audit_skips_test_code_and_comments() {
|
||||
let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n";
|
||||
let lines = shipped(text);
|
||||
assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::<usize>(), 1, "{lines:?}");
|
||||
}
|
||||
|
||||
/// The walk leaves out test files and folders and this file; a shipped call site is counted.
|
||||
#[test]
|
||||
fn the_audit_counts_shipped_files_only() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-grant-sites-{}", std::process::id()));
|
||||
let file = |p: &str| {
|
||||
let path = dir.join(p);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "fn f() { registry::grant(t); }\n").unwrap();
|
||||
};
|
||||
for p in [
|
||||
"crates/x/src/lib.rs",
|
||||
"crates/x/src/tests.rs",
|
||||
"crates/x/src/a_tests.rs",
|
||||
"crates/x/tests/it.rs",
|
||||
"crates/x/benches/b.rs",
|
||||
"xtask/src/grant_sites.rs",
|
||||
] {
|
||||
file(p);
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
for top in ["crates", "apps", "xtask"] {
|
||||
sources(&dir.join(top), &mut files);
|
||||
}
|
||||
let found = scan(&dir, &files);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(found.unwrap(), BTreeMap::from([(("registry::grant", "crates/x/src/lib.rs".to_owned()), 1)]));
|
||||
}
|
||||
}
|
||||
+67
-53
@@ -9,6 +9,7 @@ mod brands;
|
||||
mod bundle;
|
||||
mod cache_units;
|
||||
mod cursors;
|
||||
mod grant_sites;
|
||||
mod ico;
|
||||
mod layers;
|
||||
mod pdf_deps;
|
||||
@@ -33,6 +34,7 @@ commands:
|
||||
assets check that every icon/image/font/asset is attributed in ASSETS.md
|
||||
brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products
|
||||
cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails)
|
||||
grant-sites check that only the listed shipped code makes a plug-in grant token or records a grant
|
||||
test-lint [--base <rev>] [--all]
|
||||
weak tests in the lines changed since the base: fail on self-compares, reasonless
|
||||
#[ignore], sleeps, reads of Rust source and tests no CI target runs; list only
|
||||
@@ -46,7 +48,7 @@ commands:
|
||||
layers enforce the crate dependency layering (plan/architecture.md §3)
|
||||
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker
|
||||
test the workspace tests (cargo nextest when installed, else cargo test), then the doctests
|
||||
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
|
||||
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
|
||||
the tests and doctests of its crates, the last shard the other steps
|
||||
ci warm build what every shard builds, without running it (fills the gate's cache); with
|
||||
@@ -82,6 +84,7 @@ fn main() -> ExitCode {
|
||||
Some("assets") => assets::run(&root()),
|
||||
Some("brands") => brands::run(&root()),
|
||||
Some("cursors") => cursors::run(&root()),
|
||||
Some("grant-sites") => grant_sites::run(&root()),
|
||||
Some("test-lint") => test_lint::run(&root(), &rest),
|
||||
Some("i18n-report") => cmd_i18n_report(),
|
||||
Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")),
|
||||
@@ -273,23 +276,21 @@ fn has_nextest() -> bool {
|
||||
/// The workspace's unit and integration tests, without examples (clippy still checks those).
|
||||
/// nextest runs each test in its own process, in parallel across all test binaries.
|
||||
fn cmd_test() -> Result<(), String> {
|
||||
test_packages(&["--workspace".to_owned()], "--workspace", None)
|
||||
test_packages(&["--workspace".to_owned()], "--workspace", shards::Targets::All, None)
|
||||
}
|
||||
|
||||
/// The test targets that [`test_packages`] runs and `ci warm` builds.
|
||||
const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"];
|
||||
|
||||
/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`;
|
||||
/// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest.
|
||||
/// A part runs its counted share, then its pinned tests, each with nextest's default thread count.
|
||||
/// Every run finishes before the first error is returned.
|
||||
fn test_packages(select: &[String], shown: &str, part: Option<shards::Part>) -> Result<(), String> {
|
||||
/// [`cmd_test`] for the `targets` of the packages `select` picks (`--workspace` or `-p` ids),
|
||||
/// shown as `shown`; with `part`, only that part's share of their tests (xtask/src/shards.rs),
|
||||
/// which needs nextest. A part runs its counted share, then its pinned tests, each with
|
||||
/// nextest's default thread count. Every run finishes before the first error is returned.
|
||||
fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option<shards::Part>) -> Result<(), String> {
|
||||
let (listed, targets) = (targets.shown(), targets.args());
|
||||
if let Some(part) = part {
|
||||
if !has_nextest() {
|
||||
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest"));
|
||||
}
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(TARGETS);
|
||||
c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets);
|
||||
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
|
||||
@@ -303,9 +304,9 @@ fn test_packages(select: &[String], shown: &str, part: Option<shards::Part>) ->
|
||||
}
|
||||
let command = |args: Vec<String>| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "run"]).args(select).args(TARGETS).args(&args);
|
||||
c.args(["nextest", "run"]).args(select).args(targets).args(&args);
|
||||
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
|
||||
(c, format!("cargo nextest run {shown} --lib --bins --tests {quoted}"))
|
||||
(c, format!("cargo nextest run {shown} {listed} {quoted}"))
|
||||
};
|
||||
let mut result = Ok(());
|
||||
for args in part.runs() {
|
||||
@@ -316,12 +317,12 @@ fn test_packages(select: &[String], shown: &str, part: Option<shards::Part>) ->
|
||||
}
|
||||
let mut c = cargo();
|
||||
if has_nextest() {
|
||||
c.args(["nextest", "run"]).args(select).args(TARGETS);
|
||||
run(c, &format!("cargo nextest run {shown} --lib --bins --tests"))
|
||||
c.args(["nextest", "run"]).args(select).args(targets);
|
||||
run(c, &format!("cargo nextest run {shown} {listed}"))
|
||||
} else {
|
||||
eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)");
|
||||
c.arg("test").args(select).args(TARGETS);
|
||||
run(c, &format!("cargo test {shown} --lib --bins --tests"))
|
||||
c.arg("test").args(select).args(targets);
|
||||
run(c, &format!("cargo test {shown} {listed}"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,22 +378,33 @@ fn cmd_ci_shard() -> Result<(), String> {
|
||||
let checked = shards::run()?;
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
match &checked[shard - 1] {
|
||||
shards::Shard::Tests(crates, part) => {
|
||||
let names = shards::names(crates);
|
||||
shards::Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {names}{share}");
|
||||
let select = shards::select(crates);
|
||||
let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs));
|
||||
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
let part = *part;
|
||||
let (s, w) = (select.clone(), shown.clone());
|
||||
steps.push(("test", Box::new(move || test_packages(&s, &w, part))));
|
||||
let tests: Vec<(Vec<String>, String, shards::Targets)> =
|
||||
runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
|
||||
// Each run finishes before the first error is returned.
|
||||
steps.push((
|
||||
"test",
|
||||
Box::new(move || {
|
||||
let mut result = Ok(());
|
||||
for (s, w, t) in &tests {
|
||||
result = result.and(test_packages(s, w, *t, part));
|
||||
}
|
||||
result
|
||||
}),
|
||||
));
|
||||
// The doctests and the i18n report run once, on a split's first part.
|
||||
let first = part.is_none_or(|p| p.is_first());
|
||||
if first {
|
||||
let c = crates.clone();
|
||||
let c = shards::unit_crates(runs);
|
||||
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
|
||||
}
|
||||
if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") {
|
||||
let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui"));
|
||||
if let Some(r) = all.filter(|_| first) {
|
||||
let (select, shown) = (shards::select(&r.crates), shown(&r.crates));
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
|
||||
}
|
||||
}
|
||||
@@ -404,13 +416,11 @@ fn cmd_ci_shard() -> Result<(), String> {
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration
|
||||
/// tests without running them, then builds what the checks shard builds, so one dependency-cache
|
||||
/// entry holds the dependencies of every shard with the features that shard builds them with (cargo
|
||||
/// resolves features over the packages each command selects). The test builds select the same
|
||||
/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the
|
||||
/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that
|
||||
/// only an integration test uses.
|
||||
/// `cargo xtask ci warm`: for each run of each test shard, builds the test targets it runs without
|
||||
/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the
|
||||
/// dependencies of every shard with the features that shard builds them with (cargo resolves
|
||||
/// features over the packages each command selects). The test builds select the same crates and
|
||||
/// targets as the test shards' runs, so the cache also holds the test executables the shards run.
|
||||
///
|
||||
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
|
||||
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
|
||||
@@ -431,14 +441,16 @@ fn cmd_ci_warm() -> Result<(), String> {
|
||||
let (tests, checks) = shards::warm_plan(&checked, only);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
for i in tests {
|
||||
if let shards::Shard::Tests(crates, _) = checked[i].clone() {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
let (c, what) = warm_tests(&crates);
|
||||
cache_units::run(c, &what)
|
||||
}),
|
||||
));
|
||||
if let shards::Shard::Tests(runs, _) = checked[i].clone() {
|
||||
for r in runs {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
let (c, what) = warm_tests(&r);
|
||||
cache_units::run(c, &what)
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if checks {
|
||||
@@ -474,11 +486,11 @@ fn push_warm_checks(steps: &mut Vec<Step>) {
|
||||
steps.push(("wasm", Box::new(cmd_wasm)));
|
||||
}
|
||||
|
||||
/// The command `ci warm` builds one test shard's tests with, and its description.
|
||||
fn warm_tests(crates: &[shards::Member]) -> (Command, String) {
|
||||
/// The command `ci warm` builds the tests of one run of a test shard with, and its description.
|
||||
fn warm_tests(r: &shards::Run) -> (Command, String) {
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates)))
|
||||
c.arg("test").args(shards::select(&r.crates)).args(r.targets.args()).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", r.targets.shown(), shards::names(&r.crates)))
|
||||
}
|
||||
|
||||
/// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed
|
||||
@@ -548,6 +560,7 @@ fn ci_steps() -> Vec<Step> {
|
||||
("pdf-deps", Box::new(|| pdf_deps::run(&root()))),
|
||||
("assets", Box::new(|| assets::run(&root()))),
|
||||
("brands", Box::new(|| brands::run(&root()))),
|
||||
("grant-sites", Box::new(|| grant_sites::run(&root()))),
|
||||
("cursors", Box::new(|| cursors::run(&root()))),
|
||||
("test-lint", Box::new(|| test_lint::run(&root(), &[]))),
|
||||
("i18n-report", Box::new(cmd_ci_i18n_report)),
|
||||
@@ -630,13 +643,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn warm_builds_the_test_targets_the_shards_run() {
|
||||
let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }];
|
||||
let (c, what) = warm_tests(&crates);
|
||||
let args: Vec<String> = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]);
|
||||
for target in TARGETS {
|
||||
assert!(args.iter().any(|a| a == target), "ci warm does not build {target}");
|
||||
}
|
||||
assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)");
|
||||
let a = shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true };
|
||||
let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<String>>();
|
||||
let all = shards::Run::all(vec![a.clone()]);
|
||||
assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]);
|
||||
assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --tests --no-run (a)");
|
||||
let units = shards::Run { targets: shards::Targets::Units, crates: vec![a.clone()] };
|
||||
assert_eq!(args(&units), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![a] };
|
||||
assert_eq!(args(&integration), ["test", "-p", "path+file:///w/a#0.1.0", "--test", "*", "--no-run"]);
|
||||
}
|
||||
}
|
||||
+249
-43
@@ -17,6 +17,11 @@
|
||||
//! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n
|
||||
//! report run on part 1. A part runs its counted share and then its pinned tests, each with
|
||||
//! nextest's default thread count, and runs both even when the first fails.
|
||||
//!
|
||||
//! A [`Group::Targets`] shard can run a crate's library and binary tests ([`Targets::Units`]) while
|
||||
//! another shard runs its integration tests ([`Targets::Integration`]), so a shard that already
|
||||
//! builds that crate's library takes those tests without building the library's test harness. Each
|
||||
//! list of a shard is its own cargo command, and its doctests run with its library tests.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -25,16 +30,49 @@ use serde_json::Value;
|
||||
/// What one shard runs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Group {
|
||||
/// The tests of these workspace crates (package names).
|
||||
Crates(&'static [&'static str]),
|
||||
/// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards.
|
||||
Part(&'static Split, usize),
|
||||
/// The given test targets of each list of workspace crates (package names). A crate whose
|
||||
/// [`Targets::Units`] run on one shard has its [`Targets::Integration`] run on another.
|
||||
Targets(&'static [(Targets, &'static [&'static str])]),
|
||||
/// The tests of every workspace member no other group names.
|
||||
Rest,
|
||||
/// The `cargo xtask ci` steps that are not tests.
|
||||
Checks,
|
||||
}
|
||||
|
||||
/// The test targets a shard builds and runs for a crate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Targets {
|
||||
/// The library, binary and integration tests.
|
||||
All,
|
||||
/// The library and binary tests.
|
||||
Units,
|
||||
/// The integration tests (`tests/`).
|
||||
Integration,
|
||||
}
|
||||
|
||||
impl Targets {
|
||||
/// The target selection `cargo test` and `cargo nextest run` take.
|
||||
pub fn args(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Targets::All => &["--lib", "--bins", "--tests"],
|
||||
Targets::Units => &["--lib", "--bins"],
|
||||
// `--tests` would also take the library's and binaries' test harnesses (every target with `test = true`).
|
||||
Targets::Integration => &["--test", "*"],
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Targets::args`] as a shell would take them, for messages.
|
||||
pub fn shown(self) -> &'static str {
|
||||
match self {
|
||||
Targets::All => "--lib --bins --tests",
|
||||
Targets::Units => "--lib --bins",
|
||||
Targets::Integration => "--test '*'",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Crates whose tests run on several shards, one [`Group::Part`] each.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Split {
|
||||
@@ -70,12 +108,17 @@ pub static UI_EGUI: Split = Split {
|
||||
],
|
||||
};
|
||||
|
||||
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length.
|
||||
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its
|
||||
/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on
|
||||
/// shard 4, which already builds the engine library for the app crates.
|
||||
pub const GROUPS: &[Group] = &[
|
||||
Group::Part(&UI_EGUI, 1),
|
||||
Group::Part(&UI_EGUI, 2),
|
||||
Group::Crates(&["vectorcraft-engine"]),
|
||||
Group::Crates(&["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]),
|
||||
Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]),
|
||||
Group::Targets(&[
|
||||
(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]),
|
||||
(Targets::Integration, &["vectorcraft-engine"]),
|
||||
]),
|
||||
Group::Rest,
|
||||
Group::Checks,
|
||||
];
|
||||
@@ -97,10 +140,29 @@ pub struct Member {
|
||||
/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Shard {
|
||||
Tests(Vec<Member>, Option<Part>),
|
||||
Tests(Vec<Run>, Option<Part>),
|
||||
Checks,
|
||||
}
|
||||
|
||||
/// One test run of a shard: the given targets of these crates.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Run {
|
||||
pub targets: Targets,
|
||||
pub crates: Vec<Member>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
/// A run of every test target of `crates`.
|
||||
pub fn all(crates: Vec<Member>) -> Run {
|
||||
Run { targets: Targets::All, crates }
|
||||
}
|
||||
}
|
||||
|
||||
/// The crates of `runs` whose library is tested there, which run their doctests on that shard.
|
||||
pub fn unit_crates(runs: &[Run]) -> Vec<Member> {
|
||||
runs.iter().filter(|r| r.targets != Targets::Integration).flat_map(|r| r.crates.iter().cloned()).collect()
|
||||
}
|
||||
|
||||
/// Part `index` (1-based) of `split`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Part {
|
||||
@@ -191,14 +253,15 @@ pub fn with_doctests(crates: &[Member]) -> Vec<Member> {
|
||||
}
|
||||
|
||||
/// Each group of `groups` with its crates: a named crate must be a workspace member and named
|
||||
/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's
|
||||
/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice.
|
||||
/// once, or with its [`Targets::Units`] on one shard and its [`Targets::Integration`] on another;
|
||||
/// there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's parts 1
|
||||
/// to n must be consecutive shards, with at least two parts, and no test pinned twice.
|
||||
pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String> {
|
||||
const WHERE: &str = "xtask/src/shards.rs › GROUPS";
|
||||
let mut named: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
let mut named: BTreeMap<&str, Vec<(usize, Targets)>> = BTreeMap::new();
|
||||
for (i, g) in groups.iter().enumerate() {
|
||||
let names = match g {
|
||||
Group::Crates(names) => *names,
|
||||
let lists: Vec<(Targets, &[&str])> = match g {
|
||||
Group::Targets(lists) => lists.to_vec(),
|
||||
Group::Part(split, k) => {
|
||||
let n = split.parts();
|
||||
if n < 2 {
|
||||
@@ -221,22 +284,39 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1));
|
||||
}
|
||||
}
|
||||
split.crates
|
||||
vec![(Targets::All, split.crates)]
|
||||
}
|
||||
Group::Rest | Group::Checks => continue,
|
||||
};
|
||||
if names.is_empty() {
|
||||
if lists.iter().all(|(_, names)| names.is_empty()) {
|
||||
return Err(format!("shard {} names no crates ({WHERE})", i + 1));
|
||||
}
|
||||
for name in names {
|
||||
if !members.iter().any(|m| m.name == *name) {
|
||||
return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1));
|
||||
}
|
||||
if let Some(first) = named.insert(name, i) {
|
||||
return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1));
|
||||
for (targets, names) in lists {
|
||||
for name in names {
|
||||
if !members.iter().any(|m| m.name == *name) {
|
||||
return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1));
|
||||
}
|
||||
let entries = named.entry(name).or_default();
|
||||
// The one allowed second entry: the other half of a crate split into units and integration tests.
|
||||
let halves =
|
||||
|a: Targets, b: Targets| matches!((a, b), (Targets::Units, Targets::Integration) | (Targets::Integration, Targets::Units));
|
||||
match entries.as_slice() {
|
||||
[] => {}
|
||||
[(first, t)] if halves(*t, targets) && *first != i => {}
|
||||
[(first, _), ..] => return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)),
|
||||
}
|
||||
entries.push((i, targets));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, entries) in &named {
|
||||
if let [(i, t)] = entries.as_slice()
|
||||
&& *t != Targets::All
|
||||
{
|
||||
let other = if *t == Targets::Units { "integration" } else { "library and binary" };
|
||||
return Err(format!("shard {} runs part of `{name}`'s tests, and no shard runs its {other} tests ({WHERE})", i + 1));
|
||||
}
|
||||
}
|
||||
let rests = groups.iter().filter(|g| **g == Group::Rest).count();
|
||||
if rests != 1 {
|
||||
return Err(format!("{rests} shards take the remaining crates, not 1 ({WHERE})"));
|
||||
@@ -246,14 +326,23 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| match g {
|
||||
Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())), None)),
|
||||
Group::Part(split, index) => Ok(Shard::Tests(pick(&|m| split.crates.contains(&m.name.as_str())), Some(Part { split, index: *index }))),
|
||||
Group::Targets(lists) => Ok(Shard::Tests(
|
||||
lists
|
||||
.iter()
|
||||
.filter(|(_, names)| !names.is_empty())
|
||||
.map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) })
|
||||
.collect(),
|
||||
None,
|
||||
)),
|
||||
Group::Part(split, index) => {
|
||||
Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index })))
|
||||
}
|
||||
Group::Rest => {
|
||||
let rest = pick(&|m| !named.contains_key(m.name.as_str()));
|
||||
if rest.is_empty() {
|
||||
return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1));
|
||||
}
|
||||
Ok(Shard::Tests(rest, None))
|
||||
Ok(Shard::Tests(vec![Run::all(rest)], None))
|
||||
}
|
||||
Group::Checks => Ok(Shard::Checks),
|
||||
})
|
||||
@@ -324,6 +413,17 @@ pub fn names(crates: &[Member]) -> String {
|
||||
crates.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The crates of `runs` for messages, each run's targets after its crates unless it runs all of them.
|
||||
pub fn describe(runs: &[Run]) -> String {
|
||||
runs.iter()
|
||||
.map(|r| match r.targets {
|
||||
Targets::All => names(&r.crates),
|
||||
t => format!("{} ({})", names(&r.crates), t.shown()),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`].
|
||||
pub fn check() -> Result<Vec<Shard>, String> {
|
||||
let members = members(&crate::metadata()?)?;
|
||||
@@ -331,9 +431,12 @@ pub fn check() -> Result<Vec<Shard>, String> {
|
||||
let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members);
|
||||
let mut differences = Vec::new();
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if let Shard::Tests(crates, _) = shard {
|
||||
let alone = tree_features(&tree(&select(crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, crates, &workspace, &alone));
|
||||
// Each run is its own cargo command, so cargo resolves features over that run's crates.
|
||||
if let Shard::Tests(runs, _) = shard {
|
||||
for r in runs {
|
||||
let alone = tree_features(&tree(&select(&r.crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
@@ -353,9 +456,9 @@ pub fn run() -> Result<Vec<Shard>, String> {
|
||||
let shards = check()?;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
match shard {
|
||||
Shard::Tests(crates, part) => {
|
||||
Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
|
||||
println!("shard {}/{}: tests of {} crate(s): {}{share}", i + 1, shards.len(), crates.len(), names(crates))
|
||||
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs))
|
||||
}
|
||||
Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()),
|
||||
}
|
||||
@@ -440,7 +543,7 @@ mod tests {
|
||||
// builds nothing), and the legs together, like a full warm, build every crate's tests
|
||||
// once and the checks.
|
||||
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).collect();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect();
|
||||
owned.sort_unstable();
|
||||
let (mut legs, mut leg_checks) = (Vec::new(), 0);
|
||||
for i in 0..GROUPS.len() {
|
||||
@@ -488,17 +591,18 @@ mod tests {
|
||||
|
||||
fn crates(shard: &Shard) -> Vec<&str> {
|
||||
match shard {
|
||||
Shard::Tests(c, _) => c.iter().map(|m| m.name.as_str()).collect(),
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The crates of each shard that runs a crate's tests from the start: a part after the first
|
||||
/// Each crate a shard tests from the start, with the targets it runs: a part after the first
|
||||
/// runs a share of the same tests, so it is counted with part 1.
|
||||
fn owners(shard: &Shard) -> Vec<&str> {
|
||||
fn owners(shard: &Shard) -> Vec<(&str, Targets)> {
|
||||
match shard {
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(),
|
||||
_ => crates(shard),
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,12 +651,12 @@ mod tests {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]);
|
||||
assert_eq!(shards[1], Shard::Tests(vec![m("a")], Some(Part { split: &SPLIT, index: 2 })));
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 })));
|
||||
let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err();
|
||||
assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}");
|
||||
let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err();
|
||||
assert!(missing.contains("shard 1 is part 2"), "{missing}");
|
||||
let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err();
|
||||
let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), ALL_A, Group::Rest], &ws).unwrap_err();
|
||||
assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}");
|
||||
const ONE: Split = Split { crates: &["a"], pinned: &[&[]] };
|
||||
assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more"));
|
||||
@@ -615,26 +719,61 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rest_shard_takes_every_crate_no_group_names() {
|
||||
let ws = [m("a"), m("b"), m("c"), m("d")];
|
||||
let shards = assign(&[Group::Crates(&["c"]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]);
|
||||
assert_eq!(shards[2], Shard::Checks);
|
||||
}
|
||||
|
||||
/// Every test target of `a`.
|
||||
const ALL_A: Group = Group::Targets(&[(Targets::All, &["a"])]);
|
||||
const UNITS: (Targets, &[&str]) = (Targets::Units, &["a"]);
|
||||
const INTEGRATION: (Targets, &[&str]) = (Targets::Integration, &["a"]);
|
||||
|
||||
#[test]
|
||||
fn a_crate_s_units_and_integration_tests_run_on_two_shards() {
|
||||
let ws = [m("a"), m("b"), m("c")];
|
||||
let shards =
|
||||
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None));
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None));
|
||||
assert_eq!(crates(&shards[2]), ["c"]);
|
||||
assert_eq!(
|
||||
unit_crates(match &shards[1] {
|
||||
Shard::Tests(r, _) => r,
|
||||
Shard::Checks => panic!("shard 2 is a test shard"),
|
||||
}),
|
||||
[m("b")]
|
||||
);
|
||||
let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(half.contains("no shard runs its integration tests"), "{half}");
|
||||
let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(other_half.contains("no shard runs its library and binary tests"), "{other_half}");
|
||||
let with_all = assign(&[ALL_A, Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(with_all.contains("`a` is in shard 1 and shard 2"), "{with_all}");
|
||||
let same_shard = assign(&[Group::Targets(&[UNITS, INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(same_shard.contains("`a` is in shard 1 and shard 1"), "{same_shard}");
|
||||
let units_twice = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(units_twice.contains("`a` is in shard 1 and shard 2"), "{units_twice}");
|
||||
let third =
|
||||
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[INTEGRATION]), Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(third.contains("`a` is in shard 1 and shard 3"), "{third}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crate_named_twice_or_unknown_fails() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let twice = assign(&[Group::Crates(&["a"]), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err();
|
||||
let twice = assign(&[ALL_A, ALL_A, Group::Rest], &ws).unwrap_err();
|
||||
assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}");
|
||||
let unknown = assign(&[Group::Crates(&["z"]), Group::Rest], &ws).unwrap_err();
|
||||
let unknown = assign(&[Group::Targets(&[(Targets::All, &["z"])]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(unknown.contains("`z`, which is not a workspace member"), "{unknown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_groups_and_a_missing_or_second_rest_fail() {
|
||||
let ws = [m("a"), m("b")];
|
||||
assert!(assign(&[Group::Crates(&[]), Group::Rest], &ws).unwrap_err().contains("names no crates"));
|
||||
assert!(assign(&[Group::Crates(&["a", "b"]), Group::Rest], &ws).unwrap_err().contains("there are none"));
|
||||
assert!(assign(&[Group::Crates(&["a"])], &ws).unwrap_err().contains("0 shards take the remaining crates"));
|
||||
assert!(assign(&[Group::Targets(&[(Targets::All, &[])]), Group::Rest], &ws).unwrap_err().contains("names no crates"));
|
||||
assert!(assign(&[Group::Targets(&[(Targets::All, &["a", "b"])]), Group::Rest], &ws).unwrap_err().contains("there are none"));
|
||||
assert!(assign(&[ALL_A], &ws).unwrap_err().contains("0 shards take the remaining crates"));
|
||||
assert!(assign(&[Group::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates"));
|
||||
}
|
||||
|
||||
@@ -642,11 +781,22 @@ mod tests {
|
||||
fn every_workspace_member_is_tested_on_exactly_one_shard() {
|
||||
let ws = members(&crate::metadata().unwrap()).unwrap();
|
||||
let shards = assign(GROUPS, &ws).unwrap();
|
||||
let mut tested: Vec<&str> = shards.iter().flat_map(owners).collect();
|
||||
tested.sort_unstable();
|
||||
let mut tested: BTreeMap<&str, Vec<Targets>> = BTreeMap::new();
|
||||
for (name, targets) in shards.iter().flat_map(owners) {
|
||||
tested.entry(name).or_default().push(targets);
|
||||
}
|
||||
for targets in tested.values_mut() {
|
||||
targets.sort_unstable();
|
||||
}
|
||||
let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect();
|
||||
all.sort_unstable();
|
||||
assert_eq!(tested, all);
|
||||
assert_eq!(tested.keys().copied().collect::<Vec<_>>(), all);
|
||||
for (name, targets) in &tested {
|
||||
assert!(
|
||||
*targets == [Targets::All] || *targets == [Targets::Units, Targets::Integration],
|
||||
"`{name}` runs {targets:?}, not each test target once"
|
||||
);
|
||||
}
|
||||
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
|
||||
}
|
||||
|
||||
@@ -683,4 +833,60 @@ geom v0.1.0 (/w/geom)|
|
||||
["lib: features absent in shard 4, [default,synth] with the whole workspace"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The lines of the `shard-members: |` block in `workflow`, trimmed.
|
||||
fn shard_members(workflow: &str) -> Vec<&str> {
|
||||
let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |");
|
||||
let Some(key) = lines.next() else { return Vec::new() };
|
||||
let indent = |l: &str| l.len() - l.trim_start().len();
|
||||
lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ci_names_the_crates_of_every_shard_for_test_selection() {
|
||||
// The shared gate runs only the shards that test a crate a pull request reaches, by these lines.
|
||||
let expected: Vec<String> = GROUPS
|
||||
.iter()
|
||||
.map(|g| match g {
|
||||
Group::Part(split, _) => split.crates.join(" "),
|
||||
// The selection names each crate on one line only, so a shard that runs a crate's
|
||||
// integration tests leaves it off its line and relies on a crate there that
|
||||
// depends on it (checked below).
|
||||
Group::Targets(lists) => {
|
||||
lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
Group::Rest => "(rest)".to_owned(),
|
||||
Group::Checks => "(always)".to_owned(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml");
|
||||
let meta = crate::metadata().unwrap();
|
||||
let deps: BTreeMap<&str, Vec<&str>> = meta["packages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| (p["name"].as_str().unwrap(), p["dependencies"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect()))
|
||||
.collect();
|
||||
let reaches = |from: &str, to: &str| {
|
||||
let (mut seen, mut stack) = (BTreeSet::new(), vec![from]);
|
||||
while let Some(c) = stack.pop() {
|
||||
if c == to {
|
||||
return true;
|
||||
}
|
||||
if seen.insert(c) {
|
||||
stack.extend(deps.get(c).into_iter().flatten().copied());
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
for g in GROUPS {
|
||||
let Group::Targets(lists) = g else { continue };
|
||||
let named: Vec<&str> = lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect();
|
||||
for crate_ in lists.iter().filter(|(t, _)| *t == Targets::Integration).flat_map(|(_, c)| c.iter().copied()) {
|
||||
assert!(named.iter().any(|n| reaches(n, crate_)), "no crate on the shard of `{crate_}`'s integration tests depends on it");
|
||||
}
|
||||
}
|
||||
assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]);
|
||||
assert!(shard_members("test-shards: 6\n").is_empty());
|
||||
}
|
||||
}
|
||||
+2720
-89
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user