mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge upstream main into Script Console row menu
This commit is contained in:
commit
6bfe0016ba
423 files changed
+38302
-3742
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,24 +9,28 @@ 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:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
@@ -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
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
require-craft-fonts: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
run-package-check: true
|
||||
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
|
||||
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
|
||||
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
tooling-revision: main
|
||||
app-name: vectorcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
app-title: VectorCraft
|
||||
macos-runner: macos-15
|
||||
macos-split-build: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
|
||||
|
||||
@@ -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" }
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
@@ -183,6 +185,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -629,6 +629,7 @@ mod tests {
|
||||
|
||||
/// On Windows `busy_cores` gives a number between 0 and the cores.
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_reads_how_many_cores_are_busy() {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
@@ -639,6 +640,7 @@ mod tests {
|
||||
/// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than
|
||||
/// 10,000 MB.
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_reads_the_working_set() {
|
||||
let mb = rss_mb().map(|(mb, _)| mb);
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() {
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
|
||||
}
|
||||
// Every choice Preferences offer means something here.
|
||||
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
|
||||
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
|
||||
}
|
||||
// Preferences offer the three choices read above, and no other.
|
||||
let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect();
|
||||
assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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")))]
|
||||
|
||||
@@ -99,6 +99,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A layer without a color space is tagged sRGB once; the second call leaves it as it is.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn an_untagged_layer_becomes_srgb() {
|
||||
let layer = CAMetalLayer::new();
|
||||
@@ -110,6 +111,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A layer with a color space of its own keeps it.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn a_layer_with_a_color_space_keeps_it() {
|
||||
let layer = CAMetalLayer::new();
|
||||
@@ -121,6 +123,7 @@ mod tests {
|
||||
|
||||
/// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal
|
||||
/// layers are returned.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn metal_layers_are_found_under_the_view_layer() {
|
||||
let metal = CAMetalLayer::new();
|
||||
|
||||
@@ -52,6 +52,7 @@ mod tests {
|
||||
use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL};
|
||||
|
||||
/// CoreText lists the installed fonts, by their files' full paths.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn coretext_lists_the_installed_font_files() {
|
||||
let files = super::font_files();
|
||||
@@ -61,6 +62,7 @@ mod tests {
|
||||
|
||||
/// A font registered with CoreText from another folder, as apps and font managers register
|
||||
/// fonts, is listed while it is registered.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn fonts_registered_from_other_folders_are_listed() {
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
|
||||
|
||||
@@ -94,6 +94,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Files queue until the UI takes them; URLs that aren't files are left out.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn opened_files_wait_for_the_ui() {
|
||||
let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap();
|
||||
|
||||
@@ -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()
|
||||
@@ -14,8 +19,14 @@ impl PrintService for SystemPrint {
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
|
||||
Some(std::sync::Arc::new(system::queues))
|
||||
}
|
||||
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 applies_paper(&self) -> bool {
|
||||
!cfg!(windows)
|
||||
}
|
||||
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 +42,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,18 +147,214 @@ 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 installed queues and the default one, without asking each driver for its capabilities.
|
||||
pub fn queues() -> Vec<Printer> {
|
||||
craft::print::printer_queues().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();
|
||||
}
|
||||
let named = cups_server();
|
||||
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
|
||||
// so its sizes come from the server.
|
||||
if scheduler_is_local(named.as_deref()) {
|
||||
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));
|
||||
let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() };
|
||||
if !papers.is_empty() {
|
||||
return papers;
|
||||
}
|
||||
}
|
||||
// A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes.
|
||||
let mut command = Command::new("lpoptions");
|
||||
command.args(["-p", printer, "-l"]);
|
||||
let papers = paper_output(&mut command)
|
||||
.map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out)))
|
||||
.unwrap_or_default();
|
||||
if !papers.is_empty() {
|
||||
return papers;
|
||||
}
|
||||
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
|
||||
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
||||
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
|
||||
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
|
||||
use std::io::Write as _;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let test_path =
|
||||
std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers };
|
||||
let written = test.write_all(
|
||||
b"{\n\
|
||||
VERSION 1.1\n\
|
||||
OPERATION Get-Printer-Attributes\n\
|
||||
GROUP operation-attributes-tag\n\
|
||||
ATTR charset attributes-charset utf-8\n\
|
||||
ATTR language attributes-natural-language en\n\
|
||||
ATTR uri printer-uri $uri\n\
|
||||
ATTR keyword requested-attributes media-supported\n\
|
||||
STATUS successful-ok\n\
|
||||
}\n",
|
||||
);
|
||||
drop(test);
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&test_path);
|
||||
return papers;
|
||||
}
|
||||
let mut command = Command::new("ipptool");
|
||||
command.args(["-T", "10", "-tv", &uri]).arg(&test_path);
|
||||
let output = paper_output(&mut command);
|
||||
let _ = std::fs::remove_file(&test_path);
|
||||
output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
|
||||
#[cfg(not(windows))]
|
||||
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
|
||||
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
|
||||
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
|
||||
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
|
||||
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
|
||||
/// does not go to.
|
||||
///
|
||||
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
|
||||
match named {
|
||||
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
|
||||
Some(server) => Some(server),
|
||||
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
|
||||
}
|
||||
}
|
||||
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
|
||||
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
|
||||
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
|
||||
#[cfg(not(windows))]
|
||||
fn cups_server() -> Option<String> {
|
||||
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
|
||||
return Some(server.trim().to_string());
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
return None;
|
||||
}
|
||||
let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf"));
|
||||
home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| {
|
||||
use std::io::Read as _;
|
||||
let mut text = String::new();
|
||||
std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?;
|
||||
client_conf_server_name(&text)
|
||||
})
|
||||
}
|
||||
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
|
||||
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
|
||||
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
|
||||
let Some(server) = server.map(str::trim) else { return true };
|
||||
if server.starts_with('/') {
|
||||
return true;
|
||||
}
|
||||
// A network name may end in `/version=1.1`.
|
||||
let server = server.split_once('/').map_or(server, |(server, _)| server);
|
||||
let (host, port) = if let Some(rest) = server.strip_prefix('[') {
|
||||
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
|
||||
} else if server.matches(':').count() == 1 {
|
||||
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
|
||||
} else {
|
||||
(server, None)
|
||||
};
|
||||
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
|
||||
loopback && port.is_none_or(|port| port.trim() == "631")
|
||||
}
|
||||
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
|
||||
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
|
||||
/// dropped and the rest of the line is kept as written.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
|
||||
text.lines().rev().find_map(|line| {
|
||||
let kept = match line.find('#') {
|
||||
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
|
||||
Some(at) => line[..at].to_string(),
|
||||
None => line.to_string(),
|
||||
};
|
||||
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
|
||||
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
|
||||
})
|
||||
}
|
||||
/// Drain output while polling the child, and stop discovery after ten seconds.
|
||||
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);
|
||||
}
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string())
|
||||
}
|
||||
/// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve
|
||||
/// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper
|
||||
/// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for.
|
||||
pub(crate) fn settings(job: &PrintJob) -> craft::print::Job {
|
||||
let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect();
|
||||
craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -133,6 +433,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;
|
||||
@@ -149,3 +601,90 @@ mod turn_tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
mod client_conf_tests {
|
||||
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
|
||||
|
||||
#[test]
|
||||
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
|
||||
let none = |_: &str| false;
|
||||
let socket = |s: &str| s == "/run/cups/cups.sock";
|
||||
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
|
||||
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
|
||||
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
|
||||
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
|
||||
assert_eq!(ipp_server(None, socket), None);
|
||||
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_scheduler_on_this_machine_counts_as_local() {
|
||||
for local in [
|
||||
None,
|
||||
Some("/run/cups/cups.sock"),
|
||||
Some("localhost"),
|
||||
Some("LocalHost:631"),
|
||||
Some("localhost:631"),
|
||||
Some("127.0.0.1:631"),
|
||||
Some("::1"),
|
||||
Some("[::1]:631"),
|
||||
Some("[::1]"),
|
||||
Some("localhost/version=1.1"),
|
||||
Some("localhost:631/version=1.1"),
|
||||
] {
|
||||
assert!(scheduler_is_local(local), "{local:?}");
|
||||
}
|
||||
for remote in [
|
||||
"print.example.com",
|
||||
"print.example.com:631",
|
||||
"192.0.2.7",
|
||||
"[2001:db8::1]:631",
|
||||
"2001:db8::1",
|
||||
"localhost.example.com",
|
||||
"print.example.com:631/version=1.1",
|
||||
"localhost:8631",
|
||||
"127.0.0.1:8631",
|
||||
"[::1]:8631",
|
||||
"localhost:8631/version=1.1",
|
||||
] {
|
||||
assert!(!scheduler_is_local(Some(remote)), "{remote}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
|
||||
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
|
||||
assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com"));
|
||||
assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com"));
|
||||
assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock"));
|
||||
// After an escaped first `#`, a later `#` stays as written.
|
||||
assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c"));
|
||||
// A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one.
|
||||
assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example"));
|
||||
assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod job_settings_tests {
|
||||
use super::system::settings;
|
||||
use vectorcraft_ui_egui::print::PrintJob;
|
||||
|
||||
fn job(paper: Option<&str>) -> PrintJob<'_> {
|
||||
PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chosen_paper_goes_to_cups_as_media() {
|
||||
let args = craft::print::lp_args(&settings(&job(Some("CR80"))));
|
||||
assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_paper_the_queue_keeps_its_own() {
|
||||
let args = craft::print::lp_args(&settings(&job(None)));
|
||||
assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}");
|
||||
}
|
||||
}
|
||||
@@ -2220,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
serde_json::to_value(Variation::ALL).unwrap(),
|
||||
serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"])
|
||||
);
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id()));
|
||||
let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect();
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids");
|
||||
assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel));
|
||||
assert_eq!(Variation::parse("wheel"), None);
|
||||
assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel));
|
||||
}
|
||||
|
||||
@@ -2228,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
#[test]
|
||||
fn junk_pressure_brushes_draw_finite_art() {
|
||||
let bp = preview_path(120.0, 24.0);
|
||||
let mut drawn = 0;
|
||||
for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] {
|
||||
for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] {
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile));
|
||||
@@ -2236,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() {
|
||||
all_points(n, &mut pts);
|
||||
}
|
||||
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}");
|
||||
drawn += usize::from(!pts.is_empty());
|
||||
}
|
||||
}
|
||||
assert_eq!(drawn, 12, "brushes that draw");
|
||||
}
|
||||
|
||||
/// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says.
|
||||
|
||||
@@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() {
|
||||
let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;");
|
||||
let widths: Vec<f64> = leaves(&i.document).iter().map(|n| stroke(n).width).collect();
|
||||
let want = [MM, 2.0 * MM, MM, 0.35 * MM];
|
||||
assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
|
||||
assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
|
||||
let o = DxfOptions { crop: true, ..opts(&d) };
|
||||
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
|
||||
// The red fill: its outline and its hatch.
|
||||
assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]);
|
||||
}
|
||||
|
||||
/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
|
||||
|
||||
@@ -464,9 +464,10 @@ impl Gradient {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or
|
||||
/// reflects? One without stops paints as one that pads.
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty()
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
|
||||
@@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
// Without stops it paints as one that pads.
|
||||
let empty = Gradient { stops: vec![], ..repeat.clone() };
|
||||
assert!(!empty.is_spread());
|
||||
assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1));
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
|
||||
+17
-3
@@ -2784,10 +2784,13 @@ mod tests {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() })))
|
||||
};
|
||||
let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
|
||||
let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
|
||||
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -2840,6 +2843,7 @@ mod tests {
|
||||
let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]);
|
||||
let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]);
|
||||
let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
for s in &m.gradient.stops {
|
||||
assert_eq!(s.swatch.as_deref(), Some("Spot"));
|
||||
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
|
||||
@@ -2848,6 +2852,7 @@ mod tests {
|
||||
// Without plates on either side the steps print the spot ink alone, as before.
|
||||
let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]);
|
||||
let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -2882,10 +2887,12 @@ mod tests {
|
||||
let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
|
||||
let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]);
|
||||
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
|
||||
m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]));
|
||||
// The ends keep their own plates.
|
||||
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
|
||||
// Another swatch, or an unlinked stop: process steps with no plates, as before.
|
||||
@@ -2897,6 +2904,7 @@ mod tests {
|
||||
let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]);
|
||||
for b in [&other, &plain] {
|
||||
let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
}
|
||||
@@ -2906,11 +2914,14 @@ mod tests {
|
||||
let p = [0.4, 0.8, 0.0, 0.2];
|
||||
let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
|
||||
let Paint::Gradient(g) = &gradient else { panic!() };
|
||||
assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none()));
|
||||
let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient);
|
||||
assert_eq!(linked.stops.len(), 2);
|
||||
assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops);
|
||||
let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 };
|
||||
// The solid's end has no plates: they grow from none toward the gradient's, both ways round.
|
||||
for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] {
|
||||
let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
for s in &m.gradient.stops {
|
||||
assert_eq!(s.swatch.as_deref(), Some("Spot"));
|
||||
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
|
||||
@@ -2919,6 +2930,7 @@ mod tests {
|
||||
}
|
||||
// A process solid unlinks the steps, and they take no plates.
|
||||
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -3401,7 +3413,8 @@ mod tests {
|
||||
#[test]
|
||||
fn odd_dash_blends_to_solid_with_closed_gaps() {
|
||||
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
|
||||
assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern);
|
||||
// Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it.
|
||||
assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3412,7 +3425,8 @@ mod tests {
|
||||
let mid = lerp_node(&a, &b, 0.4);
|
||||
let mut ids = vec![];
|
||||
mid.walk(&mut |n| ids.push(n.id));
|
||||
assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}");
|
||||
// The step and its two members, all of them new.
|
||||
assert_eq!(ids, [NodeId(0); 3]);
|
||||
}
|
||||
|
||||
/// A blend of `a` and `b` spaced by `spacing`.
|
||||
|
||||
@@ -64,11 +64,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn modes_read_back_and_unknown_ones_are_add() {
|
||||
for m in ShapeMode::ALL {
|
||||
let v = serde_json::to_value(m).unwrap();
|
||||
assert_eq!(v, serde_json::json!(m.name()));
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), m);
|
||||
}
|
||||
assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract"));
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude);
|
||||
assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect));
|
||||
assert_eq!(ShapeMode::parse("Intersect"), None);
|
||||
for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] {
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), ShapeMode::Add);
|
||||
}
|
||||
|
||||
@@ -613,6 +613,7 @@ mod tests {
|
||||
d.limit_depth_noting(&mut warnings);
|
||||
assert_eq!(warnings, [symbols_note()]);
|
||||
assert!(!d.too_deep(None), "{count} {last}");
|
||||
assert_eq!(d.symbols.len(), count, "every symbol is kept");
|
||||
assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group");
|
||||
}
|
||||
// An edit that makes one hold itself is seen, whatever else stayed as it was.
|
||||
|
||||
@@ -757,6 +757,16 @@ impl Document {
|
||||
{
|
||||
on_path.rename(&renamed);
|
||||
}
|
||||
// An Image Trace object names the objects its trace made by id: the copy names the copies of
|
||||
// those objects, and no other object.
|
||||
if let Some(made) = node.trace_made() {
|
||||
let mut old = vec![];
|
||||
node.walk(&mut |d| old.push(d.id));
|
||||
let mut new = vec![];
|
||||
n.walk(&mut |d| new.push(d.id));
|
||||
let copies = old.into_iter().zip(new).skip(1).filter(|(o, _)| made.contains(*o)).map(|(_, c)| c);
|
||||
n.set_trace_made(&crate::TraceMade::of(copies));
|
||||
}
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ pub use text::{
|
||||
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
pub use trace::{TraceMade, TraceView};
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
pub use vectorcraft_geom as geom;
|
||||
|
||||
@@ -253,6 +253,7 @@ mod tests {
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
|
||||
assert_eq!(t.runs.len(), 1);
|
||||
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
|
||||
|
||||
// A path whose stroke has neither paint nor weight gets 1 pt too.
|
||||
|
||||
@@ -822,6 +822,28 @@ fn reid_gives_fresh_ids() {
|
||||
assert!(!ids.contains(&a) && !ids.contains(&b));
|
||||
}
|
||||
|
||||
/// A copy of an Image Trace object records the copies of the objects its trace made, nested ones
|
||||
/// included, and not the copy of an object added to it later.
|
||||
#[test]
|
||||
fn reid_remaps_what_a_tracing_records_it_made() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let na = (*d.remove(a).unwrap()).clone();
|
||||
let nb = (*d.remove(b).unwrap()).clone();
|
||||
let inner = d.alloc_id();
|
||||
let inner = Node::group(inner, vec![Arc::new(na)]);
|
||||
let mut tracing = Node::group(d.alloc_id(), vec![Arc::new(inner.clone()), Arc::new(nb)]);
|
||||
tracing.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
|
||||
tracing.set_trace_made(&crate::TraceMade::of([inner.id, a]));
|
||||
let copy = d.reid(&tracing);
|
||||
let made = copy.trace_made().unwrap();
|
||||
let ch = copy.children().unwrap();
|
||||
let (inner_copy, added_copy) = (&ch[0], &ch[1]);
|
||||
let a_copy = inner_copy.children().unwrap()[0].id;
|
||||
assert!(made.contains(inner_copy.id) && made.contains(a_copy));
|
||||
assert!(!made.contains(added_copy.id) && !made.contains(inner.id) && !made.contains(a) && !made.contains(b));
|
||||
assert_eq!(made, crate::TraceMade::of([inner_copy.id, a_copy]));
|
||||
}
|
||||
|
||||
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
|
||||
/// another document with the same id does not.
|
||||
#[test]
|
||||
|
||||
@@ -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`.
|
||||
///
|
||||
|
||||
@@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() {
|
||||
assert_eq!(map(d, "a-Z ٪"), "a-Z ٪");
|
||||
}
|
||||
assert_eq!(map(Digits::Devanagari, "page 12"), "page १२");
|
||||
for d in Digits::ALL {
|
||||
assert_eq!(serde_json::to_value(d).unwrap(), d.id());
|
||||
assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d);
|
||||
assert_eq!(Digits::from_id(d.id()), Some(d));
|
||||
}
|
||||
assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari");
|
||||
assert_eq!(serde_json::from_value::<Digits>("farsi".into()).unwrap(), Digits::Farsi);
|
||||
assert_eq!(Digits::Malayalam.id(), "malayalam");
|
||||
assert_eq!(Digits::from_id("default"), Some(Digits::Default));
|
||||
assert_eq!(Digits::from_id("roman"), None);
|
||||
assert!(serde_json::from_value::<Digits>("roman".into()).is_err());
|
||||
}
|
||||
@@ -695,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
|
||||
|
||||
+107
-7
@@ -1,11 +1,64 @@
|
||||
//! Image Trace objects' View: how a live trace draws on screen.
|
||||
//!
|
||||
//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see
|
||||
//! An Image Trace object is a group whose `trace` holds `{preset, params, view, made}` (see
|
||||
//! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the
|
||||
//! tracing result, whatever it is set to.
|
||||
//! tracing result, whatever it is set to. `made` names the objects the trace made ([`TraceMade`]).
|
||||
|
||||
use crate::NodeId;
|
||||
use crate::node::Node;
|
||||
|
||||
/// The key of an Image Trace object's `trace` settings that names the objects its trace made.
|
||||
pub const TRACE_MADE: &str = "made";
|
||||
|
||||
/// The objects the trace of an Image Trace object made, by id: the ranges `[first, last]` of their
|
||||
/// ids, ascending and apart. A trace gives out its ids one after the other, so a trace of any size
|
||||
/// is a few ranges.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceMade(Vec<(u64, u64)>);
|
||||
|
||||
impl TraceMade {
|
||||
/// The objects `ids` name.
|
||||
pub fn of(ids: impl IntoIterator<Item = NodeId>) -> Self {
|
||||
let mut ids: Vec<u64> = ids.into_iter().map(|i| i.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut ranges: Vec<(u64, u64)> = vec![];
|
||||
for id in ids {
|
||||
match ranges.last_mut() {
|
||||
Some((_, last)) if last.checked_add(1) == Some(id) => *last = id,
|
||||
_ => ranges.push((id, id)),
|
||||
}
|
||||
}
|
||||
Self(ranges)
|
||||
}
|
||||
|
||||
/// Whether the trace made the object `id`.
|
||||
pub fn contains(&self, id: NodeId) -> bool {
|
||||
let i = self.0.partition_point(|(_, last)| *last < id.0);
|
||||
self.0.get(i).is_some_and(|(first, _)| *first <= id.0)
|
||||
}
|
||||
|
||||
/// The ranges as the `trace` settings save them: `[[first, last], ...]`.
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
serde_json::Value::Array(self.0.iter().map(|(a, b)| serde_json::json!([a, b])).collect())
|
||||
}
|
||||
|
||||
/// The ranges `v` saves, or `None` when it is not a list of `[first, last]` pairs of whole
|
||||
/// numbers, ascending and apart.
|
||||
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
|
||||
let mut ranges: Vec<(u64, u64)> = vec![];
|
||||
for r in v.as_array()? {
|
||||
let [a, b] = r.as_array()?.as_slice() else { return None };
|
||||
let (a, b) = (a.as_u64()?, b.as_u64()?);
|
||||
if a > b || ranges.last().is_some_and(|(_, last)| *last >= a) {
|
||||
return None;
|
||||
}
|
||||
ranges.push((a, b));
|
||||
}
|
||||
Some(Self(ranges))
|
||||
}
|
||||
}
|
||||
|
||||
/// Image Trace › View.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TraceView {
|
||||
@@ -90,6 +143,21 @@ impl Node {
|
||||
pub fn trace_split(&self) -> f64 {
|
||||
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
|
||||
}
|
||||
|
||||
/// The objects the trace of this Image Trace object made ([`TRACE_MADE`]), or `None` when its
|
||||
/// `trace` settings name none, as in a tracing saved before they did, or name them in any other
|
||||
/// form than [`TraceMade::to_json`]'s.
|
||||
pub fn trace_made(&self) -> Option<TraceMade> {
|
||||
self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json)
|
||||
}
|
||||
|
||||
/// Records `made` as the objects the trace of this Image Trace object made, when its `trace`
|
||||
/// settings are an object.
|
||||
pub fn set_trace_made(&mut self, made: &TraceMade) {
|
||||
if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) {
|
||||
t.insert(TRACE_MADE.into(), made.to_json());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -98,11 +166,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn ids_round_trip_and_unknown_views_show_the_result() {
|
||||
for v in TraceView::ALL {
|
||||
assert_eq!(TraceView::from_id(v.id()), Some(v));
|
||||
assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v));
|
||||
assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something");
|
||||
}
|
||||
assert_eq!(TraceView::Source.id(), "sourceImage");
|
||||
assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource));
|
||||
assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter");
|
||||
assert_eq!(TraceView::from_id("tracing"), None);
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"})));
|
||||
@@ -111,6 +178,39 @@ mod tests {
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() {
|
||||
let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId);
|
||||
let made = TraceMade::of(ids);
|
||||
assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]]));
|
||||
for id in 0..12 {
|
||||
assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}");
|
||||
}
|
||||
assert!(made.contains(crate::NodeId(u64::MAX)));
|
||||
assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone()));
|
||||
assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default()));
|
||||
for bad in [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!([[5, 3]]),
|
||||
serde_json::json!([[1, 4], [4, 6]]),
|
||||
serde_json::json!([[6, 7], [1, 2]]),
|
||||
serde_json::json!([[1]]),
|
||||
serde_json::json!([[1, 2, 3]]),
|
||||
serde_json::json!([[-1, 2]]),
|
||||
serde_json::json!([[1.5, 2]]),
|
||||
serde_json::json!(["1", "2"]),
|
||||
] {
|
||||
assert_eq!(TraceMade::from_json(&bad), None, "{bad}");
|
||||
}
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
g.set_trace_made(&made);
|
||||
assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing");
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
|
||||
assert_eq!(g.trace_made(), None);
|
||||
g.set_trace_made(&made);
|
||||
assert_eq!(g.trace_made(), Some(made));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
|
||||
@@ -173,13 +173,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 {
|
||||
curves.iter().map(|c| c.signed_area()).sum()
|
||||
}
|
||||
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each
|
||||
/// quarter turn or part of one.
|
||||
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
|
||||
if t1 <= t0 {
|
||||
return;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0);
|
||||
let d = (t1 - t0) / n;
|
||||
let k = 4.0 / 3.0 * (d / 4.0).tan();
|
||||
for i in 0..n as usize {
|
||||
@@ -294,20 +295,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
return four_quadrants(&spot_quadrant(t, h, kind));
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
let mut end: Option<Point> = None;
|
||||
// Corners that meet at a point on the cell's side are joined without an anchor of their own.
|
||||
let mut add = |curves: Vec<CubicBez>| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
match end {
|
||||
None => bp.move_to(c.p0),
|
||||
Some(e) if e.distance(c.p0) < 1e-9 => {}
|
||||
Some(_) => bp.line_to(c.p0),
|
||||
}
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
end = Some(c.p3);
|
||||
}
|
||||
};
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))));
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)));
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))));
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
@@ -410,21 +418,28 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
|
||||
}
|
||||
|
||||
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
|
||||
/// three quadrants, counterclockwise.
|
||||
/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor
|
||||
/// of their own at the join.
|
||||
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
let mut end: Option<Point> = None;
|
||||
let mut add = |curves: Vec<CubicBez>| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
match end {
|
||||
None => bp.move_to(c.p0),
|
||||
Some(e) if e.distance(c.p0) < 1e-9 => {}
|
||||
Some(_) => bp.line_to(c.p0),
|
||||
}
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
end = Some(c.p3);
|
||||
}
|
||||
};
|
||||
add(q1.to_vec(), true);
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
|
||||
add(q1.to_vec());
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))));
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)));
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
@@ -731,6 +746,7 @@ mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::Shape;
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
|
||||
/// A black square's samples: `side` points of black from (10, 10), white around it.
|
||||
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
|
||||
@@ -833,6 +849,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_inside_its_cell_is_four_curves() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse] {
|
||||
let bp = shape.path(0.2, 10.0).to_bezpath();
|
||||
let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count();
|
||||
let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count();
|
||||
assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_quadrants_join_without_a_repeated_anchor() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
|
||||
for t in [0.2, 0.45, 0.55, 0.6, 0.85] {
|
||||
for sp in &shape.path(t, 10.0).subpaths {
|
||||
let n = sp.anchors.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p);
|
||||
assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
|
||||
@@ -964,6 +964,10 @@ pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in
|
||||
/// one.
|
||||
pub(crate) use buildcmds::{TRACE_NAME, is_seam_fills, is_trace_group, is_trace_source};
|
||||
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
@@ -1002,7 +1006,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
pub const ALIASES: &[(&str, &str)] =
|
||||
&[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")];
|
||||
|
||||
/// Is `id` an [`ALIASES`] entry?
|
||||
pub fn is_alias(id: &str) -> bool {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -449,6 +449,7 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() {
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!(own.dimensions(), (6, 5), "the cut's pixels");
|
||||
assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included");
|
||||
assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden");
|
||||
s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap();
|
||||
|
||||
@@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.bridge",
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
[],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
@@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError {
|
||||
)
|
||||
}
|
||||
|
||||
/// The parameters that shape a curved bridge.
|
||||
const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"];
|
||||
|
||||
fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all");
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
let kinds = choice(p, C, "tangents", &KINDS)?;
|
||||
let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None };
|
||||
if switch_or(p, "curved", false, C)? {
|
||||
if kinds.is_some_and(|k| k != "external") {
|
||||
return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out"));
|
||||
}
|
||||
if given("centerline") {
|
||||
return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`"));
|
||||
}
|
||||
if connect == Some(false) {
|
||||
return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true"));
|
||||
}
|
||||
// The outline is Smooth Bridge's.
|
||||
let mut bridged = serde_json::Map::new();
|
||||
for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) {
|
||||
bridged.insert((*key).to_owned(), p[*key].clone());
|
||||
}
|
||||
return super::bridge::bridge(s, &Value::Object(bridged));
|
||||
}
|
||||
if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) {
|
||||
return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it")));
|
||||
}
|
||||
let kinds = kinds.unwrap_or("all");
|
||||
let connect = connect.unwrap_or(false);
|
||||
let centerline = switch_or(p, "centerline", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
|
||||
};
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
// With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed
|
||||
// shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind.
|
||||
let shapes: Vec<(Vec<Point>, bool)> = if connect {
|
||||
let mut out = vec![];
|
||||
for kind in [pt::TangentKind::External, pt::TangentKind::Internal] {
|
||||
let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect();
|
||||
match of.as_slice() {
|
||||
[l, m] => {
|
||||
// A point's two lines share the point, which then closes the ring once.
|
||||
let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size());
|
||||
let mut ring = vec![l.from, l.to, m.to, m.from];
|
||||
ring.dedup_by(|q, p| same(*q, *p));
|
||||
if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) {
|
||||
ring.pop();
|
||||
}
|
||||
out.push((ring, true));
|
||||
}
|
||||
_ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))),
|
||||
}
|
||||
if point {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
} else {
|
||||
lines.iter().map(|&(from, to)| (vec![from, to], false)).collect()
|
||||
};
|
||||
if lines.is_empty() && point {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds it.
|
||||
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
|
||||
@@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
let mut ids = vec![];
|
||||
let mut center_id = None;
|
||||
for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() {
|
||||
let center = center.map(|(from, to)| (vec![from, to], false));
|
||||
for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() {
|
||||
let id = d.alloc_id();
|
||||
let path = PathData::single(SubPath::polyline(&[from, to], false));
|
||||
let path = PathData::single(SubPath::polyline(&points, closed));
|
||||
let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
|
||||
look.apply(d, &mut n);
|
||||
d.insert(parent, idx + 1 + k, n)?;
|
||||
if k == lines.len() {
|
||||
if k == shapes.len() {
|
||||
center_id = Some(id);
|
||||
}
|
||||
ids.push(id);
|
||||
|
||||
@@ -354,3 +354,113 @@ fn bad_selections_and_params_are_refused() {
|
||||
let g = group_of(&mut s, &[b]);
|
||||
assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths"));
|
||||
}
|
||||
|
||||
/// The one closed outline of path `id`.
|
||||
fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
|
||||
let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) };
|
||||
assert!(sp.closed);
|
||||
sp.clone()
|
||||
}
|
||||
|
||||
/// The anchors of path `id`'s one closed outline.
|
||||
fn corners(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
outline(s, id).anchors.iter().map(|a| a.p).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() {
|
||||
let mut s = session();
|
||||
let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0));
|
||||
let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 1, "one shape in place of two lines");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay");
|
||||
let found = corners(&s, NodeId(ids[0].as_u64().unwrap()));
|
||||
assert_eq!(found.len(), 4);
|
||||
// The tangents above and below both circles, joined by each circle's vertical diameter.
|
||||
for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] {
|
||||
assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}");
|
||||
}
|
||||
// In order around the band, not crossing itself: the area is the 100 by 40 rectangle's.
|
||||
let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>() / 2.0;
|
||||
assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), count);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() {
|
||||
let mut s = session();
|
||||
let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0));
|
||||
let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1));
|
||||
let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap();
|
||||
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
|
||||
assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline");
|
||||
for &id in &ids[..2] {
|
||||
let found = corners(&s, id);
|
||||
assert_eq!(found.len(), 4);
|
||||
let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count();
|
||||
assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}");
|
||||
}
|
||||
assert_ne!(corners(&s, ids[0]), corners(&s, ids[1]));
|
||||
assert_eq!(r["centerline"], json!(ids[2].0));
|
||||
|
||||
let mut s = session();
|
||||
let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0));
|
||||
let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap();
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 1);
|
||||
let found = corners(&s, NodeId(ids[0].as_u64().unwrap()));
|
||||
assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}");
|
||||
assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curved_makes_the_bridge_the_smooth_bridge_command_makes() {
|
||||
let build = || {
|
||||
let mut s = session();
|
||||
let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)];
|
||||
select(&mut s, &ids);
|
||||
s
|
||||
};
|
||||
for (merged, old) in [
|
||||
(json!({"curved": true}), json!({})),
|
||||
(
|
||||
json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}),
|
||||
json!({"gap": 5, "reach": 30, "keepOriginals": true}),
|
||||
),
|
||||
] {
|
||||
let (mut s, mut t) = (build(), build());
|
||||
let r = s.execute(C, &merged).unwrap();
|
||||
let q = t.execute("addon.pathtools.bridge", &old).unwrap();
|
||||
assert_eq!(r, q, "{merged}");
|
||||
let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(kinds(&s), kinds(&t), "{merged}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_the_other_mode_are_refused() {
|
||||
let mut s = session();
|
||||
let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
for (p, says) in [
|
||||
(json!({"connect": "yes"}), "connect"),
|
||||
(json!({"curved": true, "tangents": "all"}), "external"),
|
||||
(json!({"curved": true, "centerline": true}), "centerline"),
|
||||
(json!({"curved": true, "connect": false}), "connected"),
|
||||
(json!({"radius": 50}), "curved"),
|
||||
(json!({"connect": true, "keepOriginals": true}), "curved"),
|
||||
(json!({"curved": true, "radius": 50, "gap": 2}), "not both"),
|
||||
(json!({"curved": true, "radius": 0}), "radius"),
|
||||
] {
|
||||
assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone()));
|
||||
}
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
}
|
||||
@@ -237,6 +237,7 @@ fn add_points_splits_selected_segments_evenly() {
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3));
|
||||
let xs: Vec<f64> = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect();
|
||||
assert_eq!(xs.len(), 5, "{xs:?}");
|
||||
assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -69,7 +69,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() {
|
||||
assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size");
|
||||
assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone");
|
||||
let undone: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect();
|
||||
assert_eq!(undone, [('a', 20.0), ('b', 20.0), (' ', 20.0), ('c', 20.0), ('d', 20.0)], "undone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_copy_region, sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{
|
||||
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
|
||||
};
|
||||
pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source};
|
||||
use trace::{
|
||||
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
|
||||
};
|
||||
|
||||
@@ -17,12 +17,17 @@ thread_local! {
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
pub(crate) fn is_trace_group(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& n.name.as_deref() == Some(TRACE_NAME)
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child.
|
||||
pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool {
|
||||
d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id))
|
||||
}
|
||||
|
||||
/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
@@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made
|
||||
/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one
|
||||
/// of stroked paths without fills. (Auto Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
pub(crate) fn is_seam_fills(n: &Node) -> bool {
|
||||
let path = |m: &Arc<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None;
|
||||
@@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The source image an Image Trace object keeps is traced through that object, so it is never
|
||||
// the object traced, and naming only such images is an error.
|
||||
let source = |r: &NodeId| is_trace_source(d, *r);
|
||||
roots
|
||||
.iter()
|
||||
.filter(|r| !source(r))
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
@@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObj
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
|
||||
.ok_or_else(|| match roots.iter().find(|r| source(r)) {
|
||||
Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)),
|
||||
None => bad(c, "select an image (or an Image Trace group)"),
|
||||
})
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now. A script's trace
|
||||
// stops when the script is asked to stop.
|
||||
let stop = s.script_in_run.then(|| s.script_interrupt());
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
@@ -1098,6 +1112,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
for (rgb, paint) in &library {
|
||||
by_color.entry(*rgb).or_insert(paint);
|
||||
}
|
||||
// A stop asked for after the trace's last check, or while a handed-in trace is applied, does
|
||||
// not commit the trace.
|
||||
if stop.as_ref().is_some_and(|i| i.is_set()) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
@@ -1206,6 +1225,18 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
|
||||
// appearance items, visibility and lock.
|
||||
if !expand && is_trace_group(&src) {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
}
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
// view's divider.
|
||||
@@ -1215,6 +1246,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
t["split"] = split.clone();
|
||||
}
|
||||
g.extras_mut().trace = Some(Box::new(t));
|
||||
// Records the objects this trace made: every object in the tracing.
|
||||
let mut made = vec![];
|
||||
g.walk(&mut |n| made.push(n.id));
|
||||
g.set_trace_made(&vectorcraft_doc::TraceMade::of(made.into_iter().filter(|i| *i != gid)));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
@@ -1386,7 +1421,8 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.name = None;
|
||||
n.extras_mut().trace = None;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
let source = ch.first().map(|c| c.id);
|
||||
ch.retain(|c| Some(c.id) != source);
|
||||
}
|
||||
if by_color {
|
||||
let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default();
|
||||
@@ -1586,6 +1622,8 @@ mod trace_limit_tests {
|
||||
// anchors each.
|
||||
let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::<usize>();
|
||||
let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap();
|
||||
assert!(!outlined.strokes.is_empty(), "{res:?}");
|
||||
assert_eq!(outlined.strokes.len(), all.as_ref().unwrap().strokes.len(), "one outline for each seam fill: {outlined:?}");
|
||||
assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}");
|
||||
let n = strokes(all.as_ref().unwrap());
|
||||
assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined));
|
||||
|
||||
@@ -696,9 +696,13 @@ mod tests {
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(c, layer, "the scenario needs the id to be reused");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
let compound = d.node(NodeId(c)).unwrap();
|
||||
assert!(compound.children().unwrap().iter().all(|ch| matches!(ch.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
assert_eq!(compound.children().unwrap().len(), 1, "the compound path holds only the rectangle it was made from");
|
||||
let pasted = st.selection.objects.clone();
|
||||
assert_eq!(pasted.len(), 1);
|
||||
assert!(d.parent_of(pasted[0]).is_some_and(|p| d.node(p).unwrap().is_layer()), "the copy lands on a layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -385,6 +385,16 @@ impl Session {
|
||||
self.prefs.copy_as_svg && !self.clipboard_svg_refused()
|
||||
}
|
||||
|
||||
/// After a Copy or Cut has filled the clipboard: counts it in [`Session::copies`] when it put
|
||||
/// something there, and marks the clipboard as holding a copy ([`Session::clipboard_copied`]).
|
||||
pub(crate) fn note_copy(&mut self) {
|
||||
let filled = !self.clipboard.is_empty();
|
||||
if filled {
|
||||
self.copies = self.copies.wrapping_add(1);
|
||||
}
|
||||
self.clipboard_copied = filled;
|
||||
}
|
||||
|
||||
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
|
||||
/// artboard's centre) → the number of objects.
|
||||
pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result<usize> {
|
||||
@@ -400,6 +410,7 @@ impl Session {
|
||||
}
|
||||
let count = clip.nodes.len();
|
||||
self.clipboard = clip;
|
||||
self.clipboard_copied = false;
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1722,7 +1722,7 @@ mod tests {
|
||||
let jags = polyline(&ring);
|
||||
let sp = SubPath::new(jags.clone(), true);
|
||||
assert!(subpath_len(&sp) < 24.0);
|
||||
assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor");
|
||||
assert_eq!(smooth_corners(&jags, true, 1e-6), vec![true; 16], "each jag turns sharply at its anchor");
|
||||
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
|
||||
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New…",
|
||||
["File"],
|
||||
None,
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
always,
|
||||
super::newdoc::file_new
|
||||
),
|
||||
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -1221,6 +1221,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
s.note_copy();
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
}
|
||||
|
||||
@@ -1311,6 +1312,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator<Item = NodeId>) -> BTreeSet<NodeId> {
|
||||
ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect()
|
||||
}
|
||||
|
||||
pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet<NodeId>) {
|
||||
for id in ids {
|
||||
if let Some(n) = d.node_mut(id)
|
||||
&& n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide()))
|
||||
{
|
||||
n.set_clips(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?;
|
||||
@@ -1347,6 +1362,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let clipped = clipped_ancestors(d, ids.iter().copied());
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
@@ -1362,6 +1378,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gone = sel.guides.clone();
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
}
|
||||
release_empty_clips(d, clipped);
|
||||
if is_explicit {
|
||||
sel.remove_all(ids.iter().copied());
|
||||
sel.prune(d);
|
||||
|
||||
@@ -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) ----------
|
||||
@@ -267,6 +265,17 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
/// [`may_write`], and an error when something other than a regular file is at `path` (a folder):
|
||||
/// the check each file of a set gets before the first of them is written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write_file(path: &str) -> Result<()> {
|
||||
may_write(path)?;
|
||||
match std::fs::metadata(path) {
|
||||
Ok(m) if !m.is_file() => Err(EngineError::Other(format!("{path}: not a file"))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The most a file read during a script command holds, the limit an importer reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
|
||||
@@ -325,8 +334,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 +375,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 +389,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 +782,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,17 @@ 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());
|
||||
let (clipboard_copied, copies) = (s.clipboard_copied, s.copies);
|
||||
// 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,10 +43,13 @@ 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();
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
(s.clipboard_copied, s.copies) = (clipboard_copied, copies);
|
||||
s.pending_paint = None;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
super::may_write(p)?;
|
||||
super::access::may_write_file(p)?;
|
||||
}
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -602,6 +602,8 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
/// The client did not give the path: a file the file access refuses before anything is
|
||||
/// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]).
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
@@ -972,6 +974,14 @@ impl SaveJob {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
/// The job for a save whose path the client did not give: a file the file access refuses
|
||||
/// before anything is written is named in the error as the request being served may see it
|
||||
/// ([`super::access::naming_in_error`]).
|
||||
pub(crate) fn naming_refusals(mut self) -> Self {
|
||||
self.redact_paths = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The document when the job was made (what counts as saved once the file is written).
|
||||
pub(crate) fn snapshot(&self) -> &Arc<Document> {
|
||||
&self.snapshot
|
||||
@@ -1072,14 +1082,14 @@ impl SaveJob {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force before the first file is
|
||||
// written. A refused file is not handed to `write`, so a writer that does not check the
|
||||
// file access writes none of the files; the error is the file access's own refusal, as
|
||||
// the writers that check it give.
|
||||
// written. A refused file, or a folder at a file's path, is not handed to `write`, so a
|
||||
// writer that does not check the file access writes none of the files; the error is the
|
||||
// file access's own refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some(refused) = files
|
||||
.iter()
|
||||
.find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }))
|
||||
&& let Some(refused) = files.iter().find_map(|(p, _)| {
|
||||
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
|
||||
})
|
||||
{
|
||||
return Err(refused);
|
||||
}
|
||||
@@ -1219,6 +1229,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 {
|
||||
@@ -1243,10 +1255,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
|
||||
/// A save command: plan, then write with the file system (a native file as it is encoded).
|
||||
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let mut job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
job.redact_paths = !given;
|
||||
let job = save_job(s, plan)?;
|
||||
let job = if given { job } else { job.naming_refusals() };
|
||||
let uid = s.doc()?.uid;
|
||||
// Without a path, the files written are the document's own file and those beside it.
|
||||
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
|
||||
|
||||
@@ -1040,6 +1040,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that writes several files, through a writer that does not check the file access in
|
||||
/// force, writes none of them when that access refuses one: the save refuses it itself.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() {
|
||||
let d = tmp_dir("refused-files");
|
||||
let mut s = session(100.0, 100.0, 2);
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let path = d.join("logo.eps").to_string_lossy().to_string();
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
let mut written = vec![];
|
||||
let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || {
|
||||
job.write(|p, b| {
|
||||
std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
written.push(p.to_string());
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}");
|
||||
assert!(written.is_empty(), "{written:?}");
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them.
|
||||
#[test]
|
||||
fn a_failed_save_does_not_stamp_the_documents_dates() {
|
||||
|
||||
@@ -71,9 +71,163 @@ fn export(s: &mut Session, p: Value) -> (Vec<u8>, Vec<String>) {
|
||||
(bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect())
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries.
|
||||
/// Whether `b` ends a PDF token: white space or a delimiter.
|
||||
fn ends_token(b: u8) -> bool {
|
||||
b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b)
|
||||
}
|
||||
|
||||
/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the
|
||||
/// `startxref` at `startxref` and following `/Prev`.
|
||||
fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option<usize> {
|
||||
let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::<usize>().ok()?;
|
||||
let mut visited = vec![];
|
||||
loop {
|
||||
if visited.contains(&offset) {
|
||||
return None;
|
||||
}
|
||||
visited.push(offset);
|
||||
let table = String::from_utf8_lossy(pdf.get(offset..)?);
|
||||
let mut words = table.split_ascii_whitespace();
|
||||
if words.next()? != "xref" {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
let first = words.next()?;
|
||||
if first == "trailer" {
|
||||
break;
|
||||
}
|
||||
let first = first.parse::<usize>().ok()?;
|
||||
let count = words.next()?.parse::<usize>().ok()?;
|
||||
for index in 0..count {
|
||||
let at = words.next()?.parse::<usize>().ok()?;
|
||||
let entry_generation = words.next()?.parse::<usize>().ok()?;
|
||||
let status = words.next()?;
|
||||
if first.checked_add(index)? == number {
|
||||
return (status == "n" && entry_generation == generation).then_some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
let trailer = table.split_once("trailer")?.1.split_once(">>")?.0;
|
||||
let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty());
|
||||
words.find(|&w| w == "Prev")?;
|
||||
offset = words.next()?.parse().ok()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary
|
||||
/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white
|
||||
/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its
|
||||
/// object in `pdf`. `None` when it is missing or cannot be read.
|
||||
fn stream_length(text: &[u8], pdf: &[u8]) -> Option<usize> {
|
||||
let from = text
|
||||
.windows(3)
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')))
|
||||
.map_or(0, |(at, _)| at + 3);
|
||||
let dict = &text[from..];
|
||||
let mut i = dict.windows(2).position(|w| w == b"<<")? + 2;
|
||||
let mut depth = 1usize;
|
||||
let mut length = None;
|
||||
while i < dict.len() && depth > 0 {
|
||||
let rest = &dict[i..];
|
||||
if rest.starts_with(b"<<") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if rest.starts_with(b">>") {
|
||||
depth -= 1;
|
||||
i += 2;
|
||||
} else if rest[0] == b'<' {
|
||||
// A hex string.
|
||||
i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1);
|
||||
} else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) {
|
||||
let value = String::from_utf8_lossy(&rest[7..]);
|
||||
let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect();
|
||||
length = match words[..] {
|
||||
// `n g R` is an indirect length: the integer in object `n g`.
|
||||
[n, g, "R", ..] => {
|
||||
let header = format!("{n} {g} obj");
|
||||
let read_length = |at: usize| {
|
||||
let body = String::from_utf8_lossy(&pdf[at + header.len()..]);
|
||||
match body.split_ascii_whitespace().take(2).collect::<Vec<_>>()[..] {
|
||||
[n, "endobj"] => n.parse::<usize>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") {
|
||||
let at =
|
||||
xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref");
|
||||
let object = pdf.get(at..).expect("stream /Length xref offset is outside the file");
|
||||
assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object");
|
||||
read_length(at)
|
||||
} else {
|
||||
pdf.windows(header.len())
|
||||
.enumerate()
|
||||
// An object header starts a line, and the length object holds one integer.
|
||||
.filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n')))
|
||||
.find_map(|(at, _)| read_length(at))
|
||||
}
|
||||
}
|
||||
[n, ..] => n.parse::<usize>().ok(),
|
||||
[] => None,
|
||||
};
|
||||
i += 7;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
length
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out:
|
||||
/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time
|
||||
/// and can spell `/BM`.
|
||||
fn transparency(pdf: &[u8]) -> Vec<&'static str> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
let mut text = Vec::with_capacity(pdf.len());
|
||||
let mut i = 0;
|
||||
while i < pdf.len() {
|
||||
let rest = &pdf[i..];
|
||||
// A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name.
|
||||
let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>';
|
||||
if keyword_start && rest.starts_with(b"endstream") {
|
||||
text.extend_from_slice(b"endstream");
|
||||
i += b"endstream".len();
|
||||
} else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) {
|
||||
// Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to
|
||||
// `endstream`); its bytes are not PDF syntax.
|
||||
let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 };
|
||||
i = match stream_length(&text, pdf) {
|
||||
Some(n) => {
|
||||
let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream");
|
||||
while matches!(pdf.get(end), Some(b'\r' | b'\n')) {
|
||||
end += 1;
|
||||
}
|
||||
assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream");
|
||||
end
|
||||
}
|
||||
None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"),
|
||||
};
|
||||
} else if rest[0] == b'(' {
|
||||
// A literal string: balanced parentheses, with `\` escaping the next byte.
|
||||
let mut depth = 0usize;
|
||||
while i < pdf.len() {
|
||||
match pdf[i] {
|
||||
b'\\' => i += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
text.push(rest[0]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&text);
|
||||
let mut found = vec![];
|
||||
for (what, there) in [
|
||||
("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")),
|
||||
@@ -193,3 +347,79 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
|
||||
s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check
|
||||
/// reads the file's dictionaries only, not its strings or its XMP packet.
|
||||
#[test]
|
||||
fn the_transparency_check_skips_strings_and_metadata() {
|
||||
let pdf = b"%PDF-1.3\n5 0 obj\n<</Title(a/BM/SMask/CA 0.5)>>\nendobj\n6 0 obj\n<</Type/Metadata>>\nstream\n<?xpacket begin=\"\"?><x>q/BMx/S/Transparency</x><?xpacket end=\"r\"?>\nendstream\nendobj\ntrailer\n<</ID[(hIX/BMcE)(hIX/BMcE)]>>\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
assert_eq!(transparency(b"<</ExtGState<</G<</BM/Multiply/CA 0.5>>>>>>"), vec!["blend modes", "opacity"]);
|
||||
// A `(` in image data starts no string, and nested and escaped parentheses end where the
|
||||
// string does.
|
||||
let pdf = b"<</Length 3>>\nstream\n(\x00(\nendstream\n<</T(a(b)c\\)d)/SMask 9 0 R>>\n<</S/Transparency>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]);
|
||||
// Stream data is skipped by its length, even when it holds `endstream` itself.
|
||||
let pdf = b"1 0 obj\n<</Length 15>>\nstream\nendstream (/BM\nendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 13>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabc\r\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabcendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// Only the stream dictionary's own `/Length` counts, not one in a nested dictionary.
|
||||
let pdf = b"1 0 obj\n<</Length 4/DecodeParms<</Length 1>>>>\nstream\n/BM \nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
// `stream` inside a name is not the keyword.
|
||||
let pdf = b"1 0 obj\n<</Type/Upstream\n/BM/Multiply>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Type/stream\n/SMask 9 0 R>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// An indirect length is read from its object, so `endstream` in the data does not end it.
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let payload = b"2 0 obj\n13\nendobj\nendstream /BM";
|
||||
let mut pdf = b"%PDF-1.3\n".to_vec();
|
||||
let stream_at = pdf.len();
|
||||
pdf.extend_from_slice(b"1 0 obj\n<</Length 2 0 R>>\nstream\n");
|
||||
pdf.extend_from_slice(payload);
|
||||
pdf.extend_from_slice(b"\nendstream\nendobj\n");
|
||||
let length_at = pdf.len();
|
||||
pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes());
|
||||
let catalog_at = pdf.len();
|
||||
pdf.extend_from_slice(b"3 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n");
|
||||
let pages_at = pdf.len();
|
||||
pdf.extend_from_slice(b"4 0 obj\n<</Type/Pages/Kids[]/Count 0>>\nendobj\n");
|
||||
let xref_at = pdf.len();
|
||||
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
|
||||
for at in [stream_at, length_at, catalog_at, pages_at] {
|
||||
pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 3 0 R>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
|
||||
assert_eq!(transparency(&pdf), Vec::<&str>::new());
|
||||
// A stream with no length and no `endstream` fails rather than hiding the rest of the file.
|
||||
let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<</SMask 9 0 R>>";
|
||||
assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err());
|
||||
for length in [2, 20, 999, usize::MAX] {
|
||||
let pdf = format!("1 0 obj\n<</Length {length}>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R/BM/Multiply>>");
|
||||
let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic");
|
||||
let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
|
||||
assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the
|
||||
/// stream's `/Length` is still read from the outer dictionary.
|
||||
#[test]
|
||||
fn the_stream_length_skips_names_that_end_in_obj() {
|
||||
let text = b"1 0 obj\n<</Length 5/Tag/obj>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
// NUL is PDF white space, so it may separate the generation number from `obj`.
|
||||
let text = b"1 0 obj\n<</Length 9>>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<</Length 5>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
let pdf = b"1 0 obj\n<</Length 13/Tag/obj>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
}
|
||||
@@ -104,8 +104,15 @@ fn bmp_options_reach_the_file() {
|
||||
assert_eq!(i32::from_le_bytes(flipped[22..26].try_into().unwrap()), -40, "top-down rows");
|
||||
let os2 = bmp(&mut s, json!({"fileFormat": "os2", "depth": 4}));
|
||||
assert_eq!(u32::from_le_bytes(os2[14..18].try_into().unwrap()), 12, "OS/2 core header");
|
||||
let gray = image::load_from_memory_with_format(&bmp(&mut s, json!({"colorModel": "gray", "depth": 8})), image::ImageFormat::Bmp).unwrap();
|
||||
assert!(gray.to_rgb8().pixels().all(|p| p[0] == p[1] && p[1] == p[2]));
|
||||
// A red square, whose gray is neither black nor white.
|
||||
let red = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 40})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [red], "color": "#ff0000"})).unwrap();
|
||||
let gray =
|
||||
image::load_from_memory_with_format(&bmp(&mut s, json!({"colorModel": "gray", "depth": 8})), image::ImageFormat::Bmp).unwrap().to_rgb8();
|
||||
assert_eq!(gray.dimensions(), (60, 40));
|
||||
assert!(gray.pixels().all(|p| p[0] == p[1] && p[1] == p[2]));
|
||||
let [r, _, _] = gray.get_pixel(5, 20).0;
|
||||
assert!(r > 0 && r < 255, "red is a middle gray: {r}");
|
||||
for bad in [
|
||||
json!({"depth": 2}),
|
||||
json!({"depth": 24, "rle": true}),
|
||||
|
||||
@@ -30,19 +30,29 @@ impl Visitor for Names {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every file, and waits on reading one until its channel sends or closes.
|
||||
struct Blocked(Mutex<mpsc::Receiver<()>>);
|
||||
/// Reads every file, says on its second channel that a read began, and waits on reading one until
|
||||
/// its first channel sends or closes.
|
||||
struct Blocked(Mutex<mpsc::Receiver<()>>, mpsc::Sender<()>);
|
||||
|
||||
impl Visitor for Blocked {
|
||||
fn wants(&self, _: &str) -> bool {
|
||||
true
|
||||
}
|
||||
fn items(&self, _: &Path) -> Vec<usize> {
|
||||
let _ = self.1.send(());
|
||||
let _ = self.0.lock().unwrap().recv();
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Blocked`] visitor with the sender that lets its reads end and the receiver that hears each
|
||||
/// read begin.
|
||||
fn blocked() -> (mpsc::Sender<()>, mpsc::Receiver<()>, Arc<dyn Visitor>) {
|
||||
let (go, wait_for_go) = mpsc::channel();
|
||||
let (entered, reading) = mpsc::channel();
|
||||
(go, reading, Arc::new(Blocked(Mutex::new(wait_for_go), entered)))
|
||||
}
|
||||
|
||||
/// A test's folder tree, removed with everything in it when dropped, also when the test panics,
|
||||
/// and also when the test locked a folder in it. A removal that fails (a walker still holding a
|
||||
/// file open) is ignored.
|
||||
@@ -316,29 +326,35 @@ fn the_search_ends_at_its_limits_and_when_stopped() {
|
||||
#[test]
|
||||
fn the_search_answers_at_its_deadline_while_a_walker_is_blocked() {
|
||||
let root = tree("blocked", &["f.ttf"]);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (tx, reading, visitor) = blocked();
|
||||
let started = Instant::now();
|
||||
let s = begin(root.clone(), rules(&root), Limits { seconds: 0.2, ..Limits::default() }, 1, 1, Arc::new(Blocked(Mutex::new(rx))));
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
let s = begin(root.clone(), rules(&root), Limits::default(), 1, 1, visitor);
|
||||
// The walker is blocked reading the file.
|
||||
assert!(reading.recv_timeout(WAIT).is_ok(), "the walker reads the file");
|
||||
assert_eq!((s.progress().state(), s.progress().read), ("searching", 1));
|
||||
s.expire();
|
||||
let p = s.progress();
|
||||
// The search ended when it answered, and it ran no longer than the test has waited.
|
||||
let waited = started.elapsed().as_secs_f64();
|
||||
assert_eq!((p.state(), p.stopped()), ("stopped", Some("time")), "{p:?}");
|
||||
assert!(p.seconds >= 0.2 && p.seconds <= waited, "{p:?}, {waited} s");
|
||||
let (tx2, rx2) = mpsc::channel();
|
||||
let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx2))));
|
||||
let until = Instant::now() + WAIT;
|
||||
while s2.progress().read == 0 && Instant::now() < until {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
assert!(p.seconds <= waited, "{p:?}, {waited} s");
|
||||
assert_eq!(s.progress().seconds, p.seconds, "the time it ended at stays");
|
||||
// A limit of no seconds has run out as the search starts; a long one hasn't.
|
||||
let (_tx0, _, visitor) = blocked();
|
||||
let none = begin(root.clone(), rules(&root), Limits { seconds: 0.0, ..Limits::default() }, 1, 1, visitor);
|
||||
assert_eq!(none.progress().stopped(), Some("time"));
|
||||
let (tx2, reading2, visitor) = blocked();
|
||||
let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, visitor);
|
||||
assert!(reading2.recv_timeout(WAIT).is_ok(), "the walker reads the file");
|
||||
assert_eq!(s2.progress().state(), "searching");
|
||||
s2.stop();
|
||||
assert_eq!(s2.progress().stopped(), Some("stop"));
|
||||
drop((tx, tx2));
|
||||
}
|
||||
|
||||
/// Every file is item 0; reading the second file waits until the channel closes.
|
||||
struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>);
|
||||
/// Every file is item 0; reading the second file says so on the second channel, then waits until
|
||||
/// the first channel closes.
|
||||
struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>, mpsc::Sender<()>);
|
||||
|
||||
impl Visitor for SecondBlocks {
|
||||
fn wants(&self, _: &str) -> bool {
|
||||
@@ -348,6 +364,7 @@ impl Visitor for SecondBlocks {
|
||||
let mut read = self.0.lock().unwrap();
|
||||
read.0 += 1;
|
||||
if read.0 == 2 {
|
||||
let _ = self.1.send(());
|
||||
let _ = read.1.recv();
|
||||
}
|
||||
vec![0]
|
||||
@@ -360,11 +377,9 @@ impl Visitor for SecondBlocks {
|
||||
fn files_found_are_kept_as_they_are_read() {
|
||||
let root = tree("kept", &["a.ttf", "b.ttf", "c.ttf"]);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx)))));
|
||||
let until = Instant::now() + WAIT;
|
||||
while s.progress().read < 2 && Instant::now() < until {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
let (second, reading_second) = mpsc::channel();
|
||||
let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx)), second)));
|
||||
assert!(reading_second.recv_timeout(WAIT).is_ok(), "the walker reads a second file");
|
||||
let p = s.progress();
|
||||
assert_eq!((p.state(), p.hits.len()), ("searching", 1), "{p:?}");
|
||||
s.stop();
|
||||
@@ -527,16 +542,12 @@ fn system_roots_and_homes_are_told_by_what_they_hold() {
|
||||
fn a_search_starts_with_the_threads_left_and_fails_when_none_is() {
|
||||
static POOL: Pool = Pool::new(3);
|
||||
let root = tree("pool", &["f.ttf"]);
|
||||
let blocked = || {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
(tx, Arc::new(Blocked(Mutex::new(rx))) as Arc<dyn Visitor>)
|
||||
};
|
||||
let (tx_a, a) = blocked();
|
||||
let (tx_b, b) = blocked();
|
||||
let (tx_a, _, a) = blocked();
|
||||
let (tx_b, _, b) = blocked();
|
||||
let a = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 2, 1, a).unwrap();
|
||||
let b = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 4, 1, b).unwrap();
|
||||
assert_eq!(POOL.live(), 3);
|
||||
let (_, c) = blocked();
|
||||
let (_, _, c) = blocked();
|
||||
let c = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 1, 1, c);
|
||||
assert_eq!(c.err().as_deref(), Some("the search couldn't start: try again in a moment"));
|
||||
drop((tx_a, tx_b));
|
||||
|
||||
@@ -238,12 +238,18 @@ impl Search {
|
||||
self.shared.finish(&mut w, End::Stopped);
|
||||
}
|
||||
|
||||
/// Move the search's deadline to now, as if its time had run out.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn expire(&self) {
|
||||
self.shared.deadline.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Where the search stands. Past its deadline it has ended ([`End::Time`]), even while a walker
|
||||
/// is still waiting for a slow folder or file.
|
||||
pub fn progress(&self) -> Progress {
|
||||
let s = &self.shared;
|
||||
let mut w = s.lock();
|
||||
if w.end.is_none() && Instant::now() >= s.deadline {
|
||||
if w.end.is_none() && s.time_up() {
|
||||
s.finish(&mut w, End::Time);
|
||||
}
|
||||
Progress {
|
||||
@@ -310,7 +316,7 @@ pub(crate) fn start_in(
|
||||
entries: AtomicU64::new(0),
|
||||
read: AtomicU64::new(0),
|
||||
started,
|
||||
deadline: started + Duration::from_secs_f64(seconds),
|
||||
deadline: AtomicU64::new(u64::try_from(Duration::from_secs_f64(seconds).as_nanos()).unwrap_or(u64::MAX)),
|
||||
limits,
|
||||
items,
|
||||
given: rules,
|
||||
@@ -355,7 +361,8 @@ struct Shared {
|
||||
entries: AtomicU64,
|
||||
read: AtomicU64,
|
||||
started: Instant,
|
||||
deadline: Instant,
|
||||
/// Nanoseconds after `started` at which the search's time is up.
|
||||
deadline: AtomicU64,
|
||||
limits: Limits,
|
||||
items: usize,
|
||||
/// The rules given to [`start`], else this computer's, read by the first walker.
|
||||
@@ -419,7 +426,12 @@ impl Shared {
|
||||
|
||||
/// Whether to stop listing and reading: the search ended or its time is up.
|
||||
fn should_stop(&self) -> bool {
|
||||
self.stop.load(Ordering::Relaxed) || Instant::now() >= self.deadline
|
||||
self.stop.load(Ordering::Relaxed) || self.time_up()
|
||||
}
|
||||
|
||||
/// Whether the search's time is up: [`Shared::deadline`] nanoseconds passed since it started.
|
||||
fn time_up(&self) -> bool {
|
||||
u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX) >= self.deadline.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether the folders waiting to be listed and `more` folders found in the folder being listed
|
||||
@@ -618,7 +630,7 @@ fn walker(s: &Shared) {
|
||||
if w.end.is_some() {
|
||||
return;
|
||||
}
|
||||
if Instant::now() >= s.deadline {
|
||||
if s.time_up() {
|
||||
s.finish(&mut w, End::Time);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio
|
||||
}
|
||||
}
|
||||
}
|
||||
let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
// The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it
|
||||
// again right away.
|
||||
let raw = craft_image_codecs::Image::from_raw(
|
||||
img.width,
|
||||
img.height,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
img.to_straight(),
|
||||
)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip })
|
||||
}
|
||||
|
||||
|
||||
@@ -2588,6 +2588,7 @@ fn a_line_series_draws_its_kept_stroke_on_the_line_and_its_kept_fill_on_the_mark
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let (drawn, others) = line_parts(&s, id);
|
||||
assert_eq!((drawn.appearance.fill_paint(), drawn.appearance.stroke_paint()), (Paint::None, red));
|
||||
assert!(!others.is_empty(), "the markers and the legend swatch are drawn");
|
||||
assert!(others.iter().all(|m| m.appearance.fill_paint() == blue), "{others:?}");
|
||||
}
|
||||
|
||||
@@ -4867,7 +4868,7 @@ fn blanks_read_back_as_null_and_year_header_rows_still_read_as_headers() {
|
||||
#[test]
|
||||
fn a_huge_ragged_grid_is_capped() {
|
||||
let g = GraphSpec { rows: vec![vec![0.0; vectorcraft_doc::MAX_GRAPH_SERIES + 10]; 3], ..GraphSpec::default() };
|
||||
assert!(g.cells().iter().all(|r| r.len() == vectorcraft_doc::MAX_GRAPH_SERIES));
|
||||
assert_eq!(g.cells().iter().map(Vec::len).collect::<Vec<_>>(), [vectorcraft_doc::MAX_GRAPH_SERIES; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -6720,7 +6721,17 @@ fn designs_and_markers_survive_save_and_open() {
|
||||
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Dot".into(), art: std::sync::Arc::new(dot) });
|
||||
let art = super::generate(&mut d, &g);
|
||||
let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
let marks = s0.children().unwrap();
|
||||
assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(marks.iter().filter(|n| sized(n, 5.0)).count(), 1, "a default square at the one data point");
|
||||
}
|
||||
|
||||
/// Whether `n` is a square path `side` points across, drawn as the four corners of its bounds (a default point marker
|
||||
/// is 5, a default legend swatch 8).
|
||||
fn sized(n: &vectorcraft_doc::Node, side: f64) -> bool {
|
||||
let Some(b) = n.geometric_bounds() else { return false };
|
||||
let square = matches!(&n.kind, NodeKind::Path { path, .. } if *path == vectorcraft_geom::shapes::rectangle(b));
|
||||
square && (b.width() - side).abs() < 1e-6 && (b.height() - side).abs() < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -6773,7 +6784,11 @@ fn designs_too_big_for_a_graph_are_refused_and_drawn_as_squares() {
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let art = super::generate(&mut d, &g);
|
||||
let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
let marks = s0.children().unwrap();
|
||||
assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(marks.iter().filter(|n| sized(n, 5.0)).count(), 200, "a default square at each of the 200 points");
|
||||
let line = marks.iter().filter(|n| n.geometric_bounds().is_some_and(|b| b.width() > 100.0)).count();
|
||||
assert_eq!(line, 1, "the series line is drawn as well");
|
||||
// Too many objects for one design.
|
||||
let ids: Vec<u64> = (0..2001)
|
||||
.map(|i| s.execute("shape.rectangle", &json!({"x": i % 40, "y": i / 40, "width": 1, "height": 1})).unwrap()["id"].as_u64().unwrap())
|
||||
@@ -7157,7 +7172,16 @@ fn graph_column_params_are_checked_and_designs_too_big_are_drawn_plain() {
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let art = super::generate(&mut d, &g);
|
||||
let s0 = art.iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
assert!(s0.children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
let marks = s0.children().unwrap();
|
||||
assert!(marks.iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(marks.iter().filter(|n| sized(n, 8.0)).count(), 1, "a default square as the legend swatch");
|
||||
let columns: Vec<_> = marks.iter().filter(|n| !sized(n, 8.0)).collect();
|
||||
assert_eq!(columns.len(), 1, "one plain column for the one value");
|
||||
let bounds = columns[0].geometric_bounds();
|
||||
let height = bounds.map(|b| b.height());
|
||||
assert!(height.is_some_and(|h| (h - 140.0).abs() < 1e-6), "the column has the value's height: {height:?}");
|
||||
let rectangle = bounds.map(vectorcraft_geom::shapes::rectangle);
|
||||
assert!(matches!(&columns[0].kind, NodeKind::Path { path, .. } if Some(path) == rectangle.as_ref()), "the plain column is a rectangle");
|
||||
// Columns of 0 on a value axis from 10,000 to 10,001 run 2,000,000 points from the clamped zero line: a copy each
|
||||
// 0.1 is past the budget too.
|
||||
let far = one_series(&mut s, "column", &[0.0, 0.0]);
|
||||
@@ -7840,7 +7864,9 @@ fn the_legend_across_top_keeps_above_labels_over_the_plot() {
|
||||
let n = s.doc().unwrap().doc.node(col).unwrap().clone();
|
||||
let texts: Vec<_> = group(&n, "Legend").children().unwrap().iter().filter_map(|c| c.geometric_bounds()).collect();
|
||||
let last_row = texts.iter().map(|b| b.y0).fold(f64::MIN, f64::max);
|
||||
assert!(texts.iter().filter(|b| b.y0 < last_row - 1e-6).all(|b| b.x1 <= 400.0 + 1e-6), "{texts:?}");
|
||||
let above: Vec<_> = texts.iter().filter(|b| b.y0 < last_row - 1e-6).collect();
|
||||
assert!(!above.is_empty(), "the legend takes more than one row: {texts:?}");
|
||||
assert!(above.iter().all(|b| b.x1 <= 400.0 + 1e-6), "{texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -8024,6 +8050,7 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() {
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 12})).unwrap();
|
||||
let looks = label_looks(&mut s, id);
|
||||
assert!(!looks.is_empty());
|
||||
assert!(looks.iter().all(|(_, size, _)| (*size - 12.0).abs() < 1e-6), "{looks:?}");
|
||||
let g = spec(&s, id);
|
||||
assert!(g.label_styles.values.is_some() && g.label_styles.categories.is_some() && g.label_styles.legend.is_some());
|
||||
@@ -9145,10 +9172,13 @@ fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) {
|
||||
(stroke, n.appearance.stroke_width(), n.opacity)
|
||||
}
|
||||
|
||||
/// The looks of graph `id`'s lines after it is drawn again.
|
||||
/// The looks of graph `id`'s lines after it is drawn again: more than three (a radar graph's
|
||||
/// three spokes come first, then its rings).
|
||||
fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> {
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
line_nodes(s, id).iter().map(line_look).collect()
|
||||
let looks: Vec<_> = line_nodes(s, id).iter().map(line_look).collect();
|
||||
assert!(looks.len() > 3, "the graph is drawn with its lines: {looks:?}");
|
||||
looks
|
||||
}
|
||||
|
||||
/// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder",
|
||||
[],
|
||||
None,
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
has_doc,
|
||||
move_node
|
||||
),
|
||||
@@ -1001,9 +1001,32 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index);
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if !accepts(d, parent, n) {
|
||||
let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if let Some(c) = compound {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, .. }) {
|
||||
return Err(bad(C, "a compound path holds only paths"));
|
||||
}
|
||||
// A clip group's or clipping layer's clipping path stays where it is: without it, the
|
||||
// next object up would become the clipping path.
|
||||
if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) {
|
||||
return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first"));
|
||||
}
|
||||
if !d.is_editable(c.id) {
|
||||
return Err(bad(C, "the compound path is hidden or locked"));
|
||||
}
|
||||
} else if !accepts(d, parent, n) {
|
||||
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
|
||||
}
|
||||
// An empty compound path takes the paint of the first path that goes into it: the path's own,
|
||||
// or the paint of the compound path it leaves, which is what painted it.
|
||||
let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
let shown = from_compound.map_or(&n.appearance, |p| &p.appearance);
|
||||
let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone()));
|
||||
let into = compound.map(|c| c.id);
|
||||
let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned);
|
||||
// A path that leaves a compound path for a layer or a group takes the compound path's paint and
|
||||
// pixel alignment, as Release Compound Path gives them to its paths.
|
||||
let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned));
|
||||
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
@@ -1013,6 +1036,36 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let left = super::intertwine::groups_of(d, &[id]);
|
||||
s.edit(label, |d, sel| {
|
||||
d.move_node(id, parent, index)?;
|
||||
if let Some((c, appearance)) = paint
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
n.appearance = appearance;
|
||||
}
|
||||
// A path in a compound path keeps no paint, live shape or pixel alignment of its own, as
|
||||
// Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when
|
||||
// the path was, or when the compound path it leaves was.
|
||||
if let Some(c) = into {
|
||||
let mut aligned = from_aligned;
|
||||
if let Some(m) = d.node_mut(id) {
|
||||
m.appearance = vectorcraft_doc::Appearance::default().into();
|
||||
aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned);
|
||||
if let NodeKind::Path { live, .. } = &mut m.kind {
|
||||
*live = None;
|
||||
}
|
||||
}
|
||||
if aligned && let Some(cn) = d.node_mut(c) {
|
||||
cn.extras_mut().pixel_aligned = true;
|
||||
super::object::snap_if_aligned(cn);
|
||||
}
|
||||
}
|
||||
if let Some((appearance, aligned)) = out_of
|
||||
&& let Some(m) = d.node_mut(id)
|
||||
{
|
||||
m.appearance = appearance;
|
||||
if aligned {
|
||||
m.extras_mut().pixel_aligned = true;
|
||||
}
|
||||
}
|
||||
super::intertwine::settle_members(d, &[(id, from)], &left)?;
|
||||
live_paint.finish(d, sel, &[id])?;
|
||||
sel.prune(d);
|
||||
|
||||
@@ -415,6 +415,10 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
|
||||
Some(f)
|
||||
}
|
||||
|
||||
pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option<String> {
|
||||
locate(link, base).map(|f| f.path)
|
||||
}
|
||||
|
||||
/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`]
|
||||
/// finds each linked image's and placed document's file from `base` and from no document (as
|
||||
/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from
|
||||
|
||||
@@ -858,6 +858,18 @@ pub fn find(s: &Session, name: &str) -> Option<DocSettings> {
|
||||
.or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name)))
|
||||
}
|
||||
|
||||
/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names
|
||||
/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without
|
||||
/// `preset`.
|
||||
fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) };
|
||||
let found = match str_param(p, "presetCategory") {
|
||||
Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))),
|
||||
None => find(s, name),
|
||||
};
|
||||
found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)")))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
@@ -871,10 +883,7 @@ const RECENT: usize = 12;
|
||||
/// `file.new`: a new document from a preset and/or explicit settings.
|
||||
pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.new";
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
|
||||
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let size = str_param(p, "preset").map(|_| sorted(&base));
|
||||
@@ -911,9 +920,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() });
|
||||
@@ -959,10 +973,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(str::trim)
|
||||
.filter(|n| !n.is_empty() && n.chars().count() <= 64)
|
||||
.ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?;
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
let mut preset = base.with_params_inner(p, C, s.replaying())?;
|
||||
preset.name = name.to_string();
|
||||
let saved = &mut s.prefs.new_doc_presets;
|
||||
@@ -1103,8 +1114,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 }))
|
||||
}
|
||||
|
||||
@@ -105,6 +105,49 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": gid.0 }))
|
||||
}
|
||||
|
||||
/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a
|
||||
/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The
|
||||
/// selection stays as it is.
|
||||
pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.newGroup";
|
||||
// Only an omitted key takes its default; `null` is refused like any other bad value.
|
||||
let compound = match p.get("compound") {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let parent = match p.get("parent") {
|
||||
None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
|
||||
Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?),
|
||||
};
|
||||
let index = match p.get("index") {
|
||||
None => usize::MAX,
|
||||
Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?,
|
||||
};
|
||||
let d = &st.doc;
|
||||
let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) };
|
||||
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() {
|
||||
return Err(bad(C, format!("{} is not a layer or group", parent.0)));
|
||||
}
|
||||
if !d.is_editable(parent) {
|
||||
return Err(bad(C, "the layer or group is hidden or locked"));
|
||||
}
|
||||
let label = if compound { "Compound Path" } else { "Group" };
|
||||
let gid = s.edit(label, |d, _| {
|
||||
let gid = d.alloc_id();
|
||||
let clips = d.node(parent).is_some_and(Node::clips);
|
||||
let index = if clips { index.max(1) } else { index };
|
||||
let node = if compound {
|
||||
Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero })
|
||||
} else {
|
||||
Node::group(gid, Vec::new())
|
||||
};
|
||||
d.insert(Some(parent), index, node)?;
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": gid.0 }))
|
||||
}
|
||||
|
||||
/// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was.
|
||||
pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result<NodeId> {
|
||||
if ids.is_empty() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::align::{align, can_distribute, distribute, distribute_spacing};
|
||||
use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all};
|
||||
use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all};
|
||||
use super::bounds::set_bounds;
|
||||
use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release};
|
||||
use super::pixelgrid::set_pixel_aligned;
|
||||
@@ -137,6 +137,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
group
|
||||
),
|
||||
cmd!(
|
||||
"object.newGroup",
|
||||
"Group",
|
||||
[],
|
||||
None,
|
||||
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
|
||||
has_doc,
|
||||
new_group
|
||||
),
|
||||
cmd!(
|
||||
"object.ungroup",
|
||||
"Ungroup",
|
||||
|
||||
@@ -384,6 +384,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
}
|
||||
}
|
||||
s.clipboard = clip;
|
||||
s.note_copy();
|
||||
Ok(json!({"copied": copied}))
|
||||
}
|
||||
|
||||
|
||||
@@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("addon.pathtools.bridge", "radius", "gap"),
|
||||
("addon.pathtools.commonTangents", "radius", "gap"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
@@ -1921,6 +1921,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
.copied()
|
||||
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
|
||||
.collect();
|
||||
let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied());
|
||||
// The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`.
|
||||
let compounds: BTreeSet<NodeId> = if keep_empty {
|
||||
BTreeSet::new()
|
||||
@@ -2002,6 +2003,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
d.remove(p)?;
|
||||
}
|
||||
}
|
||||
super::edit::release_empty_clips(d, clipped);
|
||||
selection.set(survivors);
|
||||
for (id, next) in following {
|
||||
if !next.is_empty() {
|
||||
|
||||
@@ -1563,6 +1563,12 @@ pub fn auto_simplify_level(s: &Session) -> Result<f64> {
|
||||
fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.path.simplify";
|
||||
let (auto, given_level, given_tolerance) = (switch_or(p, "auto", false, C)?, number_given(p, "level", C)?, length_given(p, "tolerance", C)?);
|
||||
if given_tolerance.is_some_and(|t| t < 0.0) {
|
||||
return Err(bad(C, "`tolerance` must be 0 or more"));
|
||||
}
|
||||
if given_level.is_some_and(|l| !(0.0..=100.0).contains(&l)) {
|
||||
return Err(bad(C, "`level` must be from 0 to 100"));
|
||||
}
|
||||
let corner_angle = number_given(p, "cornerAngle", C)?.unwrap_or(30.0).clamp(0.0, 180.0);
|
||||
let (straight_lines, whole) = (switch_or(p, "straightLines", false, C)?, switch_or(p, "wholePaths", false, C)?);
|
||||
// With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given.
|
||||
|
||||
@@ -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.
|
||||
@@ -563,6 +639,8 @@ struct Saved {
|
||||
draw_mode: crate::DrawMode,
|
||||
draw_inside: Option<vectorcraft_doc::NodeId>,
|
||||
clipboard: crate::Clipboard,
|
||||
clipboard_copied: bool,
|
||||
copies: u64,
|
||||
untitled_counter: u32,
|
||||
explicit_undo_group: Option<Option<String>>,
|
||||
prefs: crate::Prefs,
|
||||
@@ -588,6 +666,8 @@ impl Saved {
|
||||
draw_mode: s.draw_mode,
|
||||
draw_inside: s.draw_inside,
|
||||
clipboard: s.clipboard.clone(),
|
||||
clipboard_copied: s.clipboard_copied,
|
||||
copies: s.copies,
|
||||
untitled_counter: s.untitled_counter,
|
||||
explicit_undo_group: s.explicit_undo_group.clone(),
|
||||
prefs: s.prefs.clone(),
|
||||
@@ -612,6 +692,8 @@ impl Saved {
|
||||
s.draw_mode = self.draw_mode;
|
||||
s.draw_inside = self.draw_inside;
|
||||
s.clipboard = self.clipboard;
|
||||
s.clipboard_copied = self.clipboard_copied;
|
||||
s.copies = self.copies;
|
||||
s.untitled_counter = self.untitled_counter;
|
||||
s.explicit_undo_group = self.explicit_undo_group;
|
||||
s.prefs = self.prefs;
|
||||
@@ -952,4 +1034,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);
|
||||
}
|
||||
}
|
||||
@@ -346,6 +346,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.mesh.movePoints",
|
||||
"object.mesh.setPointColor",
|
||||
"object.move",
|
||||
"object.newGroup",
|
||||
"object.nudge",
|
||||
"object.objectsOnPath.attach",
|
||||
"object.objectsOnPath.detach",
|
||||
@@ -758,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.
|
||||
|
||||
@@ -419,8 +419,9 @@ impl FolderStore {
|
||||
|
||||
/// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on
|
||||
/// Windows they must be the same file (volume serial number and file index); elsewhere `path`
|
||||
/// must exist. When either file can't be read, it does not.
|
||||
fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
/// must exist. A link at `path` is not followed, so it names the link and not `file`. When
|
||||
/// either file can't be read, it does not.
|
||||
pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
@@ -431,8 +432,19 @@ impl FolderStore {
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt as _;
|
||||
// FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and
|
||||
// FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path`
|
||||
// opens one.
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
let opened = file.try_clone().and_then(same_file::Handle::from_file);
|
||||
match (opened, same_file::Handle::from_path(path)) {
|
||||
let named = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)
|
||||
.and_then(same_file::Handle::from_file);
|
||||
match (opened, named) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
|
||||
@@ -1753,6 +1753,29 @@ fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool,
|
||||
if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact }
|
||||
}
|
||||
|
||||
/// Joins whole shape `pc`, whose matches `ms` are near ones in faces other than `l`'s alone, to line
|
||||
/// `l` by its near matches among the glyphs of `l`'s face in `indexes`: the 256 glyphs closest to a
|
||||
/// shape in proportion can all be glyphs of other faces drawn alike (a period, a dot). Those
|
||||
/// matches when the shape joins, `None` when it does not (`l` unchanged).
|
||||
fn join_in_line_face(l: &mut Line, pc: &Piece, ms: &[GlyphMatch], indexes: &[RetypeIndex], tolerance: f64) -> Option<Vec<GlyphMatch>> {
|
||||
let face = l.face.id();
|
||||
if ms.iter().any(|m| m.exact || m.face.id() == face) {
|
||||
return None;
|
||||
}
|
||||
let fill = pc.filled.then_some(pc.nonzero);
|
||||
let own: Vec<GlyphMatch> = indexes
|
||||
.iter()
|
||||
.flat_map(|ix| {
|
||||
let found = ix.near_matches_in(&pc.path, tolerance, face);
|
||||
match fill {
|
||||
Some(nonzero) => found.iter().filter_map(|m| ix.painted_agrees(m, &pc.path, nonzero, tolerance)).collect(),
|
||||
None => found,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
join(l, pc, &own).then_some(own)
|
||||
}
|
||||
|
||||
/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour
|
||||
/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is
|
||||
/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as
|
||||
@@ -1886,14 +1909,17 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
extra.push(f);
|
||||
}
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
let indexes: Vec<RetypeIndex> = if extra.is_empty() {
|
||||
vec![index]
|
||||
} else {
|
||||
// Near matching spends an index's comparison budget, so with a tolerance the
|
||||
// candidates are indexed again for this pass.
|
||||
let first = if tolerance > 0.0 { build(cands) } else { index };
|
||||
let others: Vec<RetypeIndex> = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect();
|
||||
let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect();
|
||||
found = match_pieces(&pieces, &groups, &all, tolerance);
|
||||
}
|
||||
let mut all = vec![first];
|
||||
all.extend(extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())));
|
||||
found = match_pieces(&pieces, &groups, &all.iter().collect::<Vec<_>>(), tolerance);
|
||||
all
|
||||
};
|
||||
// The face most shapes match, so a glyph several fonts share is set in the same font as
|
||||
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
|
||||
// them closest in all (the least leftover distance summed over those shapes), so every
|
||||
@@ -1949,11 +1975,19 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for ms in parts {
|
||||
// The part's candidates in the face most shapes fit (see `ranked`).
|
||||
let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id());
|
||||
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
|
||||
let joined = match lines.last_mut() {
|
||||
let mut cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
|
||||
let mut joined = match lines.last_mut() {
|
||||
Some(l) if open => join(l, pc, &cands),
|
||||
_ => false,
|
||||
};
|
||||
if !joined
|
||||
&& open
|
||||
&& parts.len() == 1
|
||||
&& let Some(own) = lines.last_mut().and_then(|l| join_in_line_face(l, pc, ms, &indexes, tolerance))
|
||||
{
|
||||
joined = true;
|
||||
cands = own;
|
||||
}
|
||||
// A part that joined a line, perhaps as a mark, that is also another character, in
|
||||
// that face or else in the face most shapes fit of those it is a character in: the
|
||||
// character, should a split leave the part first on a line ([`verified`]). Kept by
|
||||
|
||||
@@ -149,6 +149,10 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() {
|
||||
db.add_font(named_copy(true, (FAMILY, "Regular", "Version 2.000", "VersiontestSans-Regular")).unwrap());
|
||||
assert_eq!(db.face(FAMILY, "Regular").unwrap().version, "Version 1.000");
|
||||
let mut s = session();
|
||||
// Live type in the family puts the font among those compared first. Added last, after the
|
||||
// bundled fonts and however many faces craft-fonts supplies, it can fall past the fonts
|
||||
// Retype compares (`MAX_FACES`).
|
||||
s.execute("text.create", &json!({"x": 40, "y": 300, "text": "live", "size": 40, "font": FAMILY, "style": "Regular"})).unwrap();
|
||||
let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kg", "size": 40, "font": "Inter", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [inter]})).unwrap();
|
||||
let r = query(&mut s, json!({"count": 96}), &db);
|
||||
|
||||
@@ -102,10 +102,12 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
|
||||
use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font};
|
||||
// The comma below of Source Sans 3 is only marks there, and a modifier letter in this face.
|
||||
vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap());
|
||||
// Named, so it is among the fonts compared first, however many faces are loaded before it.
|
||||
let fonts = json!([SPACING_COMMA_FAMILY]);
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"fonts": fonts})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
|
||||
// After a base, it joins the line as the mark; moved off its base, the split leaves it first,
|
||||
@@ -115,7 +117,7 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"fonts": fonts})).unwrap();
|
||||
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}");
|
||||
assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
|
||||
}
|
||||
@@ -1099,7 +1101,9 @@ fn lines_that_do_not_stack_as_a_paragraph_stay_apart() {
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}");
|
||||
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}");
|
||||
let fonts = r["fonts"].as_array().unwrap();
|
||||
assert!(!fonts.is_empty(), "{r}");
|
||||
assert!(fonts.iter().all(|f| f["area"] == json!(false)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1918,19 +1922,28 @@ fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
|
||||
lines_in_family(s, g, None)
|
||||
}
|
||||
|
||||
/// [`lines_in`] with the face of the first glyph's match in `family` when given.
|
||||
/// [`lines_in`] with the face of the first glyph's match in `family` when given. The family is
|
||||
/// compared first, as `type.retype`'s `fonts` puts it, so the faces loaded before it cannot leave it
|
||||
/// out of the fonts Retype compares.
|
||||
fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
|
||||
super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted);
|
||||
let first = index.matches(&pieces[0].path);
|
||||
let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id();
|
||||
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);
|
||||
// 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],
|
||||
}
|
||||
.face
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -1854,9 +1854,12 @@ fn kana_style_and_roman_italics_are_character_features() {
|
||||
}
|
||||
assert_eq!(runs(&s), before);
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "featureChanges": ["-hkna", "-ital"]})).unwrap();
|
||||
let text = |s: &Session| runs(s).into_iter().map(|(t, _)| t).collect::<String>();
|
||||
assert_eq!(text(&s), "かなAB");
|
||||
assert!(runs(&s).iter().all(|(_, f)| f.is_empty()), "{:?}", runs(&s));
|
||||
s.execute("charStyle.new", &json!({"name": "Kana", "attrs": {"features": ["hkna", "ital"]}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Kana", "id": id})).unwrap();
|
||||
assert_eq!(text(&s), "かなAB");
|
||||
assert!(runs(&s).iter().all(|(_, f)| *f == ["hkna", "ital"]), "{:?}", runs(&s));
|
||||
let e = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"features": ["ital=2"]}})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown OpenType feature `ital=2`"), "{e}");
|
||||
|
||||
@@ -257,6 +257,7 @@ fn gaps_set_word_spacing_and_leading() {
|
||||
// The layout uses the gap as the Desired word spacing; the paragraph keeps its own.
|
||||
assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]);
|
||||
assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]);
|
||||
assert_eq!(t.plain_text(), "two words\nthree more words", "the runs hold the text");
|
||||
assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs);
|
||||
assert_block(&t);
|
||||
assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room");
|
||||
@@ -850,6 +851,7 @@ fn a_range_leading_change_with_block_on_moves_the_line_gap() {
|
||||
let t = text(&s, id);
|
||||
assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap);
|
||||
assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4));
|
||||
assert_eq!(t.plain_text(), "BIG\na much longer second line\nmid one", "the runs hold the text");
|
||||
assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads");
|
||||
// Reset Panel's form: the leading is set and Block keeps the line gap.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap();
|
||||
|
||||
@@ -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,27 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without adding `path` to the files a script run reports as written, for a
|
||||
/// check made before anything is 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 +1257,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 +1276,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]
|
||||
@@ -1390,6 +1481,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
@@ -1471,6 +1563,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_refuses_a_stream_inside_a_write_root() {
|
||||
let (base, roots) = folders("streams");
|
||||
|
||||
@@ -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;
|
||||
@@ -65,6 +66,10 @@ pub struct Session {
|
||||
pub fill_active: bool,
|
||||
/// Internal clipboard: the copied objects and the document resources they use.
|
||||
pub clipboard: Clipboard,
|
||||
/// How many times Copy or Cut has put art, guides or artboards on [`Self::clipboard`].
|
||||
pub(crate) copies: u64,
|
||||
/// [`Self::clipboard`] holds what the last Copy or Cut put there, not what an import put there.
|
||||
pub(crate) clipboard_copied: bool,
|
||||
/// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]).
|
||||
pub journal: Journal,
|
||||
/// About the most memory the undo steps of all the open documents may keep together
|
||||
@@ -384,6 +389,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 +412,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>>,
|
||||
@@ -530,7 +545,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::{HeldInteraction, PreviewCopies};
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
|
||||
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs, ScriptPreference};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -463,6 +463,34 @@ pub struct Prefs {
|
||||
/// preferences keeps it.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub import_matches: Vec<cmd::importmatches::ImportMatch>,
|
||||
/// The values scripts store with `app.preferences` under keys that are not VectorCraft
|
||||
/// preferences. Not a Preferences dialog field: it has no [`cmd::prefscmds::PREF_SPECS`] row,
|
||||
/// and resetting the preferences keeps it.
|
||||
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub script_preferences: std::collections::BTreeMap<String, ScriptPreference>,
|
||||
}
|
||||
|
||||
/// A value a script stored with `app.preferences`, with the type it was stored as. Two real
|
||||
/// values are equal when their bits are, so 0 and -0 differ.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScriptPreference {
|
||||
Boolean(bool),
|
||||
Integer(i64),
|
||||
Real(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl PartialEq for ScriptPreference {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Boolean(a), Self::Boolean(b)) => a == b,
|
||||
(Self::Integer(a), Self::Integer(b)) => a == b,
|
||||
(Self::Real(a), Self::Real(b)) => a.to_bits() == b.to_bits(),
|
||||
(Self::String(a), Self::String(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
|
||||
@@ -712,6 +740,7 @@ impl Default for Prefs {
|
||||
blend_options: None,
|
||||
perspective_widget: Default::default(),
|
||||
import_matches: vec![],
|
||||
script_preferences: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -253,7 +253,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
});
|
||||
let active = match &chosen {
|
||||
Some(chosen) => std::slice::from_ref(chosen),
|
||||
None => h.active_artboards.as_slice(),
|
||||
};
|
||||
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
|
||||
@@ -200,6 +200,13 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app does when the person answers Yes to a confirm it opens for a script ([`Dialogs::ask`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum OnYes {
|
||||
/// Turn off the warning before a script picked with File › Scripts › Other Script… runs.
|
||||
ExternalScriptWarningOff,
|
||||
}
|
||||
|
||||
/// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits
|
||||
/// for the person's answer, and the list the report gives.
|
||||
pub(crate) struct Dialogs {
|
||||
@@ -209,6 +216,10 @@ pub(crate) struct Dialogs {
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
answers: RefCell<VecDeque<DialogAnswer>>,
|
||||
waiting: RefCell<Option<ScriptDialog>>,
|
||||
/// What Yes to the waiting dialog does, when the app opened it with [`Dialogs::ask`].
|
||||
on_yes: Cell<Option<OnYes>>,
|
||||
/// What the person approved with Yes, until [`Dialogs::take_approved`] takes it.
|
||||
approved: Cell<Option<OnYes>>,
|
||||
/// The error that ended the run when an answer could not reach the script.
|
||||
failed: RefCell<Option<RunError>>,
|
||||
records: RefCell<Vec<Value>>,
|
||||
@@ -233,6 +244,8 @@ impl Dialogs {
|
||||
can_wait: realm.wait_flag(),
|
||||
answers: RefCell::new(answers.into()),
|
||||
waiting: RefCell::default(),
|
||||
on_yes: Cell::new(None),
|
||||
approved: Cell::new(None),
|
||||
failed: RefCell::default(),
|
||||
records: RefCell::default(),
|
||||
record_bytes: Cell::new(0),
|
||||
@@ -444,14 +457,45 @@ impl Dialogs {
|
||||
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
|
||||
self.record(d, answer.json());
|
||||
*waiting = None;
|
||||
if let Err(e) = realm.answer(answer.data()) {
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
if let Err(e) = realm.answer(data) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens `dialog`, a confirm the app shows for the script, whose Yes does `on_yes`; the call
|
||||
/// that opens it then waits ([`HostError::Wait`]) and returns `undefined`. Only a person answers
|
||||
/// it, never `script.run`'s `answers`. → false when it cannot open: the run has nobody to ask,
|
||||
/// or the call comes from a callback, a getter, a conversion or a file `$.evalFile` runs.
|
||||
pub(crate) fn ask(&self, dialog: ScriptDialog, on_yes: OnYes) -> bool {
|
||||
if !self.framed || !self.can_wait.get() {
|
||||
return false;
|
||||
}
|
||||
*self.waiting.borrow_mut() = Some(dialog);
|
||||
self.on_yes.set(Some(on_yes));
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the waiting dialog is the confirm [`Dialogs::ask`] opened to turn off the external
|
||||
/// script warning, whatever a script's own dialogs say.
|
||||
pub(crate) fn asks_warning_off(&self) -> bool {
|
||||
self.waiting.borrow().is_some() && self.on_yes.get() == Some(OnYes::ExternalScriptWarningOff)
|
||||
}
|
||||
|
||||
/// What the person approved with Yes to a confirm from [`Dialogs::ask`], once.
|
||||
pub(crate) fn take_approved(&self) -> Option<OnYes> {
|
||||
self.approved.take()
|
||||
}
|
||||
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
|
||||
pub(crate) fn stopped(&self) {
|
||||
self.on_yes.set(None);
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
}
|
||||
|
||||
+450
-125
@@ -18,7 +18,8 @@
|
||||
//!
|
||||
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
|
||||
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound
|
||||
//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! gives, and a script may name the application's members without `app.`, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
|
||||
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
|
||||
@@ -52,8 +53,8 @@
|
||||
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
|
||||
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
|
||||
//! error. A run that fails leaves the tool as it was.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of
|
||||
//! the paths in the object; a clipping group counts its clipping path only.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
//! in view-number order, and none without one. View objects keep their window's identity when
|
||||
//! windows are renumbered. The screen mode is the app's:
|
||||
@@ -97,10 +98,17 @@ use vectorcraft_js::{
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod clipboard;
|
||||
mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -127,6 +135,10 @@ pub(crate) use paths::POINT_LOOKS;
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
pub const STALE_ITEM: &str = "Stale page item";
|
||||
/// The error for a new name given to a `PluginItem`.
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -158,6 +170,7 @@ const ITEM_CLASSES: &[&str] = &[
|
||||
"RepeatItem",
|
||||
"PlacedDocumentItem",
|
||||
"IntertwineItem",
|
||||
"PluginItem",
|
||||
];
|
||||
|
||||
/// `app.coordinateSystem`.
|
||||
@@ -171,6 +184,14 @@ pub(super) enum Coords {
|
||||
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
|
||||
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
|
||||
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
/// How many lists of art the art collections have built on this thread.
|
||||
pub(crate) static ART_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
@@ -208,6 +229,21 @@ pub(super) struct State {
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
/// Each document made during the run whose active artboard `setActiveArtboardIndex` chose,
|
||||
/// with the index it chose the first time.
|
||||
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
/// The print option objects ([`print`]).
|
||||
@@ -217,13 +253,17 @@ pub(super) struct State {
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
/// What the placed and raster items keep ([`images::State`]).
|
||||
images: images::State,
|
||||
/// What the tracings keep ([`tracing::State`]).
|
||||
tracing: tracing::State,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state of a run whose heap is `heap_bytes`.
|
||||
pub(super) fn new(heap_bytes: usize) -> Self {
|
||||
Self { preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
/// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`.
|
||||
pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self {
|
||||
Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether a call's own savepoint is open: its commands take none of their own.
|
||||
@@ -430,7 +470,7 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item, path point or text range `this` is still there.
|
||||
/// the check that a document, layer, page item, path point or text range `this` is still there.
|
||||
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
|
||||
/// `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
@@ -443,7 +483,10 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "PathItem" | "TextFrame" => {
|
||||
"Layer" => {
|
||||
layers::layer_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
c if c == "PageItem" || ITEM_CLASSES.contains(&c) => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
@@ -583,16 +626,25 @@ fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
Some((doc, id_of(high, low)?))
|
||||
}
|
||||
|
||||
/// The page item `d` names, which must still be in its document.
|
||||
/// The page item `d` names, which must still be in its document and still be of its class (an
|
||||
/// embedded `PlacedItem` is a `RasterItem` after, and its old object is stale).
|
||||
fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) };
|
||||
if handle.len() != 5 {
|
||||
let Some((class, handle)) = host_ref_parts(d).filter(|(c, _)| ITEM_CLASSES.contains(c)) else {
|
||||
return Err(HostError::Type("this is not a page item".into()));
|
||||
}
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
};
|
||||
let (doc, id) = match handle.as_slice() {
|
||||
[_, _, _, _, _] => node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?,
|
||||
&[run, uid, _, _, _, slot] => {
|
||||
let id = images::pending_id(h, run, uid, slot)?;
|
||||
(find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, id)
|
||||
}
|
||||
_ => return Err(HostError::Type("this is not a page item".into())),
|
||||
};
|
||||
let original = id;
|
||||
let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id };
|
||||
let s = h.session.borrow();
|
||||
let st = &s.documents()[doc.index];
|
||||
if st.doc.node(id).is_none_or(|n| typename(n).is_none()) {
|
||||
if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok(Item { doc, id })
|
||||
@@ -603,6 +655,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> {
|
||||
Some(match &n.kind {
|
||||
NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None,
|
||||
NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem",
|
||||
NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem",
|
||||
NodeKind::Group { .. } => "GroupItem",
|
||||
NodeKind::Path { .. } => "PathItem",
|
||||
NodeKind::Compound { .. } => "CompoundPathItem",
|
||||
@@ -626,6 +679,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
|
||||
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
match st.doc.node(id) {
|
||||
Some(n) => match typename(n) {
|
||||
Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))),
|
||||
Some("PluginItem") => {
|
||||
tracing::remember_source(h, st.uid, n);
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
},
|
||||
@@ -649,7 +707,10 @@ fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, H
|
||||
_ => {
|
||||
out.push(n.id);
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, out);
|
||||
// The source image an Image Trace object keeps hidden as its first child is
|
||||
// reached through that object's `tracing`.
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
walk(children.get(source..).unwrap_or_default(), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -686,9 +747,11 @@ fn top_items(d: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `n` and every object inside it are shown and unlocked.
|
||||
/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace
|
||||
/// object keeps hidden as its first child is part of that object and is not counted.
|
||||
fn all_editable(n: &crate::doc::Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c)))
|
||||
let source = usize::from(crate::cmd::is_trace_group(n));
|
||||
n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c)))
|
||||
}
|
||||
|
||||
/// Whether the object and every layer and group it is in are shown and unlocked.
|
||||
@@ -881,7 +944,8 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
|
||||
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
|
||||
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// hidden or locked; the current layer, which selecting art changes, is put back too while it is
|
||||
/// still a layer that can be edited. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
|
||||
/// changes are undone as well.
|
||||
fn on_doc<T>(
|
||||
@@ -890,14 +954,27 @@ fn on_doc<T>(
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
|
||||
on_doc_layer(h, uid, keep_selection, true, f)
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc`].
|
||||
/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`,
|
||||
/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current.
|
||||
fn on_doc_layer<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
keep_layer: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
atomically(h, |h| on_doc_steps(h, uid, keep_selection, keep_layer, f))
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc_layer`].
|
||||
fn on_doc_steps<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
keep_layer: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before, layer, activated) = {
|
||||
@@ -911,6 +988,12 @@ fn on_doc_steps<T>(
|
||||
command(h, "document.activate", &json!({"index": index}))?;
|
||||
}
|
||||
let r = f(h);
|
||||
let layer = if keep_layer {
|
||||
layer
|
||||
} else {
|
||||
let s = h.session.borrow();
|
||||
s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows()))
|
||||
};
|
||||
let mut restored = Ok(());
|
||||
if keep_selection {
|
||||
let doc = {
|
||||
@@ -975,9 +1058,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
|
||||
}
|
||||
@@ -2126,22 +2216,35 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
@@ -2161,6 +2264,9 @@ fn position(n: f64) -> Option<usize> {
|
||||
/// 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 object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
@@ -2184,6 +2290,9 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
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)
|
||||
@@ -2200,6 +2309,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
@@ -2217,6 +2329,9 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = top_items(&st.doc);
|
||||
@@ -2300,6 +2415,28 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
// An Image Trace object is known by its name, so renaming one would end the tracing, and giving
|
||||
// an ordinary group that holds an image first the tracing's name would make it one.
|
||||
let item = this_item(h, a)?;
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).and_then(|n| {
|
||||
let tracing = crate::cmd::is_trace_group(n);
|
||||
let would_trace = !tracing
|
||||
&& name == crate::cmd::TRACE_NAME
|
||||
&& matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. })
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_))));
|
||||
if tracing && n.name.as_deref() != Some(&**name) {
|
||||
Some(TRACING_NAME)
|
||||
} else if would_trace {
|
||||
Some(NOT_A_TRACING)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(msg) = refused {
|
||||
return Err(HostError::Error(msg.into()));
|
||||
}
|
||||
set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name}))
|
||||
}
|
||||
|
||||
@@ -2369,8 +2506,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four
|
||||
/// decimals.
|
||||
fn reported_opacity(opacity: f32) -> f64 {
|
||||
(f64::from(opacity) * 100.0 * 1e4).round() / 1e4
|
||||
}
|
||||
|
||||
fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
|
||||
read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2387,7 +2530,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
|
||||
let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0);
|
||||
let keeps_other =
|
||||
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
|
||||
(now, keeps_other)
|
||||
@@ -2470,8 +2613,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)?)))
|
||||
}
|
||||
|
||||
@@ -2491,24 +2638,26 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
|
||||
bounds(h, a, true)
|
||||
}
|
||||
|
||||
/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
|
||||
/// the object.
|
||||
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
|
||||
/// object with nothing in it.
|
||||
fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
// An object with nothing in it reads zeros, as its other bounds do.
|
||||
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
|
||||
let r = with_doc(h, item.doc, |_, st| {
|
||||
let mut r = r;
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
|
||||
r = r.union(handles);
|
||||
}
|
||||
});
|
||||
}
|
||||
r
|
||||
});
|
||||
Ok(f.bounds(h.dom.coords.get(), r))
|
||||
let (r, f) = item_rect(h, item, true)?;
|
||||
let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds));
|
||||
match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) {
|
||||
Some(r) => Ok(f.bounds(h.dom.coords.get(), r)),
|
||||
None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown
|
||||
/// paths in its children (a clip group's from its clipping path).
|
||||
fn handle_bounds(n: &crate::doc::Node) -> Option<Rect> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.control_bounds(),
|
||||
NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)),
|
||||
_ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))),
|
||||
}
|
||||
}
|
||||
|
||||
fn item_position(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2543,20 +2692,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)
|
||||
}
|
||||
|
||||
@@ -2590,18 +2764,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)
|
||||
}
|
||||
|
||||
@@ -2641,6 +2826,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
// A compound path whose last path this is stays, empty, as it does after `move`.
|
||||
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
|
||||
Ok(Data::Undefined)
|
||||
@@ -2694,14 +2883,20 @@ struct Destination {
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
// A page item is looked up as its class names it (a wrapper whose object changed class is
|
||||
// stale), a layer by its handle.
|
||||
let (doc, target) = if handle_of(target, "PageItem").is_some() {
|
||||
let t = item_of(h, target)?;
|
||||
(t.doc, t.id)
|
||||
} else {
|
||||
let Some(handle) = handle_of(target, "Layer").filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
};
|
||||
node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?
|
||||
};
|
||||
let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
if doc.uid != item.doc.uid {
|
||||
return Err(HostError::Error(CROSS_DOCUMENT.into()));
|
||||
}
|
||||
@@ -2714,7 +2909,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
}
|
||||
let (parent, beside) = match how {
|
||||
Placement::Top | Placement::Bottom => {
|
||||
if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
|
||||
if matches!(t.kind, NodeKind::Compound { .. }) {
|
||||
if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) {
|
||||
return Err(HostError::Error("a compound path holds only paths".into()));
|
||||
}
|
||||
} else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
|
||||
return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer"))));
|
||||
}
|
||||
(target, None)
|
||||
@@ -2741,17 +2940,64 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
|
||||
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
|
||||
}
|
||||
// Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A
|
||||
// tracing's source image moved out keeps the error `place` gives it.
|
||||
let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)));
|
||||
if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) {
|
||||
// Where the image comes from: its index in `parent` when it is already there.
|
||||
let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy);
|
||||
let count = d.children(Some(parent)).map_or(0, Vec::len);
|
||||
let first = match how {
|
||||
Placement::Bottom => true,
|
||||
Placement::Top => count == usize::from(own.is_some()),
|
||||
Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))),
|
||||
Placement::Above => false,
|
||||
};
|
||||
if first {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
}
|
||||
Ok(Destination { parent, beside, how })
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put
|
||||
/// first in it would make it a tracing.
|
||||
fn named_as_tracing(d: &Document, id: NodeId) -> bool {
|
||||
d.node(id).is_some_and(|p| {
|
||||
!crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of
|
||||
/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it.
|
||||
fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option<usize>) -> bool {
|
||||
if !named_as_tracing(d, parent) {
|
||||
return false;
|
||||
}
|
||||
let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_));
|
||||
let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::<Vec<_>>()).unwrap_or_default();
|
||||
match at {
|
||||
Some(0) => d.node(id).is_some_and(image),
|
||||
_ => rest.first().is_some_and(|n| image(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place.
|
||||
fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
|
||||
let index = with_doc(h, doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let from = d.position(id);
|
||||
let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent)));
|
||||
let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0;
|
||||
// A clip group's first child is its clipping path, and an Image Trace object's its source
|
||||
// image: both stay first, and the source image moved within its own tracing stays where it is.
|
||||
if crate::cmd::is_trace_source(d, id) {
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
let at = match (to.how, to.beside) {
|
||||
(Placement::Top, _) => count,
|
||||
(Placement::Bottom, _) => 0,
|
||||
@@ -2767,7 +3013,22 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
}
|
||||
(_, None) => count,
|
||||
};
|
||||
Ok::<_, HostError>(if clips { at.max(1) } else { at })
|
||||
let at = if clips { at.max(1) } else { at };
|
||||
// The index `node.move` puts the object at: art stays below the ruler guides.
|
||||
// This is `Node::insert_index` on the parent's children without the object, read in place
|
||||
// so that no list of them is copied.
|
||||
let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let rest = || d.children(Some(to.parent)).into_iter().flatten().filter(|n| n.id != id);
|
||||
let start = rest().enumerate().filter(|(_, n)| !n.is_ruler_guide()).last().map_or(0, |(i, _)| i + 1);
|
||||
let i = at.min(rest().count());
|
||||
let at = if node.is_ruler_guide() { i.max(start) } else { i.min(start) };
|
||||
// An image left or put first in an ordinary group named as a tracing would make that group
|
||||
// one, in the group it leaves as in the group it goes into.
|
||||
let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent);
|
||||
if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
Ok::<_, HostError>(at)
|
||||
})?;
|
||||
let now = with_doc(h, doc, |_, st| st.doc.position(id));
|
||||
if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) {
|
||||
@@ -2862,39 +3123,54 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
// The source image an Image Trace object keeps first stays first, and the other objects in it
|
||||
// stay above it.
|
||||
let (before, floor, art, parent, source, in_trace) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let in_trace = parent.and_then(|p| d.node(p)).is_some_and(crate::cmd::is_trace_group);
|
||||
let clips = parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips);
|
||||
let floor = usize::from(clips || in_trace);
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
(at.map(|(_, i, _)| i), floor, art, parent, crate::cmd::is_trace_source(d, item.id), in_trace)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
if source {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
if unchanged {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Where the Arrange command puts the item among its parent's art, worked out as
|
||||
// `object.arrange` works it out for one object. An image put first, or another object moved
|
||||
// from above an image that becomes first, in an ordinary group named as a tracing would make
|
||||
// that group one.
|
||||
let to = match id {
|
||||
"object.arrange.bringToFront" => art - 1,
|
||||
"object.arrange.bringForward" => i + 1,
|
||||
"object.arrange.sendBackward" => i - 1,
|
||||
_ => floor,
|
||||
};
|
||||
if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
match parent {
|
||||
Some(p) if in_trace && id == "object.arrange.sendToBack" => {
|
||||
edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?;
|
||||
}
|
||||
_ => {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn layer_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
|
||||
}
|
||||
|
||||
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
layer_name(h, a)?;
|
||||
Ok(text("Layer"))
|
||||
}
|
||||
|
||||
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
|
||||
fn named_text(class: &str, name: Answer) -> Answer {
|
||||
match name? {
|
||||
@@ -2911,10 +3187,6 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Document", doc_name(h, a))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
/// `toString()` of an object without a name: `[Class]`.
|
||||
fn class_text(name: &'static str) -> HostMember {
|
||||
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
|
||||
@@ -2957,6 +3229,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
|
||||
("DocumentColorSpace", &["CMYK", "RGB"]),
|
||||
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
|
||||
("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]),
|
||||
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
|
||||
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
|
||||
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
|
||||
@@ -2982,8 +3255,10 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
@@ -3020,6 +3295,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(preferences::app_members());
|
||||
application.extend(matrix::app_members(l));
|
||||
application.extend(clipboard::app_members(l));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(print::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
@@ -3039,6 +3317,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
};
|
||||
let mut classes = vec![
|
||||
class("Application", None, application, None),
|
||||
preferences::class(l),
|
||||
preset,
|
||||
class(
|
||||
"Documents",
|
||||
@@ -3100,10 +3379,12 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
document.extend(images::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
@@ -3138,7 +3419,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
named(vec![
|
||||
("typename", get(l, items_typename), typed("string")),
|
||||
("length", get(l, items_length), typed("number")),
|
||||
("parent", get(l, items_parent), typed("Document")),
|
||||
("parent", get(l, items_parent), typed("*")),
|
||||
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
@@ -3178,32 +3459,82 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, item_remove), returns("undefined", &[])),
|
||||
("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, item_to_string), returns("string", &[])),
|
||||
]);
|
||||
page_item.extend(
|
||||
[
|
||||
"artworkKnockout",
|
||||
"isIsolated",
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
"sliced",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"wrapInside",
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
"bringInPerspective",
|
||||
"resize",
|
||||
"rotate",
|
||||
"transform",
|
||||
(
|
||||
"translate",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
method(l, transform::translate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("deltaX", "number"),
|
||||
("deltaY", "number"),
|
||||
("transformObjects", "boolean"),
|
||||
("transformFillPatterns", "boolean"),
|
||||
("transformFillGradients", "boolean"),
|
||||
("transformStrokePatterns", "boolean"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"rotate",
|
||||
method(l, transform::rotate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("angle", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("rotateAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"resize",
|
||||
method(l, transform::resize),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("scaleX", "number"),
|
||||
("scaleY", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("scaleAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"transform",
|
||||
method(l, transform::transform),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("transformationMatrix", "Matrix"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("transformAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
]);
|
||||
page_item.extend(layers::page_item_members(l));
|
||||
page_item.extend(
|
||||
["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = layers::members(c, l);
|
||||
members.extend(variables::item_members(l, c));
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
@@ -3213,18 +3544,12 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(layers::classes(l));
|
||||
classes.extend(images::classes(l));
|
||||
tracing::add_trace(&mut classes, l);
|
||||
classes.extend(tracing::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, layer_typename), typed("string")),
|
||||
("name", get(l, layer_name), typed("string")),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
classes
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `app.copy()`, `app.cut()` and `app.paste()`, as the help page
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> describes them: Edit › Copy, Cut
|
||||
//! and Paste on the active document, run as `edit.copy`, `edit.cut` and `edit.paste` in the run's
|
||||
//! transaction.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state: with nothing selected, or no
|
||||
//! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and
|
||||
//! `paste` with no document open throws `No active document`. `paste` takes the session's
|
||||
//! clipboard, not art another app copied since. A run that finishes after a Copy or Cut, by any
|
||||
//! command, with the clipboard still holding what it copied, reports `copied`, and the desktop app
|
||||
//! then offers the clipboard to other apps.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
|
||||
use super::{Answer, Described, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named, returns};
|
||||
|
||||
/// The clipboard functions of `Application`.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("copy", method(link, copy), returns("undefined", &[])),
|
||||
("cut", method(link, cut), returns("undefined", &[])),
|
||||
("paste", method(link, paste), returns("undefined", &[])),
|
||||
])
|
||||
}
|
||||
|
||||
/// Runs `id` when the active document has something it acts on.
|
||||
fn on_selection(h: &Host, id: &str) -> Answer {
|
||||
let ready = crate::cmd::has_selection_guides_or_artboard_tool(&h.session.borrow()).is_ok();
|
||||
if ready {
|
||||
command(h, id, &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn copy(h: &Host, _: &[Data]) -> Answer {
|
||||
on_selection(h, "edit.copy")
|
||||
}
|
||||
|
||||
fn cut(h: &Host, _: &[Data]) -> Answer {
|
||||
on_selection(h, "edit.cut")
|
||||
}
|
||||
|
||||
fn paste(h: &Host, _: &[Data]) -> Answer {
|
||||
let ready = {
|
||||
let s = h.session.borrow();
|
||||
if s.active().is_none() {
|
||||
return Err(HostError::Error(NO_ACTIVE_DOCUMENT.into()));
|
||||
}
|
||||
!s.clipboard.is_empty()
|
||||
};
|
||||
if ready {
|
||||
command(h, "edit.paste", &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[
|
||||
("PatternColor", &[]),
|
||||
];
|
||||
|
||||
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
let mut items = vec![("typename".to_string(), text(class))];
|
||||
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
|
||||
Data::Object(items)
|
||||
|
||||
Loaded 100 of 423 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user