mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into feat/scripts-api-d11-perspective-presets
This commit is contained in:
commit
3950a5b6b9
148 files changed
+17850
-1537
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
|
||||
|
||||
@@ -69,7 +69,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator-
|
||||
- `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd.
|
||||
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`.
|
||||
- Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`.
|
||||
- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch.
|
||||
- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table and every behaviour table; every row is `unknown` until checked (350 unknown today). A checked row may be marked `no (<reach>)` or `partial (<reach>)` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the row cites a registry command id (LightCraft's `cmd:<id>` is the model). Some rows already cite ids such as `toolbar.show`, but none is a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows.
|
||||
- Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md).
|
||||
|
||||
### Checks
|
||||
|
||||
Generated
+97
-97
@@ -1231,7 +1231,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1272,7 +1272,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1283,7 +1283,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1295,7 +1295,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1303,7 +1303,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1328,7 +1328,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1346,7 +1346,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1364,7 +1364,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1373,7 +1373,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1381,7 +1381,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1390,12 +1390,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1415,7 +1415,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
@@ -1426,7 +1426,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1436,7 +1436,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1444,7 +1444,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1470,7 +1470,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1486,7 +1486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1494,7 +1494,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1513,7 +1513,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1525,7 +1525,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1535,12 +1535,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1555,7 +1555,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1574,7 +1574,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1583,7 +1583,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1606,12 +1606,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1619,7 +1619,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1627,7 +1627,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1640,7 +1640,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1670,7 +1670,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1697,7 +1697,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1715,7 +1715,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1723,7 +1723,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1734,7 +1734,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1749,7 +1749,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1763,7 +1763,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1781,7 +1781,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1793,7 +1793,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1804,7 +1804,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1814,7 +1814,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1823,7 +1823,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1839,7 +1839,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1850,7 +1850,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1862,7 +1862,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1895,7 +1895,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1904,7 +1904,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1928,7 +1928,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1939,7 +1939,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1953,7 +1953,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1964,7 +1964,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1977,7 +1977,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1996,7 +1996,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2013,7 +2013,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2024,7 +2024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2045,7 +2045,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2057,7 +2057,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2082,7 +2082,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2097,7 +2097,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2112,7 +2112,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2122,7 +2122,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2131,7 +2131,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2146,12 +2146,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2165,7 +2165,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2182,7 +2182,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2220,7 +2220,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2231,7 +2231,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2249,7 +2249,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2270,7 +2270,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2291,7 +2291,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2310,7 +2310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2342,7 +2342,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2353,7 +2353,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2363,7 +2363,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2374,7 +2374,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2382,7 +2382,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2414,7 +2414,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2759,7 +2759,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -2792,7 +2792,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2827,7 +2827,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2846,7 +2846,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2865,7 +2865,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2890,7 +2890,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2904,7 +2904,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -2917,7 +2917,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -2943,7 +2943,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -3024,7 +3024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -3050,7 +3050,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=07c20531f89717e461c0f387dd1f9649553f9321#07c20531f89717e461c0f387dd1f9649553f9321"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=861d60a65c50850e995bbb3dcee7c1f3b06815f6#861d60a65c50850e995bbb3dcee7c1f3b06815f6"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -3773,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3782,7 +3782,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3800,7 +3800,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3818,12 +3818,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4806,7 +4806,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4963,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
+49
-49
@@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -194,22 +194,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
print: Some(Box::new(printing::SystemPrint::default())),
|
||||
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
|
||||
// only while the active tool uses the wheel.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Desktop printer transport. VectorCraft composes every page and copy before submission;
|
||||
//! craft-print owns discovery and spooling.
|
||||
use std::process::Command;
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer};
|
||||
|
||||
mod direct_pdf;
|
||||
|
||||
pub struct SystemPrint;
|
||||
#[derive(Default)]
|
||||
pub struct SystemPrint {
|
||||
/// The paper-size lookup in flight, dropped when its worker answers or disconnects.
|
||||
papers: PaperLookup,
|
||||
}
|
||||
|
||||
impl PrintService for SystemPrint {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
system::printers()
|
||||
@@ -15,7 +20,7 @@ impl PrintService for SystemPrint {
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
||||
}
|
||||
fn turns_landscape(&self) -> bool {
|
||||
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
|
||||
@@ -31,6 +36,99 @@ impl PrintService for SystemPrint {
|
||||
fn scripts_may_print(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
|
||||
self.papers.poll(printer, fresh, std::time::Instant::now(), |printer| installed_papers(&printer))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 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));
|
||||
}
|
||||
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.current = None;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up only an installed printer's own name.
|
||||
fn installed_papers(printer: &str) -> Vec<Paper> {
|
||||
if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) {
|
||||
return Vec::new();
|
||||
}
|
||||
system::papers(printer)
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
@@ -43,10 +141,80 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
use super::{Command, Paper, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft::print::printers().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
||||
pub fn papers(printer: &str) -> Vec<Paper> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// The name goes in as an environment variable, never into the script's text.
|
||||
const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \
|
||||
$s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }";
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
// CREATE_NO_WINDOW: no console window opens over the app.
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let mut command = Command::new("powershell.exe");
|
||||
command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW);
|
||||
paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
use std::io::Read as _;
|
||||
// CUPS queue names never hold `/`, so the name can't leave the PPD folder.
|
||||
if printer.contains(['/', '\\']) || printer.starts_with('.') {
|
||||
return Vec::new();
|
||||
}
|
||||
const PPD_CAP: u64 = 16 << 20;
|
||||
let mut bytes = Vec::new();
|
||||
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
|
||||
if read.is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes))
|
||||
}
|
||||
}
|
||||
/// Drain output while polling the child, and stop discovery after ten seconds.
|
||||
#[cfg(windows)]
|
||||
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
use std::process::Stdio;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const LIMIT: Duration = Duration::from_secs(10);
|
||||
let started = Instant::now();
|
||||
let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
let stdout = child.stdout.take();
|
||||
let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
// Retain at most 16 MiB, but drain the rest so the child can finish.
|
||||
let read = stdout.map(|mut out| {
|
||||
out.by_ref().take(16 << 20).read_to_end(&mut bytes)?;
|
||||
std::io::copy(&mut out, &mut std::io::sink())
|
||||
});
|
||||
let _ = send.send(read.and_then(Result::ok).map(|_| bytes));
|
||||
});
|
||||
if reader.is_err() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None };
|
||||
}
|
||||
Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
if job.direct_pdf {
|
||||
return super::direct_pdf::print(job);
|
||||
@@ -133,6 +301,158 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod paper_lookup_tests {
|
||||
use super::PaperLookup;
|
||||
use vectorcraft_ui_egui::print::{Paper, Papers};
|
||||
|
||||
fn paper(key: &str) -> Vec<Paper> {
|
||||
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
|
||||
}
|
||||
|
||||
/// 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 lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) {
|
||||
Papers::Ready(papers) => return papers,
|
||||
Papers::Pending => std::thread::yield_now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A read that answers `key` once `gate` lets it.
|
||||
fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec<Paper> + Send + 'static) {
|
||||
let (open, gate) = std::sync::mpsc::channel::<()>();
|
||||
(open, move |_| {
|
||||
let _ = gate.recv();
|
||||
paper(key)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
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, at(0), read), Papers::Pending));
|
||||
let (other, read) = gated("Office");
|
||||
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, 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)]
|
||||
mod turn_tests {
|
||||
use super::sent;
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_source_objects, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -694,6 +694,15 @@ fn a_wrap_object_below_every_area_type_object_makes_no_outline() {
|
||||
});
|
||||
assert_eq!(sources, 1);
|
||||
assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined");
|
||||
// The objects alone come without a copy of any shape into text space.
|
||||
let mut found = vec![];
|
||||
wrap_source_objects(&d, |n, objects| found.push((n.id, objects.iter().map(|o| o.id).collect::<Vec<_>>())));
|
||||
let mut expected = vec![];
|
||||
wrap_sources(&d, |n, objects, _| expected.push((n.id, objects.iter().map(|o| o.id).collect::<Vec<_>>())));
|
||||
assert_eq!(found, expected);
|
||||
wrap::SHAPES_COPIED.with(|c| c.set(0));
|
||||
wrap_source_objects(&d, |_, _| {});
|
||||
assert_eq!(wrap::SHAPES_COPIED.with(|c| c.get()), 0, "no wrap shape is copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::{Document, Node, NodeId, NodeKind};
|
||||
thread_local! {
|
||||
/// How many wrap outlines [`each_text`] has made on this thread (for tests).
|
||||
pub(super) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many wrap shapes [`shapes_of`] has copied into text space on this thread (for tests).
|
||||
pub(super) static SHAPES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
@@ -167,6 +169,8 @@ fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(_, s)| {
|
||||
#[cfg(test)]
|
||||
SHAPES_COPIED.with(|c| c.set(c.get() + 1));
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
@@ -189,6 +193,18 @@ pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a N
|
||||
}
|
||||
}
|
||||
|
||||
/// [`wrap_sources`] without the shapes: each area text object that gets wrap shapes, with the wrap
|
||||
/// objects whose outlines make them, bottom first. No shape is copied into text space.
|
||||
pub fn wrap_source_objects<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>)) {
|
||||
for layer in &doc.layers {
|
||||
each_text(layer, |n, above| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !above.is_empty() {
|
||||
f(n, above.iter().rev().map(|(s, _)| *s).collect());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
|
||||
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
|
||||
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Mark Bounds of Each",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
|
||||
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
|
||||
has_selection,
|
||||
mark_bounds
|
||||
)]
|
||||
@@ -55,10 +55,16 @@ fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the
|
||||
/// side each runs along.
|
||||
fn legs(r: Rect, length: f64) -> (f64, f64) {
|
||||
(length.min(r.width() / 2.0), length.min(r.height() / 2.0))
|
||||
}
|
||||
|
||||
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
|
||||
/// corner, a line where `r` has no width or no height.
|
||||
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
|
||||
let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0));
|
||||
let (lx, ly) = legs(r, length);
|
||||
corners(r)
|
||||
.into_iter()
|
||||
.filter_map(|(p, sx, sy)| {
|
||||
@@ -103,14 +109,23 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
|
||||
let mut too_small = false;
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
|
||||
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
|
||||
if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) {
|
||||
let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue };
|
||||
// Corner legs are at most half a side, so an object too small for any leg gets no marks.
|
||||
let (lx, ly) = legs(r, length);
|
||||
if rectangle || lx > FLAT || ly > FLAT {
|
||||
marked.push((anchor(d, id), r));
|
||||
} else {
|
||||
too_small = true;
|
||||
}
|
||||
}
|
||||
if marked.is_empty() {
|
||||
if too_small {
|
||||
return Err(bad(C, "nothing to mark: the selection is too small for corner marks"));
|
||||
}
|
||||
return Err(bad(C, "nothing to mark: the selection has no bounds"));
|
||||
}
|
||||
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
|
||||
|
||||
@@ -325,6 +325,28 @@ fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_too_small_for_corner_legs_gets_no_empty_group() {
|
||||
let mut s = session();
|
||||
// Wider than the flat limit, but each leg (half the side at most) is shorter than it.
|
||||
let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[tiny]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}");
|
||||
assert_eq!(steps(&s), n, "no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
// The rectangle style still marks it, and a real object beside it gets its corner marks alone.
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
select(&mut s, &[tiny, a]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
pub mod numbers;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -65,6 +66,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
cmd!(
|
||||
"addon.type.numbers",
|
||||
"Make Numbers Sequence…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}",
|
||||
has_selection,
|
||||
numbers::make_numbers
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Make Numbers Sequence (`addon.type.numbers`): numbers the selected type objects from a start
|
||||
//! value by a step, replacing each object's whole text, the numbers in it, or a `{%n}` placeholder.
|
||||
//! The objects are taken in stacking order, by rows or by columns. Leading and trailing zeros pad
|
||||
//! the numbers to one width. Based on Sergey Osokin's MIT-licensed MakeNumbersSequence script
|
||||
//! (<https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence>).
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_text::edit;
|
||||
use vectorcraft_text::retype::is_combining_mark;
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::textedit::text_mut;
|
||||
use super::super::super::threads;
|
||||
use super::super::super::typecmd::refresh_bounds;
|
||||
use super::super::super::typemenu::text_ids;
|
||||
use super::super::super::{bad, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The command id.
|
||||
pub const COMMAND: &str = "addon.type.numbers";
|
||||
/// The orders the objects are numbered in.
|
||||
pub const ORDERS: [&str; 3] = ["stacking", "rows", "columns"];
|
||||
/// What each object's number replaces.
|
||||
pub const REPLACES: [&str; 3] = ["all", "numbers", "placeholder"];
|
||||
/// The placeholder `replace: "placeholder"` replaces, in any case.
|
||||
pub const PLACEHOLDER: &str = "{%n}";
|
||||
/// The largest start, end or step.
|
||||
const MAX_VALUE: f64 = 1e12;
|
||||
/// The most decimal places a number keeps.
|
||||
const MAX_DECIMALS: usize = 6;
|
||||
/// The largest fixed number of digits.
|
||||
pub const MAX_DIGITS: u64 = 30;
|
||||
/// The most type objects one run numbers.
|
||||
const MAX_TEXTS: usize = 100_000;
|
||||
/// The most numbers or placeholders one run replaces.
|
||||
pub(crate) const MAX_MATCHES: usize = 10_000;
|
||||
|
||||
/// What one run does, read from its params.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct Options {
|
||||
pub start: f64,
|
||||
/// None: the numbers run to the last type object.
|
||||
pub end: Option<f64>,
|
||||
pub step: f64,
|
||||
pub order: &'static str,
|
||||
pub replace: &'static str,
|
||||
/// Some(seed): the numbers go to the objects in random order.
|
||||
pub shuffle: Option<u64>,
|
||||
pub leading_zeros: bool,
|
||||
/// The least number of whole digits with leading zeros; None: as many as the widest number.
|
||||
pub digits: Option<usize>,
|
||||
pub trailing_zeros: bool,
|
||||
pub remove_unused: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
pub(crate) fn parse(p: &Value) -> Result<Self> {
|
||||
const C: &str = COMMAND;
|
||||
let value = |key: &str, default: f64| -> Result<f64> {
|
||||
let v = number_or(p, key, default, C)?;
|
||||
if !v.is_finite() || v.abs() > MAX_VALUE {
|
||||
return Err(bad(C, format!("`{key}` must be from -{MAX_VALUE} to {MAX_VALUE}")));
|
||||
}
|
||||
Ok(v)
|
||||
};
|
||||
let start = value("start", 1.0)?;
|
||||
let step = value("step", 1.0)?;
|
||||
let end = match p.get("end") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(value("end", 0.0)?),
|
||||
};
|
||||
let order = pick(choice(p, C, "order", &ORDERS)?.unwrap_or("stacking"), &ORDERS);
|
||||
let replace = pick(choice(p, C, "replace", &REPLACES)?.unwrap_or("all"), &REPLACES);
|
||||
let seed = whole_or(p, "seed", 0, C)?;
|
||||
let shuffle = if switch_or(p, "shuffle", false, C)? { Some(seed) } else { None };
|
||||
let digits = match p.get("digits") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
let d = whole_or(p, "digits", 1, C)?;
|
||||
if !(1..=MAX_DIGITS).contains(&d) {
|
||||
return Err(bad(C, format!("`digits` must be from 1 to {MAX_DIGITS}")));
|
||||
}
|
||||
Some(usize::try_from(d).unwrap_or(1))
|
||||
}
|
||||
};
|
||||
let remove_unused = switch_or(p, "removeUnused", false, C)?;
|
||||
if remove_unused && end.is_none() {
|
||||
return Err(bad(C, "`removeUnused` needs an `end`"));
|
||||
}
|
||||
Ok(Self {
|
||||
start,
|
||||
end,
|
||||
step,
|
||||
order,
|
||||
replace,
|
||||
shuffle,
|
||||
leading_zeros: switch_or(p, "leadingZeros", true, C)?,
|
||||
digits,
|
||||
trailing_zeros: switch_or(p, "trailingZeros", false, C)?,
|
||||
remove_unused,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as the static entry of `list` it equals.
|
||||
fn pick(v: &str, list: &[&'static str]) -> &'static str {
|
||||
list.iter().copied().find(|x| *x == v).unwrap_or(list[0])
|
||||
}
|
||||
|
||||
/// The decimal places `v` is written with, at most [`MAX_DECIMALS`].
|
||||
fn decimals(v: f64) -> usize {
|
||||
let s = format!("{v}");
|
||||
s.split_once('.').map_or(0, |(_, f)| f.len()).min(MAX_DECIMALS)
|
||||
}
|
||||
|
||||
/// Round the shortest decimal representation of `v` to fixed point at `places`.
|
||||
fn scaled(v: f64, places: usize) -> i128 {
|
||||
let s = format!("{v}");
|
||||
let magnitude = s.trim_start_matches('-');
|
||||
let (whole, fraction) = magnitude.split_once('.').unwrap_or((magnitude, ""));
|
||||
let digits = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places));
|
||||
let mut value = digits.fold(0_i128, |n, digit| n * 10 + i128::from(digit - b'0'));
|
||||
if fraction.as_bytes().get(places).is_some_and(|digit| *digit >= b'5') {
|
||||
value += 1;
|
||||
}
|
||||
if v < 0.0 { -value } else { value }
|
||||
}
|
||||
|
||||
/// `v` scaled by `10^places`, without trailing zeros and with no minus sign on zero.
|
||||
fn write(v: i128, places: usize) -> String {
|
||||
let scale = 10_u128.pow(places as u32);
|
||||
let magnitude = v.unsigned_abs();
|
||||
let sign = if v < 0 { "-" } else { "" };
|
||||
let whole = magnitude / scale;
|
||||
if places == 0 {
|
||||
return format!("{sign}{whole}");
|
||||
}
|
||||
let fraction = magnitude % scale;
|
||||
let s = format!("{sign}{whole}.{fraction:0places$}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// The numbers for `count` objects as text: from `start` by `step` (its sign set to run toward
|
||||
/// `end`), stopping past `end`, then padded with zeros as `o` says.
|
||||
pub(crate) fn sequence(o: &Options, count: usize) -> Vec<String> {
|
||||
let places = [Some(o.start), Some(o.step), o.end].into_iter().flatten().map(decimals).max().unwrap_or(0);
|
||||
let step = match o.end {
|
||||
Some(end) if (o.start <= end) == (o.step < 0.0) => -o.step,
|
||||
_ => o.step,
|
||||
};
|
||||
// Count steps at the supported decimal precision so an inclusive end survives rounding.
|
||||
let scaled = |v: f64| scaled(v, places);
|
||||
let start_i = scaled(o.start);
|
||||
let step_i = scaled(step);
|
||||
let fit = match o.end {
|
||||
Some(end) if step_i != 0 => usize::try_from((scaled(end) - start_i) / step_i + 1).unwrap_or(usize::MAX),
|
||||
_ => count,
|
||||
};
|
||||
let values: Vec<i128> = (0..count.min(fit)).map(|i| start_i + i as i128 * step_i).collect();
|
||||
let mut out: Vec<String> = values.iter().map(|v| write(*v, places)).collect();
|
||||
if o.trailing_zeros {
|
||||
let most = out.iter().map(|s| s.split_once('.').map_or(0, |(_, f)| f.len())).max().unwrap_or(0);
|
||||
if most > 0 {
|
||||
for s in &mut out {
|
||||
let have = s.split_once('.').map_or(0, |(_, f)| f.len());
|
||||
if have == 0 {
|
||||
s.push('.');
|
||||
}
|
||||
s.extend(std::iter::repeat_n('0', most - have));
|
||||
}
|
||||
}
|
||||
}
|
||||
if o.leading_zeros {
|
||||
let last = o.end.map(scaled).unwrap_or_else(|| values.last().copied().unwrap_or(start_i));
|
||||
// Whole digits as written, after rounding to `places`.
|
||||
let whole = |v: i128| {
|
||||
let s = write(v, places);
|
||||
let s = s.trim_start_matches('-');
|
||||
s.split_once('.').map_or(s.len(), |(w, _)| w.len())
|
||||
};
|
||||
let width = whole(start_i).max(whole(last)).max(o.digits.unwrap_or(1));
|
||||
for s in &mut out {
|
||||
if s.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let have = s.split_once('.').map_or(s.len(), |(w, _)| w.len());
|
||||
if have < width {
|
||||
s.insert_str(0, &"0".repeat(width - have));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The byte ranges of `text` a number replaces: each run of ASCII digits, with any `.` or `,`
|
||||
/// followed by more digits inside it, and a `-` before it that does not follow a letter or digit.
|
||||
pub(crate) fn number_spans(text: &str) -> Vec<(usize, usize)> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = vec![];
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if !b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let signed = i > 0 && b[i - 1] == b'-' && !text[..i - 1].chars().rev().find(|c| !is_combining_mark(*c)).is_some_and(char::is_alphanumeric);
|
||||
let start = if signed { i - 1 } else { i };
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
while i + 1 < b.len() && matches!(b[i], b'.' | b',') && b[i + 1].is_ascii_digit() {
|
||||
i += 1;
|
||||
while i < b.len() && b[i].is_ascii_digit() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out.push((start, i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The byte ranges of `text` that hold the placeholder, in any case.
|
||||
pub(crate) fn placeholder_spans(text: &str) -> Vec<(usize, usize)> {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
lower.match_indices(PLACEHOLDER).map(|(i, m)| (i, i + m.len())).collect()
|
||||
}
|
||||
|
||||
/// `ids` in rows (top to bottom, each row left to right) or columns (left to right, each top to
|
||||
/// bottom), by the centres of `bounds`. Objects whose centres are within half the median height
|
||||
/// (width for columns) of a row's first object share its row.
|
||||
fn by_position(ids: Vec<(NodeId, Rect)>, rows: bool) -> Vec<NodeId> {
|
||||
let along = |r: &Rect| if rows { r.center().y } else { r.center().x };
|
||||
let across = |r: &Rect| if rows { r.center().x } else { r.center().y };
|
||||
let mut sizes: Vec<f64> = ids.iter().map(|(_, r)| if rows { r.height() } else { r.width() }).collect();
|
||||
sizes.sort_by(f64::total_cmp);
|
||||
let n = sizes.len();
|
||||
let median = match n {
|
||||
0 | 1 => 0.0,
|
||||
_ if n.is_multiple_of(2) => (sizes[n / 2 - 1] + sizes[n / 2]) / 2.0,
|
||||
_ => sizes[n / 2],
|
||||
};
|
||||
let tolerance = median / 2.0;
|
||||
let mut ids = ids;
|
||||
ids.sort_by(|a, b| along(&a.1).total_cmp(&along(&b.1)));
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
let mut row: Vec<(NodeId, Rect)> = vec![];
|
||||
for item in ids {
|
||||
if row.first().is_some_and(|first| along(&item.1) - along(&first.1) > tolerance) {
|
||||
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
|
||||
out.extend(row.drain(..).map(|(id, _)| id));
|
||||
}
|
||||
row.push(item);
|
||||
}
|
||||
row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1)));
|
||||
out.extend(row.into_iter().map(|(id, _)| id));
|
||||
out
|
||||
}
|
||||
|
||||
/// One replacement in a text: its start and end bytes and the number that goes there.
|
||||
type Edit = (usize, usize, String);
|
||||
|
||||
/// Each span of `spans` in `text` replaced by `number`, as edits from the last to the first. A
|
||||
/// span that already reads `number` is left out, so its formatting stays.
|
||||
pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec<Edit> {
|
||||
spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let o = Options::parse(p)?;
|
||||
let named = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(id) = named.iter().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
// Type objects, groups' included, in stacking order from the back; locked or hidden ones stay.
|
||||
let mut texts = text_ids(d, &named);
|
||||
{
|
||||
let editable = d.editable();
|
||||
texts.retain(|id| editable(*id));
|
||||
}
|
||||
let paths = d.index_paths(texts.iter().copied());
|
||||
texts.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
if texts.len() > MAX_TEXTS {
|
||||
return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}")));
|
||||
}
|
||||
let threads = threads::ThreadIndex::of(d);
|
||||
if texts.iter().any(|id| threads.threaded(*id)) {
|
||||
return Err(bad(C, "threaded type can't be numbered: its frames share one story"));
|
||||
}
|
||||
let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t.plain_text(),
|
||||
_ => String::new(),
|
||||
};
|
||||
// Only objects that hold a number or the placeholder count, for the order too.
|
||||
let mut texts: Vec<(NodeId, String)> = texts
|
||||
.into_iter()
|
||||
.map(|id| (id, plain(id)))
|
||||
.filter(|(_, t)| match o.replace {
|
||||
"numbers" => t.bytes().any(|b| b.is_ascii_digit()),
|
||||
"placeholder" => !placeholder_spans(t).is_empty(),
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
if o.order != "stacking" && o.shuffle.is_none() {
|
||||
let placed: Vec<(NodeId, Rect)> = texts
|
||||
.iter()
|
||||
.map(|(id, _)| (*id, effects::preview::bounds_of(d, &[*id], false).unwrap_or(Rect::new(f64::MAX, f64::MAX, f64::MAX, f64::MAX))))
|
||||
.collect();
|
||||
let mut by_id: std::collections::HashMap<NodeId, String> = texts.into_iter().collect();
|
||||
texts = by_position(placed, o.order == "rows").into_iter().filter_map(|id| by_id.remove(&id).map(|t| (id, t))).collect();
|
||||
}
|
||||
// The objects are shuffled, not the numbers, so an end limit can number any of them.
|
||||
if let Some(seed) = o.shuffle {
|
||||
let mut rng = Rng::new(seed);
|
||||
for i in (1..texts.len()).rev() {
|
||||
let j = usize::try_from(rng.next_u64() % (i as u64 + 1)).unwrap_or(0);
|
||||
texts.swap(i, j);
|
||||
}
|
||||
}
|
||||
let numbers = sequence(&o, texts.len());
|
||||
let mut plans: Vec<(NodeId, Vec<Edit>)> = vec![];
|
||||
let mut matches = 0;
|
||||
for ((id, text), number) in texts.iter().zip(&numbers) {
|
||||
let spans = match o.replace {
|
||||
"numbers" => number_spans(text),
|
||||
"placeholder" => placeholder_spans(text),
|
||||
_ => vec![],
|
||||
};
|
||||
// Checked before any replacement text is made.
|
||||
matches += spans.iter().filter(|(a, b)| text.get(*a..*b) != Some(number.as_str())).count();
|
||||
if matches > MAX_MATCHES {
|
||||
return Err(bad(C, format!("too many numbers or placeholders to replace: at most {MAX_MATCHES}")));
|
||||
}
|
||||
let changes = match o.replace {
|
||||
"numbers" | "placeholder" => edits(text, spans, number),
|
||||
_ => vec![(0, text.len(), number.clone())],
|
||||
};
|
||||
// The text it would have, to leave out objects that already read so.
|
||||
let mut after = text.clone();
|
||||
for (a, b, n) in &changes {
|
||||
after.replace_range(*a..*b, n);
|
||||
}
|
||||
if after != *text {
|
||||
plans.push((*id, changes));
|
||||
}
|
||||
}
|
||||
let numbered: Vec<u64> = texts.iter().take(numbers.len()).map(|(id, _)| id.0).collect();
|
||||
// A clipping group's or layer's mask is its first child; removing it would make the next child the mask.
|
||||
let mask = |id: NodeId| {
|
||||
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| g.clips() && g.children().and_then(|c| c.first()).is_some_and(|c| c.id == id))
|
||||
};
|
||||
let removed: Vec<NodeId> =
|
||||
if o.remove_unused { texts.iter().skip(numbers.len()).map(|(id, _)| *id).filter(|id| !mask(*id)).collect() } else { vec![] };
|
||||
if plans.is_empty() && removed.is_empty() {
|
||||
return Ok(json!({ "count": 0, "ids": numbered, "removed": [] }));
|
||||
}
|
||||
let count = plans.len();
|
||||
s.edit("Make Numbers Sequence", |d, sel| {
|
||||
for (id, changes) in &plans {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
for (a, b, n) in changes {
|
||||
t.splice_paras(*a, *b, n);
|
||||
edit::replace_range(&mut t.runs, *a, *b, n);
|
||||
t.ruby_after_replace(*a, *b, n.len());
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
d.remove_many(&removed)?;
|
||||
if !removed.is_empty() {
|
||||
sel.remove_all(removed.iter().copied());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": count, "ids": numbered, "removed": removed.iter().map(|id| id.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
//! Make Numbers Sequence: the numbers a sequence gives, what each replace mode changes, the
|
||||
//! orders, removed objects, one undo step, and bad params refused without a change.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn text_at(s: &mut Session, x: f64, y: f64, words: &str) -> NodeId {
|
||||
NodeId(s.execute("text.create", &json!({"x": x, "y": y, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn seq(p: Value, count: usize) -> Vec<String> {
|
||||
sequence(&Options::parse(&p).unwrap(), count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sequence_steps_toward_its_end_and_pads_with_zeros() {
|
||||
assert_eq!(seq(json!({"start": 1, "step": 5, "end": 20}), 10), ["01", "06", "11", "16"], "stops past the end");
|
||||
assert_eq!(seq(json!({"start": 10, "step": 3, "end": 1, "leadingZeros": false}), 10), ["10", "7", "4", "1"], "the step turns to run down");
|
||||
assert_eq!(seq(json!({"start": 8, "digits": 3}), 3), ["008", "009", "010"]);
|
||||
assert_eq!(seq(json!({"start": -1, "step": 1}), 3), ["-1", "0", "1"], "negative numbers get no zeros");
|
||||
assert_eq!(seq(json!({"start": 0.1, "step": 0.1, "leadingZeros": false}), 3), ["0.1", "0.2", "0.3"], "no rounding noise");
|
||||
assert_eq!(seq(json!({"start": 1, "step": 0.25, "trailingZeros": true}), 3), ["1.00", "1.25", "1.50"]);
|
||||
assert_eq!(seq(json!({"start": 4, "step": 0}), 3), ["4", "4", "4"]);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 1e9 + 0.1, "step": 0.1, "end": 1e9 + 0.3}), 5),
|
||||
["1000000000.1", "1000000000.2", "1000000000.3"],
|
||||
"a value that rounds to the end counts"
|
||||
);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 10000000000.1, "step": 0.1, "end": 10000000000.3}), 5),
|
||||
["10000000000.1", "10000000000.2", "10000000000.3"],
|
||||
"large values keep the inclusive decimal end"
|
||||
);
|
||||
assert_eq!(seq(json!({"start": 1e12, "step": 0.000001, "end": 1e12}), 3), ["1000000000000"], "an end equal to the start counts");
|
||||
assert_eq!(
|
||||
seq(json!({"start": 999999999999.9_f64, "step": 0.000001}), 3),
|
||||
["999999999999.9", "999999999999.900001", "999999999999.900002"],
|
||||
"large values keep their decimal digits when scaled for a small step"
|
||||
);
|
||||
assert_eq!(
|
||||
seq(json!({"start": 999999999999.9_f64, "step": 0.000001, "end": 999999999999.9_f64}), 3),
|
||||
["999999999999.9"],
|
||||
"the end uses the same decimal scaling as the start"
|
||||
);
|
||||
assert_eq!(seq(json!({"start": 0.1, "step": 3.3}), 4), ["00.1", "03.4", "06.7", "10"], "padded to the rounded last number");
|
||||
assert_eq!(seq(json!({"start": 1, "step": 1_000_000_000_000_u64}), 9009).last().map(String::as_str), Some("9008000000000001"));
|
||||
assert_eq!(seq(json!({"start": -0.25, "step": 0.125}), 5), ["-0.25", "-0.125", "0", "0.125", "0.25"]);
|
||||
assert_eq!(seq(json!({"start": -0.0000001, "step": 0}), 1), ["0"], "rounded zero has no minus sign");
|
||||
assert_eq!(seq(json!({"start": 9.9999999, "step": 0}), 1), ["10"], "width uses the rounded whole part");
|
||||
assert_eq!(seq(json!({"start": -0.0000005, "step": 0}), 1), ["-0.000001"], "decimal ties round away from zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unthreaded_type_checks_the_threads_once() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let scans = super::threads::thread_scans();
|
||||
super::make_numbers(&mut s, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert_eq!(super::threads::thread_scans() - scans, 1, "selection size does not multiply thread scans");
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threaded_type_is_refused() {
|
||||
let mut s = session();
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "1 2 3", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert!(s.execute(C, &json!({"ids": [a, b]})).is_err());
|
||||
assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spans_find_numbers_and_placeholders() {
|
||||
assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]);
|
||||
assert!(number_spans("none").is_empty());
|
||||
assert_eq!(placeholder_spans("a{%N}b{%n}"), [(1, 5), (6, 10)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_whole_text_gets_numbered_in_stacking_order_as_one_step() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let n = steps(&s);
|
||||
let out = s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[1].0], "start": 7})).unwrap();
|
||||
assert_eq!(out["count"], json!(3));
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["7", "8", "9"], "from the back");
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(ids.iter().all(|id| plain(&s, *id) == "x"), "undone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_and_placeholders_are_replaced_inside_the_text() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "Seat 99, row 4");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "no digits");
|
||||
let c = text_at(&mut s, 40.0, 180.0, "Seat 1");
|
||||
s.execute(C, &json!({"ids": [a.0, b.0, c.0], "replace": "numbers", "start": 5})).unwrap();
|
||||
assert_eq!([plain(&s, a), plain(&s, b), plain(&s, c)], ["Seat 5, row 5", "no digits", "Seat 6"], "text with no number is skipped");
|
||||
let d = text_at(&mut s, 40.0, 220.0, "Tag {%N} / {%n}");
|
||||
let e = text_at(&mut s, 40.0, 260.0, "Tag 3");
|
||||
s.execute(C, &json!({"ids": [d.0, e.0], "replace": "placeholder", "start": 2})).unwrap();
|
||||
assert_eq!([plain(&s, d), plain(&s, e)], ["Tag 2 / 2", "Tag 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_follows_each_number_or_placeholder_replacement() {
|
||||
let mut s = session();
|
||||
let word = "漢字";
|
||||
for (replace, words) in [("numbers", "1 2 漢字"), ("placeholder", "{%n} {%N} 漢字")] {
|
||||
let id = text_at(&mut s, 40.0, 100.0, words);
|
||||
let start = words.find(word).unwrap();
|
||||
s.execute("type.ruby", &json!({"ids": [id.0], "start": start, "end": start + word.len(), "text": "かんじ"})).unwrap();
|
||||
s.execute(C, &json!({"ids": [id.0], "replace": replace, "start": 123456})).unwrap();
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") };
|
||||
let text = t.plain_text();
|
||||
assert_eq!(text, "123456 123456 漢字");
|
||||
assert_eq!(t.ruby.len(), 1);
|
||||
let ruby = &t.ruby[0];
|
||||
assert_eq!(&text[ruby.start..ruby.end], word, "ruby follows both replacements in {replace} mode");
|
||||
assert_eq!(ruby.text, "かんじ");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_and_columns_order_by_position() {
|
||||
let mut s = session();
|
||||
// Created bottom-right first, so stacking order differs from both positions.
|
||||
let br = text_at(&mut s, 300.0, 200.0, "x");
|
||||
let tl = text_at(&mut s, 40.0, 100.0, "x");
|
||||
let bl = text_at(&mut s, 40.0, 200.0, "x");
|
||||
let tr = text_at(&mut s, 300.0, 102.0, "x");
|
||||
let ids = json!([br.0, tl.0, bl.0, tr.0]);
|
||||
s.execute(C, &json!({"ids": ids, "order": "rows"})).unwrap();
|
||||
assert_eq!([tl, tr, bl, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"], "a small offset stays in its row");
|
||||
s.execute(C, &json!({"ids": ids, "order": "columns"})).unwrap();
|
||||
assert_eq!([tl, bl, tr, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_leaves_the_rest_or_removes_it() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..4).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
s.execute(C, &json!({"ids": all, "end": 2})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "2", "x", "x"]);
|
||||
let out = s.execute(C, &json!({"ids": all, "start": 5, "end": 6, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([ids[2].0, ids[3].0]));
|
||||
assert!(s.doc().unwrap().doc.node(ids[3]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_gives_every_number_once() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 3, "leadingZeros": false})).unwrap();
|
||||
let mut got: Vec<String> = ids.iter().map(|id| plain(&s, *id)).collect();
|
||||
assert_ne!(got, ["1", "2", "3", "4", "5", "6"], "seed 3 moves them");
|
||||
got.sort();
|
||||
assert_eq!(got, ["1", "2", "3", "4", "5", "6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_with_an_end_can_number_any_object() {
|
||||
let mut numbered = [false; 6];
|
||||
for seed in 0..40 {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": seed, "end": 2, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"].as_array().unwrap().len(), 4);
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
numbered[i] |= s.doc().unwrap().doc.node(*id).is_some();
|
||||
}
|
||||
}
|
||||
assert_eq!(numbered, [true; 6], "every object is numbered for some seed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_numbers_and_removes_the_same_objects() {
|
||||
let run = || {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..8).map(|i| text_at(&mut s, 40.0, 40.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let all = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 11, "end": 4, "removeUnused": true})).unwrap();
|
||||
let texts: Vec<Option<String>> = ids.iter().map(|id| s.doc().unwrap().doc.node(*id).map(|_| plain(&s, *id))).collect();
|
||||
let removed: Vec<usize> =
|
||||
out["removed"].as_array().unwrap().iter().map(|r| ids.iter().position(|id| Some(id.0) == r.as_u64()).unwrap()).collect();
|
||||
(texts, removed)
|
||||
};
|
||||
let (texts, removed) = run();
|
||||
assert_eq!(removed.len(), 4);
|
||||
assert_eq!(run(), (texts, removed), "seed 11 gives each object the same number and removes the same ones");
|
||||
}
|
||||
|
||||
fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.parent_of(ids[0]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_number_in_the_text_is_replaced_with_its_sign() {
|
||||
assert_eq!(number_spans("Seat -4, A-4"), [(5, 7), (11, 12)], "a hyphen after a letter is not a sign");
|
||||
assert_eq!(number_spans("É-4"), [(3, 4)], "nor after a letter outside ASCII");
|
||||
assert_eq!(number_spans("E\u{301}-4"), [(4, 5)], "nor after a letter with a combining mark");
|
||||
assert_eq!(number_spans("क्-4"), [(7, 8)], "nor after a letter with a virama");
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "Seat -4");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "Seat 9");
|
||||
s.execute(C, &json!({"ids": [a.0, b.0], "replace": "numbers", "start": 2, "step": -3})).unwrap();
|
||||
assert_eq!([plain(&s, a), plain(&s, b)], ["Seat 2", "Seat -1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_that_already_reads_the_number_is_not_edited() {
|
||||
let text = "5 and 4";
|
||||
assert_eq!(super::edits(text, number_spans(text), "5"), [(6, 7, "5".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_matches_in_one_run_are_refused() {
|
||||
let mut unchanged = session();
|
||||
let text = vec!["1"; super::MAX_MATCHES + 1].join(" ");
|
||||
let id = text_at(&mut unchanged, 40.0, 100.0, &text);
|
||||
let before = steps(&unchanged);
|
||||
let out = unchanged.execute(C, &json!({"ids": [id.0], "start": 1, "replace": "numbers"})).unwrap();
|
||||
assert_eq!(out["count"], 0);
|
||||
assert_eq!(plain(&unchanged, id), text);
|
||||
assert_eq!(steps(&unchanged), before);
|
||||
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, &"{%n}".repeat(super::MAX_MATCHES + 1));
|
||||
let n = steps(&s);
|
||||
assert!(s.execute(C, &json!({"ids": [a.0], "replace": "placeholder"})).is_err());
|
||||
assert_eq!(steps(&s), n);
|
||||
// Whole texts are not matches: the object limit covers them.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
text_at(&mut s, 40.0, 140.0, "x");
|
||||
// Each duplicate of the whole selection doubles it: 2^14 objects in 14 steps.
|
||||
for _ in 0..14 {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
let count = s.doc().unwrap().selection.objects.len();
|
||||
assert!(count > super::MAX_MATCHES, "{count} objects");
|
||||
let out = s.execute(C, &json!({"step": 0}));
|
||||
assert!(out.is_ok());
|
||||
let out = out.unwrap();
|
||||
assert!(out["count"].as_u64().unwrap() > super::MAX_MATCHES as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_type_in_a_group_is_left_alone() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect();
|
||||
let group = group_of(&mut s, &ids);
|
||||
s.execute("object.setProps", &json!({"ids": [ids[1].0], "locked": true})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [ids[2].0], "visible": false})).unwrap();
|
||||
let out = s.execute(C, &json!({"ids": [group.0], "end": 1, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([]));
|
||||
assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::<Vec<_>>(), ["1", "x", "x"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_type_keeps_a_clipping_mask_and_the_selection() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "x");
|
||||
let b = text_at(&mut s, 40.0, 140.0, "x");
|
||||
// The top object becomes the mask; it sits lowest on the page, so rows number it last.
|
||||
let mask = text_at(&mut s, 40.0, 300.0, "x");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, mask.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().doc.parent_of(mask).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let out = s.execute(C, &json!({"order": "rows", "end": 1, "removeUnused": true})).unwrap();
|
||||
assert_eq!(out["removed"], json!([b.0]), "the mask stays");
|
||||
assert!(s.doc().unwrap().doc.node(mask).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [group], "the group stays selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_are_found_among_the_type_that_gets_numbers() {
|
||||
let mut s = session();
|
||||
let upper = text_at(&mut s, 300.0, 100.0, "1");
|
||||
let lower = text_at(&mut s, 40.0, 135.0, "1");
|
||||
let h1 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
let h2 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 700, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute(C, &json!({"ids": [upper.0, lower.0, h1.0, h2.0], "replace": "numbers", "order": "rows", "start": 1, "leadingZeros": false})).unwrap();
|
||||
assert_eq!([plain(&s, upper), plain(&s, lower)], ["1", "2"], "headings without numbers do not merge the rows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() {
|
||||
let mut s = session();
|
||||
let a = text_at(&mut s, 40.0, 100.0, "1");
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0]})).unwrap()["count"], json!(0));
|
||||
assert_eq!(steps(&s), n);
|
||||
for p in [
|
||||
json!({"ids": [a.0], "start": "one"}),
|
||||
json!({"ids": [a.0], "step": 1e13}),
|
||||
json!({"ids": [a.0], "order": "diagonal"}),
|
||||
json!({"ids": [a.0], "digits": 0}),
|
||||
json!({"ids": [a.0], "removeUnused": true}),
|
||||
json!({"ids": [a.0], "shuffle": "yes"}),
|
||||
json!({"ids": [a.0], "seed": "x"}),
|
||||
] {
|
||||
assert!(s.execute(C, &p).is_err(), "{p} fails");
|
||||
}
|
||||
assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n));
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::write_atomic;
|
||||
use super::{EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
// ---------- the file system (none on the web, where commands take and return bytes) ----------
|
||||
@@ -325,8 +323,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
// Work that stops early for a cancel can leave a truncated result: none of it is written.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
|
||||
// Never a half-written file: see [`vectorcraft_format::write_atomic`].
|
||||
write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes
|
||||
/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is
|
||||
/// checked again as it is opened, and the file goes into that open folder
|
||||
/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the
|
||||
/// check does not redirect the write.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> {
|
||||
let path = std::path::Path::new(path);
|
||||
if !crate::file_access::writes_checked() {
|
||||
return vectorcraft_format::write_atomic_with(path, fill);
|
||||
}
|
||||
vectorcraft_format::write_atomic_checked(path, fill, |opened| {
|
||||
// On Unix `opened` is the open folder's real path with the file's name: compared as it is,
|
||||
// without looking the folder up again. Elsewhere it is `path` itself.
|
||||
#[cfg(unix)]
|
||||
let checked = crate::file_access::check_write_real(opened);
|
||||
#[cfg(not(unix))]
|
||||
let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy());
|
||||
checked.map_err(std::io::Error::other)
|
||||
})
|
||||
}
|
||||
|
||||
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
|
||||
@@ -344,7 +364,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
@@ -358,7 +378,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -751,4 +771,43 @@ mod tests {
|
||||
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The second check of a checked write compares the open folder's real path as it is: a folder
|
||||
/// on that path replaced afterwards by a link into the write root does not make a place outside
|
||||
/// the root pass.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() {
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (root, out) = (base.join("root"), base.join("out"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(out.join("x")).unwrap();
|
||||
let real = out.join("x/doc.svg");
|
||||
std::fs::remove_dir(out.join("x")).unwrap();
|
||||
std::os::unix::fs::symlink(&root, out.join("x")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap();
|
||||
assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes");
|
||||
let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real));
|
||||
assert!(checked.is_err_and(|e| e.contains("outside the write root")));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A checked write through a link to a folder whose name is not valid UTF-8, inside the write
|
||||
/// root, is saved.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff"));
|
||||
std::fs::create_dir_all(&bytes).unwrap();
|
||||
std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap();
|
||||
let path = base.join("text/doc.svg").to_string_lossy().into_owned();
|
||||
confine(roots.as_ref(), || write_file(&path, b"new")).unwrap();
|
||||
assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -759,12 +759,13 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
|
||||
/// report where it is on disk.
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and
|
||||
/// report where it is on disk, or edit text once per match with no limit on the matches in one call.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1933,7 +1933,8 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
|
||||
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
let fonts: Vec<String> = family.into_iter().map(str::to_string).collect();
|
||||
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &fonts), &wanted);
|
||||
let first = index.matches(&pieces[0].path);
|
||||
// Every match, as Retype reads them: the first MAX_CANDIDATES can all be faces drawn alike.
|
||||
let first = index.all_matches(&pieces[0].path);
|
||||
let face = match family {
|
||||
Some(f) => first.iter().find(|m| m.face.family == f).unwrap_or_else(|| panic!("the first glyph matches no glyph of {f}")),
|
||||
None => &first[0],
|
||||
@@ -1942,7 +1943,7 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
|
||||
.id();
|
||||
let mut lines: Vec<super::Line> = vec![];
|
||||
for pc in &pieces {
|
||||
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
let cands: Vec<_> = index.all_matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
|
||||
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
|
||||
lines.extend(super::new_line(pc, &cands, 0.0));
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, contai
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -12,6 +12,8 @@ use vectorcraft_doc::{Node, Scaling};
|
||||
|
||||
const CMD: &str = "object.stepAndRepeat";
|
||||
const MAX_CELLS: usize = 10_000;
|
||||
/// The most objects the copies may hold in all, counting every object inside each copy.
|
||||
const MAX_COPIED_OBJECTS: usize = 250_000;
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -20,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Step and Repeat…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
|
||||
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
|
||||
has_selection,
|
||||
step_and_repeat
|
||||
)]
|
||||
@@ -174,6 +176,12 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if rows.saturating_mul(cols) > MAX_CELLS {
|
||||
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
|
||||
}
|
||||
// Each copy holds every object of the selection, the art of opacity masks included, and the
|
||||
// group that a selection of several objects goes into.
|
||||
let objects = roots.iter().filter_map(|r| d.node(*r)).fold(usize::from(roots.len() > 1), |sum, n| sum.saturating_add(n.count_with_masks()));
|
||||
if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS {
|
||||
return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects")));
|
||||
}
|
||||
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
|
||||
let cells = layout(w, h, gx, gy, rows, cols, alt);
|
||||
let center = b.center().to_vec2();
|
||||
|
||||
@@ -131,6 +131,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() {
|
||||
assert!(e.execute(CMD, &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_grid_whose_copies_would_hold_too_many_objects() {
|
||||
let (mut s, _) = setup();
|
||||
for i in 1..25 {
|
||||
s.execute("shape.rectangle", &json!({"x": i, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let (count, steps) = (s.doc().unwrap().doc.node_count(), undo_steps(&s));
|
||||
// 25 objects and the group they go into, in each of 9,999 copies, are more than the limit,
|
||||
// though the cells are not.
|
||||
let e = s.execute(CMD, &json!({"rows": 100, "columns": 100})).unwrap_err();
|
||||
assert!(e.to_string().contains("objects"), "{e}");
|
||||
assert_eq!((s.doc().unwrap().doc.node_count(), undo_steps(&s)), (count, steps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() {
|
||||
let (mut s, _) = setup();
|
||||
|
||||
@@ -115,7 +115,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
let mut wraps = false;
|
||||
vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
|
||||
vectorcraft_doc::text::wrap_source_objects(&s.doc()?.doc, |_, sources| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
|
||||
if !wraps {
|
||||
out["warning"] = json!(NO_AREA_TYPE_BELOW);
|
||||
}
|
||||
|
||||
@@ -100,16 +100,9 @@ impl AutomationRoots {
|
||||
/// May the file or folder at `path` be read (or written)? It must lie inside one of the roots
|
||||
/// of that kind. `Err` says why not.
|
||||
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let roots = match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
};
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
let roots = self.of(access);
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
|
||||
};
|
||||
return Err(refused(roots, path, access));
|
||||
}
|
||||
// Resolving a path on another computer connects to it: unless a root is on a network
|
||||
// share, such a path is refused by its name before anything is looked up.
|
||||
@@ -120,12 +113,22 @@ impl AutomationRoots {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")),
|
||||
([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")),
|
||||
(_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))),
|
||||
(_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))),
|
||||
Err(refused(roots, path, access))
|
||||
}
|
||||
|
||||
/// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared with the roots as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
let roots = self.of(access);
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +160,24 @@ impl AutomationRoots {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `path` is refused `access` under `roots`, the roots of that kind.
|
||||
fn refused(roots: &[Root], path: &str, access: Access) -> String {
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"),
|
||||
Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"),
|
||||
};
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"),
|
||||
([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"),
|
||||
(_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")),
|
||||
(_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
|
||||
#[derive(Clone, Debug)]
|
||||
enum Scope {
|
||||
@@ -371,18 +392,34 @@ impl ScriptGate {
|
||||
also.check(path, access)?;
|
||||
}
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.contains(&real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
|
||||
/// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
if let Some(also) = &self.also {
|
||||
also.check_real(real, access)?;
|
||||
}
|
||||
if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Script file access denied: {}", real.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// May the place at the real path `real` be read (or written) through this gate alone?
|
||||
fn allows_real(&self, real: &Path, access: Access) -> bool {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(real) || self.write.allows(real),
|
||||
Access::Write => self.write.allows(real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,8 +499,7 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
check_write_unrecorded(path)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -474,6 +510,26 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without recording `path` as written.
|
||||
pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)
|
||||
}
|
||||
|
||||
/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been
|
||||
/// followed already (the folder a checked write has opened): it is compared as it is, so the folder
|
||||
/// is not looked up again by its path.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_write_real(real: &Path) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?;
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))
|
||||
}
|
||||
|
||||
/// Whether a write here is checked: roots are in force, or a script's command runs.
|
||||
pub(crate) fn writes_checked() -> bool {
|
||||
current().is_some() || in_script_command()
|
||||
}
|
||||
|
||||
/// A file's modification time and length; `None` when there is no file at `path`.
|
||||
type Stamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
@@ -1200,6 +1256,7 @@ mod tests {
|
||||
fn a_script_gate_does_not_write_over_a_read_only_file() {
|
||||
let (base, _) = folders("gate-read-only");
|
||||
let out = base.join("out/kept.svg");
|
||||
let _cleanup = ReadOnlyFixture { file: out.clone(), folder: base.clone() };
|
||||
std::fs::write(&out, "<svg/>").unwrap();
|
||||
let gate = ScriptGate {
|
||||
read: ScriptScope::default(),
|
||||
@@ -1218,14 +1275,47 @@ mod tests {
|
||||
assert!(document_write(), "an open document's file is written");
|
||||
let mut perms = std::fs::metadata(&out).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&out, perms.clone()).unwrap();
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
|
||||
assert!(check(&fresh).0, "a new file next to it is written");
|
||||
assert!(!document_write(), "also when it is an open document's file");
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Makes `file` writable again and removes `folder` when the test ends, a failed assertion
|
||||
/// included: Windows does not delete a read-only file.
|
||||
struct ReadOnlyFixture {
|
||||
file: PathBuf,
|
||||
folder: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for ReadOnlyFixture {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(meta) = std::fs::metadata(&self.file) {
|
||||
let mut perms = meta.permissions();
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
let _ = std::fs::set_permissions(&self.file, perms);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&self.folder);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_only_fixture_is_removed_when_its_test_fails() {
|
||||
let (base, _) = folders("read-only-fixture");
|
||||
let file = base.join("out/locked.svg");
|
||||
std::fs::write(&file, "<svg/>").unwrap();
|
||||
let failed = std::panic::catch_unwind(|| {
|
||||
let _cleanup = ReadOnlyFixture { file: file.clone(), folder: base.clone() };
|
||||
let mut perms = std::fs::metadata(&file).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&file, perms).unwrap();
|
||||
assert!(std::fs::metadata(&file).unwrap().permissions().readonly(), "the fixture is read-only");
|
||||
panic!("a failed assertion");
|
||||
});
|
||||
let payload = failed.err().unwrap_or_else(|| panic!("the closure did not panic"));
|
||||
assert_eq!(payload.downcast_ref::<&str>(), Some(&"a failed assertion"), "the test's own panic, not a setup failure");
|
||||
assert!(!base.exists(), "{} is left", base.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1017,9 +1017,16 @@ pub(super) fn after_kept_command(h: &Host) {
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
edit_item_with(h, item, |h| command(h, id, params))
|
||||
}
|
||||
|
||||
/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document
|
||||
/// is made active, so bounds it reads take in type that the switch measured again (in the
|
||||
/// document's own composite fonts, [`Session::set_active`]).
|
||||
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
paths::see_all_points(h);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
@@ -2554,8 +2561,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)?)))
|
||||
}
|
||||
|
||||
@@ -2627,20 +2638,45 @@ 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))?;
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
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 {
|
||||
edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
// 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);
|
||||
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(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -2674,18 +2710,29 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
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 {
|
||||
// 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")));
|
||||
}
|
||||
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);
|
||||
}
|
||||
let pct = size / now * 100.0;
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"});
|
||||
edit_item(h, item, "object.scale", &p)?;
|
||||
// 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"}))?;
|
||||
}
|
||||
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()
|
||||
@@ -435,13 +436,32 @@ 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 {
|
||||
if super::layers::is_scoped_paths(a) {
|
||||
return super::layers::paths_at(h, a);
|
||||
}
|
||||
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))))
|
||||
}
|
||||
|
||||
@@ -451,10 +471,15 @@ 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()))
|
||||
})
|
||||
}
|
||||
@@ -465,10 +490,13 @@ 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())),
|
||||
}
|
||||
}
|
||||
@@ -494,7 +522,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)?;
|
||||
|
||||
@@ -366,7 +366,12 @@ const AI_KEPT: &[(&str, Default)] = &[
|
||||
];
|
||||
|
||||
fn ai_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))]
|
||||
vec![
|
||||
("compatibility", text("Compatibility.ILLUSTRATOR19")),
|
||||
("compressed", Data::Bool(true)),
|
||||
("pdfCompatible", Data::Bool(true)),
|
||||
("embedICCProfile", Data::Bool(false)),
|
||||
]
|
||||
}
|
||||
|
||||
fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
@@ -1010,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));
|
||||
@@ -1027,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();
|
||||
|
||||
@@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8.
|
||||
fn decode(s: &str) -> String {
|
||||
pub(crate) fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
|
||||
@@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool {
|
||||
p.split(['/', '\\']).any(|name| name == "..")
|
||||
}
|
||||
|
||||
/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give
|
||||
/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…`
|
||||
/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a
|
||||
/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written
|
||||
/// misses. A `//host/share` path, and a form with a `..` name, is left out.
|
||||
pub fn uri_forms(value: &str, windows: bool) -> Vec<String> {
|
||||
if !value.starts_with('/') || value.starts_with("//") {
|
||||
return Vec::new();
|
||||
}
|
||||
let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| {
|
||||
let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
let letter = first.as_bytes();
|
||||
(letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char))
|
||||
});
|
||||
let mut forms = Vec::new();
|
||||
for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) {
|
||||
let decoded = crate::script::files::decode(form);
|
||||
for f in [decoded.as_str(), form] {
|
||||
if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) {
|
||||
forms.push(f.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// A real path as people read it.
|
||||
fn display(path: &Path) -> Arc<str> {
|
||||
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
|
||||
@@ -575,13 +601,18 @@ impl Files {
|
||||
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
|
||||
// A script given as text has no folder, and so no file it may read.
|
||||
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
|
||||
// Each candidate, and whether the scope's refusal passes it over.
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
|
||||
// Each candidate, and whether the scope's refusal passes it over. The path as written comes
|
||||
// first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in
|
||||
// URI notation are tried, and when none of them is read either, the error of the path as written stands.
|
||||
let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) };
|
||||
let mut literal_error = None;
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())];
|
||||
candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true)));
|
||||
if search && !path.is_absolute() {
|
||||
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
|
||||
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
|
||||
}
|
||||
for (candidate, passed_over_when_refused) in candidates {
|
||||
for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() {
|
||||
let Some(candidate) = candidate else { return Err(refused()) };
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
@@ -590,12 +621,22 @@ impl Files {
|
||||
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
|
||||
Ok(found) => return Ok(found),
|
||||
Err(ScriptRead::Missing) => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {
|
||||
if i == 0 {
|
||||
literal_error = Some(refused());
|
||||
}
|
||||
}
|
||||
Err(ScriptRead::Refused) => return Err(refused()),
|
||||
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
|
||||
Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => {
|
||||
literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}")));
|
||||
}
|
||||
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
|
||||
}
|
||||
}
|
||||
if let Some(error) = literal_error {
|
||||
return Err(error);
|
||||
}
|
||||
Err((FailKind::Error, format!("include file not found: {value}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -2198,6 +2208,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();
|
||||
@@ -2596,6 +2608,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();
|
||||
@@ -2677,6 +2690,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,
|
||||
@@ -2706,6 +2722,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
@@ -155,6 +155,89 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
|
||||
}
|
||||
|
||||
/// Type in a document in the back that the switch to that document measures again (here: not
|
||||
/// measured yet) is sized and moved by the bounds measured after the switch.
|
||||
#[test]
|
||||
fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the_switch() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
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 unmeasure = |s: &mut Session| {
|
||||
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 mut got = Vec::new();
|
||||
for (set, want) in
|
||||
[("t.width = 150; vc.log(t.width);", 150.0), ("t.height = 90; vc.log(t.height);", 90.0), ("t.top = 200; vc.log(t.top);", 200.0)]
|
||||
{
|
||||
unmeasure(&mut s);
|
||||
let out = log(&mut s, &format!("var t = app.documents[1].pageItems[0]; {set}"));
|
||||
got.push((set, out[0].as_f64().unwrap(), want));
|
||||
}
|
||||
for (set, got, want) in got {
|
||||
assert!((got - want).abs() < 1e-6, "{set} read {got}");
|
||||
}
|
||||
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]
|
||||
@@ -1672,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();
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
//! specifiers and paths, the run's limits, and errors at the file they are in.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::folder::Clock;
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
|
||||
@@ -217,8 +219,11 @@ fn script_module_is_listed_and_taken_by_path() {
|
||||
write(&root.join("tool.mjs"), "export var a = 1;");
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
// The listing's time limit is checked against a clock that does not move.
|
||||
s.set_script_listing_clock(Clock::Fixed(Duration::ZERO));
|
||||
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
|
||||
assert_eq!(listed["truncated"], false);
|
||||
// A script given as text is not a module, whatever its name.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() {
|
||||
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
|
||||
}
|
||||
|
||||
/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives
|
||||
/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded,
|
||||
/// after the path as written misses. Relative, share, device and `..` forms are not tried.
|
||||
#[test]
|
||||
fn include_paths_in_uri_notation_name_a_windows_drive() {
|
||||
use crate::script::include::uri_forms;
|
||||
assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]);
|
||||
assert_eq!(uri_forms("/d", true), ["D:/"]);
|
||||
assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]);
|
||||
assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]);
|
||||
assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty());
|
||||
for kept in
|
||||
["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"]
|
||||
{
|
||||
assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true));
|
||||
}
|
||||
assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name");
|
||||
// From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read.
|
||||
let dir = fresh_folder("uri forms");
|
||||
std::fs::write(dir.join("more.jsx"), "'more';").unwrap();
|
||||
let main = dir.join("main.jsx");
|
||||
std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}");
|
||||
assert_eq!(r["log"][1], "more", "{r}");
|
||||
// A file whose name holds `%20` as written is read before the decoded name.
|
||||
std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap();
|
||||
std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap();
|
||||
let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/");
|
||||
std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["literal"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2015");
|
||||
@@ -370,6 +404,37 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri
|
||||
assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("proxy");
|
||||
let write = |name: &str, text: &str| {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
json!({"path": p.to_string_lossy()})
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let names = "vc.log(typeof Proxy + ' ' + typeof Reflect);";
|
||||
let modern = s.execute("script.run", &write("names.js", names)).unwrap();
|
||||
assert_eq!(modern["log"], json!(["function object"]), "{modern}");
|
||||
let legacy = s.execute("script.run", &write("names.jsx", names)).unwrap();
|
||||
assert_eq!(legacy["log"], json!(["undefined undefined"]), "{legacy}");
|
||||
assert_eq!(run(&mut s, names).unwrap()["log"], json!(["undefined undefined"]));
|
||||
// A proxy given to the app is refused by name, and its traps do not run.
|
||||
let given = "var ran = false;\nvar p = new Proxy({}, { ownKeys: function () { ran = true; return []; } });\n\
|
||||
try { vc.run('document.list', p); } catch (e) { vc.log(e.name + ': ' + e.message); }\nvc.log(ran);";
|
||||
let r = s.execute("script.run", &write("given.js", given)).unwrap();
|
||||
let log = r["log"].as_array().unwrap();
|
||||
assert!(log[0].as_str().is_some_and(|m| m.starts_with("TypeError") && m.contains("is a proxy")), "{r}");
|
||||
assert_eq!(log[1], json!(false), "{r}");
|
||||
// An engine that `#targetengine` keeps gets both at its first `.js` run, after a `.jsx` one.
|
||||
let kept = format!("#targetengine proxykept\n{names}");
|
||||
let first = s.execute("script.run", &write("kept.jsx", &kept)).unwrap();
|
||||
assert_eq!(first["log"], json!(["undefined undefined"]), "{first}");
|
||||
let second = s.execute("script.run", &write("kept.js", &kept)).unwrap();
|
||||
assert_eq!(second["log"], json!(["function object"]), "{second}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2020");
|
||||
|
||||
@@ -10,13 +10,77 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
/// A test's folder, removed when the test ends, a failed assertion included. A read-only file in
|
||||
/// it, which Windows does not delete, is made writable first when the first removal fails.
|
||||
struct Workspace(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Workspace {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for Workspace {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Workspace {
|
||||
fn drop(&mut self) {
|
||||
if std::fs::remove_dir_all(&self.0).is_err() {
|
||||
make_writable(&self.0);
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the read-only flag of every file and folder in `path`, `path` included. Links are not
|
||||
/// followed.
|
||||
fn make_writable(path: &Path) {
|
||||
let Ok(meta) = std::fs::symlink_metadata(path) else { return };
|
||||
if meta.file_type().is_symlink() {
|
||||
return;
|
||||
}
|
||||
let mut perms = meta.permissions();
|
||||
if perms.readonly() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
let _ = std::fs::set_permissions(path, perms);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
for entry in std::fs::read_dir(path).into_iter().flatten().flatten() {
|
||||
make_writable(&entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
fn folder(name: &str) -> Workspace {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
Workspace(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
/// A test that fails leaves no folder behind, also when it made a file in it read-only.
|
||||
#[test]
|
||||
fn a_failed_test_leaves_no_folder() {
|
||||
let base = folder("failed");
|
||||
let path = base.to_path_buf();
|
||||
let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
|
||||
let locked = base.join("main/locked.txt");
|
||||
std::fs::write(&locked, b"x").unwrap();
|
||||
let mut perms = std::fs::metadata(&locked).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&locked, perms).unwrap();
|
||||
panic!("a failed assertion");
|
||||
}));
|
||||
assert!(failed.is_err());
|
||||
assert!(!path.exists(), "{} is left", path.display());
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
|
||||
@@ -212,6 +276,28 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves
|
||||
/// with it untouched.
|
||||
#[test]
|
||||
fn illustrator_save_options_start_at_illustrator19_compatibility() {
|
||||
let base = folder("aicompat");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new IllustratorSaveOptions(); vc.log(o.compatibility);\
|
||||
app.activeDocument.saveAs(new File({}), o);",
|
||||
quoted(&dir.join("a.ai"))
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!("Compatibility.ILLUSTRATOR19"));
|
||||
assert!(dir.join("a.ai").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or
|
||||
/// opened, so no file with a lossy copy of the name is touched.
|
||||
#[cfg(unix)]
|
||||
@@ -1185,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");
|
||||
@@ -1195,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
|
||||
}
|
||||
|
||||
+999
-25
File diff suppressed because it is too large.
Load diff
@@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob};
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
|
||||
+67
-10
@@ -6,7 +6,8 @@
|
||||
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`),
|
||||
//! the iterators of arrays, strings and `arguments` objects (in `iterator`), the generator
|
||||
//! objects' prototypes with `GeneratorFunction` (in `generator`), `Map`, `Set`, `WeakMap` and
|
||||
//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`).
|
||||
//! `WeakSet` (in `collections`), `ArrayBuffer`, `DataView` and the typed arrays (in `binary`), and
|
||||
//! `Proxy` and `Reflect` (in `reflect`).
|
||||
//!
|
||||
//! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object
|
||||
//! or property it makes is checked against the heap limit before it is made, so no built-in can
|
||||
@@ -21,8 +22,9 @@ mod global;
|
||||
pub(crate) mod iterator;
|
||||
mod json;
|
||||
mod math;
|
||||
mod object;
|
||||
pub(crate) mod object;
|
||||
pub(crate) mod promise;
|
||||
mod reflect;
|
||||
mod symbol;
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -197,6 +199,13 @@ pub(crate) fn install(interp: &mut Interp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `Proxy` and `Reflect` to a realm that does not have them yet, for a run with
|
||||
/// [`crate::Options::es2015`] in a realm made without it. A `Proxy` or `Reflect` global that an
|
||||
/// earlier run defined stays as it is.
|
||||
pub(crate) fn install_es2015(interp: &mut Interp) -> JsResult<()> {
|
||||
if interp.es2015_installed { Ok(()) } else { reflect::install(interp, true) }
|
||||
}
|
||||
|
||||
fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
let object_proto = alloc(interp, Class::Ordinary, None);
|
||||
interp.intrinsics.object_proto = object_proto;
|
||||
@@ -231,6 +240,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
data(interp, global, "eval", Value::Object(eval), HIDDEN)?;
|
||||
|
||||
let object = native(interp, "Object", object_ctor, 1, NativeKind::Plain, true)?;
|
||||
interp.intrinsics.object_ctor = object;
|
||||
constructor(interp, "Object", object, object_proto)?;
|
||||
method(interp, object_proto, "toString", object_to_string, 0)?;
|
||||
method(interp, object_proto, "toLocaleString", object_to_locale_string, 0)?;
|
||||
@@ -275,6 +285,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
|
||||
promise::install(interp)?;
|
||||
collections::install(interp)?;
|
||||
binary::install(interp)?;
|
||||
reflect::install(interp, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -536,6 +547,18 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J
|
||||
let class = match &this {
|
||||
Value::Undefined => "Undefined",
|
||||
Value::Null => "Null",
|
||||
// A proxy reads as an array when its target is one, and a revoked proxy is a
|
||||
// `TypeError` (ECMA-262 2020 section 19.1.3.6).
|
||||
Value::Object(o) if interp.is_proxy(*o) => {
|
||||
let array = interp.is_array(&this)?;
|
||||
// `Symbol.toStringTag` is read through the proxy to its target.
|
||||
let o = *o;
|
||||
if let Some(tag) = interp.rooted(std::slice::from_ref(&this), |i| i.string_tag_of(o))? {
|
||||
let roots = [Value::String(tag.clone())];
|
||||
return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]"));
|
||||
}
|
||||
if array { "Array" } else { interp.heap.object(o).map_or("Object", |o| o.class.name()) }
|
||||
}
|
||||
_ => {
|
||||
let o = interp.to_object(&this)?;
|
||||
// The tag's getter can run script that collects, and the object of a primitive is
|
||||
@@ -607,17 +630,33 @@ fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
/// `Object.prototype.isPrototypeOf` (section 15.2.4.6). The chain is read with
|
||||
/// [[GetPrototypeOf]], so a proxy on it answers with its trap; the object being read and `this`
|
||||
/// stay rooted.
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let Value::Object(mut v) = arg(args, 0) else { return Ok(Value::Bool(false)) };
|
||||
let o = interp.to_object(&this)?;
|
||||
while let Some(p) = interp.heap.object(v).and_then(|v| v.proto) {
|
||||
let slot = interp.temp_roots.len();
|
||||
interp.temp_roots.extend([Value::Object(o), Value::Object(v)]);
|
||||
let r = loop {
|
||||
let p = match interp.get_prototype_of(v) {
|
||||
Ok(Some(p)) => p,
|
||||
Ok(None) => break Ok(Value::Bool(false)),
|
||||
Err(e) => break Err(e),
|
||||
};
|
||||
if p == o {
|
||||
return Ok(Value::Bool(true));
|
||||
break Ok(Value::Bool(true));
|
||||
}
|
||||
v = p;
|
||||
interp.use_fuel()?;
|
||||
}
|
||||
Ok(Value::Bool(false))
|
||||
if let Some(root) = interp.temp_roots.get_mut(slot + 1) {
|
||||
*root = Value::Object(v);
|
||||
}
|
||||
if let Err(e) = interp.use_fuel() {
|
||||
break Err(e);
|
||||
}
|
||||
};
|
||||
interp.temp_roots.truncate(slot);
|
||||
r
|
||||
}
|
||||
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -703,6 +742,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) ->
|
||||
Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Bound { .. }) => "function () { [native code] }".to_string(),
|
||||
None if interp.is_callable(&this) => "function () { [native code] }".to_string(),
|
||||
None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")),
|
||||
};
|
||||
Ok(Value::str(&text))
|
||||
@@ -716,13 +756,30 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
|
||||
let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into();
|
||||
// With ECMAScript 2015 the bound function inherits from the target's prototype, read before
|
||||
// `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function
|
||||
// inherits from %GeneratorFunction.prototype%.
|
||||
let target_proto = interp.heap.object(target).and_then(|o| o.proto);
|
||||
// inherits from %GeneratorFunction.prototype%. A proxy's prototype comes from its
|
||||
// `getPrototypeOf` trap, and it stays reachable while `length` and `name` are read.
|
||||
let target_proto = if interp.options.es2015 { interp.get_prototype_of(target)? } else { interp.heap.object(target).and_then(|o| o.proto) };
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(target_proto.map(Value::Object));
|
||||
let r = bind_from(interp, &this, target, target_proto, bound_this, bound_args);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// The steps of `Function.prototype.bind` after the target's prototype is read.
|
||||
fn bind_from(
|
||||
interp: &mut Interp,
|
||||
this: &Value,
|
||||
target: ObjId,
|
||||
target_proto: Option<ObjId>,
|
||||
bound_this: Value,
|
||||
bound_args: Rc<[Value]>,
|
||||
) -> JsResult<Value> {
|
||||
// A host function's `length` is an ordinary property a script can set, so it is converted
|
||||
// to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is
|
||||
// read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run.
|
||||
let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some();
|
||||
let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined };
|
||||
let length_value = if has_length { interp.get_from(target, &key("length"), this)? } else { Value::Undefined };
|
||||
let target_length = match length_value {
|
||||
Value::Number(n) if n.is_nan() => 0.0,
|
||||
Value::Number(n) => n.trunc(),
|
||||
|
||||
@@ -107,16 +107,20 @@ fn index_count(class: &Class) -> usize {
|
||||
}
|
||||
|
||||
/// The objects of the prototype chain from `obj`, with how many properties (and String object or
|
||||
/// typed array indices) each holds.
|
||||
fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> {
|
||||
/// typed array indices) each holds, or `None` when a proxy is on the chain: its traps decide which
|
||||
/// indices it has, so every index is visited.
|
||||
fn chain(interp: &Interp, obj: ObjId) -> Option<Vec<(ObjId, usize)>> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = Some(obj);
|
||||
while let Some(id) = cur {
|
||||
if interp.is_proxy(id) {
|
||||
return None;
|
||||
}
|
||||
let Some(o) = interp.heap.object(id) else { break };
|
||||
out.push((id, o.props.len().saturating_add(index_count(&o.class))));
|
||||
cur = o.proto;
|
||||
}
|
||||
out
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl Indices {
|
||||
@@ -124,10 +128,13 @@ impl Indices {
|
||||
let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None };
|
||||
// An object of a host class with an indexer holds its elements in the host, not in
|
||||
// properties, so every index of the range is visited.
|
||||
if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() {
|
||||
let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add);
|
||||
if hi.saturating_sub(lo) > DENSE_SPAN
|
||||
&& interp.host_indexer(obj)?.is_none()
|
||||
&& let Some(links) = chain(interp, obj)
|
||||
{
|
||||
let present: usize = links.iter().map(|(_, n)| *n).fold(0, usize::saturating_add);
|
||||
if hi - lo > (present as u64).saturating_mul(8) {
|
||||
it.sparse = Some(it.gather(interp)?);
|
||||
it.sparse = it.gather(interp)?;
|
||||
}
|
||||
}
|
||||
Ok(it)
|
||||
@@ -141,12 +148,13 @@ impl Indices {
|
||||
Self::new(interp, obj, lo, hi, false, vec![Map::Shift(0)])
|
||||
}
|
||||
|
||||
/// Lists the indices left to visit from the properties of the object and its prototypes.
|
||||
/// Each property takes a unit of fuel.
|
||||
fn gather(&self, interp: &mut Interp) -> JsResult<Sparse> {
|
||||
/// Lists the indices left to visit from the properties of the object and its prototypes, or
|
||||
/// gives `None` when a proxy is on the chain. Each property takes a unit of fuel.
|
||||
fn gather(&self, interp: &mut Interp) -> JsResult<Option<Sparse>> {
|
||||
let epoch = interp.heap.index_epoch;
|
||||
let mut list: Vec<u64> = Vec::new();
|
||||
for (id, n) in chain(interp, self.obj) {
|
||||
let Some(links) = chain(interp, self.obj) else { return Ok(None) };
|
||||
for (id, n) in links {
|
||||
for _ in 0..n {
|
||||
interp.use_fuel()?;
|
||||
}
|
||||
@@ -174,7 +182,7 @@ impl Indices {
|
||||
list.sort_unstable_by(|a, b| b.cmp(a));
|
||||
}
|
||||
list.dedup();
|
||||
Ok(Sparse { list, pos: 0, epoch })
|
||||
Ok(Some(Sparse { list, pos: 0, epoch }))
|
||||
}
|
||||
|
||||
/// The next index to visit; it takes a unit of fuel.
|
||||
@@ -183,7 +191,7 @@ impl Indices {
|
||||
return Ok(None);
|
||||
}
|
||||
if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) {
|
||||
self.sparse = Some(self.gather(interp)?);
|
||||
self.sparse = self.gather(interp)?;
|
||||
}
|
||||
let k = match &mut self.sparse {
|
||||
None if self.ascending => self.lo,
|
||||
@@ -250,10 +258,10 @@ fn array_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResul
|
||||
})
|
||||
}
|
||||
|
||||
/// `Array.isArray` (section 15.4.3.2).
|
||||
/// `Array.isArray` (section 15.4.3.2). A proxy whose target is an array is one, and a revoked
|
||||
/// proxy is a `TypeError` (ECMA-262 2020 section 7.2.2).
|
||||
fn is_array(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let a = arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Array { .. }));
|
||||
Ok(Value::Bool(a))
|
||||
interp.is_array(&arg(args, 0)).map(Value::Bool)
|
||||
}
|
||||
|
||||
// ---- conversions ----
|
||||
@@ -381,13 +389,30 @@ 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()?;
|
||||
let spread = e.as_object().filter(|&id| interp.heap.object(id).is_some_and(|x| matches!(x.class, Class::Array { .. })));
|
||||
// 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"));
|
||||
}
|
||||
create_at(interp, a, n as f64, e)?;
|
||||
n += 1;
|
||||
continue;
|
||||
};
|
||||
let len = u64::from(length_of(interp, e)?);
|
||||
let len = super::collections::length_of(interp, e)?;
|
||||
if len > 9_007_199_254_740_991 - n {
|
||||
return Err(interp.type_error("concat exceeds the maximum safe length"));
|
||||
}
|
||||
if len > interp.fuel && chain(interp, e).is_none() {
|
||||
return Err(Abrupt::Limit(crate::LimitKind::Fuel));
|
||||
}
|
||||
let mut it = Indices::up(interp, e, 0, len)?;
|
||||
while let Some(k) = it.next(interp)? {
|
||||
if let Some(v) = element(interp, e, k)? {
|
||||
|
||||
@@ -342,6 +342,11 @@ pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does the numeric name `n` name an element of the typed array `id` (IsValidIntegerIndex)?
|
||||
pub(crate) fn is_element(interp: &Interp, id: ObjId, n: f64) -> bool {
|
||||
view_of(interp, id).is_some_and(|view| valid_index(n, view.length).is_some())
|
||||
}
|
||||
|
||||
/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the
|
||||
/// configurable elements of later editions).
|
||||
pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
@@ -424,8 +429,48 @@ fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing
|
||||
if !constructing {
|
||||
return Err(interp.type_error("ArrayBuffer must be called with new"));
|
||||
}
|
||||
array_buffer_with_target(interp, args, None)
|
||||
}
|
||||
|
||||
fn array_buffer_with_target(interp: &mut Interp, args: &[Value], new_target: Option<ObjId>) -> JsResult<Value> {
|
||||
let len = to_index(interp, &arg(args, 0), "the length")?;
|
||||
new_buffer(interp, len, 0).map(Value::Object)
|
||||
let fallback = interp.intrinsics.es2015.array_buffer_proto;
|
||||
let proto = match new_target {
|
||||
Some(nt) => interp.prototype_from(nt, fallback)?,
|
||||
None => fallback,
|
||||
};
|
||||
interp.rooted(&[Value::Object(proto)], |i| {
|
||||
let buffer = new_buffer(i, len, 0)?;
|
||||
i.object_mut(buffer)?.proto = Some(proto);
|
||||
Ok(Value::Object(buffer))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn defers_prototype(interp: &Interp, intrinsic: Option<ObjId>, args: &[Value]) -> bool {
|
||||
let i = &interp.intrinsics.es2015;
|
||||
intrinsic.is_some_and(|p| {
|
||||
p == i.array_buffer_proto || p == i.data_view_proto || (i.typed_protos.contains(&p) && !matches!(arg(args, 0), Value::Object(_)))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn construct_with_target(interp: &mut Interp, intrinsic: Option<ObjId>, args: &[Value], new_target: ObjId) -> JsResult<Value> {
|
||||
let i = &interp.intrinsics.es2015;
|
||||
if intrinsic == Some(i.array_buffer_proto) {
|
||||
return array_buffer_with_target(interp, args, Some(new_target));
|
||||
}
|
||||
if intrinsic == Some(i.data_view_proto) {
|
||||
return data_view_with_target(interp, args, Some(new_target));
|
||||
}
|
||||
let elem = Elem::ALL.into_iter().find(|e| intrinsic == Some(typed_proto(interp, *e)));
|
||||
let Some(elem) = elem else { return Err(Abrupt::Internal("not a binary constructor".into())) };
|
||||
let len = to_index(interp, &arg(args, 0), "the length")?;
|
||||
let fallback = typed_proto(interp, elem);
|
||||
let proto = interp.prototype_from(new_target, fallback)?;
|
||||
interp.rooted(&[Value::Object(proto)], |i| {
|
||||
let view = new_typed(i, elem, len)?;
|
||||
i.object_mut(view)?.proto = Some(proto);
|
||||
Ok(Value::Object(view))
|
||||
})
|
||||
}
|
||||
|
||||
/// `ArrayBuffer.isView` (section 24.1.3.1).
|
||||
@@ -511,6 +556,10 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b
|
||||
if !constructing {
|
||||
return Err(interp.type_error("DataView must be called with new"));
|
||||
}
|
||||
data_view_with_target(interp, args, None)
|
||||
}
|
||||
|
||||
fn data_view_with_target(interp: &mut Interp, args: &[Value], new_target: Option<ObjId>) -> JsResult<Value> {
|
||||
let buffer = match arg(args, 0).as_object() {
|
||||
Some(o) if bytes(interp, o).is_some() => o,
|
||||
_ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")),
|
||||
@@ -527,8 +576,12 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b
|
||||
if offset.saturating_add(view_len) > len {
|
||||
return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer"));
|
||||
}
|
||||
interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?;
|
||||
let proto = interp.intrinsics.es2015.data_view_proto;
|
||||
let fallback = interp.intrinsics.es2015.data_view_proto;
|
||||
let proto = match new_target {
|
||||
Some(nt) => interp.prototype_from(nt, fallback)?,
|
||||
None => fallback,
|
||||
};
|
||||
interp.rooted(&[Value::Object(buffer), Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?;
|
||||
let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 };
|
||||
Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto)))
|
||||
}
|
||||
@@ -771,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) {
|
||||
@@ -783,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() {
|
||||
|
||||
@@ -250,7 +250,7 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo
|
||||
}
|
||||
|
||||
/// A new collection object of `class` with `proto`, filled from `args[0]`.
|
||||
fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult<Value> {
|
||||
pub(crate) fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult<Value> {
|
||||
if !constructing {
|
||||
return Err(interp.type_error(&format!("{name} must be called with new")));
|
||||
}
|
||||
@@ -264,6 +264,21 @@ fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str
|
||||
Ok(Value::Object(o))
|
||||
}
|
||||
|
||||
pub(crate) fn constructor_class(interp: &Interp, proto: ObjId) -> Option<(&'static str, Class)> {
|
||||
let i = &interp.intrinsics.es2015;
|
||||
if proto == i.map_proto {
|
||||
Some(("Map", Class::Map(Box::default())))
|
||||
} else if proto == i.set_proto {
|
||||
Some(("Set", Class::Set(Box::default())))
|
||||
} else if proto == i.weak_map_proto {
|
||||
Some(("WeakMap", Class::WeakMap(Box::default())))
|
||||
} else if proto == i.weak_set_proto {
|
||||
Some(("WeakSet", Class::WeakSet(Box::default())))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
|
||||
let proto = interp.intrinsics.es2015.map_proto;
|
||||
construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer};
|
||||
use super::{Builder, ELEMENT_BYTES, arg, data, key_of, method, new_array, new_string, to_integer};
|
||||
use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes};
|
||||
use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult};
|
||||
use crate::string_builtins::flat_charged;
|
||||
@@ -326,6 +326,7 @@ struct Walk {
|
||||
name: Key,
|
||||
val: Value,
|
||||
keys: Vec<Key>,
|
||||
_held_keys: Option<crate::interp::HeldBytes>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
@@ -335,23 +336,35 @@ fn enter(interp: &mut Interp, holder: ObjId, name: Key) -> JsResult<Walk> {
|
||||
let val = interp.get_from(holder, &name, &Value::Object(holder))?;
|
||||
interp.temp_roots.push(val.clone());
|
||||
let mut keys = Vec::new();
|
||||
let mut held_keys = None;
|
||||
if let Value::Object(o) = val {
|
||||
if interp.heap.object(o).is_some_and(|x| matches!(x.class, Class::Array { .. })) {
|
||||
let len = length_of(interp, o)?;
|
||||
interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?;
|
||||
if interp.is_array(&val)? {
|
||||
let len = super::collections::length_of(interp, o)?;
|
||||
if len > (interp.limits.heap_bytes / crate::heap::PROP_BYTES) as u64 {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Heap));
|
||||
}
|
||||
if len > interp.fuel {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel));
|
||||
}
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
held.add(interp, (len as usize).saturating_mul(crate::heap::PROP_BYTES))?;
|
||||
held_keys = Some(held);
|
||||
keys = Vec::with_capacity(len as usize);
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
keys.push(key_of(f64::from(i)));
|
||||
keys.push(key_of(i as f64));
|
||||
}
|
||||
} else {
|
||||
for k in interp.own_keys(o)? {
|
||||
let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?;
|
||||
held_keys = Some(held);
|
||||
for k in names {
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
keys.push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Walk { holder, name, val, keys, next: 0 })
|
||||
Ok(Walk { holder, name, val, keys, _held_keys: held_keys, next: 0 })
|
||||
}
|
||||
|
||||
/// Walks the parsed value bottom-up, calling the reviver for each property and replacing or
|
||||
@@ -401,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>,
|
||||
}
|
||||
|
||||
@@ -415,6 +429,7 @@ enum Item {
|
||||
struct Writing {
|
||||
obj: ObjId,
|
||||
keys: Vec<Key>,
|
||||
_held_keys: Option<crate::interp::HeldBytes>,
|
||||
array: bool,
|
||||
next: usize,
|
||||
count: usize,
|
||||
@@ -460,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.heap.object(*r).is_some_and(|o| matches!(o.class, Class::Array { .. })) {
|
||||
s.properties = Some(property_list(interp, *r)?);
|
||||
} else if interp.is_array(replacer)? {
|
||||
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());
|
||||
@@ -481,13 +498,18 @@ 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>> {
|
||||
let len = length_of(interp, r)?;
|
||||
/// 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));
|
||||
}
|
||||
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 {
|
||||
interp.use_fuel()?;
|
||||
let v = interp.get_from(r, &key_of(f64::from(i)), &Value::Object(r))?;
|
||||
let v = interp.get_from(r, &key_of(i as f64), &Value::Object(r))?;
|
||||
let item = match &v {
|
||||
Value::String(s) => Some(s.clone()),
|
||||
Value::Number(_) => Some(interp.primitive_to_str(&v)),
|
||||
@@ -511,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
|
||||
@@ -628,26 +651,35 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J
|
||||
if w.open.contains(&o) {
|
||||
return Err(interp.type_error("JSON.stringify cannot write a structure that contains itself"));
|
||||
}
|
||||
let array = interp.heap.object(o).is_some_and(|x| matches!(x.class, Class::Array { .. }));
|
||||
// A proxy whose target is an array is written as one (ECMA-262 2020 section 24.5.2.1).
|
||||
let array = interp.is_array(&Value::Object(o))?;
|
||||
let mut held_keys = None;
|
||||
let keys = if array {
|
||||
let len = length_of(interp, o)?;
|
||||
let len = super::collections::length_of(interp, o)?;
|
||||
// Every element is written as at least `null` and a comma, so a length that cannot fit
|
||||
// is refused before anything is listed.
|
||||
if u64::from(len).saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 {
|
||||
if len.saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Heap));
|
||||
}
|
||||
interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?;
|
||||
if len > interp.fuel {
|
||||
return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel));
|
||||
}
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
held.add(interp, (len as usize).saturating_mul(crate::heap::PROP_BYTES))?;
|
||||
held_keys = Some(held);
|
||||
let mut keys = Vec::with_capacity(len as usize);
|
||||
for i in 0..len {
|
||||
interp.use_fuel()?;
|
||||
keys.push(key_of(f64::from(i)));
|
||||
keys.push(key_of(i as f64));
|
||||
}
|
||||
keys
|
||||
} else if let Some(list) = &settings.properties {
|
||||
list.clone()
|
||||
} else {
|
||||
let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?;
|
||||
held_keys = Some(held);
|
||||
let mut keys = Vec::new();
|
||||
for k in interp.own_keys(o)? {
|
||||
for k in names {
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
keys.push(k);
|
||||
}
|
||||
@@ -658,7 +690,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J
|
||||
let stepback = w.indent.len();
|
||||
w.indent.extend_from_slice(&settings.gap);
|
||||
w.out.push_str(interp, if array { "[" } else { "{" })?;
|
||||
w.stack.push(Writing { obj: o, keys, array, next: 0, count: 0, stepback });
|
||||
w.stack.push(Writing { obj: o, keys, _held_keys: held_keys, array, next: 0, count: 0, stepback });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use super::{ELEMENT_BYTES, arg, create_at, method, new_array};
|
||||
use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key};
|
||||
use crate::interp::{Desc, Interp, JsResult};
|
||||
use crate::proxy::desc_values;
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value};
|
||||
|
||||
@@ -23,7 +24,11 @@ pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> {
|
||||
method(interp, object, "isSealed", is_sealed, 1)?;
|
||||
method(interp, object, "isFrozen", is_frozen, 1)?;
|
||||
method(interp, object, "isExtensible", is_extensible, 1)?;
|
||||
method(interp, object, "keys", keys, 1)
|
||||
method(interp, object, "keys", keys, 1)?;
|
||||
if interp.options.es2015 {
|
||||
method(interp, object, "setPrototypeOf", set_prototype_of, 2)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_object(interp: &mut Interp, v: &Value, function: &str) -> JsResult<ObjId> {
|
||||
@@ -33,16 +38,8 @@ fn require_object(interp: &mut Interp, v: &Value, function: &str) -> JsResult<Ob
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a descriptor holds, to keep them reachable while more JavaScript runs.
|
||||
fn desc_values(desc: &Desc) -> Vec<Value> {
|
||||
let mut out: Vec<Value> = desc.value.iter().cloned().collect();
|
||||
out.extend(desc.get.flatten().map(Value::Object));
|
||||
out.extend(desc.set.flatten().map(Value::Object));
|
||||
out
|
||||
}
|
||||
|
||||
/// ToPropertyDescriptor (section 8.10.5).
|
||||
pub(super) fn to_desc(interp: &mut Interp, v: &Value) -> JsResult<Desc> {
|
||||
pub(crate) fn to_desc(interp: &mut Interp, v: &Value) -> JsResult<Desc> {
|
||||
let Value::Object(o) = v else { return Err(interp.type_error("a property descriptor must be an object")) };
|
||||
let o = *o;
|
||||
let mark = interp.temp_roots.len();
|
||||
@@ -88,8 +85,41 @@ fn read_desc(interp: &mut Interp, o: ObjId) -> JsResult<Desc> {
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
/// FromPropertyDescriptor (section 8.10.4).
|
||||
fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult<Value> {
|
||||
/// FromPropertyDescriptor (ECMA-262 2020 section 6.2.5.4) of a descriptor that may leave fields
|
||||
/// out: an object with the fields `desc` has, in the order `value`, `writable`, `get`, `set`,
|
||||
/// `enumerable`, `configurable`.
|
||||
pub(crate) fn from_desc(interp: &mut Interp, desc: &Desc) -> JsResult<Value> {
|
||||
let roots = desc_values(desc);
|
||||
interp.rooted(&roots, |interp| interp.reserve_heap(OBJECT_BYTES + 6 * ELEMENT_BYTES))?;
|
||||
let o = interp.new_object();
|
||||
let fields = [
|
||||
("value", desc.value.clone()),
|
||||
("writable", desc.writable.map(Value::Bool)),
|
||||
("get", desc.get.map(|g| g.map_or(Value::Undefined, Value::Object))),
|
||||
("set", desc.set.map(|s| s.map_or(Value::Undefined, Value::Object))),
|
||||
("enumerable", desc.enumerable.map(Value::Bool)),
|
||||
("configurable", desc.configurable.map(Value::Bool)),
|
||||
];
|
||||
for (name, v) in fields {
|
||||
if let Some(v) = v {
|
||||
interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(o))
|
||||
}
|
||||
|
||||
/// FromPropertyDescriptor (section 8.10.4). The property's values stay rooted while the
|
||||
/// descriptor object is made, since a proxy's trap can give values no other object holds.
|
||||
pub(crate) fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult<Value> {
|
||||
let roots: Vec<Value> = match prop {
|
||||
Prop::Data { value, .. } => vec![value.clone()],
|
||||
Prop::Accessor { get, set, .. } => get.iter().chain(set).map(|f| Value::Object(*f)).collect(),
|
||||
};
|
||||
interp.rooted(&roots, |interp| descriptor_object(interp, prop))
|
||||
}
|
||||
|
||||
/// The descriptor object of `prop`, whose values the caller keeps rooted.
|
||||
fn descriptor_object(interp: &mut Interp, prop: &Prop) -> JsResult<Value> {
|
||||
interp.reserve_heap(OBJECT_BYTES + 4 * ELEMENT_BYTES)?;
|
||||
let o = interp.new_object();
|
||||
let flags = prop.flags();
|
||||
@@ -109,7 +139,7 @@ fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult<Value> {
|
||||
}
|
||||
|
||||
/// An array of the names, kept reachable while it is filled.
|
||||
fn names_array(interp: &mut Interp, names: Vec<Key>) -> JsResult<Value> {
|
||||
pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator<Item = Key>) -> JsResult<Value> {
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, k) in names.into_iter().enumerate() {
|
||||
@@ -122,16 +152,24 @@ fn names_array(interp: &mut Interp, names: Vec<Key>) -> JsResult<Value> {
|
||||
|
||||
/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section
|
||||
/// 9.1.11).
|
||||
fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<Vec<PropKey>> {
|
||||
let mut keys: Vec<PropKey> = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect();
|
||||
keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym));
|
||||
Ok(keys)
|
||||
fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<(Vec<PropKey>, crate::interp::HeldBytes)> {
|
||||
Ok(interp.own_keys_and_symbols(o)?.into_prop_keys())
|
||||
}
|
||||
|
||||
/// Returns the Symbol roots for a property-key list.
|
||||
fn prop_key_roots(keys: &[PropKey]) -> Vec<Value> {
|
||||
keys.iter()
|
||||
.filter_map(|k| match k {
|
||||
PropKey::Sym(s) => Some(Value::Symbol(s.clone())),
|
||||
PropKey::Str(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `Object.getPrototypeOf` (section 15.2.3.2).
|
||||
fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
Ok(interp.heap.object(o).and_then(|o| o.proto).map_or(Value::Null, Value::Object))
|
||||
Ok(interp.rooted(&[Value::Object(o)], |interp| interp.get_prototype_of(o))?.map_or(Value::Null, Value::Object))
|
||||
}
|
||||
|
||||
/// `Object.getOwnPropertyDescriptor` (section 15.2.3.3).
|
||||
@@ -172,6 +210,28 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
|
||||
Ok(Value::Object(o))
|
||||
}
|
||||
|
||||
/// `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18): `o` with `proto` as its
|
||||
/// prototype. `undefined` or `null` for `o`, or a `proto` that is neither an object nor `null`,
|
||||
/// is a `TypeError`; any other primitive `o` is returned unchanged. An object whose
|
||||
/// [[SetPrototypeOf]] gives `false`, a proxy's `setPrototypeOf` trap included, is a `TypeError`
|
||||
/// too.
|
||||
fn set_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = arg(args, 0);
|
||||
if matches!(o, Value::Undefined | Value::Null) {
|
||||
return Err(interp.type_error("Object.setPrototypeOf was given undefined or null"));
|
||||
}
|
||||
let proto = match arg(args, 1) {
|
||||
Value::Object(p) => Some(p),
|
||||
Value::Null => None,
|
||||
_ => return Err(interp.type_error("Object.setPrototypeOf's prototype must be an object or null")),
|
||||
};
|
||||
let Value::Object(id) = o else { return Ok(o) };
|
||||
if !interp.set_prototype_of(id, proto)? {
|
||||
return Err(interp.type_error("Object.setPrototypeOf could not set the prototype"));
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// `Object.defineProperty` (section 15.2.3.6).
|
||||
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = require_object(interp, &arg(args, 0), "defineProperty")?;
|
||||
@@ -198,7 +258,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
|
||||
interp.temp_roots.push(Value::Object(p));
|
||||
let r = (|| {
|
||||
let mut descs = Vec::new();
|
||||
let keys = own_prop_keys(interp, p)?;
|
||||
let (keys, _held) = own_prop_keys(interp, p)?;
|
||||
// A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted
|
||||
// until they are defined on `o`.
|
||||
for k in &keys {
|
||||
@@ -227,33 +287,33 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
|
||||
r
|
||||
}
|
||||
|
||||
/// Makes every own property non-configurable, and with `freeze` every data property read-only,
|
||||
/// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9).
|
||||
/// SetIntegrityLevel (ECMA-262 2020 section 7.3.14): makes the object non-extensible, then every
|
||||
/// own property non-configurable, and with `freeze` every data property read-only (sections
|
||||
/// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`.
|
||||
fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = v else { return Ok(v) };
|
||||
for k in own_prop_keys(interp, o)? {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
let mut desc = match &prop {
|
||||
Prop::Data { value, flags } => Desc::data(value.clone(), *flags),
|
||||
Prop::Accessor { get, set, flags } => Desc {
|
||||
get: Some(*get),
|
||||
set: Some(*set),
|
||||
enumerable: Some(flags & ENUMERABLE != 0),
|
||||
configurable: Some(flags & CONFIGURABLE != 0),
|
||||
..Desc::default()
|
||||
},
|
||||
};
|
||||
desc.configurable = Some(false);
|
||||
if freeze && desc.is_data() {
|
||||
desc.writable = Some(false);
|
||||
if !interp.prevent_extensions(o)? {
|
||||
let what = if freeze { "frozen" } else { "sealed" };
|
||||
return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible")));
|
||||
}
|
||||
let (keys, _held) = own_prop_keys(interp, o)?;
|
||||
let roots = prop_key_roots(&keys);
|
||||
interp.rooted(&roots, |interp| {
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let desc = if freeze {
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
match prop {
|
||||
Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() },
|
||||
Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() },
|
||||
}
|
||||
} else {
|
||||
Desc { configurable: Some(false), ..Desc::default() }
|
||||
};
|
||||
interp.define_own_pk(o, k, &desc, true)?;
|
||||
}
|
||||
interp.define_own_pk(o, k, &desc, true)?;
|
||||
}
|
||||
if let Some(obj) = interp.heap.object_mut(o) {
|
||||
obj.extensible = false;
|
||||
}
|
||||
Ok(Value::Object(o))
|
||||
Ok(Value::Object(o))
|
||||
})
|
||||
}
|
||||
|
||||
fn seal(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -268,26 +328,34 @@ fn freeze(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
|
||||
fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let v = arg(args, 0);
|
||||
if let Value::Object(o) = v
|
||||
&& let Some(obj) = interp.heap.object_mut(o)
|
||||
&& !interp.prevent_extensions(o)?
|
||||
{
|
||||
obj.extensible = false;
|
||||
return Err(interp.type_error("Object.preventExtensions: the proxy did not stop being extensible"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether no own property is configurable (and with `frozen`, no data property is writable)
|
||||
/// and the object is not extensible (sections 15.2.3.11 and 15.2.3.12).
|
||||
/// TestIntegrityLevel (ECMA-262 2020 section 7.3.15): whether the object is not extensible and no
|
||||
/// own property is configurable (and with `frozen`, no data property is writable) (sections
|
||||
/// 15.2.3.11 and 15.2.3.12).
|
||||
fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = v else { return Ok(Value::Bool(true)) };
|
||||
let o = *o;
|
||||
for k in own_prop_keys(interp, o)? {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
if interp.is_extensible(o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
Ok(Value::Bool(!interp.heap.object(o).is_some_and(|o| o.extensible)))
|
||||
let (keys, _held) = own_prop_keys(interp, o)?;
|
||||
let roots = prop_key_roots(&keys);
|
||||
interp.rooted(&roots, |interp| {
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
}
|
||||
Ok(Value::Bool(true))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -301,20 +369,21 @@ fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult
|
||||
/// `Object.isExtensible` (section 15.2.3.13).
|
||||
fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = arg(args, 0) else { return Ok(Value::Bool(false)) };
|
||||
Ok(Value::Bool(interp.heap.object(o).is_some_and(|o| o.extensible)))
|
||||
interp.is_extensible(o).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Object.keys` (section 15.2.3.14).
|
||||
fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let crate::interp::HeldKeys { keys, held, .. } = interp.own_keys(o)?;
|
||||
let mut names = Vec::new();
|
||||
for k in interp.own_keys(o)? {
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
names.push(k);
|
||||
}
|
||||
}
|
||||
names_array(interp, names)
|
||||
names_array(interp, crate::interp::HeldKeys { keys: names, syms: Vec::new(), ordered: None, held })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
//! `Proxy` and `Reflect` (ECMA-262 2020 sections 26.2 and 26.1,
|
||||
//! <https://262.ecma-international.org/11.0/#sec-reflection>), installed in a realm with
|
||||
//! [`crate::Options::es2015`]. The proxy objects themselves are in `crate::proxy`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::object::{from_prop, to_desc};
|
||||
use super::{arg, create_at, method, native, new_array};
|
||||
use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key};
|
||||
use crate::interp::{Desc, Interp, JsResult};
|
||||
use crate::proxy::desc_values;
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value};
|
||||
|
||||
/// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them
|
||||
/// after earlier runs, a global of the same name that a script defined stays as it is. Each
|
||||
/// global is defined after its functions, so an install that stops part way leaves no global
|
||||
/// that a later install would keep without them.
|
||||
pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> {
|
||||
let global = interp.global;
|
||||
if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) {
|
||||
let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?;
|
||||
// Naming a new method can collect, and the constructor is reachable from nowhere else
|
||||
// until it is published.
|
||||
interp.rooted(&[Value::Object(proxy)], |interp| method(interp, proxy, "revocable", revocable, 2))?;
|
||||
interp.define_own_property(global, key("Proxy"), &Desc::data(Value::Object(proxy), HIDDEN), true)?;
|
||||
}
|
||||
if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) {
|
||||
install_reflect(interp)?;
|
||||
}
|
||||
interp.es2015_installed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `Reflect` object and its functions (section 26.1).
|
||||
fn install_reflect(interp: &mut Interp) -> JsResult<()> {
|
||||
let global = interp.global;
|
||||
let object_proto = interp.intrinsics.object_proto;
|
||||
let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
|
||||
interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?;
|
||||
interp.define_own_property(global, key("Reflect"), &Desc::data(Value::Object(reflect), HIDDEN), true).map(|_| ())
|
||||
}
|
||||
|
||||
/// Defines `Reflect`'s functions on `reflect`, which the caller keeps reachable.
|
||||
fn reflect_methods(interp: &mut Interp, reflect: ObjId) -> JsResult<()> {
|
||||
method(interp, reflect, "apply", apply, 3)?;
|
||||
method(interp, reflect, "construct", construct, 2)?;
|
||||
method(interp, reflect, "defineProperty", define_property, 3)?;
|
||||
method(interp, reflect, "deleteProperty", delete_property, 2)?;
|
||||
method(interp, reflect, "get", get, 2)?;
|
||||
method(interp, reflect, "getOwnPropertyDescriptor", get_own_property_descriptor, 2)?;
|
||||
method(interp, reflect, "getPrototypeOf", get_prototype_of, 1)?;
|
||||
method(interp, reflect, "has", has, 2)?;
|
||||
method(interp, reflect, "isExtensible", is_extensible, 1)?;
|
||||
method(interp, reflect, "ownKeys", own_keys, 1)?;
|
||||
method(interp, reflect, "preventExtensions", prevent_extensions, 1)?;
|
||||
method(interp, reflect, "set", set, 3)?;
|
||||
method(interp, reflect, "setPrototypeOf", set_prototype_of, 2)?;
|
||||
if let Some(tag) = interp.well_known(|w| &w.to_string_tag) {
|
||||
interp.define_sym(reflect, tag, Prop::Data { value: Value::str("Reflect"), flags: CONFIGURABLE })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Proxy ----
|
||||
|
||||
/// `new Proxy(target, handler)` (section 26.2.1.1). Calling it without `new` is a `TypeError`.
|
||||
fn proxy_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult<Value> {
|
||||
if !constructing {
|
||||
return Err(interp.type_error("Proxy must be called with new"));
|
||||
}
|
||||
interp.proxy_create(&arg(args, 0), &arg(args, 1)).map(Value::Object)
|
||||
}
|
||||
|
||||
/// `Proxy.revocable(target, handler)` (section 26.2.2.1): an object whose `proxy` is a new proxy
|
||||
/// and whose `revoke` function revokes it. The function's bound `this` holds a private slot
|
||||
/// whose proxy reference is cleared by the first call.
|
||||
fn revocable(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let p = interp.proxy_create(&arg(args, 0), &arg(args, 1))?;
|
||||
interp.rooted(&[Value::Object(p)], |interp| {
|
||||
interp.reserve_heap(4 * OBJECT_BYTES + crate::interp::binding_bytes("proxy".len()))?;
|
||||
let inner = native(interp, "", revoke, 0, NativeKind::Plain, false)?;
|
||||
let slot = interp.heap.alloc_object(Object::new(Class::Ordinary, None));
|
||||
interp.define(slot, key("proxy"), Prop::Data { value: Value::Object(p), flags: 0 })?;
|
||||
let proto = interp.intrinsics.function_proto;
|
||||
let class = Class::Function(Func::Bound { target: inner, this: Value::Object(slot), args: Rc::from(Vec::new()) });
|
||||
let f = interp.heap.alloc_object(Object::new(class, Some(proto)));
|
||||
interp.define(f, key("length"), Prop::Data { value: Value::Number(0.0), flags: CONFIGURABLE })?;
|
||||
interp.define(f, key("name"), Prop::Data { value: Value::String(crate::value::Str::from("")), flags: CONFIGURABLE })?;
|
||||
let result = interp.new_object();
|
||||
interp.define(result, key("proxy"), Prop::Data { value: Value::Object(p), flags: OPEN })?;
|
||||
interp.define(result, key("revoke"), Prop::Data { value: Value::Object(f), flags: OPEN })?;
|
||||
Ok(Value::Object(result))
|
||||
})
|
||||
}
|
||||
|
||||
/// A revocation function's call (section 26.2.2.1.1): `this` contains its private revocation slot.
|
||||
fn revoke(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
if let Value::Object(slot) = this
|
||||
&& let Some(Prop::Data { value, .. }) = interp.object_mut(slot)?.props.get_mut(&key("proxy"))
|
||||
&& let Value::Object(p) = std::mem::replace(value, Value::Undefined)
|
||||
{
|
||||
interp.proxy_revoke(p);
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
// ---- Reflect ----
|
||||
|
||||
/// The `target` argument of a `Reflect` function, which must be an object.
|
||||
fn target(interp: &mut Interp, args: &[Value], function: &str) -> JsResult<ObjId> {
|
||||
match arg(args, 0) {
|
||||
Value::Object(o) => Ok(o),
|
||||
_ => Err(interp.type_error(&format!("Reflect.{function}: the target is not an object"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// CreateListFromArrayLike (section 7.3.17) of an argument list, which must be an object.
|
||||
fn argument_list(interp: &mut Interp, list: &Value, function: &str) -> JsResult<Vec<Value>> {
|
||||
if !matches!(list, Value::Object(_)) {
|
||||
return Err(interp.type_error(&format!("Reflect.{function}: the argument list is not an object")));
|
||||
}
|
||||
interp.create_list_from_array_like(list)
|
||||
}
|
||||
|
||||
/// `Reflect.apply(target, thisArgument, argumentsList)` (section 26.1.1).
|
||||
fn apply(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let f = arg(args, 0);
|
||||
if !interp.is_callable(&f) {
|
||||
return Err(interp.type_error("Reflect.apply: the target is not a function"));
|
||||
}
|
||||
let list = argument_list(interp, &arg(args, 2), "apply")?;
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(list.iter().cloned());
|
||||
let r = interp.call(&f, &arg(args, 1), &list);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// `Reflect.construct(target, argumentsList[, newTarget])` (section 26.1.2). Without
|
||||
/// `newTarget` the target is constructed with its own prototype. A constructor written in
|
||||
/// JavaScript gives its new object the `prototype` of `newTarget`; a built-in constructor makes
|
||||
/// its object as it does for `new`.
|
||||
fn construct(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let f = arg(args, 0);
|
||||
if !interp.is_constructor(&f) {
|
||||
return Err(interp.type_error("Reflect.construct: the target is not a constructor"));
|
||||
}
|
||||
let new_target = if args.len() > 2 { arg(args, 2) } else { f.clone() };
|
||||
if !interp.is_constructor(&new_target) {
|
||||
return Err(interp.type_error("Reflect.construct: newTarget is not a constructor"));
|
||||
}
|
||||
let list = argument_list(interp, &arg(args, 1), "construct")?;
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(list.iter().cloned());
|
||||
let r = interp.construct_value(&f, &list, &new_target);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// `Reflect.defineProperty(target, propertyKey, attributes)` (section 26.1.3): whether the
|
||||
/// property was defined.
|
||||
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "defineProperty")?;
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| {
|
||||
let desc: Desc = to_desc(interp, &arg(args, 2))?;
|
||||
let roots = desc_values(&desc);
|
||||
interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, false)).map(Value::Bool)
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone.
|
||||
fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "deleteProperty")?;
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.delete_pk(o, &k, false)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5).
|
||||
fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "get")?;
|
||||
let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) };
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| match k {
|
||||
PropKey::Str(name) => interp.get_from(o, &name, &receiver),
|
||||
PropKey::Sym(s) => interp.get_sym_from(o, &s, &receiver),
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6).
|
||||
fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "getOwnPropertyDescriptor")?;
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| match interp.own_pk(o, &k)? {
|
||||
Some(p) => from_prop(interp, &p),
|
||||
None => Ok(Value::Undefined),
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.getPrototypeOf(target)` (section 26.1.7).
|
||||
fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "getPrototypeOf")?;
|
||||
Ok(interp.get_prototype_of(o)?.map_or(Value::Null, Value::Object))
|
||||
}
|
||||
|
||||
/// `Reflect.has(target, propertyKey)` (section 26.1.8).
|
||||
fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "has")?;
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.has_pk_indexed(o, &k)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.isExtensible(target)` (section 26.1.9).
|
||||
fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "isExtensible")?;
|
||||
interp.is_extensible(o).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.ownKeys(target)` (section 26.1.10): every own property key, enumerable or not: the
|
||||
/// names, then the Symbols.
|
||||
fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "ownKeys")?;
|
||||
// A proxy's list holds its Symbols already, in its trap's order, from the one `ownKeys` call.
|
||||
let mut keys = interp.ecma_own_keys(o)?;
|
||||
if !interp.is_proxy(o) {
|
||||
keys.syms = interp.own_symbols(o)?;
|
||||
keys.held.add(interp, keys.syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?;
|
||||
}
|
||||
let roots: Vec<Value> = keys.syms.iter().cloned().map(Value::Symbol).collect();
|
||||
let (keys, _held) = keys.into_prop_keys();
|
||||
interp.rooted(&roots, |interp| {
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, k) in keys.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
let v = match k {
|
||||
PropKey::Str(name) => Value::String(Str::from_rc(name)),
|
||||
PropKey::Sym(s) => Value::Symbol(s),
|
||||
};
|
||||
create_at(interp, a, i as f64, v)?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not
|
||||
/// extensible.
|
||||
fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "preventExtensions")?;
|
||||
interp.prevent_extensions(o).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.set(target, propertyKey, V[, receiver])` (section 26.1.12): whether the value was
|
||||
/// set.
|
||||
fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "set")?;
|
||||
let receiver = if args.len() > 3 { arg(args, 3) } else { Value::Object(o) };
|
||||
let v = arg(args, 2);
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.set_pk_with_receiver(o, k, v, &receiver)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A
|
||||
/// `proto` that is neither an object nor `null` is a `TypeError`.
|
||||
fn set_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "setPrototypeOf")?;
|
||||
let proto = match arg(args, 1) {
|
||||
Value::Object(p) => Some(p),
|
||||
Value::Null => None,
|
||||
_ => return Err(interp.type_error("Reflect.setPrototypeOf: the prototype is neither an object nor null")),
|
||||
};
|
||||
interp.set_prototype_of(o, proto).map(Value::Bool)
|
||||
}
|
||||
@@ -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());
|
||||
@@ -169,14 +171,26 @@ fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool)
|
||||
fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let syms = interp.own_symbols(o)?;
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, s) in syms.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
create_at(interp, a, i as f64, Value::Symbol(s))?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
// 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, false)?;
|
||||
(keys.syms, keys.held)
|
||||
} else {
|
||||
let syms = interp.own_symbols(o)?;
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
held.add(interp, syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?;
|
||||
(syms, held)
|
||||
};
|
||||
let roots: Vec<Value> = syms.iter().cloned().map(Value::Symbol).collect();
|
||||
interp.rooted(&roots, |interp| {
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, s) in syms.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
create_at(interp, a, i as f64, Value::Symbol(s))?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
+179
-33
@@ -13,12 +13,13 @@
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::LimitKind;
|
||||
use crate::bytecode::{Code, NamePrefix};
|
||||
use crate::heap::{
|
||||
Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key,
|
||||
string_bytes,
|
||||
};
|
||||
use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, binding_bytes, closure_bytes, internal};
|
||||
use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, ProxyCall, binding_bytes, closure_bytes, internal};
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value};
|
||||
|
||||
@@ -150,6 +151,9 @@ impl Interp {
|
||||
pub(crate) fn is_constructor(&self, v: &Value) -> bool {
|
||||
let mut v = v.clone();
|
||||
for _ in 0..MAX_BOUND_CHAIN {
|
||||
if let Some(Class::Proxy(p)) = v.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) {
|
||||
return p.constructor;
|
||||
}
|
||||
match self.func_of(&v) {
|
||||
Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator),
|
||||
Some(Func::Native { constructor, .. }) => return constructor,
|
||||
@@ -164,7 +168,7 @@ impl Interp {
|
||||
/// Does the built-in constructor `f` make objects that a subclass may give its own
|
||||
/// prototype? It does when its `prototype` is one of the realm's built-in prototypes.
|
||||
fn subclassable(&self, f: ObjId) -> JsResult<bool> {
|
||||
let Some(Prop::Data { value: Value::Object(p), .. }) = self.get_own_property(f, &key("prototype"))? else { return Ok(false) };
|
||||
let Some(Prop::Data { value: Value::Object(p), .. }) = self.ordinary_own_property(f, &key("prototype"))? else { return Ok(false) };
|
||||
let i = &self.intrinsics;
|
||||
Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto]
|
||||
.contains(&p)
|
||||
@@ -172,10 +176,32 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14).
|
||||
fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult<ObjId> {
|
||||
/// Before falling back it runs GetFunctionRealm (section 7.3.22) on `new.target`, which
|
||||
/// throws a `TypeError` for a revoked proxy in its bound or proxy chain.
|
||||
pub(crate) fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult<ObjId> {
|
||||
match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? {
|
||||
Value::Object(p) => Ok(p),
|
||||
_ => Ok(fallback),
|
||||
_ => {
|
||||
self.function_realm(new_target)?;
|
||||
Ok(fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// GetFunctionRealm (section 7.3.22). There is one realm, so this only walks the bound
|
||||
/// and proxy chain of `f` and throws a `TypeError` when it reaches a revoked proxy.
|
||||
/// Each hop takes a unit of fuel.
|
||||
fn function_realm(&mut self, mut f: ObjId) -> JsResult<()> {
|
||||
loop {
|
||||
let next = match self.symbol_lookup_target(f)? {
|
||||
Some(t) => t,
|
||||
None => match self.func_of(&Value::Object(f)) {
|
||||
Some(Func::Bound { target, .. }) => target,
|
||||
_ => return Ok(()),
|
||||
},
|
||||
};
|
||||
self.use_fuel()?;
|
||||
f = next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,17 +225,73 @@ impl Interp {
|
||||
/// Constructs `f` with `args` and `new_target` (`f` itself when `None`) and pushes the
|
||||
/// result, or the frame that makes it, after taking the stack back to `start`. The operands
|
||||
/// at `start` and above keep `f` and `args` reachable.
|
||||
pub(crate) fn construct(&mut self, start: usize, f: Value, mut args: Vec<Value>, new_target: Option<ObjId>) -> JsResult<()> {
|
||||
pub(crate) fn construct(&mut self, start: usize, f: Value, args: Vec<Value>, new_target: Option<ObjId>) -> JsResult<()> {
|
||||
self.construct_at(start, f, args, new_target, false)
|
||||
}
|
||||
|
||||
/// Construct (ECMA-262 2020 section 7.3.13) from Rust, as `Reflect.construct` needs it: runs
|
||||
/// a constructor written in JavaScript to its end and gives the new object.
|
||||
pub(crate) fn construct_value(&mut self, f: &Value, args: &[Value], new_target: &Value) -> JsResult<Value> {
|
||||
if self.reentry >= self.limits.reentry {
|
||||
return Err(Abrupt::Limit(LimitKind::Reentry));
|
||||
}
|
||||
self.reentry += 1;
|
||||
let start = self.stack.len();
|
||||
let frames = self.frames.len();
|
||||
// The operands keep `f`, `new_target` and the arguments reachable, as for `new`.
|
||||
let r = self.push(f.clone()).and_then(|()| self.push(new_target.clone())).and_then(|()| {
|
||||
for a in args {
|
||||
self.push(a.clone())?;
|
||||
}
|
||||
self.construct_at(start, f.clone(), args.to_vec(), new_target.as_object(), true)
|
||||
});
|
||||
let r = match r {
|
||||
Ok(()) if self.frames.len() > frames => self.execute(),
|
||||
Ok(()) => self.pop(),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
self.stack.truncate(start);
|
||||
self.reentry -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Interp::construct`], the frame a constructor written in JavaScript enters marked as a
|
||||
/// boundary when `boundary` is set. A proxy runs its `construct` trap, or without one
|
||||
/// constructs its target with the same `new.target` (section 9.5.13).
|
||||
fn construct_at(&mut self, start: usize, f: Value, mut args: Vec<Value>, new_target: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let forwarding = new_target.is_none() || new_target == f.as_object();
|
||||
let mut f = f;
|
||||
let mut new_target = new_target;
|
||||
// A bound function constructs its target with its arguments first, and a `new.target`
|
||||
// that is the bound function becomes the target (section 9.4.1.2).
|
||||
let mut steps = 0usize;
|
||||
while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) {
|
||||
self.use_fuel()?;
|
||||
let mark = self.temp_roots.len();
|
||||
let r = loop {
|
||||
if let Some(p) = f.as_object().filter(|&p| self.is_proxy(p)) {
|
||||
let nt = Value::Object(new_target.unwrap_or(p));
|
||||
new_target = nt.as_object();
|
||||
match self.proxy_construct(p, &args, &nt) {
|
||||
Ok(ProxyCall::Target(target)) => {
|
||||
f = Value::Object(target);
|
||||
self.temp_roots.push(f.clone());
|
||||
continue;
|
||||
}
|
||||
Ok(ProxyCall::Done(v)) => {
|
||||
self.stack.truncate(start);
|
||||
break self.push(v);
|
||||
}
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
}
|
||||
let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) else {
|
||||
break self.construct_function(start, f, args, new_target, boundary, forwarding);
|
||||
};
|
||||
if let Err(e) = self.use_fuel() {
|
||||
break Err(e);
|
||||
}
|
||||
steps += 1;
|
||||
if steps > MAX_BOUND_CHAIN {
|
||||
return Err(self.type_error("the value is not a constructor"));
|
||||
break Err(self.type_error("the value is not a constructor"));
|
||||
}
|
||||
let mut all = bound_args.to_vec();
|
||||
all.append(&mut args);
|
||||
@@ -218,7 +300,21 @@ impl Interp {
|
||||
new_target = Some(target);
|
||||
}
|
||||
f = Value::Object(target);
|
||||
}
|
||||
};
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// The steps of [`Interp::construct_at`] for `f` once it is neither a proxy nor bound.
|
||||
fn construct_function(
|
||||
&mut self,
|
||||
start: usize,
|
||||
f: Value,
|
||||
args: Vec<Value>,
|
||||
new_target: Option<ObjId>,
|
||||
boundary: bool,
|
||||
forwarding: bool,
|
||||
) -> JsResult<()> {
|
||||
let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) };
|
||||
let nt = new_target.unwrap_or(callee);
|
||||
match self.func_of(&f) {
|
||||
@@ -227,18 +323,19 @@ impl Interp {
|
||||
Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")),
|
||||
Some(Func::Closure { code, env }) if code.derived => {
|
||||
self.stack.truncate(start);
|
||||
self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, false)
|
||||
self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, boundary)
|
||||
}
|
||||
Some(Func::Closure { code, env }) => {
|
||||
let fallback = self.intrinsics.object_proto;
|
||||
let proto = self.prototype_from(nt, fallback)?;
|
||||
let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
|
||||
self.stack.truncate(start);
|
||||
self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), false)
|
||||
self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), boundary)
|
||||
}
|
||||
Some(Func::Native { f: native, constructor: true, .. }) => {
|
||||
let subclass = nt != callee;
|
||||
if subclass && !self.subclassable(callee)? {
|
||||
Some(Func::Native { f: native, constructor: true, name, .. }) => {
|
||||
// `Proxy` does not read `new.target` (section 26.2.1.1).
|
||||
let subclass = nt != callee && name != "Proxy";
|
||||
if !boundary && subclass && !forwarding && !self.subclassable(callee)? && self.unwrapped_proxy_target(nt)? != callee {
|
||||
return Err(self.type_error("this built-in cannot be subclassed"));
|
||||
}
|
||||
let intrinsic = match self.get_own_property(callee, &key("prototype"))? {
|
||||
@@ -251,21 +348,56 @@ impl Interp {
|
||||
let fallback = self.intrinsics.object_proto;
|
||||
let proto = self.prototype_from(nt, fallback)?;
|
||||
Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))))
|
||||
} else if let Some((name, class)) =
|
||||
intrinsic.filter(|_| subclass).and_then(|p| crate::builtins::collections::constructor_class(self, p))
|
||||
{
|
||||
let proto = self.prototype_from(nt, intrinsic.unwrap_or(self.intrinsics.object_proto))?;
|
||||
let held = self.held_bytes;
|
||||
let r = self.rooted(&[Value::Object(proto)], |i| crate::builtins::collections::construct(i, &args, true, name, class, proto));
|
||||
self.held_bytes = held;
|
||||
r?
|
||||
} else if subclass && crate::builtins::binary::defers_prototype(self, intrinsic, &args) {
|
||||
let held = self.held_bytes;
|
||||
let r = crate::builtins::binary::construct_with_target(self, intrinsic, &args, nt);
|
||||
self.held_bytes = held;
|
||||
r?
|
||||
} else {
|
||||
if subclass && name == "Promise" && !args.first().is_some_and(|v| self.is_callable(v)) {
|
||||
return Err(self.type_error("the Promise executor is not a function"));
|
||||
}
|
||||
// `Number`, `String` and `Date` convert arguments before reading `prototype`
|
||||
// (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction`
|
||||
// convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1).
|
||||
let converts_first = {
|
||||
let i = &self.intrinsics;
|
||||
intrinsic.is_some_and(|p| {
|
||||
[i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p)
|
||||
|| self.symbols.objects.is_some_and(|o| p == o.generator_function_proto)
|
||||
})
|
||||
};
|
||||
let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto);
|
||||
let mark = self.temp_roots.len();
|
||||
let early = if subclass && !converts_first { Some(self.prototype_from(nt, fallback)?) } else { None };
|
||||
self.temp_roots.extend(early.map(Value::Object));
|
||||
let held = self.held_bytes;
|
||||
let r = native(self, Value::Undefined, &args, true);
|
||||
self.held_bytes = held;
|
||||
let v = r?;
|
||||
if subclass && let Value::Object(o) = v {
|
||||
let proto = self.rooted(std::slice::from_ref(&v), |i| {
|
||||
let fallback = intrinsic.unwrap_or(i.intrinsics.object_proto);
|
||||
i.prototype_from(nt, fallback)
|
||||
})?;
|
||||
let r = r.and_then(|v| {
|
||||
let Value::Object(o) = v else { return Ok(v) };
|
||||
if !subclass || self.is_proxy(o) || args.iter().any(|a| crate::interp::same_value(a, &v)) {
|
||||
return Ok(v);
|
||||
}
|
||||
let proto = match early {
|
||||
Some(p) => p,
|
||||
None => self.rooted(std::slice::from_ref(&v), |i| i.prototype_from(nt, fallback))?,
|
||||
};
|
||||
if self.object(o)?.proto == intrinsic && !self.chain_reaches(proto, o)? {
|
||||
self.object_mut(o)?.proto = Some(proto);
|
||||
}
|
||||
}
|
||||
v
|
||||
Ok(v)
|
||||
});
|
||||
self.temp_roots.truncate(mark);
|
||||
r?
|
||||
};
|
||||
self.stack.truncate(start);
|
||||
self.push(v)
|
||||
@@ -274,7 +406,7 @@ impl Interp {
|
||||
// object it gives inherits from the class's prototype. The class's other functions are
|
||||
// not constructors. A constructor called with `new` cannot wait for its result.
|
||||
Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => {
|
||||
if nt != callee {
|
||||
if nt != callee && !forwarding {
|
||||
return Err(self.type_error("this built-in cannot be subclassed"));
|
||||
}
|
||||
let was = std::mem::replace(&mut self.constructing, true);
|
||||
@@ -467,21 +599,13 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The key as text for a message.
|
||||
fn pk_name(&mut self, k: &PropKey) -> JsResult<String> {
|
||||
pub(crate) fn pk_name(&mut self, k: &PropKey) -> JsResult<String> {
|
||||
match k {
|
||||
PropKey::Str(name) => Ok(String::from_utf16_lossy(name)),
|
||||
PropKey::Sym(s) => self.sym_name(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// The property `k` of `start` or an object it inherits from.
|
||||
fn find_pk(&mut self, start: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.find_property(start, name),
|
||||
PropKey::Sym(s) => self.find_sym(start, s),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Get]] of `k` from `start` with `receiver` as `this`.
|
||||
fn get_pk_from(&mut self, start: ObjId, k: &PropKey, receiver: &Value) -> JsResult<Value> {
|
||||
match k {
|
||||
@@ -522,7 +646,29 @@ impl Interp {
|
||||
/// 6.2.3.2).
|
||||
fn super_put(&mut self, proto: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<()> {
|
||||
let throw = self.strict_writes();
|
||||
let why = match self.find_pk(proto, &k)? {
|
||||
let inherited = match &k {
|
||||
PropKey::Str(name) => match self.lookup(proto, name)? {
|
||||
crate::interp::Lookup::Proxy(p) => {
|
||||
if !self.set_with_receiver(p, name.clone(), v, receiver)? {
|
||||
return self.super_reject(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::interp::Lookup::Found(prop) => Some(prop),
|
||||
crate::interp::Lookup::Missing => None,
|
||||
},
|
||||
PropKey::Sym(s) => match self.sym_holder(proto, s)? {
|
||||
Some((p, None)) => {
|
||||
if !self.set_sym_with_receiver(p, s.clone(), v, receiver)? {
|
||||
return self.super_reject(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Some((_, prop)) => prop,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
let why = match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Object literals with computed names, shorthand properties and methods, and the `name` and
|
||||
//! `length` of functions, with [`Options::es2015`].
|
||||
//! Object literals with computed names, shorthand properties and methods, the `name` and
|
||||
//! `length` of functions, and `Object.setPrototypeOf`, proxies included, with [`Options::es2015`].
|
||||
|
||||
use proptest::prelude::*;
|
||||
|
||||
@@ -504,6 +504,125 @@ fn function_lengths_can_be_redefined() {
|
||||
truth("delete Math.max.length && Math.max.hasOwnProperty('length') === false");
|
||||
}
|
||||
|
||||
// ---- Object.setPrototypeOf ----
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_sets_the_prototype_and_returns_the_object() {
|
||||
truth("var p = { x: 1 }; var o = {}; Object.setPrototypeOf(o, p) === o && Object.getPrototypeOf(o) === p && o.x === 1");
|
||||
truth("var o = {}; Object.setPrototypeOf(o, null) === o && Object.getPrototypeOf(o) === null && !('toString' in o)");
|
||||
truth("var a = [1, 2]; Object.setPrototypeOf(a, Object.prototype); a.length === 2 && a.push === undefined");
|
||||
truth("var a = []; a.length = 3; Object.setPrototypeOf(a, { 1: 'p' }); a[1] === 'p' && Array.prototype.indexOf.call(a, 'p') === 1");
|
||||
truth("function F() {} var o = Object.setPrototypeOf({}, F.prototype); o instanceof F");
|
||||
// The prototype it already has is set again even when the object is not extensible.
|
||||
truth("var p = {}; var o = Object.preventExtensions(Object.create(p)); Object.setPrototypeOf(o, p) === o");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_returns_a_primitive_unchanged() {
|
||||
truth("Object.setPrototypeOf(1, null) === 1 && Object.setPrototypeOf('s', {}) === 's' && Object.setPrototypeOf(true, null) === true");
|
||||
truth("var s = Symbol(); Object.setPrototypeOf(s, null) === s");
|
||||
truth("Object.getPrototypeOf(Object.setPrototypeOf(2, null)) === Number.prototype");
|
||||
}
|
||||
|
||||
/// `Object.setPrototypeOf` throws a `TypeError` of its own for the script.
|
||||
fn refused(src: &str) {
|
||||
throws(src, "TypeError: Object.setPrototypeOf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_throws_for_undefined_null_and_a_bad_prototype() {
|
||||
refused("Object.setPrototypeOf(undefined, {})");
|
||||
refused("Object.setPrototypeOf(null, null)");
|
||||
refused("Object.setPrototypeOf()");
|
||||
refused("Object.setPrototypeOf({})");
|
||||
refused("Object.setPrototypeOf({}, 1)");
|
||||
refused("Object.setPrototypeOf(1, 'p')");
|
||||
refused("Object.setPrototypeOf(undefined, 1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_throws_when_the_prototype_cannot_change() {
|
||||
refused("Object.setPrototypeOf(Object.preventExtensions({}), {})");
|
||||
refused("Object.setPrototypeOf(Object.freeze({}), null)");
|
||||
refused("var a = {}; var b = Object.create(a); Object.setPrototypeOf(a, b)");
|
||||
refused("var o = {}; Object.setPrototypeOf(o, o)");
|
||||
refused("Object.setPrototypeOf(Object.prototype, {})");
|
||||
refused("Object.setPrototypeOf(Object.prototype, Object.create(null))");
|
||||
truth("Object.setPrototypeOf(Object.prototype, null) === Object.prototype");
|
||||
// A refused change leaves the prototype as it was.
|
||||
truth(
|
||||
"var p = {}; var o = Object.preventExtensions(Object.create(p)); try { Object.setPrototypeOf(o, {}); } catch (e) {} Object.getPrototypeOf(o) === p",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_lets_a_later_forward_walk_see_the_new_prototype_indices() {
|
||||
truth(
|
||||
"var p = { 500000: 'p' }; var a = []; a.length = 1000000; a[0] = 0; var seen = ''; \
|
||||
a.forEach(function (v, i) { seen += i + ';'; if (i === 0) Object.setPrototypeOf(a, p); }); seen === '0;500000;'",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_calls_a_proxy_trap() {
|
||||
truth(
|
||||
"var t = {}; var p = {}; var log = []; \
|
||||
var x = new Proxy(t, { setPrototypeOf: function (target, proto) { log.push(target === t, proto === p); return Reflect.setPrototypeOf(target, proto); } }); \
|
||||
Object.setPrototypeOf(x, p) === x && Object.getPrototypeOf(t) === p && log.join() === 'true,true'",
|
||||
);
|
||||
// Without a trap the target's prototype is set.
|
||||
truth("var t = {}; var p = {}; var x = new Proxy(t, {}); Object.setPrototypeOf(x, p) === x && Object.getPrototypeOf(t) === p");
|
||||
// A proxy in the new prototype's chain ends the cycle check.
|
||||
truth("var o = {}; var x = new Proxy(o, {}); Object.setPrototypeOf(o, x) === o && Object.getPrototypeOf(o) === x");
|
||||
refused("Object.setPrototypeOf(new Proxy({}, { setPrototypeOf: function () { return false; } }), {})");
|
||||
refused("Object.setPrototypeOf(new Proxy({}, { setPrototypeOf: function () { return 0; } }), null)");
|
||||
truth(
|
||||
"var t = {}; var x = new Proxy(t, { setPrototypeOf: function () { return false; } }); \
|
||||
try { Object.setPrototypeOf(x, null); } catch (e) {} Object.getPrototypeOf(t) === Object.prototype",
|
||||
);
|
||||
// A trap that reports success for a non-extensible target it did not change breaks an invariant.
|
||||
throws(
|
||||
"var t = Object.preventExtensions({}); Object.setPrototypeOf(new Proxy(t, { setPrototypeOf: function () { return true; } }), null)",
|
||||
"TypeError: the proxy's setPrototypeOf trap",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_throws_for_a_revoked_proxy() {
|
||||
throws(
|
||||
"var r = Proxy.revocable({}, {}); r.revoke(); Object.setPrototypeOf(r.proxy, {})",
|
||||
"TypeError: cannot set the prototype of a revoked proxy",
|
||||
);
|
||||
// The prototype check comes before the proxy is read.
|
||||
refused("var r = Proxy.revocable({}, {}); r.revoke(); Object.setPrototypeOf(r.proxy, 1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_has_the_length_and_name_of_a_built_in() {
|
||||
truth(&name_is("Object.setPrototypeOf", "setPrototypeOf"));
|
||||
truth(
|
||||
"var d = Object.getOwnPropertyDescriptor(Object, 'setPrototypeOf'); \
|
||||
d.writable && !d.enumerable && d.configurable && Object.setPrototypeOf.length === 2",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_prototype_of_charges_fuel_along_a_long_chain() {
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("var p = {}; for (var i = 0; i < 5000; i++) p = Object.create(p); true"), Ok(JsValue::Bool(true)));
|
||||
realm.set_limits(Limits { fuel: 1_000, ..Limits::default() });
|
||||
let e = realm.run("Object.setPrototypeOf({}, p); true").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_option_there_is_no_set_prototype_of() {
|
||||
for options in [Options::default(), Options { e4x: true, ..Options::default() }] {
|
||||
let mut realm = Realm::with_options(options, Limits::default());
|
||||
assert_eq!(realm.run("typeof Object.setPrototypeOf"), Ok(JsValue::String("undefined".into())));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the language mode ----
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -302,6 +302,22 @@ fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings()
|
||||
assert_eq!(realm.run(local), Ok(JsValue::Number(8.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_without_the_option_cannot_redeclare_an_earlier_runs_let() {
|
||||
// An earlier run's `let` stays a `let` when the option is turned off: an eval `var` or
|
||||
// function of the same name is a `SyntaxError`, and the binding keeps its value.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("let x = 1; 0"), Ok(JsValue::Number(0.0)));
|
||||
realm.set_es2015(false);
|
||||
for src in ["eval('var x = 2')", "eval('function x() {}')", "(0, eval)('var x = 2')"] {
|
||||
let r = realm.run(src);
|
||||
assert!(is_thrown(&r, "SyntaxError"), "{src}: {r:?}");
|
||||
}
|
||||
assert_eq!(realm.run("x === 1 && !this.hasOwnProperty('x')"), Ok(JsValue::Bool(true)));
|
||||
// A name no `let` holds is still declared.
|
||||
assert_eq!(realm.run("eval('var y = 3'); y"), Ok(JsValue::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_var_makes_its_own_property_over_an_inherited_one() {
|
||||
// ECMA-262 2015 section 8.1.1.4.17 reads the global object's own property, so `var` makes a
|
||||
|
||||
@@ -138,9 +138,10 @@ fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the own data property `name` of `o`, `undefined` when it has none.
|
||||
/// The value of the own data property `name` of `o`, `undefined` when it has none. A proxy's
|
||||
/// traps do not run: a proxy has no such property.
|
||||
fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
Ok(match i.get_own_property(o, &key(name))? {
|
||||
Ok(match i.ordinary_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
|
||||
+38
-2
@@ -215,10 +215,22 @@ pub(crate) struct ArgMap {
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ForIn {
|
||||
pub(crate) keys: Vec<Key>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// A proxy on a `for-in` loop's chain and the positions, in ascending order, of the listed names
|
||||
/// its `ownKeys` trap returned. The loop asks the proxy for a name's descriptor only when the
|
||||
/// name's position is here.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Listed {
|
||||
/// The proxy returned by this proxy's prototype lookup, if any.
|
||||
pub(crate) prototype: Option<ObjId>,
|
||||
pub(crate) positions: Vec<u32>,
|
||||
}
|
||||
|
||||
/// What kind of object it is, with the internal state that kind has.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Class {
|
||||
@@ -268,6 +280,9 @@ pub(crate) enum Class {
|
||||
},
|
||||
/// A `.( )` filter in progress.
|
||||
XmlFilter(Box<XmlFilterState>),
|
||||
/// A proxy (ECMA-262 2020 section 9.5), made by `Proxy` in a realm with
|
||||
/// [`crate::Options::es2015`].
|
||||
Proxy(Box<ProxyData>),
|
||||
/// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]).
|
||||
Xmp(Box<crate::xmp::Meta>),
|
||||
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
|
||||
@@ -523,6 +538,16 @@ pub(crate) struct View {
|
||||
pub(crate) elem: Elem,
|
||||
}
|
||||
|
||||
/// A proxy's target and handler, `None` once it is revoked, and whether it can be called and
|
||||
/// constructed, which its target decided when it was made.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ProxyData {
|
||||
pub(crate) target: Option<ObjId>,
|
||||
pub(crate) handler: Option<ObjId>,
|
||||
pub(crate) callable: bool,
|
||||
pub(crate) constructor: bool,
|
||||
}
|
||||
|
||||
/// What an XML value is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum XmlKind {
|
||||
@@ -605,6 +630,8 @@ impl Class {
|
||||
Class::String(_) => "String",
|
||||
Class::RegExp(_) => "RegExp",
|
||||
Class::Date(_) => "Date",
|
||||
Class::Proxy(p) if p.callable => "Function",
|
||||
Class::Proxy(_) => "Object",
|
||||
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
|
||||
Class::ModuleNamespace(_) => "Module",
|
||||
Class::UnitValue(_) => "UnitValue",
|
||||
@@ -749,6 +776,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96;
|
||||
pub(crate) const XML_REF_BYTES: usize = 8;
|
||||
/// The estimated bytes of a namespace an XML node holds.
|
||||
pub(crate) const XML_NS_BYTES: usize = 48;
|
||||
/// The estimated bytes of a proxy's target, handler and flags.
|
||||
pub(crate) const PROXY_BYTES: usize = 32;
|
||||
/// The estimated bytes of a Symbol without its description.
|
||||
pub(crate) const SYMBOL_BYTES: usize = 48;
|
||||
/// The estimated bytes of the measurement a `UnitValue` object holds.
|
||||
@@ -776,8 +805,8 @@ pub(crate) struct Heap {
|
||||
/// How many collections have run.
|
||||
pub(crate) collections: usize,
|
||||
/// Counts the properties whose names start with a digit (the array indices among them) added
|
||||
/// to any object, so an operation that lists the indices an object has can tell whether a
|
||||
/// script added one since.
|
||||
/// to any object, and the prototypes changed, so an operation that lists the indices an object
|
||||
/// and its prototypes have can tell whether a script added one since.
|
||||
pub(crate) index_epoch: u64,
|
||||
}
|
||||
|
||||
@@ -1162,7 +1191,10 @@ 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.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);
|
||||
}
|
||||
Class::Symbol(s) => strings.add_symbol(s),
|
||||
Class::IterRecord(r) => {
|
||||
@@ -1220,6 +1252,10 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::Proxy(p) => {
|
||||
work.extend(p.target.iter().chain(&p.handler).map(|o| o.0));
|
||||
extra = PROXY_BYTES;
|
||||
}
|
||||
Class::Map(c) | Class::Set(c) => {
|
||||
for v in c.values() {
|
||||
mark_value(v, work, strings);
|
||||
|
||||
@@ -293,6 +293,9 @@ impl Interp {
|
||||
}
|
||||
Shape::Plain(o.props.iter().filter(|(_, p)| p.enumerable()).map(|(k, p)| (k.clone(), p.clone())).collect())
|
||||
}
|
||||
// A host reads plain data without running script, so a proxy, whose traps are script,
|
||||
// is refused, as is any other object that is not plain data.
|
||||
Class::Proxy(_) => return Err(self.data_error(r, ErrorType::Type, "is a proxy, not plain data")),
|
||||
other => {
|
||||
let what = format!("is a {}, not plain data", other.name());
|
||||
return Err(self.data_error(r, ErrorType::Type, &what));
|
||||
|
||||
+128
-19
@@ -402,14 +402,18 @@ impl Interp {
|
||||
/// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index,
|
||||
/// or a name that the object and its prototypes lack, is there when the indexer gives a value other
|
||||
/// than `undefined` for it.
|
||||
pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult<bool> {
|
||||
let index = crate::value::array_index(k).is_some();
|
||||
if (index || !self.has_property(id, k)?)
|
||||
pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &Key) -> JsResult<bool> {
|
||||
// The lookup runs once, so a proxy's `has` trap is asked once.
|
||||
let found = if crate::value::array_index(k).is_some() { None } else { Some(self.has_property(id, k)?) };
|
||||
if found != Some(true)
|
||||
&& let Some(f) = self.host_indexer(id)?
|
||||
{
|
||||
return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined));
|
||||
}
|
||||
self.has_property(id, k)
|
||||
match found {
|
||||
Some(found) => Ok(found),
|
||||
None => self.has_property(id, k),
|
||||
}
|
||||
}
|
||||
|
||||
/// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`].
|
||||
@@ -421,15 +425,127 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given.
|
||||
/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. Every
|
||||
/// class's name, parent and members are checked before any class is added, and a failure part way
|
||||
/// through removes the classes and globals this call added, so a failed call leaves the realm as it
|
||||
/// was.
|
||||
pub(crate) fn install(i: &mut Interp, classes: Vec<HostClass>, instances: Vec<(String, Data)>) -> JsResult<()> {
|
||||
let members = match checked_members(&i.host_classes, &classes) {
|
||||
Ok(m) => m,
|
||||
Err(message) => return Err(i.throw(ErrorType::Type, &message)),
|
||||
};
|
||||
let mark = i.temp_roots.len();
|
||||
let mut undo = Undo { classes: i.host_classes.len(), globals: Vec::new(), objects: Vec::new() };
|
||||
let r = install_checked(i, classes, members, instances, &mut undo);
|
||||
if r.is_err() {
|
||||
undo.roll_back(i);
|
||||
}
|
||||
i.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// What [`install`] puts back when it fails part way.
|
||||
struct Undo {
|
||||
/// How many classes the realm had before the call.
|
||||
classes: usize,
|
||||
/// Each global the call defined, with the property it replaced, in the order defined. The
|
||||
/// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a
|
||||
/// collection during the call does not free them.
|
||||
globals: Vec<(Key, Option<Prop>)>,
|
||||
/// The class and prototype of the object made for each family and handle before the call. An
|
||||
/// instance of the call can give such an object one of the call's classes.
|
||||
objects: Vec<(MadeKey, u32, Option<ObjId>)>,
|
||||
}
|
||||
|
||||
impl Undo {
|
||||
fn define_global(&mut self, i: &mut Interp, name: &str, prop: Prop) -> JsResult<()> {
|
||||
let global = i.global;
|
||||
let k = key(name);
|
||||
let was = i.object(global)?.props.get(&k).cloned();
|
||||
match &was {
|
||||
Some(Prop::Data { value, .. }) => i.temp_roots.push(value.clone()),
|
||||
Some(Prop::Accessor { get, set, .. }) => i.temp_roots.extend(get.iter().chain(set).map(|&f| Value::Object(f))),
|
||||
None => {}
|
||||
}
|
||||
i.define(global, k.clone(), prop)?;
|
||||
self.globals.push((k, was));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn roll_back(self, i: &mut Interp) {
|
||||
let global = i.global;
|
||||
for (k, was) in self.globals.into_iter().rev() {
|
||||
let Ok(o) = i.object_mut(global) else { break };
|
||||
match was {
|
||||
Some(prop) => {
|
||||
o.props.insert(k, prop);
|
||||
}
|
||||
None => {
|
||||
o.props.remove(&k);
|
||||
i.heap.bytes = i.heap.bytes.saturating_sub(crate::interp::binding_bytes(k.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (made, class, proto) in self.objects {
|
||||
let Some(&id) = i.host_objects.get(&made) else { continue };
|
||||
if is_made(&i.heap, &i.host_classes, id, &made)
|
||||
&& let Ok(o) = i.object_mut(id)
|
||||
&& let Class::Host(h) = &mut o.class
|
||||
{
|
||||
h.class = class;
|
||||
o.proto = proto;
|
||||
}
|
||||
}
|
||||
i.host_classes.truncate(self.classes);
|
||||
forget_collected(&mut i.host_objects, &i.heap, &i.host_classes);
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of each of `classes` as `reflect` lists them ([`reflected_members`]), once every
|
||||
/// class has a name that neither `existing` nor an earlier class of `classes` has, and a parent
|
||||
/// that one of them has. → the error's message for the first class that does not.
|
||||
fn checked_members(existing: &[Entry], classes: &[HostClass]) -> Result<Vec<Rc<[Reflected]>>, String> {
|
||||
let mut names: HashSet<&str> = existing.iter().map(|e| &*e.name).collect();
|
||||
let mut out = Vec::with_capacity(classes.len());
|
||||
for class in classes {
|
||||
install_class(i, class)?;
|
||||
if names.contains(class.name.as_str()) {
|
||||
return Err(format!("the host class {} is defined twice", class.name));
|
||||
}
|
||||
if let Some(p) = &class.parent
|
||||
&& !names.contains(p.as_str())
|
||||
{
|
||||
return Err(format!("the host class {p} is not defined"));
|
||||
}
|
||||
out.push(reflected_members(class)?);
|
||||
names.insert(&class.name);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`install`] once [`checked_members`] has passed, recording in `undo` what it changes.
|
||||
fn install_checked(
|
||||
i: &mut Interp,
|
||||
classes: Vec<HostClass>,
|
||||
members: Vec<Rc<[Reflected]>>,
|
||||
instances: Vec<(String, Data)>,
|
||||
undo: &mut Undo,
|
||||
) -> JsResult<()> {
|
||||
for (class, members) in classes.into_iter().zip(members) {
|
||||
install_class(i, class, members, undo)?;
|
||||
}
|
||||
if !instances.is_empty() {
|
||||
for (made, &id) in &i.host_objects {
|
||||
if is_made(&i.heap, &i.host_classes, id, made)
|
||||
&& let Ok(o) = i.object(id)
|
||||
&& let Class::Host(h) = &o.class
|
||||
{
|
||||
undo.objects.push((made.clone(), h.class, o.proto));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, d) in instances {
|
||||
let v = i.write_hosted(d)?;
|
||||
let global = i.global;
|
||||
i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?;
|
||||
undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -450,22 +566,16 @@ pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
if i.host_classes.iter().any(|e| *e.name == *class.name) {
|
||||
return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name)));
|
||||
}
|
||||
/// Adds `class`, which [`checked_members`] passed with `members`.
|
||||
fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, undo: &mut Undo) -> JsResult<()> {
|
||||
let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX);
|
||||
let (parent, family, parent_class) = match &class.parent {
|
||||
None => (i.intrinsics.object_proto, own, None),
|
||||
Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) {
|
||||
Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()),
|
||||
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
|
||||
None => return Err(Abrupt::Internal(format!("the host class {p} was checked but is not defined"))),
|
||||
},
|
||||
};
|
||||
let members = match reflected_members(&class) {
|
||||
Ok(m) => m,
|
||||
Err(message) => return Err(i.throw(ErrorType::Type, &message)),
|
||||
};
|
||||
let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent)));
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.push(Value::Object(proto));
|
||||
@@ -486,8 +596,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
members,
|
||||
});
|
||||
let global = i.global;
|
||||
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the
|
||||
|
||||
@@ -1035,6 +1035,72 @@ fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it()
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
|
||||
}
|
||||
|
||||
/// A class named `name` with the parent `parent` and one read-only member `size`.
|
||||
fn sized_class(name: &str, parent: Option<&str>) -> HostClass {
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
HostClass {
|
||||
name: name.into(),
|
||||
parent: parent.map(Into::into),
|
||||
members: vec![("size".to_string(), HostMember::Get(value))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_class_leaves_the_earlier_classes_of_its_call_undefined() {
|
||||
let doubled = || {
|
||||
let mut c = sized_class("Bad", None);
|
||||
c.members.push(c.members[0].clone());
|
||||
c
|
||||
};
|
||||
for (bad, message) in [(sized_class("Bad", Some("Missing")), "Missing is not defined"), (doubled(), "names the member size twice")] {
|
||||
let mut r = realm(1_000_000);
|
||||
let e = r.define_host_classes(vec![sized_class("First", None), bad], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap_err();
|
||||
assert!(e.message.contains(message), "{}", e.message);
|
||||
assert_eq!(r.run("[typeof First, typeof first, typeof Bad].join()").unwrap(), JsValue::String("undefined,undefined,undefined".into()));
|
||||
r.define_host_classes(vec![sized_class("First", None)], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("first.size").unwrap(), JsValue::Number(1.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_class_may_follow_its_parent_in_the_same_call_but_not_precede_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base")), sized_class("Base", None)], Vec::new()).unwrap_err();
|
||||
assert!(e.message.contains("Base is not defined"), "{}", e.message);
|
||||
assert_eq!(r.run("typeof Leaf + typeof Base").unwrap(), JsValue::String("undefinedundefined".into()));
|
||||
r.define_host_classes(vec![sized_class("Base", None), sized_class("Leaf", Some("Base"))], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("it instanceof Base && it.size === 1").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_instance_removes_the_classes_and_globals_of_its_call_and_restores_held_objects() {
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_classes(vec![sized_class("Base", None)], vec![("held".into(), host_ref("Base", &[1.0]))]).unwrap();
|
||||
r.run("var keep = 'kept'").unwrap();
|
||||
let instances = vec![("keep".into(), host_ref("Leaf", &[1.0])), ("other".into(), host_ref("Missing", &[2.0]))];
|
||||
let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base"))], instances).unwrap_err();
|
||||
assert!(e.message.contains("unknown class Missing"), "{}", e.message);
|
||||
let source = "[keep, typeof Leaf, typeof other, held.constructor === Base, held.hasOwnProperty('size'), held.size].join()";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("kept,undefined,undefined,true,true,1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_restores_a_replaced_global_that_a_collection_in_the_call_would_free() {
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_classes(vec![sized_class("Base", None)], Vec::new()).unwrap();
|
||||
r.run("var keep = { sentinel: 1 }").unwrap();
|
||||
let instances =
|
||||
vec![("keep".into(), host_ref("Base", &[1.0])), ("next".into(), host_ref("Base", &[2.0])), ("other".into(), host_ref("Missing", &[3.0]))];
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let e = r.define_host_classes(Vec::new(), instances);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert!(e.unwrap_err().message.contains("unknown class Missing"));
|
||||
assert_eq!(r.run("[keep.sentinel, typeof next].join()").unwrap(), JsValue::String("1,undefined".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
+641
-135
File diff suppressed because it is too large.
Load diff
@@ -81,14 +81,17 @@ impl Interp {
|
||||
Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None)))
|
||||
}
|
||||
|
||||
/// The record of a [`Walk`] over an array, an `arguments` object, a string or a `String`
|
||||
/// object, for a realm without `Symbol.iterator`; any other value is not iterable there. A
|
||||
/// `String` object is converted to a string first, as the string iterator does. A
|
||||
/// concatenated string's flattened copy is counted against the heap before it is made.
|
||||
/// The record of a [`Walk`] over an array, a proxy whose target is an array, an `arguments`
|
||||
/// object, a string or a `String` object, for a realm without `Symbol.iterator`; any other
|
||||
/// value is not iterable there. A proxy of an array is walked through its traps, its `length`
|
||||
/// read again at each step. A `String` object is converted to a string first, as the string
|
||||
/// iterator does. A concatenated string's flattened copy is counted against the heap before it
|
||||
/// is made.
|
||||
fn walk_record(&mut self, v: &Value) -> JsResult<ObjId> {
|
||||
let walk = match v {
|
||||
Value::String(s) => Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, s)?), 0),
|
||||
Value::Object(o) if matches!(self.object(*o)?.class, Class::Array { .. } | Class::Arguments(_)) => Walk::Array(*o, 0.0),
|
||||
Value::Object(o) if self.is_proxy(*o) && self.is_array(v)? => Walk::Array(*o, 0.0),
|
||||
Value::Object(o) if matches!(self.object(*o)?.class, Class::String(_)) => {
|
||||
let s = self.to_str(v)?;
|
||||
Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, &s)?), 0)
|
||||
|
||||
+17
-6
@@ -121,6 +121,11 @@
|
||||
//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A
|
||||
//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap
|
||||
//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated.
|
||||
//!
|
||||
//! With [`Options::es2015`], the realm also has `Proxy`, with `Proxy.revocable`, and `Reflect`, as
|
||||
//! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5,
|
||||
//! <https://262.ecma-international.org/11.0/>), with string and Symbol property keys: a trap is
|
||||
//! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -143,6 +148,7 @@ mod module;
|
||||
mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
mod proxy;
|
||||
mod realm;
|
||||
mod reflect;
|
||||
mod regexp;
|
||||
@@ -204,12 +210,15 @@ pub struct Options {
|
||||
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
|
||||
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
|
||||
/// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects,
|
||||
/// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`
|
||||
/// and the typed arrays. A realm made with it off has the ES5.1 built-ins only, as the
|
||||
/// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option
|
||||
/// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does
|
||||
/// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it.
|
||||
/// Runs with it on also convert `0b` and `0o` strings to numbers.
|
||||
/// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`,
|
||||
/// the typed arrays, `Proxy` and `Reflect`. A realm made with it off has the ES5.1 built-ins
|
||||
/// only, as the app's scripts expect. Those built-ins are chosen when the realm is made:
|
||||
/// turning the option on or off later with [`Realm::set_es2015`] changes the language later
|
||||
/// runs read, and does not add or remove them, except that a realm made without it gets
|
||||
/// `Proxy` and `Reflect` at its first run with the option on and keeps them; a `Proxy` or
|
||||
/// `Reflect` global that an earlier run defined stays as it is. [`Realm::add_es2015`] adds
|
||||
/// `Promise` to a realm made without it. Runs with it on also convert `0b` and `0o` strings to
|
||||
/// numbers.
|
||||
pub es2015: bool,
|
||||
}
|
||||
|
||||
@@ -369,6 +378,8 @@ mod module_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod proxy_tests;
|
||||
#[cfg(test)]
|
||||
mod reflect_tests;
|
||||
#[cfg(test)]
|
||||
mod scriptui_tests;
|
||||
|
||||
@@ -0,0 +1,838 @@
|
||||
//! Proxy objects (ECMA-262 2020 section 9.5, <https://262.ecma-international.org/11.0/#sec-proxy-object-internal-methods-and-internal-slots>)
|
||||
//! and the internal methods every object answers through: [[GetPrototypeOf]], [[SetPrototypeOf]],
|
||||
//! [[IsExtensible]], [[PreventExtensions]], [[Set]] with a receiver, and the proxy cases of
|
||||
//! [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Delete]],
|
||||
//! [[OwnPropertyKeys]], [[Call]] and [[Construct]], which [`Interp`]'s property methods send here.
|
||||
//!
|
||||
//! A trap is a script call: each proxy operation takes a unit of fuel and counts as a nested call
|
||||
//! against [`crate::Limits::reentry`] while it runs, so a proxy whose target or handler is another
|
||||
//! proxy, or a trap that uses its own proxy, ends at that limit rather than exhausting the native
|
||||
//! stack. A trap's result is checked against the target as section 9.5 says, and a result that
|
||||
//! breaks an invariant is a `TypeError`. The proxy, its target and handler, and every value a trap
|
||||
//! gives stay rooted while the operation runs, so a trap that revokes the proxy or starts a
|
||||
//! collection leaves them in place.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::LimitKind;
|
||||
use crate::builtins::object::{from_desc, to_desc};
|
||||
use crate::heap::{
|
||||
CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes,
|
||||
};
|
||||
use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value};
|
||||
use crate::symbol::{PropKey, Sym};
|
||||
use crate::value::{Str, Value, index_key};
|
||||
|
||||
/// The most names an `ownKeys` trap may give.
|
||||
const MAX_OWN_KEYS: f64 = (1u64 << 24) as f64;
|
||||
|
||||
impl Interp {
|
||||
pub(crate) fn is_proxy(&self, id: ObjId) -> bool {
|
||||
matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_)))
|
||||
}
|
||||
|
||||
/// The target of the proxy `id`, `None` when `id` is not a proxy. A revoked proxy is a
|
||||
/// `TypeError`.
|
||||
pub(crate) fn symbol_lookup_target(&mut self, id: ObjId) -> JsResult<Option<ObjId>> {
|
||||
let Some(ProxyData { target, handler, .. }) = self.proxy_data(id) else { return Ok(None) };
|
||||
match (target, handler) {
|
||||
(Some(t), Some(_)) => Ok(Some(t)),
|
||||
_ => Err(self.type_error("the proxy has been revoked")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unwrapped_proxy_target(&mut self, mut id: ObjId) -> JsResult<ObjId> {
|
||||
while let Some(target) = self.symbol_lookup_target(id)? {
|
||||
self.use_fuel()?;
|
||||
id = target;
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn proxy_data(&self, id: ObjId) -> Option<ProxyData> {
|
||||
match self.heap.object(id).map(|o| &o.class) {
|
||||
Some(Class::Proxy(p)) => Some(**p),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// ProxyCreate (section 9.5.14): a proxy for `target` with `handler`.
|
||||
pub(crate) fn proxy_create(&mut self, target: &Value, handler: &Value) -> JsResult<ObjId> {
|
||||
let Value::Object(t) = target else { return Err(self.type_error("a proxy's target must be an object")) };
|
||||
let Value::Object(h) = handler else { return Err(self.type_error("a proxy's handler must be an object")) };
|
||||
// A revoked proxy is neither a target nor a handler (section 9.5.14, steps 2 and 4).
|
||||
for (o, what) in [(*t, "target"), (*h, "handler")] {
|
||||
if matches!(self.proxy_data(o), Some(ProxyData { handler: None, .. })) {
|
||||
return Err(self.type_error(&format!("a proxy's {what} cannot be a revoked proxy")));
|
||||
}
|
||||
}
|
||||
let data = ProxyData { target: Some(*t), handler: Some(*h), callable: self.is_callable(target), constructor: self.is_constructor(target) };
|
||||
self.rooted(&[target.clone(), handler.clone()], |i| i.reserve_heap(OBJECT_BYTES + PROXY_BYTES))?;
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(PROXY_BYTES);
|
||||
Ok(self.heap.alloc_object(Object::new(Class::Proxy(Box::new(data)), None)))
|
||||
}
|
||||
|
||||
/// Revokes the proxy `id`: every later operation on it is a `TypeError`. A value that is not a
|
||||
/// proxy is left as it is.
|
||||
pub(crate) fn proxy_revoke(&mut self, id: ObjId) {
|
||||
if let Some(Object { class: Class::Proxy(p), .. }) = self.heap.object_mut(id) {
|
||||
p.target = None;
|
||||
p.handler = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` with the proxy's target and handler for the operation `what`: a revoked proxy is a
|
||||
/// `TypeError`. The operation takes a unit of fuel and a nested call, and `p`, its target and
|
||||
/// handler and `roots` stay rooted while it runs, with anything `f` adds to the roots.
|
||||
fn proxy_op<T>(&mut self, p: ObjId, what: &str, roots: &[Value], f: impl FnOnce(&mut Self, ObjId, ObjId) -> JsResult<T>) -> JsResult<T> {
|
||||
if self.reentry >= self.limits.reentry {
|
||||
return Err(Abrupt::Limit(LimitKind::Reentry));
|
||||
}
|
||||
self.use_fuel()?;
|
||||
let Some(ProxyData { target: Some(target), handler: Some(handler), .. }) = self.proxy_data(p) else {
|
||||
return Err(self.type_error(&format!("cannot {what} a revoked proxy")));
|
||||
};
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend([Value::Object(p), Value::Object(target), Value::Object(handler)]);
|
||||
self.temp_roots.extend(roots.iter().cloned());
|
||||
self.reentry += 1;
|
||||
let r = f(self, target, handler);
|
||||
self.reentry -= 1;
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// GetMethod (section 7.3.10) of the handler: the trap `name`, or `None` when it is
|
||||
/// `undefined` or `null`.
|
||||
fn proxy_trap(&mut self, handler: ObjId, name: &str) -> JsResult<Option<Value>> {
|
||||
let trap = self.get_from(handler, &key(name), &Value::Object(handler))?;
|
||||
if trap.is_nullish() {
|
||||
return Ok(None);
|
||||
}
|
||||
if !self.is_callable(&trap) {
|
||||
return Err(self.type_error(&format!("the proxy handler's {name} is not a function")));
|
||||
}
|
||||
self.temp_roots.push(trap.clone());
|
||||
Ok(Some(trap))
|
||||
}
|
||||
|
||||
/// Calls the trap with the handler as `this`, keeping its result rooted.
|
||||
fn call_trap(&mut self, trap: &Value, handler: ObjId, args: &[Value]) -> JsResult<Value> {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
let result = self.call(trap, &Value::Object(handler), args);
|
||||
self.temp_roots.truncate(mark);
|
||||
let v = result?;
|
||||
self.temp_roots.push(v.clone());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The property name a trap is given, a copy of `k` counted against the heap limit, its code
|
||||
/// units charged as fuel.
|
||||
fn key_value(&mut self, k: &Key) -> JsResult<Value> {
|
||||
let bytes = string_bytes(k.len());
|
||||
self.reserve_heap(bytes)?;
|
||||
crate::string_builtins::charge_units(self, k.len())?;
|
||||
let copy = Value::String(Str::from_units(k.to_vec()));
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
|
||||
Ok(copy)
|
||||
}
|
||||
|
||||
fn invariant(&mut self, trap: &str, why: &str) -> Abrupt {
|
||||
self.type_error(&format!("the proxy's {trap} trap {why}"))
|
||||
}
|
||||
|
||||
// ---- [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] ----
|
||||
|
||||
/// [[GetPrototypeOf]] (sections 9.1.1 and 9.5.1).
|
||||
pub(crate) fn get_prototype_of(&mut self, id: ObjId) -> JsResult<Option<ObjId>> {
|
||||
if !self.is_proxy(id) {
|
||||
return Ok(self.object(id)?.proto);
|
||||
}
|
||||
self.proxy_op(id, "read the prototype of", &[], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "getPrototypeOf")? else { return i.get_prototype_of(target) };
|
||||
let proto = match i.call_trap(&trap, handler, &[Value::Object(target)])? {
|
||||
Value::Object(p) => Some(p),
|
||||
Value::Null => None,
|
||||
_ => return Err(i.invariant("getPrototypeOf", "returned a value that is neither an object nor null")),
|
||||
};
|
||||
if i.is_extensible(target)? {
|
||||
return Ok(proto);
|
||||
}
|
||||
if i.get_prototype_of(target)? != proto {
|
||||
return Err(i.invariant("getPrototypeOf", "returned a prototype other than its non-extensible target's"));
|
||||
}
|
||||
Ok(proto)
|
||||
})
|
||||
}
|
||||
|
||||
/// [[SetPrototypeOf]] (sections 9.1.2 and 9.5.2): whether the prototype was set. The
|
||||
/// prototype of `Object.prototype` cannot change (section 9.4.7).
|
||||
pub(crate) fn set_prototype_of(&mut self, id: ObjId, proto: Option<ObjId>) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
let arg = proto.map_or(Value::Null, Value::Object);
|
||||
return self.proxy_op(id, "set the prototype of", std::slice::from_ref(&arg), |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "setPrototypeOf")? else { return i.set_prototype_of(target, proto) };
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), arg.clone()])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
if i.is_extensible(target)? {
|
||||
return Ok(true);
|
||||
}
|
||||
if i.get_prototype_of(target)? != proto {
|
||||
return Err(i.invariant("setPrototypeOf", "reported setting a prototype its non-extensible target does not have"));
|
||||
}
|
||||
Ok(true)
|
||||
});
|
||||
}
|
||||
let o = self.object(id)?;
|
||||
if o.proto == proto {
|
||||
return Ok(true);
|
||||
}
|
||||
if !o.extensible || id == self.intrinsics.object_proto {
|
||||
return Ok(false);
|
||||
}
|
||||
// The new prototype's chain must not lead back to the object; a proxy on it ends the check.
|
||||
let mut cur = proto;
|
||||
while let Some(p) = cur {
|
||||
if p == id {
|
||||
return Ok(false);
|
||||
}
|
||||
if self.is_proxy(p) {
|
||||
break;
|
||||
}
|
||||
self.use_fuel()?;
|
||||
cur = self.object(p)?.proto;
|
||||
}
|
||||
self.object_mut(id)?.proto = proto;
|
||||
// A new prototype can bring indices with it.
|
||||
self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// [[IsExtensible]] (sections 9.1.3 and 9.5.3).
|
||||
pub(crate) fn is_extensible(&mut self, id: ObjId) -> JsResult<bool> {
|
||||
if !self.is_proxy(id) {
|
||||
return Ok(self.object(id)?.extensible);
|
||||
}
|
||||
self.proxy_op(id, "test the extensibility of", &[], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "isExtensible")? else { return i.is_extensible(target) };
|
||||
let answer = i.call_trap(&trap, handler, &[Value::Object(target)])?.truthy();
|
||||
if answer != i.is_extensible(target)? {
|
||||
return Err(i.invariant("isExtensible", "gave an answer other than its target's"));
|
||||
}
|
||||
Ok(answer)
|
||||
})
|
||||
}
|
||||
|
||||
/// [[PreventExtensions]] (sections 9.1.4 and 9.5.4): whether the object is now not
|
||||
/// extensible.
|
||||
pub(crate) fn prevent_extensions(&mut self, id: ObjId) -> JsResult<bool> {
|
||||
if !self.is_proxy(id) {
|
||||
self.object_mut(id)?.extensible = false;
|
||||
return Ok(true);
|
||||
}
|
||||
self.proxy_op(id, "prevent extensions of", &[], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "preventExtensions")? else { return i.prevent_extensions(target) };
|
||||
let done = i.call_trap(&trap, handler, &[Value::Object(target)])?.truthy();
|
||||
if done && i.is_extensible(target)? {
|
||||
return Err(i.invariant("preventExtensions", "returned true while its target is extensible"));
|
||||
}
|
||||
Ok(done)
|
||||
})
|
||||
}
|
||||
|
||||
// ---- properties ----
|
||||
|
||||
/// [[GetOwnProperty]] of a proxy (section 9.5.5).
|
||||
pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
self.proxy_op(p, "read a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.own_pk(target, k) };
|
||||
let name = i.pk_value(k)?;
|
||||
let result = i.call_trap(&trap, handler, &[Value::Object(target), name])?;
|
||||
if !matches!(result, Value::Object(_) | Value::Undefined) {
|
||||
return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined"));
|
||||
}
|
||||
let target_prop = i.own_pk(target, k)?;
|
||||
if let Some(prop) = &target_prop {
|
||||
i.temp_roots.extend(desc_values(&prop_desc(prop)));
|
||||
}
|
||||
if matches!(result, Value::Undefined) {
|
||||
let Some(current) = target_prop else { return Ok(None) };
|
||||
if !current.configurable() {
|
||||
return Err(i.invariant("getOwnPropertyDescriptor", "hid a non-configurable property of its target"));
|
||||
}
|
||||
if !i.is_extensible(target)? {
|
||||
return Err(i.invariant("getOwnPropertyDescriptor", "hid a property of its non-extensible target"));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
let extensible = i.is_extensible(target)?;
|
||||
let desc = to_desc(i, &result)?;
|
||||
i.temp_roots.extend(desc_values(&desc));
|
||||
let prop = complete(&desc);
|
||||
let desc = prop_desc(&prop);
|
||||
if !compatible(extensible, &desc, target_prop.as_ref()) {
|
||||
return Err(i.invariant("getOwnPropertyDescriptor", "gave a descriptor its target's property does not allow"));
|
||||
}
|
||||
if !prop.configurable() {
|
||||
match &target_prop {
|
||||
Some(t) if !t.configurable() => {}
|
||||
_ => {
|
||||
return Err(
|
||||
i.invariant("getOwnPropertyDescriptor", "reported a non-configurable property its target has as configurable or lacks")
|
||||
);
|
||||
}
|
||||
}
|
||||
if desc.writable == Some(false) && matches!(target_prop, Some(Prop::Data { flags, .. }) if flags & WRITABLE != 0) {
|
||||
return Err(
|
||||
i.invariant("getOwnPropertyDescriptor", "reported a writable property of its target as non-configurable and read-only")
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Some(prop))
|
||||
})
|
||||
}
|
||||
|
||||
/// [[DefineOwnProperty]] of a proxy (section 9.5.6): whether the trap defined the property.
|
||||
pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &PropKey, desc: &Desc) -> JsResult<bool> {
|
||||
let mut roots = desc_values(desc);
|
||||
roots.push(pk_root(k));
|
||||
self.proxy_op(p, "define a property of", &roots, |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_pk(target, k.clone(), desc, false) };
|
||||
let desc_obj = from_desc(i, desc)?;
|
||||
i.temp_roots.push(desc_obj.clone());
|
||||
let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.pk_value(k))?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
let target_prop = i.own_pk(target, k)?;
|
||||
let extensible = i.is_extensible(target)?;
|
||||
let setting_config_false = desc.configurable == Some(false);
|
||||
let Some(current) = target_prop else {
|
||||
if !extensible {
|
||||
return Err(i.invariant("defineProperty", "added a property to its non-extensible target"));
|
||||
}
|
||||
if setting_config_false {
|
||||
return Err(i.invariant("defineProperty", "defined a non-configurable property its target lacks"));
|
||||
}
|
||||
return Ok(true);
|
||||
};
|
||||
if !compatible(extensible, desc, Some(¤t)) {
|
||||
return Err(i.invariant("defineProperty", "defined a property its target's property does not allow"));
|
||||
}
|
||||
if setting_config_false && current.configurable() {
|
||||
return Err(i.invariant("defineProperty", "defined a property as non-configurable that is configurable on its target"));
|
||||
}
|
||||
if let Prop::Data { flags, .. } = current
|
||||
&& flags & CONFIGURABLE == 0
|
||||
&& flags & WRITABLE != 0
|
||||
&& desc.writable == Some(false)
|
||||
{
|
||||
return Err(i.invariant("defineProperty", "made a property read-only that is writable on its target"));
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// [[HasProperty]] of a proxy (section 9.5.7).
|
||||
pub(crate) fn proxy_has(&mut self, p: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
self.proxy_op(p, "test a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_pk_indexed(target, k) };
|
||||
let name = i.pk_value(k)?;
|
||||
let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy();
|
||||
if !found && let Some(current) = i.own_pk(target, k)? {
|
||||
if !current.configurable() {
|
||||
return Err(i.invariant("has", "hid a non-configurable property of its target"));
|
||||
}
|
||||
if !i.is_extensible(target)? {
|
||||
return Err(i.invariant("has", "hid a property of its non-extensible target"));
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
})
|
||||
}
|
||||
|
||||
/// [[Get]] of a proxy (section 9.5.8).
|
||||
pub(crate) fn proxy_get(&mut self, p: ObjId, k: &PropKey, receiver: &Value, indexed: bool) -> JsResult<Value> {
|
||||
self.proxy_op(p, "read a property of", &[receiver.clone(), pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "get")? else {
|
||||
return match k {
|
||||
PropKey::Str(name) if indexed => i.get_from(target, name, receiver),
|
||||
PropKey::Str(name) => i.get_property_only(target, name, receiver),
|
||||
PropKey::Sym(s) => i.get_sym_from(target, s, receiver),
|
||||
};
|
||||
};
|
||||
let name = i.pk_value(k)?;
|
||||
let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?;
|
||||
match i.own_pk(target, k)? {
|
||||
Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => {
|
||||
Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property"))
|
||||
}
|
||||
Some(Prop::Accessor { get: None, flags, .. }) if flags & CONFIGURABLE == 0 && !matches!(v, Value::Undefined) => {
|
||||
Err(i.invariant("get", "gave a value for a non-configurable property of its target that has no getter"))
|
||||
}
|
||||
_ => Ok(v),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [[Set]] of a proxy (section 9.5.9): whether the trap set the property.
|
||||
pub(crate) fn proxy_set(&mut self, p: ObjId, k: &PropKey, v: &Value, receiver: &Value) -> JsResult<bool> {
|
||||
self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_pk_with_receiver(target, k.clone(), v.clone(), receiver) };
|
||||
let name = i.pk_value(k)?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
match i.own_pk(target, k)? {
|
||||
Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => {
|
||||
Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property"))
|
||||
}
|
||||
Some(Prop::Accessor { set: None, flags, .. }) if flags & CONFIGURABLE == 0 => {
|
||||
Err(i.invariant("set", "set a non-configurable property of its target that has no setter"))
|
||||
}
|
||||
_ => Ok(true),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property.
|
||||
pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
self.proxy_op(p, "delete a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete_pk(target, k, false) };
|
||||
let name = i.pk_value(k)?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(current) = i.own_pk(target, k)? else { return Ok(true) };
|
||||
if !current.configurable() {
|
||||
return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target"));
|
||||
}
|
||||
if !i.is_extensible(target)? {
|
||||
return Err(i.invariant("deleteProperty", "deleted a property of its non-extensible target"));
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object
|
||||
/// of distinct strings and Symbols, at most [`MAX_OWN_KEYS`] of them, that holds every
|
||||
/// 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, 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 = 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))?;
|
||||
}
|
||||
return Ok(keys);
|
||||
};
|
||||
let result = i.call_trap(&trap, handler, &[Value::Object(target)])?;
|
||||
let mut held = HeldBytes::new(i);
|
||||
let TrapKeys { keys, syms, ordered } = i.trap_key_list(&result, &mut held)?;
|
||||
i.check_own_keys(target, &keys, &syms)?;
|
||||
Ok(HeldKeys { keys, syms, ordered: Some(ordered), held })
|
||||
})
|
||||
}
|
||||
|
||||
/// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]:
|
||||
/// 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, ecma_order);
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
/// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result: its names and its
|
||||
/// Symbols in the order given, refusing a value that is neither and a key given twice. Two
|
||||
/// Symbols are the same key only when they are the same Symbol.
|
||||
fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult<TrapKeys> {
|
||||
let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) };
|
||||
let length = self.get_from(*list, &key("length"), result)?;
|
||||
let n = self.to_number(&length)?;
|
||||
// ToLength (section 7.1.15).
|
||||
let n = if n.is_nan() || n <= 0.0 { 0.0 } else { n.trunc() };
|
||||
if n > MAX_OWN_KEYS {
|
||||
return Err(self.throw(ErrorType::Range, "the proxy's ownKeys trap returned too many names"));
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
let mut syms = Vec::new();
|
||||
let mut ordered = Vec::new();
|
||||
let mut seen: HashSet<Key> = HashSet::new();
|
||||
// Symbols by identity: their addresses.
|
||||
let mut seen_syms: HashSet<usize> = HashSet::new();
|
||||
let mut duplicate = None;
|
||||
for index in 0..n as u32 {
|
||||
self.use_fuel()?;
|
||||
let v = self.get_from(*list, &index_key(index), result)?;
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
held.add(self, string_bytes(s.len()).saturating_add(3 * KEY_ENTRY_BYTES))?;
|
||||
// Flattening and hashing the name read every code unit of it.
|
||||
crate::string_builtins::charge_units(self, s.len())?;
|
||||
let k = s.flat();
|
||||
if !seen.insert(k.clone()) && duplicate.is_none() {
|
||||
duplicate = Some(PropKey::Str(k.clone()));
|
||||
}
|
||||
ordered.push(PropKey::Str(k.clone()));
|
||||
keys.push(k);
|
||||
}
|
||||
Value::Symbol(s) => {
|
||||
// A Symbol read from the list stays reachable while later entries are read.
|
||||
self.temp_roots.push(Value::Symbol(s.clone()));
|
||||
held.add(self, 3 * KEY_ENTRY_BYTES)?;
|
||||
if !seen_syms.insert(s.addr()) && duplicate.is_none() {
|
||||
duplicate = Some(PropKey::Sym(s.clone()));
|
||||
}
|
||||
ordered.push(PropKey::Sym(s.clone()));
|
||||
syms.push(s);
|
||||
}
|
||||
_ => return Err(self.invariant("ownKeys", "returned a key that is neither a string nor a Symbol")),
|
||||
}
|
||||
}
|
||||
if let Some(k) = duplicate {
|
||||
let name = self.pk_name(&k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("returned the key '{name}' twice")));
|
||||
}
|
||||
Ok(TrapKeys { keys, syms, ordered })
|
||||
}
|
||||
|
||||
/// Steps 16 to 23 of section 9.5.11: the names `keys` and the Symbols `syms` the trap gave
|
||||
/// against the target's own keys of both kinds.
|
||||
fn check_own_keys(&mut self, target: ObjId, keys: &[Key], syms: &[Sym]) -> JsResult<()> {
|
||||
let extensible = self.is_extensible(target)?;
|
||||
// The target's keys in its own order (a proxy target's trap order), counted until the
|
||||
// check ends.
|
||||
let (target_keys, _held) = self.own_keys_and_symbols(target)?.into_prop_keys();
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend(target_keys.iter().filter_map(|k| match k {
|
||||
PropKey::Sym(s) => Some(Value::Symbol(s.clone())),
|
||||
PropKey::Str(_) => None,
|
||||
}));
|
||||
let r = (|| {
|
||||
let mut fixed = Vec::new();
|
||||
let mut configurable = Vec::new();
|
||||
for k in target_keys.iter().cloned() {
|
||||
self.use_fuel()?;
|
||||
if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) {
|
||||
fixed.push(k);
|
||||
} else {
|
||||
configurable.push(k);
|
||||
}
|
||||
}
|
||||
if extensible && fixed.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Building the set and each lookup in it hash every code unit of the name.
|
||||
for k in keys {
|
||||
crate::string_builtins::charge_units(self, k.len())?;
|
||||
}
|
||||
let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect();
|
||||
let mut unchecked_syms: HashSet<usize> = syms.iter().map(Sym::addr).collect();
|
||||
for k in &fixed {
|
||||
charge_lookup(self, k)?;
|
||||
if !take(&mut unchecked, &mut unchecked_syms, k) {
|
||||
let name = self.pk_name(k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target")));
|
||||
}
|
||||
}
|
||||
if extensible {
|
||||
return Ok(());
|
||||
}
|
||||
for k in &configurable {
|
||||
charge_lookup(self, k)?;
|
||||
if !take(&mut unchecked, &mut unchecked_syms, k) {
|
||||
let name = self.pk_name(k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target")));
|
||||
}
|
||||
}
|
||||
if !unchecked.is_empty() || !unchecked_syms.is_empty() {
|
||||
return Err(self.invariant("ownKeys", "gave a key its non-extensible target does not have"));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// The value a trap is given for the key `k`: a copy of a name, or the Symbol itself.
|
||||
fn pk_value(&mut self, k: &PropKey) -> JsResult<Value> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.key_value(name),
|
||||
PropKey::Sym(s) => Ok(Value::Symbol(s.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Set]] of `k` on `o` with `receiver`, for a name or a Symbol: whether the value was set.
|
||||
pub(crate) fn set_pk_with_receiver(&mut self, o: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.set_with_receiver(o, name, v, receiver),
|
||||
PropKey::Sym(s) => self.set_sym_with_receiver(o, s, v, receiver),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Set]] (sections 9.1.9 and 9.5.9) of the Symbol `k` on `o` with `receiver`: a proxy's
|
||||
/// `set` trap, a setter found on the chain, or a data property defined on the receiver
|
||||
/// through its own [[DefineOwnProperty]]. Whether the value was set.
|
||||
pub(crate) fn set_sym_with_receiver(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend([Value::Object(o), Value::Symbol(k.clone()), v.clone(), receiver.clone()]);
|
||||
let r = self.ordinary_set_sym(o, k, v, receiver);
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
fn ordinary_set_sym(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
let mut cur = o;
|
||||
let mut steps = 0usize;
|
||||
let own = loop {
|
||||
if self.is_proxy(cur) {
|
||||
return self.proxy_set(cur, &PropKey::Sym(k), &v, receiver);
|
||||
}
|
||||
if matches!(self.object(cur)?.class, Class::ModuleNamespace(_)) {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(p) = self.get_own_sym(cur, &k)? {
|
||||
break p;
|
||||
}
|
||||
match self.object(cur)?.proto {
|
||||
Some(next) => {
|
||||
self.use_fuel()?;
|
||||
cur = next;
|
||||
}
|
||||
None => break Prop::Data { value: Value::Undefined, flags: OPEN },
|
||||
}
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return Err(Abrupt::Internal("prototype chain too long".into()));
|
||||
}
|
||||
};
|
||||
match own {
|
||||
Prop::Accessor { set: Some(s), .. } => {
|
||||
self.call(&Value::Object(s), receiver, &[v])?;
|
||||
Ok(true)
|
||||
}
|
||||
Prop::Accessor { set: None, .. } => Ok(false),
|
||||
Prop::Data { flags, .. } if flags & WRITABLE == 0 => Ok(false),
|
||||
Prop::Data { .. } => {
|
||||
let Value::Object(r) = receiver else { return Ok(false) };
|
||||
let r = *r;
|
||||
match self.get_own_sym(r, &k)? {
|
||||
Some(Prop::Accessor { .. }) => Ok(false),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Ok(false),
|
||||
Some(Prop::Data { .. }) => self.define_own_sym(r, k, &Desc { value: Some(v), ..Desc::default() }, false),
|
||||
None => self.define_own_sym(r, k, &Desc::data(v, OPEN), false),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Set]] (section 9.1.9) of `k` on `o` with `receiver`: a proxy's `set` trap, a setter found
|
||||
/// on the chain, or a data property defined on the receiver. Whether the value was set.
|
||||
pub(crate) fn set_with_receiver(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend([Value::Object(o), v.clone(), receiver.clone()]);
|
||||
let r = self.ordinary_set(o, k, v, receiver);
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
fn ordinary_set(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
// A typed array set on itself writes a numeric key as its element, converting the value
|
||||
// and ignoring a key outside the view; with another receiver a key outside the view is
|
||||
// ignored and an element is set on the receiver as usual, as the typed arrays' other
|
||||
// writes follow the later editions (https://tc39.es/ecma262/#sec-typedarray-set).
|
||||
if let Some(n) = crate::builtins::binary::typed_key(self, o, &k) {
|
||||
if receiver.as_object() == Some(o) {
|
||||
crate::builtins::binary::set_element(self, o, n, &v)?;
|
||||
return Ok(true);
|
||||
}
|
||||
if !crate::builtins::binary::is_element(self, o, n) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
let found = self.lookup_for_set(o, &k)?;
|
||||
let own = match found {
|
||||
SetLookup::ReadOnly => return Ok(false),
|
||||
SetLookup::TypedArray(t, n) => {
|
||||
if receiver.as_object() == Some(t) {
|
||||
crate::builtins::binary::set_element(self, t, n, &v)?;
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
SetLookup::Proxy(p) => return self.proxy_set(p, &PropKey::Str(k), &v, receiver),
|
||||
SetLookup::Found(prop) => prop,
|
||||
SetLookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN },
|
||||
};
|
||||
match own {
|
||||
Prop::Accessor { set: Some(s), .. } => {
|
||||
self.call(&Value::Object(s), receiver, &[v])?;
|
||||
Ok(true)
|
||||
}
|
||||
Prop::Accessor { set: None, .. } => Ok(false),
|
||||
Prop::Data { flags, .. } if flags & WRITABLE == 0 => Ok(false),
|
||||
Prop::Data { .. } => {
|
||||
let Value::Object(r) = receiver else { return Ok(false) };
|
||||
let r = *r;
|
||||
match self.get_own_property(r, &k)? {
|
||||
Some(Prop::Accessor { .. }) => Ok(false),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Ok(false),
|
||||
Some(Prop::Data { .. }) => self.define_own_property(r, k, &Desc { value: Some(v), ..Desc::default() }, false),
|
||||
None => self.define_own_property(r, k, &Desc::data(v, OPEN), false),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- calls ----
|
||||
|
||||
/// [[Call]] of a proxy (section 9.5.12): the trap's result, or the target to call when the
|
||||
/// handler has no `apply` trap.
|
||||
pub(crate) fn proxy_call(&mut self, p: ObjId, this: &Value, args: &[Value]) -> JsResult<ProxyCall> {
|
||||
if !self.proxy_data(p).is_some_and(|d| d.callable) {
|
||||
return Err(self.type_error("the value is not a function"));
|
||||
}
|
||||
let mut roots = vec![this.clone()];
|
||||
roots.extend(args.iter().cloned());
|
||||
self.proxy_op(p, "call", &roots, |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "apply")? else { return Ok(ProxyCall::Target(target)) };
|
||||
let list = i.trap_array(args)?;
|
||||
let v = i.call_trap(&trap, handler, &[Value::Object(target), this.clone(), list])?;
|
||||
Ok(ProxyCall::Done(v))
|
||||
})
|
||||
}
|
||||
|
||||
/// [[Construct]] of a proxy (section 9.5.13): the object the trap made, or the target to
|
||||
/// construct when the handler has no `construct` trap.
|
||||
pub(crate) fn proxy_construct(&mut self, p: ObjId, args: &[Value], new_target: &Value) -> JsResult<ProxyCall> {
|
||||
if !self.proxy_data(p).is_some_and(|d| d.constructor) {
|
||||
return Err(self.type_error("the value is not a constructor"));
|
||||
}
|
||||
let mut roots = vec![new_target.clone()];
|
||||
roots.extend(args.iter().cloned());
|
||||
self.proxy_op(p, "construct", &roots, |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "construct")? else { return Ok(ProxyCall::Target(target)) };
|
||||
let list = i.trap_array(args)?;
|
||||
let v = i.call_trap(&trap, handler, &[Value::Object(target), list, new_target.clone()])?;
|
||||
if !matches!(v, Value::Object(_)) {
|
||||
return Err(i.invariant("construct", "returned a value that is not an object"));
|
||||
}
|
||||
Ok(ProxyCall::Done(v))
|
||||
})
|
||||
}
|
||||
|
||||
/// CreateArrayFromList (section 7.3.16) of the arguments a trap is given, checked against the
|
||||
/// heap limit and kept rooted.
|
||||
fn trap_array(&mut self, args: &[Value]) -> JsResult<Value> {
|
||||
self.reserve_heap(OBJECT_BYTES.saturating_add(args.len().saturating_mul(PROP_BYTES + string_bytes(10))))?;
|
||||
let a = Value::Object(self.array_of(args)?);
|
||||
self.temp_roots.push(a.clone());
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// IsArray (section 7.2.2): an array, or a proxy whose target is one. A revoked proxy is a
|
||||
/// `TypeError`.
|
||||
pub(crate) fn is_array(&mut self, v: &Value) -> JsResult<bool> {
|
||||
let mut cur = v.as_object();
|
||||
while let Some(o) = cur {
|
||||
match self.heap.object(o).map(|x| &x.class) {
|
||||
Some(Class::Array { .. }) => return Ok(true),
|
||||
Some(Class::Proxy(p)) => {
|
||||
let ProxyData { target, handler, .. } = **p;
|
||||
if handler.is_none() {
|
||||
return Err(self.type_error("cannot test whether a revoked proxy is an array"));
|
||||
}
|
||||
self.use_fuel()?;
|
||||
cur = target;
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys an `ownKeys` trap gave: the names, the Symbols, and both in the trap's order.
|
||||
struct TrapKeys {
|
||||
keys: Vec<Key>,
|
||||
syms: Vec<Sym>,
|
||||
ordered: Vec<PropKey>,
|
||||
}
|
||||
|
||||
/// The key `k` as a value, to keep it reachable while a trap runs.
|
||||
fn pk_root(k: &PropKey) -> Value {
|
||||
match k {
|
||||
PropKey::Str(name) => Value::String(Str::from_rc(name.clone())),
|
||||
PropKey::Sym(s) => Value::Symbol(s.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the fuel for hashing the name `k` to look it up; a Symbol is looked up by address.
|
||||
fn charge_lookup(interp: &mut Interp, k: &PropKey) -> JsResult<()> {
|
||||
match k {
|
||||
PropKey::Str(name) => crate::string_builtins::charge_units(interp, name.len()),
|
||||
PropKey::Sym(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes `k` from the keys a trap gave that are not yet matched: whether it was there.
|
||||
fn take(names: &mut HashSet<&[u16]>, syms: &mut HashSet<usize>, k: &PropKey) -> bool {
|
||||
match k {
|
||||
PropKey::Str(name) => names.remove(&**name),
|
||||
PropKey::Sym(s) => syms.remove(&s.addr()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a descriptor holds, to keep them reachable while more script runs.
|
||||
pub(crate) fn desc_values(desc: &Desc) -> Vec<Value> {
|
||||
let mut out: Vec<Value> = desc.value.iter().cloned().collect();
|
||||
out.extend(desc.get.flatten().map(Value::Object));
|
||||
out.extend(desc.set.flatten().map(Value::Object));
|
||||
out
|
||||
}
|
||||
|
||||
/// CompletePropertyDescriptor (section 6.2.5.6): the property `desc` describes, each absent field
|
||||
/// at its default.
|
||||
fn complete(desc: &Desc) -> Prop {
|
||||
let flags = desc.flags_or(0);
|
||||
if desc.is_accessor() {
|
||||
Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & (ENUMERABLE | CONFIGURABLE) }
|
||||
} else {
|
||||
Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags }
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptor with every field of `prop`.
|
||||
fn prop_desc(prop: &Prop) -> Desc {
|
||||
match prop {
|
||||
Prop::Data { value, flags } => Desc::data(value.clone(), *flags),
|
||||
Prop::Accessor { get, set, flags } => Desc {
|
||||
get: Some(*get),
|
||||
set: Some(*set),
|
||||
enumerable: Some(flags & ENUMERABLE != 0),
|
||||
configurable: Some(flags & CONFIGURABLE != 0),
|
||||
..Desc::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// IsCompatiblePropertyDescriptor (section 9.1.6.2): whether a target with `current` (and, when
|
||||
/// it has none, `extensible`) allows `desc`.
|
||||
fn compatible(extensible: bool, desc: &Desc, current: Option<&Prop>) -> bool {
|
||||
match current {
|
||||
None => extensible,
|
||||
Some(current) => merge_desc(current, desc).is_some(),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+16
-1
@@ -264,7 +264,8 @@ impl Realm {
|
||||
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
|
||||
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
|
||||
/// [`Realm::start`] that is still going keeps the language it started with for the code it
|
||||
/// evaluates; the new one applies once it ends.
|
||||
/// evaluates; the new one applies once it ends. A realm made without the option gets `Proxy`
|
||||
/// and `Reflect` at its first run with it, and keeps them when it is turned off.
|
||||
pub fn set_es2015(&mut self, es2015: bool) {
|
||||
if self.is_running() || self.interp.waiting {
|
||||
self.interp.next_es2015 = Some(es2015);
|
||||
@@ -417,6 +418,19 @@ impl Realm {
|
||||
}),
|
||||
};
|
||||
}
|
||||
let interp = &mut self.interp;
|
||||
// A realm made without `Options::es2015` gets `Proxy` and `Reflect` at its first run with it.
|
||||
if interp.options.es2015
|
||||
&& let Err(e) = crate::builtins::install_es2015(interp)
|
||||
{
|
||||
interp.temp_roots.clear();
|
||||
let (kind, message) = match e {
|
||||
Abrupt::Limit(kind) => (RunErrorKind::Limit(kind), format!("limit reached: {kind:?}")),
|
||||
Abrupt::Throw(v) => (RunErrorKind::Internal, format!("Proxy and Reflect could not be installed: {}", interp.describe(&v))),
|
||||
Abrupt::Internal(m) => (RunErrorKind::Internal, format!("Proxy and Reflect could not be installed: {m}")),
|
||||
};
|
||||
return Err(RunError { kind, message, line: 0, column: 0, authored: false });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -753,6 +767,7 @@ impl Realm {
|
||||
/// prototype holds its members, and the global objects `instances`, each made from the
|
||||
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
|
||||
/// replaced. A heap too small for them ends with the error the realm's next run would give.
|
||||
/// A call that fails adds none of its classes or instances, and can be made again.
|
||||
pub fn define_host_classes(&mut self, classes: Vec<crate::HostClass>, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> {
|
||||
match crate::host_classes::install(&mut self.interp, classes, instances) {
|
||||
Ok(()) => Ok(()),
|
||||
|
||||
@@ -100,6 +100,9 @@ fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<V
|
||||
Value::Symbol(_) => (interp.symbols.objects.map_or(interp.intrinsics.object_proto, |o| o.symbol_proto), Some("Symbol")),
|
||||
Value::Object(o) => (*o, None),
|
||||
};
|
||||
if interp.is_proxy(id) {
|
||||
return Err(interp.type_error("reflect does not support proxy objects"));
|
||||
}
|
||||
let (name, properties, methods) = match interp.host_class_members(id)? {
|
||||
Some((name, members)) if primitive.is_none() => {
|
||||
let (properties, methods) = host_infos(interp, &members)?;
|
||||
@@ -325,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,
|
||||
|
||||
@@ -211,7 +211,7 @@ fn range(i: &mut Interp, message: &str) -> Abrupt {
|
||||
|
||||
/// The value of the own data property `name` of `o`, `undefined` when it has none.
|
||||
fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
Ok(match i.get_own_property(o, &key(name))? {
|
||||
Ok(match i.ordinary_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
@@ -317,7 +317,7 @@ fn list_values(i: &Interp, a: ObjId) -> JsResult<Vec<Value>> {
|
||||
};
|
||||
(0..length)
|
||||
.map(|n| {
|
||||
Ok(match i.get_own_property(a, &index_key(n))? {
|
||||
Ok(match i.ordinary_own_property(a, &index_key(n))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
@@ -1841,7 +1841,7 @@ fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value
|
||||
/// Has each list item in `texts` the text it had when it was read?
|
||||
fn texts_unchanged(i: &Interp, texts: &[(ObjId, Value)]) -> JsResult<bool> {
|
||||
for (item, read) in texts {
|
||||
match i.get_own_property(*item, &key("text"))? {
|
||||
match i.ordinary_own_property(*item, &key("text"))? {
|
||||
Some(Prop::Data { value, .. }) if crate::interp::same_value(&value, read) => {}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
|
||||
+89
-21
@@ -143,6 +143,7 @@ impl SymProps {
|
||||
}
|
||||
|
||||
/// A property key (section 6.1.7): a name or a Symbol.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum PropKey {
|
||||
Str(crate::heap::Key),
|
||||
Sym(Sym),
|
||||
@@ -156,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>,
|
||||
}
|
||||
|
||||
@@ -170,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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,18 +324,27 @@ impl Interp {
|
||||
self.reject(true, &name, why)
|
||||
}
|
||||
|
||||
pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
/// [[GetOwnProperty]] for a Symbol key, through a proxy's `getOwnPropertyDescriptor` trap
|
||||
/// when `id` is a proxy.
|
||||
pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_get_own_property(id, &PropKey::Sym(k.clone()));
|
||||
}
|
||||
Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned())
|
||||
}
|
||||
|
||||
/// The property `k` found on the object or its prototype chain. Each step to a prototype takes
|
||||
/// a unit of fuel.
|
||||
pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
/// The object on the chain from `id` that holds `k` with the property, or the first proxy on
|
||||
/// the way, whose traps answer the rest; `None` when no object on the chain has `k`. Each step
|
||||
/// to a prototype takes a unit of fuel.
|
||||
pub(crate) fn sym_holder(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<(ObjId, Option<Prop>)>> {
|
||||
let mut cur = Some(id);
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
if let Some(p) = self.get_own_sym(o, k)? {
|
||||
return Ok(Some(p));
|
||||
if self.is_proxy(o) {
|
||||
return Ok(Some((o, None)));
|
||||
}
|
||||
if let Some(p) = self.object(o)?.syms.as_ref().and_then(|m| m.get(k)).cloned() {
|
||||
return Ok(Some((o, Some(p))));
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
if cur.is_some() {
|
||||
@@ -340,12 +358,23 @@ impl Interp {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter.
|
||||
/// [[HasProperty]] of `k`, through the `has` trap of a proxy on the prototype chain.
|
||||
pub(crate) fn has_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<bool> {
|
||||
match self.sym_holder(id, k)? {
|
||||
None => Ok(false),
|
||||
Some((_, Some(_))) => Ok(true),
|
||||
Some((p, None)) => self.proxy_has(p, &PropKey::Sym(k.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter, through the
|
||||
/// `get` trap of a proxy on the prototype chain.
|
||||
pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult<Value> {
|
||||
match self.find_sym(start, k)? {
|
||||
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
match self.sym_holder(start, k)? {
|
||||
None | Some((_, Some(Prop::Accessor { get: None, .. }))) => Ok(Value::Undefined),
|
||||
Some((_, Some(Prop::Data { value, .. }))) => Ok(value),
|
||||
Some((_, Some(Prop::Accessor { get: Some(g), .. }))) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Some((p, None)) => self.proxy_get(p, &PropKey::Sym(k.clone()), receiver, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,7 +388,8 @@ impl Interp {
|
||||
self.get_sym_from(start, k, base)
|
||||
}
|
||||
|
||||
/// Adds or replaces an own property directly, keeping the heap estimate.
|
||||
/// Adds or replaces an own property directly, keeping the heap estimate. For objects the
|
||||
/// engine made, which are never proxies.
|
||||
pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> {
|
||||
let o = self.object_mut(id)?;
|
||||
if o.syms.get_or_insert_with(Box::default).insert(k, prop) {
|
||||
@@ -370,6 +400,12 @@ impl Interp {
|
||||
|
||||
/// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key.
|
||||
pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
if !self.proxy_define_own_property(id, &PropKey::Sym(k.clone()), desc)? {
|
||||
return self.reject_sym_bool(throw, &k, "the proxy's defineProperty trap returned false");
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(current) = self.get_own_sym(id, &k)? else {
|
||||
if !self.object(id)?.extensible {
|
||||
return self.reject_sym_bool(throw, &k, "the object is not extensible");
|
||||
@@ -394,6 +430,12 @@ impl Interp {
|
||||
|
||||
/// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key.
|
||||
pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> {
|
||||
if self.is_proxy(id) {
|
||||
if !self.set_sym_with_receiver(id, k.clone(), v, &Value::Object(id))? {
|
||||
return self.reject_sym(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
match self.get_own_sym(id, &k)? {
|
||||
Some(Prop::Data { flags, .. }) => {
|
||||
if flags & WRITABLE == 0 {
|
||||
@@ -415,6 +457,13 @@ impl Interp {
|
||||
if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) {
|
||||
return self.reject_sym(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
// Past a proxy the rest is its [[Set]], with the object as the receiver.
|
||||
if self.is_proxy(object) {
|
||||
if !self.set_sym_with_receiver(object, k.clone(), v, &Value::Object(id))? {
|
||||
return self.reject_sym(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(property) = self.get_own_sym(object, &k)? {
|
||||
inherited = Some(property);
|
||||
break;
|
||||
@@ -455,10 +504,18 @@ impl Interp {
|
||||
}
|
||||
_ => {
|
||||
let proto = self.primitive_proto(base, &[])?;
|
||||
if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? {
|
||||
return self.call(&Value::Object(s), base, &[v]).map(drop);
|
||||
}
|
||||
let strict = self.strict();
|
||||
match self.sym_holder(proto, &k)? {
|
||||
Some((_, Some(Prop::Accessor { set: Some(s), .. }))) => return self.call(&Value::Object(s), base, &[v]).map(drop),
|
||||
// Past a proxy the rest is its [[Set]], with the primitive as the receiver.
|
||||
Some((p, None)) => {
|
||||
if !self.set_sym_with_receiver(p, k.clone(), v, base)? {
|
||||
return self.reject_sym(strict, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.reject_sym(strict, &k, "the value is a primitive")
|
||||
}
|
||||
}
|
||||
@@ -466,6 +523,14 @@ impl Interp {
|
||||
|
||||
/// [[Delete]] (section 9.1.10) for a Symbol key.
|
||||
pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
let deleted = self.proxy_delete(id, &PropKey::Sym(k.clone()))?;
|
||||
if !deleted && throw {
|
||||
let key = self.sym_name(k)?;
|
||||
return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false")));
|
||||
}
|
||||
return Ok(deleted);
|
||||
}
|
||||
match self.get_own_sym(id, k)? {
|
||||
None => Ok(true),
|
||||
Some(p) if p.configurable() => {
|
||||
@@ -483,8 +548,11 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and
|
||||
/// the heap for the list is checked first.
|
||||
/// 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, false)?.syms);
|
||||
}
|
||||
let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
|
||||
self.reserve_heap(count.saturating_mul(16))?;
|
||||
for _ in 0..count {
|
||||
@@ -495,7 +563,7 @@ impl Interp {
|
||||
|
||||
// ---- either kind of key ----
|
||||
|
||||
pub(crate) fn get_own_pk(&self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
pub(crate) fn get_own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.get_own_property(id, name),
|
||||
PropKey::Sym(s) => self.get_own_sym(id, s),
|
||||
@@ -505,7 +573,7 @@ impl Interp {
|
||||
pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.has_property(id, name),
|
||||
PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()),
|
||||
PropKey::Sym(s) => self.has_sym(id, s),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-32
@@ -749,7 +749,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// Whether a scope object has the variable `name`.
|
||||
pub(crate) fn scope_has(&mut self, object: ObjId, name: &[u16]) -> JsResult<bool> {
|
||||
pub(crate) fn scope_has(&mut self, object: ObjId, name: &Key) -> JsResult<bool> {
|
||||
if self.options.e4x && self.is_xml(&Value::Object(object)) {
|
||||
let k = Value::String(Str::from_units(name.to_vec()));
|
||||
return self.xml_has(&Value::Object(object), &k);
|
||||
@@ -871,7 +871,7 @@ impl Interp {
|
||||
|
||||
/// The function a call `base.name(...)` runs and its `this` (ECMA-357 section 11.2.2.1). A
|
||||
/// call looks the name up among the methods, never among the children.
|
||||
pub(crate) fn xml_method(&mut self, base: &Value, name: &[u16]) -> JsResult<(Value, Value)> {
|
||||
pub(crate) fn xml_method(&mut self, base: &Value, name: &Key) -> JsResult<(Value, Value)> {
|
||||
let mut base = base.clone();
|
||||
loop {
|
||||
let Value::Object(o) = base else { return Err(self.not_xml()) };
|
||||
@@ -895,36 +895,6 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// A method found through an XML value in scope, for a call of a bare name in a filter.
|
||||
pub(crate) fn xml_scope_method(&mut self, name: &[u16]) -> JsResult<Option<(Value, Value)>> {
|
||||
let mut cur = Some(self.frame()?.env);
|
||||
while let Some(e) = cur {
|
||||
match self.heap.env(e) {
|
||||
Some(Env::Decl { bindings, outer }) => {
|
||||
if bindings.contains(name) {
|
||||
return Ok(None);
|
||||
}
|
||||
cur = *outer;
|
||||
}
|
||||
Some(&Env::Obj { object, outer, .. }) => {
|
||||
if self.scope_has(object, name)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let this = Value::Object(object);
|
||||
if self.is_xml(&this) {
|
||||
let f = self.get_from(object, name, &this)?;
|
||||
if self.is_callable(&f) {
|
||||
return Ok(Some((f, this)));
|
||||
}
|
||||
}
|
||||
cur = outer;
|
||||
}
|
||||
None => return Err(Abrupt::Internal("environment out of range".into())),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn xml_enumerate(&mut self, id: ObjId) -> JsResult<Vec<Key>> {
|
||||
let len = match self.classify(&Value::Object(id)) {
|
||||
Xv::List(l) => self.list_len(l)?,
|
||||
|
||||
@@ -210,7 +210,7 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) {
|
||||
return Ok(fields.get(&key(name)).cloned().unwrap_or(Value::Undefined));
|
||||
}
|
||||
Ok(match i.get_own_property(o, &key(name))? {
|
||||
Ok(match i.ordinary_own_property(o, &key(name))? {
|
||||
Some(Prop::Data { value, .. }) => value,
|
||||
_ => Value::Undefined,
|
||||
})
|
||||
|
||||
+111
-1
@@ -42,6 +42,10 @@
|
||||
//! [`ES2015_COLLECTION_FEATURES`]; its failures go to `es2015-builtins-failures.txt`. It fails when
|
||||
//! the interpreter panics.
|
||||
//!
|
||||
//! A seventh test runs the tests under `test/built-ins/Proxy` and `test/built-ins/Reflect` whose
|
||||
//! feature tags are all in [`PROXY_REFLECT_FEATURES`], without and with `Options::es2015`, and
|
||||
//! prints both counts; its failures with the option go to `proxy-reflect-failures.txt`.
|
||||
//!
|
||||
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
|
||||
//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset
|
||||
//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the
|
||||
@@ -859,6 +863,15 @@ fn es2015_subset_runs() {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// The runs that panicked, one line each with the setting of [`Options::es2015`], the test's path
|
||||
/// and its mode, taken from the failures without the option and with it.
|
||||
fn panic_lines(before: &str, after: &str) -> String {
|
||||
[("without Options::es2015", before), ("with Options::es2015", after)]
|
||||
.into_iter()
|
||||
.flat_map(|(edition, failures)| failures.lines().filter(|l| l.ends_with(": PANIC")).map(move |l| format!("{edition}: {l}\n")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The counts of the ES2015 subset read with one setting of [`Options::es2015`].
|
||||
#[derive(Default)]
|
||||
struct Es2015Counts {
|
||||
@@ -977,7 +990,96 @@ fn run_es2015(dir: &Path) {
|
||||
line(&after),
|
||||
report.display()
|
||||
);
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked:\n{}", panic_lines(&before.failures, &after.failures));
|
||||
}
|
||||
|
||||
/// The feature tags of the `Proxy` and `Reflect` tests [`run_proxy_reflect`] runs: the two
|
||||
/// objects and the forms [`Options::es2015`] reads. A test with any other tag (`Symbol`, `class`
|
||||
/// and the like) is counted as skipped.
|
||||
const PROXY_REFLECT_FEATURES: &[&str] =
|
||||
&["Proxy", "Reflect", "Reflect.construct", "let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"];
|
||||
|
||||
#[test]
|
||||
fn proxy_and_reflect_run() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
println!("test262 Proxy and Reflect: SKIPPED (no suite; run cargo xtask test262)");
|
||||
return;
|
||||
};
|
||||
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_proxy_reflect(&dir)).unwrap();
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// Runs the tests under `test/built-ins/Proxy` and `test/built-ins/Reflect` whose feature tags
|
||||
/// are all in [`PROXY_REFLECT_FEATURES`], each in a new realm after the harness as [`run_tests`]
|
||||
/// runs them, once without and once with [`Options::es2015`]. Module, asynchronous and negative
|
||||
/// parse tests, and those that need another missing built-in, are counted as skipped. The counts
|
||||
/// of both runs are printed, and the failures with the option go to `proxy-reflect-failures.txt`.
|
||||
fn run_proxy_reflect(dir: &Path) {
|
||||
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let missing = missing_builtins(&[TEXT_BUILTINS, "Proxy Reflect"]);
|
||||
let modern = Options { es2015: true, ..Options::default() };
|
||||
let editions = [Options::default(), modern.clone()];
|
||||
let mut counts = [RunCounts::default(), RunCounts::default()];
|
||||
let (mut skipped, mut other_features) = (0usize, 0usize);
|
||||
for folder in ["test/built-ins/Proxy", "test/built-ins/Reflect"] {
|
||||
let root = or_fail(inside(dir, folder));
|
||||
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
for path in or_fail(test_files(&root)) {
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
if !meta.features.iter().all(|f| PROXY_REFLECT_FEATURES.contains(&f.as_str())) {
|
||||
other_features += 1;
|
||||
continue;
|
||||
}
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
if has("module")
|
||||
|| has("async")
|
||||
|| meta.negative_phase.as_deref() == Some("parse")
|
||||
|| needs_missing_builtin_in(&[&source, &includes], &missing, &modern)
|
||||
{
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
for (options, counts) in editions.iter().zip(counts.iter_mut()) {
|
||||
counts.tests += 1;
|
||||
for &strict in modes(&meta) {
|
||||
let mode = if strict { "strict" } else { "sloppy" };
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), options)) {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
counts.failed += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {why}\n"));
|
||||
}
|
||||
Err(_) => {
|
||||
counts.failed += 1;
|
||||
counts.panicked += 1;
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let [before, after] = counts;
|
||||
assert!(after.tests > 0, "no Proxy or Reflect tests under {}", dir.display());
|
||||
let report = dir.join("proxy-reflect-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, &after.failures) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
println!(
|
||||
"test262 Proxy and Reflect: without Options::es2015 {}; with it {}. Skipped {skipped} module, asynchronous, negative \
|
||||
parse or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}",
|
||||
before.summary(),
|
||||
after.summary(),
|
||||
report.display()
|
||||
);
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked:\n{}", panic_lines(&before.failures, &after.failures));
|
||||
}
|
||||
|
||||
/// The folders under `test/language/` whose module tests [`modules_run`] reads.
|
||||
@@ -1865,3 +1967,11 @@ fn a_file_over_the_limit_is_refused_before_it_is_read() {
|
||||
assert_eq!(read_source(&path), Ok("\0\0\0\0".to_string()));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panic_without_the_option_is_named_with_its_test_and_mode() {
|
||||
let before = "test/a.js (sloppy): PANIC\ntest/b.js (strict): expected 1\n";
|
||||
let after = "test/c.js (strict): PANIC\n";
|
||||
assert_eq!(panic_lines(before, after), "without Options::es2015: test/a.js (sloppy): PANIC\nwith Options::es2015: test/c.js (strict): PANIC\n");
|
||||
assert_eq!(panic_lines("test/b.js (strict): expected 1\n", ""), "");
|
||||
}
|
||||
@@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -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), 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), 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).
|
||||
|
||||
+239
-40
@@ -79,8 +79,12 @@ pub const MAX_NEAR_KEYS: usize = 1024;
|
||||
const NEAR_WORK: u64 = 2_000_000_000;
|
||||
/// Point comparisons near matching makes for one shape, at most.
|
||||
const NEAR_SHAPE_WORK: u64 = 50_000_000;
|
||||
/// Glyphs one shape is near matched against, at most: those closest to it in proportion.
|
||||
/// Outlines one shape is near matched against, at most: those closest to it in proportion, each
|
||||
/// with every glyph drawn as it is.
|
||||
const NEAR_FITS: usize = 256;
|
||||
/// Outlines with one [`outline_hash`] that near matching compares a glyph's outline with, at most:
|
||||
/// past them, a glyph whose outline hashes alike is an outline of its own.
|
||||
const MAX_HASH_CLASHES: usize = 4;
|
||||
/// Contours [`clusters`] reads, at most: past it, none.
|
||||
const MAX_CLUSTER_CONTOURS: usize = 1024;
|
||||
|
||||
@@ -173,6 +177,8 @@ struct Entry {
|
||||
sig: Signature,
|
||||
/// The glyph's outline in font units, for the whole-outline check.
|
||||
outline: BezPath,
|
||||
/// [`outline_hash`] of `outline`: glyphs drawn alike hash alike.
|
||||
drawn: u64,
|
||||
/// Whether the glyph was indexed for its exact key: only these take part in exact matching,
|
||||
/// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not.
|
||||
exact: bool,
|
||||
@@ -285,7 +291,7 @@ impl RetypeIndex {
|
||||
if keys.contains(&key) {
|
||||
let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid));
|
||||
if let Some(sig) = signatures(&outline, false).into_iter().next() {
|
||||
entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true });
|
||||
entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: true });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -308,7 +314,7 @@ impl RetypeIndex {
|
||||
break 'faces;
|
||||
}
|
||||
if let Some(sig) = signatures(&outline, false).into_iter().next() {
|
||||
entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false });
|
||||
entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,17 +502,19 @@ impl RetypeIndex {
|
||||
/// shape need not be built as the glyph is. Upright ones first, then the closest; the other
|
||||
/// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most
|
||||
/// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more
|
||||
/// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion
|
||||
/// (the spread-to-length ratio, and the share of the length each contour has), closest first,
|
||||
/// in at most 50 million point comparisons, and the index's calls make at most 2 billion in
|
||||
/// all (ranking a glyph by proportion counts as one per contour and one more); once they are
|
||||
/// spent, the glyphs not yet ranked or compared are left out.
|
||||
/// than 8 contours. A shape is compared with the glyphs of at most the 256 outlines closest to
|
||||
/// it in proportion (the spread-to-length ratio, and the share of the length each contour has),
|
||||
/// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted
|
||||
/// once. A shape takes at most 50 million point comparisons, and the index's calls make at most
|
||||
/// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more, and
|
||||
/// comparing its outline with one of at most 4 others with the same hash as one per element of
|
||||
/// its outline); once they are spent, the glyphs not yet ranked or compared are left out.
|
||||
pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec<GlyphMatch> {
|
||||
self.near_matches_among(shape, tolerance, None)
|
||||
}
|
||||
|
||||
/// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the 256
|
||||
/// of its glyphs closest to `shape` in proportion, which the glyphs of the other faces cannot
|
||||
/// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the glyphs
|
||||
/// of the 256 of its outlines closest to `shape` in proportion, which the glyphs of the other faces cannot
|
||||
/// crowd out. Empty when the index does not hold that face.
|
||||
pub fn near_matches_in(&self, shape: &BezPath, tolerance: f64, face: u32) -> Vec<GlyphMatch> {
|
||||
match self.faces.iter().position(|f| f.id() == face) {
|
||||
@@ -544,20 +552,34 @@ impl RetypeIndex {
|
||||
}
|
||||
};
|
||||
let near = self.ranked_near(&s, only, &mut work);
|
||||
for (_, e) in near {
|
||||
if work == 0 {
|
||||
break;
|
||||
}
|
||||
// The outline fitted last and its poses: the glyphs drawn alike after it take them, with no
|
||||
// second comparison of their outlines.
|
||||
let mut last: Option<(usize, Option<NearPoses>)> = None;
|
||||
for (_, outline, e) in near {
|
||||
let Some(face) = self.faces.get(e.face) else { continue };
|
||||
let fits = near_fit(&e.sig, &s, tolerance, &mut work);
|
||||
let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol));
|
||||
let Some(flat) = flat.as_ref() else { break };
|
||||
// Every turn the glyph fits the shape at, nearest upright first: the first is its
|
||||
// pose, the others its alternatives (a glyph that looks alike turned).
|
||||
let mut poses =
|
||||
fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES);
|
||||
let Some((pose, residual)) = poses.next() else { continue };
|
||||
let rest: Vec<(Pose, f64)> = poses.collect();
|
||||
let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone());
|
||||
let posed = match alike {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
if work == 0 {
|
||||
break;
|
||||
}
|
||||
let fits = near_fit(&e.sig, &s, tolerance, &mut work);
|
||||
let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol));
|
||||
let Some(flat) = flat.as_ref() else { break };
|
||||
// Every turn the glyph fits the shape at, nearest upright first: the first is its
|
||||
// pose, the others its alternatives (a glyph that looks alike turned).
|
||||
let mut poses = fits
|
||||
.into_iter()
|
||||
.filter(|f| f.1 <= tolerance)
|
||||
.filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r)))
|
||||
.take(MAX_NEAR_POSES);
|
||||
let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect()));
|
||||
last = Some((outline, p.clone()));
|
||||
p
|
||||
}
|
||||
};
|
||||
let Some((pose, residual, rest)) = posed else { continue };
|
||||
let m = GlyphMatch {
|
||||
face: face.clone(),
|
||||
gid: e.gid,
|
||||
@@ -583,12 +605,18 @@ impl RetypeIndex {
|
||||
out.into_iter().map(|(_, m)| m).collect()
|
||||
}
|
||||
|
||||
/// The glyphs of as many contours as near-matching shape `s` that are closest to it in
|
||||
/// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the
|
||||
/// share of the length each contour has, longest first. Ranking a glyph takes one comparison
|
||||
/// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are
|
||||
/// left out. With `only`, the glyphs of that face (an index into `faces`) alone.
|
||||
fn ranked_near(&self, s: &Signature, only: Option<usize>, work: &mut u64) -> Vec<(f64, &Entry)> {
|
||||
/// The glyphs of as many contours as near-matching shape `s` whose outlines are among the
|
||||
/// [`NEAR_FITS`] outlines closest to it in proportion, closest first: their spread-to-length
|
||||
/// ratio, and the share of the length each contour has, longest first. Glyphs drawn alike (one
|
||||
/// outline in several faces, or in several glyphs of one face) are one outline and come
|
||||
/// together, in index order, so copies of a font do not crowd out the glyphs of the faces they
|
||||
/// copy; outlines as close come in index order. Ranking a glyph takes one comparison per
|
||||
/// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at
|
||||
/// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the
|
||||
/// glyphs not yet ranked are left out. Each glyph comes with its distance and the number of
|
||||
/// its outline in the list, the same for every glyph drawn alike. With `only`, the glyphs of
|
||||
/// that face (an index into `faces`) alone.
|
||||
fn ranked_near(&self, s: &Signature, only: Option<usize>, work: &mut u64) -> Vec<(f64, usize, &Entry)> {
|
||||
let Some(list) = self.buckets.get(&s.contours) else { return vec![] };
|
||||
let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK);
|
||||
let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK);
|
||||
@@ -610,27 +638,64 @@ impl RetypeIndex {
|
||||
if d.is_finite() { d } else { f64::INFINITY }
|
||||
};
|
||||
let cost = s.contours as u64 + 1;
|
||||
let mut near: Vec<(f64, &Entry)> = vec![];
|
||||
for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) {
|
||||
// Each outline with its distance and its glyphs, in the order they are ranked; the list
|
||||
// is sorted by invariant and then by index, so each outline's first glyph is its lowest.
|
||||
let mut outlines: Vec<(f64, Vec<(usize, &Entry)>)> = vec![];
|
||||
let mut by_drawn: HashMap<u64, Vec<usize>> = HashMap::new();
|
||||
for (i, e) in list.iter().skip(start).filter_map(|i| Some((*i, self.entries.get(*i)?))).take_while(|(_, e)| e.sig.invariant <= hi) {
|
||||
if only.is_some_and(|f| e.face != f) {
|
||||
continue;
|
||||
}
|
||||
let Some(left) = work.checked_sub(cost) else { break };
|
||||
*work = left;
|
||||
near.push((apart(e), e));
|
||||
let same = by_drawn.entry(e.drawn).or_default();
|
||||
// Each outline that hashes alike is compared with this one in full, one comparison per
|
||||
// element of its outline.
|
||||
let compare = e.outline.elements().len() as u64;
|
||||
let (mut found, mut spent) = (None, false);
|
||||
for k in same.iter().copied() {
|
||||
let Some(left) = work.checked_sub(compare) else {
|
||||
spent = true;
|
||||
break;
|
||||
};
|
||||
*work = left;
|
||||
if outlines.get(k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e)) {
|
||||
found = Some(k);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if spent {
|
||||
break;
|
||||
}
|
||||
match found.and_then(|k| outlines.get_mut(k)) {
|
||||
Some(o) => o.1.push((i, e)),
|
||||
None => {
|
||||
// Past MAX_HASH_CLASHES outlines that hash alike, the others are not compared:
|
||||
// each is an outline of its own.
|
||||
if same.len() < MAX_HASH_CLASHES {
|
||||
same.push(outlines.len());
|
||||
}
|
||||
outlines.push((apart(e), vec![(i, e)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if near.len() > NEAR_FITS {
|
||||
near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0));
|
||||
near.truncate(NEAR_FITS);
|
||||
let first = |o: &(f64, Vec<(usize, &Entry)>)| o.1.first().map_or(usize::MAX, |(i, _)| *i);
|
||||
let order = |a: &(f64, Vec<(usize, &Entry)>), b: &(f64, Vec<(usize, &Entry)>)| a.0.total_cmp(&b.0).then(first(a).cmp(&first(b)));
|
||||
if outlines.len() > NEAR_FITS {
|
||||
outlines.select_nth_unstable_by(NEAR_FITS, order);
|
||||
outlines.truncate(NEAR_FITS);
|
||||
}
|
||||
near.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
near
|
||||
outlines.sort_by(order);
|
||||
outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives.
|
||||
const MAX_NEAR_POSES: usize = 8;
|
||||
|
||||
/// A near-matched glyph's pose and leftover distance, and its other poses, each with its own.
|
||||
type NearPoses = (Pose, f64, Vec<(Pose, f64)>);
|
||||
|
||||
/// `out` (each match with its face's index) without the matches past the first
|
||||
/// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names)
|
||||
/// do not crowd out the glyphs of the faces after them.
|
||||
@@ -643,6 +708,40 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether glyphs `a` and `b` are drawn alike: the same outline in font units.
|
||||
fn drawn_alike(a: &Entry, b: &Entry) -> bool {
|
||||
#[cfg(test)]
|
||||
OUTLINES_COMPARED.set(OUTLINES_COMPARED.get() + 1);
|
||||
a.drawn == b.drawn && a.outline == b.outline
|
||||
}
|
||||
|
||||
/// A hash of `outline`'s elements and points: outlines drawn alike hash alike.
|
||||
fn outline_hash(outline: &BezPath) -> u64 {
|
||||
// FNV-1a, as `key_and_count`; a rare clash only compares two outlines in full.
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
let mut add = |v: u64| {
|
||||
for b in v.to_le_bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
};
|
||||
for el in outline.elements() {
|
||||
let (tag, pts) = match *el {
|
||||
PathEl::MoveTo(p) => (0, [p, p, p]),
|
||||
PathEl::LineTo(p) => (1, [p, p, p]),
|
||||
PathEl::QuadTo(a, b) => (2, [a, b, b]),
|
||||
PathEl::CurveTo(a, b, c) => (3, [a, b, c]),
|
||||
PathEl::ClosePath => (4, [Point::ZERO; 3]),
|
||||
};
|
||||
add(tag);
|
||||
for p in pts {
|
||||
add(p.x.to_bits());
|
||||
add(p.y.to_bits());
|
||||
}
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so
|
||||
/// placed, lies within `tol` of the shape's (`flat`).
|
||||
fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option<Pose> {
|
||||
@@ -1742,6 +1841,8 @@ fn sample(cs: &[(Vec<PathSeg>, Vec<f64>)], starts: &[Vec<usize>], pick: &[usize]
|
||||
thread_local! {
|
||||
/// How many readings [`signatures`] tried on this thread, kept or not.
|
||||
static READINGS_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many outline comparisons [`drawn_alike`] made on this thread.
|
||||
static OUTLINES_COMPARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The first reading of `path` (for tests).
|
||||
@@ -2124,6 +2225,100 @@ mod tests {
|
||||
assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_drawn_alike_in_many_faces_are_all_near_matched() {
|
||||
// Source Sans 3 Regular first, then 40 copies of it under other names: each face has nine
|
||||
// glyphs close to a period in proportion, 369 in all, more than the 256 near matching
|
||||
// compares a shape with, but nine outlines.
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let source = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let mut faces = vec![source.clone()];
|
||||
for i in 0..40 {
|
||||
let family = format!("Alike {i} Sans");
|
||||
db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Alike{i}Sans-Regular"))).unwrap());
|
||||
faces.push(db.face(&family, "Regular").unwrap());
|
||||
}
|
||||
let gid = source.mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap();
|
||||
// Turned a half turn, as a line of type set upside down.
|
||||
let period =
|
||||
Affine::translate((300.0, 200.0)) * Affine::rotate(std::f64::consts::PI) * Affine::scale(0.04) * db.outline_uncached(&source, gid);
|
||||
let simple = simplified(&period, 0.05);
|
||||
let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
let found = index.near_matches(&simple, 0.02);
|
||||
for f in &faces {
|
||||
assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len());
|
||||
}
|
||||
// Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs
|
||||
// (two comparisons each, for one contour, and one per element of the outline for comparing
|
||||
// it with Source Sans 3's), the comparisons spent are those of Source Sans 3 alone.
|
||||
let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
let alone_found = alone.near_matches(&simple, 0.02);
|
||||
assert_eq!(found.len(), alone_found.len() * faces.len());
|
||||
let mut all = u64::MAX;
|
||||
let ranked: u64 =
|
||||
alone.ranked_near(&near_signature(&simple).unwrap(), None, &mut all).iter().map(|(_, _, e)| 2 + e.outline.elements().len() as u64).sum();
|
||||
let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire);
|
||||
assert_eq!(spent(&index), spent(&alone) + 40 * ranked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_drawn_alike_are_not_compared_again_after_ranking() {
|
||||
// Source Sans 3 Regular and 30 copies of it: ranking compares each copy's outlines with
|
||||
// the first face's and charges every comparison; fitting reuses the poses by outline and
|
||||
// compares no outline again.
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let source = db.face("Source Sans 3", "Regular").unwrap();
|
||||
let mut faces = vec![source.clone()];
|
||||
for i in 0..30 {
|
||||
let family = format!("Again {i} Sans");
|
||||
db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Again{i}Sans-Regular"))).unwrap());
|
||||
faces.push(db.face(&family, "Regular").unwrap());
|
||||
}
|
||||
let gid = source.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap();
|
||||
let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid);
|
||||
let simple = simplified(&shape, 0.05);
|
||||
let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]);
|
||||
OUTLINES_COMPARED.set(0);
|
||||
let mut all = u64::MAX;
|
||||
let ranked = index.ranked_near(&near_signature(&simple).unwrap(), None, &mut all);
|
||||
let in_ranking = OUTLINES_COMPARED.get();
|
||||
assert!(ranked.len() > faces.len(), "{} ranked", ranked.len());
|
||||
OUTLINES_COMPARED.set(0);
|
||||
let found = index.near_matches(&simple, 0.02);
|
||||
assert!(found.iter().any(|m| m.ch == 'o'), "no o among {} matches", found.len());
|
||||
assert_eq!(OUTLINES_COMPARED.get(), in_ranking, "outlines compared outside the charged ranking");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() {
|
||||
// 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is
|
||||
// compared with at most MAX_HASH_CLASHES of the others, and each comparison is charged.
|
||||
let square = |i: usize| Affine::translate((i as f64, 0.0)) * kurbo::Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1);
|
||||
let n = 5_000;
|
||||
let entries: Vec<Entry> = (0..n)
|
||||
.map(|i| Entry { face: 0, gid: i as u32, ch: 'a', sig: signature(&square(i)).unwrap(), outline: square(i), drawn: 7, exact: false })
|
||||
.collect();
|
||||
let elements = square(0).elements().len() as u64;
|
||||
let s = signature(&square(0)).unwrap();
|
||||
let cost = s.contours as u64 + 1;
|
||||
let mut buckets = HashMap::new();
|
||||
buckets.insert(s.contours, (0..n).collect::<Vec<usize>>());
|
||||
let index = RetypeIndex { faces: vec![], entries, buckets, by_glyph: HashMap::new(), near_work: AtomicU64::new(NEAR_WORK) };
|
||||
let mut work = u64::MAX;
|
||||
let ranked = index.ranked_near(&s, None, &mut work);
|
||||
assert_eq!(ranked.len(), NEAR_FITS, "each square is an outline of its own");
|
||||
let compared: u64 = (0..n as u64).map(|i| i.min(MAX_HASH_CLASHES as u64)).sum();
|
||||
assert_eq!(u64::MAX - work, n as u64 * cost + compared * elements);
|
||||
// With too little work left for the comparisons, ranking stops where it runs out.
|
||||
let mut work = n as u64 * cost / 4;
|
||||
let short = index.ranked_near(&s, None, &mut work);
|
||||
assert!(short.len() < NEAR_FITS, "{} ranked", short.len());
|
||||
assert!(work < cost + elements, "{work} left");
|
||||
// Near matching the shape spends at most one shape's allowance and returns.
|
||||
index.near_matches(&square(0), 0.02);
|
||||
assert!(NEAR_WORK - index.near_work.load(Ordering::Acquire) <= NEAR_SHAPE_WORK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_matches_in_one_face_find_its_glyphs_however_many_faces_are_drawn_alike() {
|
||||
// Source Sans 3 Regular last, after 95 copies of it under other names: every face has
|
||||
@@ -2422,9 +2617,13 @@ mod tests {
|
||||
let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]);
|
||||
let s = near_signature(&shape).unwrap();
|
||||
let mut all = u64::MAX;
|
||||
let ranked = index.ranked_near(&s, None, &mut all).len();
|
||||
assert!(ranked >= 1, "the o is ranked");
|
||||
assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three");
|
||||
let ranked = index.ranked_near(&s, None, &mut all);
|
||||
assert!(!ranked.is_empty(), "the o is ranked");
|
||||
// The Greek omicron is drawn as the o: it is also compared with the o's outline.
|
||||
let compared =
|
||||
|i: usize, e: &Entry| if ranked[..i].iter().any(|(_, _, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 };
|
||||
let spent: u64 = ranked.iter().enumerate().map(|(i, (_, _, e))| 3 + compared(i, e)).sum();
|
||||
assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison");
|
||||
// Enough to rank one glyph of two contours and nothing more.
|
||||
let mut work = 4;
|
||||
assert_eq!(index.ranked_near(&s, None, &mut work).len(), 1);
|
||||
|
||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user