mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Merge craft-libs main into the input and focus fixes
This commit is contained in:
commit
a770df044d
1009 files changed
+103596
-7250
No files matched your search
@@ -70,6 +70,7 @@ workflows:
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'dtolnay/rust-toolchain@stable'
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/pbr.yml': []
|
||||
'.github/workflows/pcraft-format.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
name: PBR feature tests
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main, next]
|
||||
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
|
||||
pull_request:
|
||||
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
features:
|
||||
name: PBR ${{ matrix.mode }} tests
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { mode: serial, arguments: '' }
|
||||
- { mode: parallel, arguments: '--features parallel' }
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["ubuntu-latest"]'
|
||||
craft-fonts-ref: ''
|
||||
require-craft-fonts: false
|
||||
timeout-minutes: 30
|
||||
command: cargo test -p craft-pbr --locked ${{ matrix.arguments }}
|
||||
@@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 |
|
||||
| Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT |
|
||||
| Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 |
|
||||
| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) |
|
||||
| `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
| `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
|
||||
| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
@@ -39,6 +40,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/font-subset/tests/data/{abeezee,abel,bbhbartle,librefranklin,orbitron,sarabun}/` (unmodified; each with its `OFL.txt`) | The ABeeZee, Abel, BBH, Libre Franklin, Orbitron and Sarabun Project Authors | [google/fonts@e7db6ca `ofl/`](https://github.com/google/fonts/tree/e7db6ca/ofl) | OFL-1.1 |
|
||||
| `crates/font-subset/tests/data/ubuntu/Ubuntu-Regular.ttf` (unmodified; with `LICENCE.txt`) | Canonical Ltd. (Dalton Maag) | [google/fonts@e7db6ca `ufl/ubuntu`](https://github.com/google/fonts/tree/e7db6ca/ufl/ubuntu) | Ubuntu-font-1.0 |
|
||||
| `crates/font-subset/tests/data/notosanscjk/NotoSansCJKsc-test.otf` (subset to the test strings; with `OFL.txt`) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via storytold/font-preview-service | OFL-1.1 |
|
||||
| `crates/ui-contract/fonts/inter/Inter-Regular.ttf`, `crates/ui-contract/fonts/inter/Inter-SemiBold.ttf` (subset to 1,298 Latin, Greek, and Cyrillic codepoints with `fontTools` 4.62.1: `hinting=True`, `notdef_outline=True`, `layout_features=["*"]`, `name_IDs=["*"]`, `glyph_names=False`) | The Inter Project Authors | `storytold/craft-fonts` (`fonts/inter/Inter-Regular.ttf` sha256 `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`, `fonts/inter/Inter-SemiBold.ttf` sha256 `78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3`, Inter 4.001 `git-9221beed3`) | OFL-1.1 (`crates/ui-contract/fonts/inter/OFL.txt`) |
|
||||
|
||||
Original assets are covered by the repository licence.
|
||||
|
||||
@@ -174,6 +176,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
|
||||
|
||||
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
|
||||
|
||||
## GPU device selection
|
||||
|
||||
`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both.
|
||||
|
||||
## Dalvik DEX inspection
|
||||
|
||||
`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained.
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
All crates share the workspace version. See [the versioning policy](docs/versioning.md).
|
||||
|
||||
## Unreleased
|
||||
|
||||
### StencilCraft document model
|
||||
|
||||
- Geometry is stored once in `Document.shapes`. Organizational layers reference shape IDs
|
||||
through `Layer.members`, and the independent, ordered `Document.operations` hold production
|
||||
passes with their own `OperationSettings` and shape memberships. Guide operations are non-output.
|
||||
- The native header now uses format version 2. This pre-release format supersedes the earlier
|
||||
schema: readers reject version 1 and other unsupported versions. Builds predating this change
|
||||
cannot open version 2 files.
|
||||
|
||||
## v0.1.0 — 2026-10-12
|
||||
|
||||
First coordinated Git release of craft-libs. Applications can pin a named baseline instead of
|
||||
|
||||
Generated
+111
-17
@@ -1819,9 +1819,11 @@ dependencies = [
|
||||
"craft-geom",
|
||||
"craft-gif",
|
||||
"craft-gpu",
|
||||
"craft-gpu-device",
|
||||
"craft-gpu-null",
|
||||
"craft-gpu-providers",
|
||||
"craft-gpu-wgpu",
|
||||
"craft-gpu-yuv",
|
||||
"craft-gridcraft-format",
|
||||
"craft-gzip",
|
||||
"craft-har",
|
||||
@@ -1863,6 +1865,7 @@ dependencies = [
|
||||
"craft-media-source",
|
||||
"craft-menu",
|
||||
"craft-mesh",
|
||||
"craft-mesh-ops",
|
||||
"craft-metadata",
|
||||
"craft-metafile",
|
||||
"craft-midi",
|
||||
@@ -1905,6 +1908,7 @@ dependencies = [
|
||||
"craft-review",
|
||||
"craft-rtf",
|
||||
"craft-sbs",
|
||||
"craft-scopes",
|
||||
"craft-score",
|
||||
"craft-scraft-format",
|
||||
"craft-settings",
|
||||
@@ -2284,7 +2288,6 @@ dependencies = [
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -2297,6 +2300,7 @@ dependencies = [
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
@@ -2502,6 +2506,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-cfb",
|
||||
"craft-drawingml",
|
||||
"craft-flow",
|
||||
"craft-math",
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
@@ -2920,6 +2925,18 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-null"
|
||||
version = "0.1.0"
|
||||
@@ -2945,6 +2962,17 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-yuv"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-null",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
"yuv",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
@@ -3418,6 +3446,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mesh-ops"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.30.10",
|
||||
"mikktspace",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
@@ -3580,6 +3619,8 @@ version = "0.1.0"
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-materialx",
|
||||
"craft-mesh",
|
||||
"craft-pbr",
|
||||
"craft-texture",
|
||||
"glam 0.30.10",
|
||||
@@ -4041,6 +4082,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-scopes"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-color",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-score"
|
||||
version = "0.1.0"
|
||||
@@ -4294,7 +4344,14 @@ dependencies = [
|
||||
name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"png 0.18.1",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4328,8 +4385,12 @@ name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-exr",
|
||||
"craft-hdr",
|
||||
"craft-image-codecs",
|
||||
"dds",
|
||||
"half",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -4674,11 +4735,13 @@ dependencies = [
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
"ed25519-dalek 2.2.0",
|
||||
"egui",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -4691,6 +4754,7 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
@@ -4928,9 +4992,14 @@ name = "craft-xtask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"flate2",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml_edit",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5656,7 +5725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5712,7 +5781,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5747,7 +5816,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5766,7 +5835,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5785,7 +5854,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5805,7 +5874,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5818,7 +5887,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5895,7 +5964,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5968,7 +6037,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5994,7 +6063,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -6804,6 +6873,12 @@ dependencies = [
|
||||
"xml-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.25.0"
|
||||
@@ -6815,6 +6890,9 @@ name = "glam"
|
||||
version = "0.30.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
@@ -8343,8 +8421,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
@@ -8660,6 +8736,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
|
||||
|
||||
[[package]]
|
||||
name = "mikktspace"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0"
|
||||
dependencies = [
|
||||
"glam 0.15.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
@@ -15033,6 +15118,15 @@ dependencies = [
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yuv"
|
||||
version = "0.8.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus"
|
||||
version = "5.19.0"
|
||||
@@ -15317,19 +15411,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
+20
-15
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
|
||||
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -37,7 +37,9 @@ acadrust = "=0.6.6"
|
||||
log = "0.4"
|
||||
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
|
||||
craft-plist = { path = "crates/plist" }
|
||||
craft-gpu-device = { path = "crates/gpu-device" }
|
||||
craft-wasm = { path = "crates/wasm" }
|
||||
craft-gpu-yuv = { path = "crates/gpu-yuv" }
|
||||
craft-platform = { path = "crates/platform" }
|
||||
craft-png = { path = "crates/png" }
|
||||
craft-aep = { path = "crates/aep" }
|
||||
@@ -82,6 +84,7 @@ craft-cloud = { path = "crates/cloud" }
|
||||
craft-cloud-local = { path = "crates/cloud-local" }
|
||||
craft-cloud-ui = { path = "crates/cloud-ui" }
|
||||
craft-color = { path = "crates/color" }
|
||||
craft-scopes = { path = "crates/scopes" }
|
||||
craft-color-ui = { path = "crates/color-ui" }
|
||||
craft-color-transform = { path = "crates/color-transform" }
|
||||
craft-frame = { path = "crates/frame" }
|
||||
@@ -133,6 +136,7 @@ craft-gcode = { path = "crates/gcode" }
|
||||
craft-gif = { path = "crates/gif" }
|
||||
craft-hdr = { path = "crates/hdr" }
|
||||
craft-mesh = { path = "crates/mesh" }
|
||||
craft-mesh-ops = { path = "crates/mesh-ops" }
|
||||
craft-html = { path = "crates/html" }
|
||||
craft-ipp = { path = "crates/ipp" }
|
||||
craft-heif = { path = "crates/heif" }
|
||||
@@ -321,20 +325,21 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
kurbo = { path = "vendor/kurbo" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
|
||||
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
|
||||
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
|
||||
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
|
||||
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
|
||||
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
|
||||
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
|
||||
@@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from:
|
||||
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
|
||||
(CC0-1.0); see ATTRIBUTION.md.
|
||||
|
||||
The mesh operations in crates/mesh-ops are moved from:
|
||||
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
|
||||
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
|
||||
https://github.com/storytold/texturecraft
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
|
||||
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
|
||||
3133062968b8a1566eda12a357cb06062db16687.
|
||||
https://github.com/storytold/materialcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
|
||||
All licensed MIT OR Apache-2.0.
|
||||
|
||||
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
|
||||
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
|
||||
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
|
||||
@@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy.
|
||||
linesweeper
|
||||
|
||||
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
|
||||
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
|
||||
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
|
||||
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman
|
||||
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
|
||||
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
|
||||
patches and the files left out.
|
||||
changes and the files left out.
|
||||
|
||||
kurbo
|
||||
|
||||
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
|
||||
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
|
||||
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
|
||||
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
|
||||
vendor/kurbo/SOURCE.json for provenance and the local patches.
|
||||
|
||||
Platform lifecycle source provenance
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
|
||||
- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target).
|
||||
- [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite.
|
||||
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft.
|
||||
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft.
|
||||
- [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral
|
||||
model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and
|
||||
TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from
|
||||
@@ -211,6 +211,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
every frame's position, delay, disposal and transparent colour, the loop count and the first
|
||||
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
|
||||
a file can hold the picture it declares before a decoder runs.
|
||||
- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to
|
||||
NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full
|
||||
range, through the `craft-gpu` job registry on the null context or on a device. Each output texel
|
||||
averages the part of the source it covers. The crate also has the render passes for a caller's
|
||||
own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the
|
||||
CPU. Encoders and scopes stay in each app.
|
||||
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
|
||||
low power, a named adapter that survives a reordered list and a driver update, or software;
|
||||
corrections for drivers that crash; the next adapter and then a software one when a device fails
|
||||
to open; a capability report; device-loss and error recording without panics; and what to reopen
|
||||
after a loss. Settings pages and the window stay in each app.
|
||||
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
|
||||
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
|
||||
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
|
||||
@@ -318,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
|
||||
glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file
|
||||
themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft.
|
||||
- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
|
||||
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
|
||||
BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft.
|
||||
- [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and
|
||||
2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per
|
||||
quarter note. From SoundCraft.
|
||||
@@ -412,11 +426,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
reference picking, selection statistics, error tags and filter buttons (`ui` feature).
|
||||
- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module
|
||||
reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals
|
||||
out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test
|
||||
whose body runs past a limit, or whose condition does not hold in time; a variable the caller names
|
||||
replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged
|
||||
copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng`
|
||||
module holds two seeded generators for repeatable test input. Not published.
|
||||
out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts
|
||||
from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its
|
||||
`deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time;
|
||||
a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation
|
||||
and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did
|
||||
not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module
|
||||
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
@@ -424,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
|
||||
(regex) are features.
|
||||
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
|
||||
bounded by `Limits`. From MaterialCraft.
|
||||
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
|
||||
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
|
||||
samples. Sizes are bounded by `Limits`. From MaterialCraft.
|
||||
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
|
||||
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
|
||||
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
|
||||
|
||||
@@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran
|
||||
/// to give each character run its paragraph's format.
|
||||
pub fn count_paragraph_lookups<T>(f: impl FnOnce() -> T) -> (T, usize) {
|
||||
crate::text::MATCH_READS.with(|reads| reads.set(0));
|
||||
let value = f();
|
||||
(value, crate::text::MATCH_READS.with(std::cell::Cell::get))
|
||||
}
|
||||
@@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Sorted by end (they are in order in every file), so both lookups below are binary
|
||||
// searches: a block can have as many paragraphs and runs as characters.
|
||||
paragraphs.sort_by_key(|(end, _)| *end);
|
||||
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
|
||||
let align_at = |i: usize| {
|
||||
let at = paragraphs.partition_point(|(end, _)| {
|
||||
count_match_read();
|
||||
*end <= i
|
||||
});
|
||||
paragraphs.get(at).map(|(_, a)| *a).or(open).unwrap_or_default()
|
||||
};
|
||||
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
|
||||
cuts.dedup();
|
||||
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
|
||||
// Split at paragraph ends so every run has one paragraph format.
|
||||
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
|
||||
let first = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c <= from
|
||||
});
|
||||
let past = cuts.partition_point(|c| {
|
||||
count_match_read();
|
||||
*c < to
|
||||
});
|
||||
let inside = cuts.get(first..past).unwrap_or_default();
|
||||
let mut a = from;
|
||||
for &c in inside.iter().chain(std::iter::once(&to)) {
|
||||
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
|
||||
@@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
(runs, first_align.unwrap_or(Align::Left))
|
||||
}
|
||||
|
||||
// Each paragraph end `story_runs` reads to match character runs to paragraphs, on this thread.
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
std::thread_local! {
|
||||
pub(crate) static MATCH_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_match_read() {
|
||||
#[cfg(any(test, feature = "synth"))]
|
||||
MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
fn characters(chars: &[char], start: usize, end: usize) -> String {
|
||||
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
|
||||
}
|
||||
|
||||
@@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() {
|
||||
|
||||
#[test]
|
||||
fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
|
||||
// 200 000 paragraphs, each with its own run and format.
|
||||
let n = 200_000;
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt =
|
||||
|end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
// (About half a second; quadratic matching took over half a minute on the same machine.)
|
||||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||||
// `n` paragraphs, each with its own run and format, and how many paragraph ends matching
|
||||
// them looks up.
|
||||
let lookups = |n: usize| {
|
||||
let text = "a\u{2029}".repeat(n);
|
||||
let fmt = |end: usize| {
|
||||
vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]
|
||||
};
|
||||
let blk = F::Obj(
|
||||
tag(b"StBl"),
|
||||
vec![
|
||||
(tag(b"Glyp"), utf8(&text)),
|
||||
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
|
||||
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
|
||||
],
|
||||
);
|
||||
let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]));
|
||||
let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story]));
|
||||
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
|
||||
assert_eq!(t.runs.len(), n);
|
||||
lookups
|
||||
};
|
||||
// Four times the paragraphs and runs: a few binary searches each, so about four times the
|
||||
// lookups (a little more for the longer searches), where matching each run against every
|
||||
// paragraph is sixteen times.
|
||||
let (quarter, full) = (lookups(50_000), lookups(200_000));
|
||||
assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000");
|
||||
}
|
||||
|
||||
/// A shape node of `size` px.
|
||||
|
||||
@@ -12,8 +12,19 @@ and contains no `unsafe` code.
|
||||
(compressor, expander and gate, limiter, maximizer, multiband and tube-modeled compressors),
|
||||
delays and reverbs (including convolution and surround), modulation, restoration (denoise,
|
||||
dehum, click remover, de-esser, de-reverb, speech enhancement), channel tools, distortion,
|
||||
dither, a signal generator, a loudness meter, and a pitch shifter for a live voice with 10 ms
|
||||
of latency.
|
||||
dither, a signal generator, a loudness meter, a pitch shifter for a live voice with 10 ms of
|
||||
latency, a formant shifter for a live voice with 10.7 ms of latency, and noise suppression for
|
||||
a live voice with 5.3 ms of latency that follows the noise floor without first learning it.
|
||||
These latencies are at 48 kHz (the STFT sizes depend on the sample rate; `latency()` reports
|
||||
them in samples). The pitch shifter's Keep Formants switch adds the formant shifter's latency,
|
||||
and `latency()` reports it while the switch is on. A ring modulator for robotic and metallic
|
||||
voices (ring, frequency modulation, and positive or negative comb resonators, with the
|
||||
frequency moved by an LFO, the input's level or a sample-and-hold source) adds no latency, and
|
||||
neither does a bitcrusher that takes one sample in every 1 to 50 and rounds it to 1 to 16 bits,
|
||||
or a tremolo that lowers the gain once per cycle of a sine, triangle or square LFO. A vibrato
|
||||
that swings the pitch by up to 100 cents through a delay moved by a sine or triangle LFO adds
|
||||
no latency either: the delay is 0 at the start of each cycle, except while it glides to new
|
||||
settings.
|
||||
- `loudness`: an ITU-R BS.1770-4 / EBU R128 meter with momentary, short-term and integrated
|
||||
loudness, loudness range (EBU Tech 3342), sample peak and true peak.
|
||||
- `pan`: stereo pan laws, a surround panner over any layout of up to 16 speakers, and first-order
|
||||
@@ -28,6 +39,14 @@ and contains no `unsafe` code.
|
||||
- `biquad` and `design`: biquad filters with their magnitude response, and IIR filter design from
|
||||
Butterworth, Bessel, Chebyshev and elliptic prototypes.
|
||||
|
||||
`noise_suppression` estimates the noise floor from minimum spectral power over 1.5 s. The first
|
||||
noise estimate after a reset starts from the median bin's power. Each bin's value is clamped
|
||||
between 30 dB below its own estimate and its own estimate. Windows that overlap a run of at
|
||||
least one hop of zeros (64 samples at 48 kHz) do not enter the noise estimate. The gain floor
|
||||
moves from 0 dB toward the attenuation set by `reduction` during the first search window
|
||||
of sound. Continuous voiced or tonal audio present from startup can enter the noise estimate
|
||||
and be attenuated afterward.
|
||||
|
||||
## Conventions
|
||||
|
||||
Audio is planar `f32`: one slice per channel, all the same length. `AudioEffect::process`,
|
||||
@@ -79,7 +98,8 @@ The crate combines two crates from the ArtCraft apps, with changes:
|
||||
offline resampler.
|
||||
- [storytold/soundcraft](https://github.com/storytold/soundcraft) `crates/dsp` at
|
||||
`915481be1b49d7e0502e07b059d0c0198c61911a`: the two crossfaded read taps of the voice pitch
|
||||
shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`).
|
||||
shifter (`src/plugins/pitch.rs`) and its YIN pitch tracker (`src/pitch_detect.rs`), and the
|
||||
ring modulator (`src/plugins/modulation.rs`).
|
||||
|
||||
`NOTICE` keeps the copyright notices of both projects.
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Audio effects and their registry.
|
||||
|
||||
pub(crate) mod channel;
|
||||
pub(crate) mod character;
|
||||
pub(crate) mod declick;
|
||||
pub(crate) mod dither;
|
||||
pub(crate) mod dynamics;
|
||||
@@ -15,11 +16,13 @@ pub(crate) mod restoration;
|
||||
pub(crate) mod reverbs;
|
||||
pub(crate) mod special;
|
||||
mod stft;
|
||||
pub(crate) mod suppress;
|
||||
pub(crate) mod time;
|
||||
pub(crate) mod util;
|
||||
pub(crate) mod voice;
|
||||
|
||||
pub(crate) use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
|
||||
pub use character::{Bitcrusher, RingMod, Tremolo, Vibrato};
|
||||
pub(crate) use declick::ClickRemover;
|
||||
pub use dither::Dither;
|
||||
pub use dynamics::{Compressor, Gate, Limiter, Maximizer};
|
||||
@@ -35,8 +38,9 @@ pub(crate) use restoration::{DeHum, DeNoise};
|
||||
pub(crate) use reverbs::{ConvolutionReverb, SurroundReverb};
|
||||
pub use special::LoudnessMeterFx;
|
||||
pub(crate) use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, Mastering, Mute, StereoExpander, VocalEnhancer};
|
||||
pub use suppress::NoiseSuppression;
|
||||
pub(crate) use time::{Delay, Reverb};
|
||||
pub use voice::VoicePitch;
|
||||
pub use voice::{VoiceFormant, VoicePitch};
|
||||
|
||||
use crate::{AudioEffect, ParamSpec, sane_channels, sane_sample_rate};
|
||||
|
||||
@@ -125,8 +129,10 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
},
|
||||
entry!("dehum", "DeHum", Restoration, DeHum),
|
||||
entry!("denoise", "DeNoise", Restoration, DeNoise),
|
||||
entry!("noise_suppression", "Noise Suppression", Restoration, NoiseSuppression),
|
||||
entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter),
|
||||
entry!("voice_pitch", "Voice Pitch", Pitch, VoicePitch),
|
||||
entry!("voice_formant", "Voice Formant", Pitch, VoiceFormant),
|
||||
entry!("deesser", "DeEsser", Restoration, DeEsser),
|
||||
entry!("dereverb", "DeReverb", Restoration, DeReverb),
|
||||
entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance),
|
||||
@@ -144,6 +150,9 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger),
|
||||
entry!("flanger", "Flanger", Modulation, Flanger),
|
||||
entry!("phaser", "Phaser", Modulation, Phaser),
|
||||
entry!("ring_mod", "Ring Modulator", Modulation, RingMod),
|
||||
entry!("tremolo", "Tremolo", Modulation, Tremolo),
|
||||
entry!("vibrato", "Vibrato", Modulation, Vibrato),
|
||||
entry!("analog_delay", "Analog Delay", Time, AnalogDelay),
|
||||
entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay),
|
||||
entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb),
|
||||
@@ -151,6 +160,7 @@ static REGISTRY: &[EffectInfo] = &[
|
||||
entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover),
|
||||
entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer),
|
||||
entry!("distortion", "Distortion", Special, Distortion),
|
||||
entry!("bitcrusher", "Bitcrusher", Special, Bitcrusher),
|
||||
entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite),
|
||||
entry!("mastering", "Mastering", Special, Mastering),
|
||||
entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer),
|
||||
|
||||
@@ -132,9 +132,11 @@ fn every_effect_is_deterministic_and_latency_is_constant() {
|
||||
f
|
||||
};
|
||||
let lat0 = (e.create)(SR, 2).latency();
|
||||
// Keep Formants adds voice_pitch's formant stage; no other parameter changes a latency.
|
||||
let want = if e.id == "voice_pitch" { lat0 + voice::VoiceFormant::new(SR, 2).latency() } else { lat0 };
|
||||
let mut a = mk();
|
||||
let mut b = mk();
|
||||
assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id);
|
||||
assert_eq!(a.latency(), want, "{}: latency depends on parameters", e.id);
|
||||
let ya = run(a.as_mut(), &l, &r);
|
||||
let yb = run(b.as_mut(), &l, &r);
|
||||
assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id);
|
||||
@@ -147,7 +149,14 @@ fn latency_is_where_the_impulse_lands() {
|
||||
// settings (FFT filter / convolution / existing STFT effects). The click remover repairs a
|
||||
// lone impulse in silence as a click, so its latency is checked on noise by
|
||||
// `neutral_settings_are_delayed_identity`.
|
||||
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("voice_pitch", vec![])] {
|
||||
for (id, p) in [
|
||||
("fft_filter", vec![]),
|
||||
("convolution_reverb", vec![("mix", 0.0)]),
|
||||
("voice_pitch", vec![]),
|
||||
("voice_pitch", vec![("formant_follow", 1.0)]),
|
||||
("voice_formant", vec![]),
|
||||
("noise_suppression", vec![("reduction", 0.0)]),
|
||||
] {
|
||||
let mut e = fx(id, &p);
|
||||
let lat = e.latency();
|
||||
assert!(lat > 0, "{id}");
|
||||
@@ -906,6 +915,8 @@ fn delays_and_reverbs_report_their_tails() {
|
||||
("chorus_flanger", &[("mode", 1.0), ("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]),
|
||||
("chorus_flanger", &[("width", 100.0), ("intensity", 100.0), ("mix", 100.0)][..]),
|
||||
("flanger", &[("final_delay", 20.0), ("feedback", 100.0), ("mix", 100.0)][..]),
|
||||
("ring_mod", &[("effect", 2.0), ("frequency", 100.0), ("resonance", 90.0)][..]),
|
||||
("ring_mod", &[("effect", 3.0), ("frequency", 60.0), ("resonance", 95.0), ("mod_source", 1.0), ("mod_depth", 100.0)][..]),
|
||||
] {
|
||||
let mut e = fx(id, params);
|
||||
let tail = e.tail_samples();
|
||||
@@ -977,6 +988,12 @@ fn direct_constructors_cap_the_channel_count() {
|
||||
filters::FullParametricEq,
|
||||
pitch::PitchShifter,
|
||||
voice::VoicePitch,
|
||||
voice::VoiceFormant,
|
||||
suppress::NoiseSuppression,
|
||||
character::RingMod,
|
||||
character::Bitcrusher,
|
||||
character::Tremolo,
|
||||
character::Vibrato,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -402,7 +402,7 @@ mod tests {
|
||||
#[test]
|
||||
fn paired_effects_match_mono_on_transients() {
|
||||
use crate::AudioEffect;
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter};
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter};
|
||||
const SR: f32 = 48_000.0;
|
||||
let len = 48_000;
|
||||
let material = |f: f64, amp: f32, phase: f64, click_every: usize, click_at: usize, noise: f32, seed: u64| -> Vec<f32> {
|
||||
@@ -427,6 +427,7 @@ mod tests {
|
||||
"DeReverb" => Box::new(DeReverb::new(SR, ch)),
|
||||
"FftFilter" => Box::new(FftFilter::new(SR, ch)),
|
||||
"DeNoise" => Box::new(DeNoise::new(SR, ch)),
|
||||
"NoiseSuppression" => Box::new(NoiseSuppression::new(SR, ch)),
|
||||
_ => Box::new(PitchShifter::new(SR, ch)),
|
||||
};
|
||||
if name == "PitchShifter" {
|
||||
@@ -445,7 +446,7 @@ mod tests {
|
||||
y
|
||||
};
|
||||
let mut failures = Vec::new();
|
||||
for name in ["PitchShifter", "DeNoise", "DeReverb", "FftFilter"] {
|
||||
for name in ["PitchShifter", "DeNoise", "NoiseSuppression", "DeReverb", "FftFilter"] {
|
||||
for (label, src) in [("identical", &identical), ("different", &different)] {
|
||||
let joint = run(name, src);
|
||||
for (ch, chan) in src.iter().enumerate() {
|
||||
@@ -502,17 +503,18 @@ mod tests {
|
||||
#[test]
|
||||
fn non_finite_sample_stays_in_its_channel() {
|
||||
use crate::AudioEffect;
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, PitchShifter};
|
||||
use crate::effects::{DeNoise, DeReverb, FftFilter, NoiseSuppression, PitchShifter};
|
||||
const SR: f32 = 48_000.0;
|
||||
let len = 24_000;
|
||||
let mut rng = Rng::new(5);
|
||||
let clean_a: Vec<f32> = crate::testutil::sine(440.0, 0.4, SR as f64, len, 0.0).iter().map(|v| v + 0.05 * rng.uniform()).collect();
|
||||
let clean_b: Vec<f32> = crate::testutil::sine(1250.0, 0.4, SR as f64, len, 0.3).iter().map(|v| v + 0.05 * rng.uniform()).collect();
|
||||
type Make = fn() -> Box<dyn AudioEffect>;
|
||||
let make: [(&str, Make, usize); 4] = [
|
||||
let make: [(&str, Make, usize); 5] = [
|
||||
("DeReverb", || Box::new(DeReverb::new(SR, 2)), 1),
|
||||
("FftFilter", || Box::new(FftFilter::new(SR, 2)), 1),
|
||||
("DeNoise", || Box::new(DeNoise::new(SR, 2)), 1),
|
||||
("NoiseSuppression", || Box::new(NoiseSuppression::new(SR, 2)), 1),
|
||||
("PitchShifter", || Box::new(PitchShifter::new(SR, 2)), 1),
|
||||
];
|
||||
let mono = |name: &str, src: &[f32]| -> Vec<f32> {
|
||||
@@ -520,6 +522,7 @@ mod tests {
|
||||
"DeReverb" => Box::new(DeReverb::new(SR, 1)),
|
||||
"FftFilter" => Box::new(FftFilter::new(SR, 1)),
|
||||
"DeNoise" => Box::new(DeNoise::new(SR, 1)),
|
||||
"NoiseSuppression" => Box::new(NoiseSuppression::new(SR, 1)),
|
||||
_ => Box::new(PitchShifter::new(SR, 1)),
|
||||
};
|
||||
if name == "PitchShifter" {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -81,7 +81,14 @@ impl DelayLine {
|
||||
let i0 = self.w + len - 1 - di as usize;
|
||||
let i0 = if i0 >= len { i0 - len } else { i0 };
|
||||
let i1 = if i0 == 0 { len - 1 } else { i0 - 1 };
|
||||
self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac
|
||||
let (a, b) = (self.buf[i0], self.buf[i1]);
|
||||
let y = a + (b - a) * frac;
|
||||
if y.is_finite() {
|
||||
y
|
||||
} else {
|
||||
// Two large samples of opposite sign overflow `b - a` in f32.
|
||||
(a as f64 + (b as f64 - a as f64) * frac as f64) as f32
|
||||
}
|
||||
}
|
||||
/// Integer read (`d` samples ago, 0 = newest).
|
||||
#[inline]
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Voice pitch shifter for live use: two read taps sweep through a short delay line and crossfade
|
||||
//! (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms.
|
||||
//! Effects for a live voice: a pitch shifter with 10 ms of latency and a formant shifter with
|
||||
//! 10.7 ms of latency (at 48 kHz).
|
||||
//!
|
||||
//! The pitch shifter (`voice_pitch`) has two read taps that sweep through a short delay line and
|
||||
//! crossfade (sin² and cos² gains), so the output moves by the pitch ratio with a latency of 10 ms.
|
||||
//!
|
||||
//! The taps sit half a sweep apart and are centered on the latency, so the delay of each one
|
||||
//! stays within `latency ± spacing`. A pitch tracker (YIN, on a copy of the input low-passed and
|
||||
@@ -11,8 +14,21 @@
|
||||
//! hertz (5 Hz for 85 Hz shifted up 5 semitones). At a shift
|
||||
//! of 0 the effect crossfades over 20 ms to the input delayed by the latency, so a neutral setting
|
||||
//! is a plain delay.
|
||||
//!
|
||||
//! The formant shifter (`voice_formant`) moves the spectral envelope of the voice up or down while
|
||||
//! its harmonics stay where they are. It runs a short STFT (512 points at up to 50 kHz, hop 128).
|
||||
//! For each frame it fits a linear predictor (one coefficient per kHz plus 2, at most 96) to the
|
||||
//! last two frame lengths of input (1,024 samples at 48 kHz), which end with the frame and add no
|
||||
//! latency, and takes the
|
||||
//! envelope from the predictor. It then multiplies every bin by the envelope read at
|
||||
//! `bin / ratio` over the envelope at the bin, with at most 24 dB of boost. Its latency is the
|
||||
//! STFT size. `voice_pitch` uses the same stage for Keep Formants: the stage moves the shifted
|
||||
//! voice's envelope back by the inverse of the pitch ratio, so the pitch changes and the formants
|
||||
//! stay, and the latency grows by the STFT size.
|
||||
|
||||
use super::stft::{Spectral, StftChannel, fft_size};
|
||||
use crate::biquad::{Biquad, Coeffs, FilterType};
|
||||
use crate::fft::Fft;
|
||||
use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, flush32, param_plumbing};
|
||||
use std::f64::consts::PI;
|
||||
|
||||
@@ -33,13 +49,31 @@ const MARGIN: f64 = 2.0;
|
||||
const MAX_STEP: f64 = 0.45;
|
||||
/// Analysis input is clipped to this level, so a huge sample cannot overflow the tracker.
|
||||
const TRACK_CLIP: f64 = 1.0e4;
|
||||
/// Fewest and most predictor coefficients of the formant envelope (one per kHz plus 2 between).
|
||||
const MIN_ORDER: usize = 8;
|
||||
const MAX_ORDER: usize = 96;
|
||||
/// Width of the Gaussian lag window, which widens each envelope peak to about this many hertz.
|
||||
const LAG_HZ: f64 = 40.0;
|
||||
/// White noise added to the autocorrelation (60 dB down), so a pure tone still gives a stable
|
||||
/// predictor.
|
||||
const WHITE: f64 = 1.0e-6;
|
||||
/// Largest boost the envelope warp gives one bin: ln 16, about 24 dB.
|
||||
const MAX_BOOST: f64 = 2.772_588_722_239_781;
|
||||
|
||||
/// STFT size of the formant stage: 512 at up to 50 kHz (10.7 ms at 48 kHz), 1024 up to 100 kHz,
|
||||
/// 2048 above.
|
||||
fn formant_size(sample_rate: f32) -> usize {
|
||||
fft_size(sample_rate) / 4
|
||||
}
|
||||
|
||||
/// Fundamental period of the recent input, from YIN (de Cheveigné and Kawahara, 2002) run on a
|
||||
/// low-passed, decimated copy. Every buffer is sized at creation.
|
||||
///
|
||||
/// It keeps two copies: the mean of the channels, and the first channel alone. A frame whose
|
||||
/// mean holds less than a quarter of the first channel's energy (channels of opposite polarity
|
||||
/// cancel in the mean) is analyzed on the first channel.
|
||||
/// It keeps two copies: the mean of the channels, and one channel alone. A frame whose mean holds
|
||||
/// less than a quarter of that channel's energy (channels of opposite polarity cancel in the
|
||||
/// mean) is analyzed on that channel. The channel is the first one until another channel holds
|
||||
/// over four times its energy through one hop; the tracker then moves to the loudest channel, and
|
||||
/// analyzes that channel's copy only once a whole frame of it has come in.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Tracker {
|
||||
/// Input samples per analysis sample.
|
||||
@@ -56,10 +90,16 @@ struct Tracker {
|
||||
max_tau: usize,
|
||||
/// Period in input samples, or `None` when the last frame was unvoiced.
|
||||
period: Option<f64>,
|
||||
/// Channel the second copy holds.
|
||||
channel: usize,
|
||||
/// Energy of each channel's clipped input since the last analysis.
|
||||
energy: Vec<f64>,
|
||||
/// Analysis samples of `channel` in the second copy, up to the frame length.
|
||||
filled: usize,
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
fn new(sample_rate: f32) -> Self {
|
||||
fn new(sample_rate: f32, channels: usize) -> Self {
|
||||
let factor = (sample_rate / TRACK_RATE).round().max(1.0) as usize;
|
||||
let rate = sample_rate / factor as f32;
|
||||
let max_hz = MAX_HZ.min(rate / 4.0);
|
||||
@@ -82,6 +122,10 @@ impl Tracker {
|
||||
min_tau,
|
||||
max_tau,
|
||||
period: None,
|
||||
channel: 0,
|
||||
energy: vec![0.0; channels.max(1)],
|
||||
// The zeros the copy starts with are the first channel's silence.
|
||||
filled: len,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,12 +135,23 @@ impl Tracker {
|
||||
self.at = 0;
|
||||
self.since = 0;
|
||||
self.period = None;
|
||||
self.channel = 0;
|
||||
self.energy.fill(0.0);
|
||||
self.filled = self.frame.len();
|
||||
}
|
||||
|
||||
/// Takes one input sample, as the mean of the channels and the first channel; runs an
|
||||
/// analysis every `hop` analysis samples.
|
||||
fn push(&mut self, mean: f32, first: f32) {
|
||||
let clipped = [mean, first].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP));
|
||||
/// Adds one input sample of channel `c` to that channel's energy.
|
||||
fn measure(&mut self, c: usize, x: f32) {
|
||||
if let Some(e) = self.energy.get_mut(c) {
|
||||
let x = (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP);
|
||||
*e += x * x;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes one input sample, as the mean of the channels and the sample of the channel in
|
||||
/// `self.channel`; runs an analysis every `hop` analysis samples.
|
||||
fn push(&mut self, mean: f32, single: f32) {
|
||||
let clipped = [mean, single].map(|x| (x as f64).clamp(-TRACK_CLIP, TRACK_CLIP));
|
||||
for (feed, x) in self.feeds.iter_mut().zip(clipped) {
|
||||
feed.filter(&self.coeffs, x);
|
||||
}
|
||||
@@ -110,16 +165,34 @@ impl Tracker {
|
||||
feed.ring[self.at] = feed.last as f32;
|
||||
}
|
||||
self.at = (self.at + 1) & mask;
|
||||
self.filled = (self.filled + 1).min(self.frame.len());
|
||||
self.since += 1;
|
||||
if self.since >= self.hop {
|
||||
self.since = 0;
|
||||
self.analyze();
|
||||
self.choose_channel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the second copy to the loudest channel when that channel held over four times the
|
||||
/// energy of the one in use since the last analysis. The first of equally loud channels wins.
|
||||
fn choose_channel(&mut self) {
|
||||
let loudest = (0..self.energy.len()).fold(0, |b, c| if self.energy[c] > self.energy[b] { c } else { b });
|
||||
if self.energy[self.channel] < 0.25 * self.energy[loudest] {
|
||||
self.channel = loudest;
|
||||
self.feeds[1].reset();
|
||||
self.filled = 0;
|
||||
}
|
||||
self.energy.fill(0.0);
|
||||
}
|
||||
|
||||
fn analyze(&mut self) {
|
||||
let [mean, first] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::<f32>());
|
||||
let feed = if mean < 0.25 * first { &self.feeds[1] } else { &self.feeds[0] };
|
||||
let [mean, single] = [0, 1].map(|f| self.feeds[f].ring.iter().map(|v| v * v).sum::<f32>());
|
||||
if mean < 0.25 * single && self.filled < self.frame.len() {
|
||||
// The channel's copy holds less than a frame since the move: keep the last period.
|
||||
return;
|
||||
}
|
||||
let feed = if mean < 0.25 * single { &self.feeds[1] } else { &self.feeds[0] };
|
||||
let mask = self.frame.len() - 1;
|
||||
for (i, v) in self.frame.iter_mut().enumerate() {
|
||||
*v = feed.ring[(self.at + i) & mask];
|
||||
@@ -229,10 +302,16 @@ struct Taps {
|
||||
delay_b: f64,
|
||||
}
|
||||
|
||||
/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents).
|
||||
/// Pitch shifter for a live voice, 10 ms of latency (±24 semitones and ±100 cents). Keep Formants
|
||||
/// (`formant_follow`) adds the formant stage's latency, 10.7 ms at 48 kHz, and `latency` reports
|
||||
/// it while the switch is on.
|
||||
pub struct VoicePitch {
|
||||
pv: ParamValues,
|
||||
latency: usize,
|
||||
/// Formant stage of Keep Formants, and the share of its output against the shifted voice.
|
||||
follow: Stage,
|
||||
follow_mix: f64,
|
||||
follow_on: bool,
|
||||
/// Widest tap spacing that keeps both taps inside the line, in samples.
|
||||
max_spacing: f64,
|
||||
lines: Vec<Vec<f32>>,
|
||||
@@ -252,6 +331,7 @@ impl VoicePitch {
|
||||
pub const PARAMS: &'static [ParamSpec] = &[
|
||||
ParamSpec::new("semitones", "Pitch", -24.0, 24.0, 0.0, Unit::Semitones),
|
||||
ParamSpec::new("cents", "Fine Tune (cents)", -100.0, 100.0, 0.0, Unit::None),
|
||||
ParamSpec::new("formant_follow", "Keep Formants", 0.0, 1.0, 0.0, Unit::Toggle),
|
||||
];
|
||||
|
||||
pub fn new(sample_rate: f32, channels: usize) -> Self {
|
||||
@@ -262,11 +342,14 @@ impl VoicePitch {
|
||||
let mut s = VoicePitch {
|
||||
pv: ParamValues::new(Self::PARAMS),
|
||||
latency,
|
||||
follow: Stage::new(sample_rate, ch),
|
||||
follow_mix: 0.0,
|
||||
follow_on: false,
|
||||
max_spacing: latency as f64 - MARGIN,
|
||||
lines: vec![vec![0.0; len]; ch],
|
||||
mask: len - 1,
|
||||
pos: 0,
|
||||
tracker: Tracker::new(sample_rate),
|
||||
tracker: Tracker::new(sample_rate, ch),
|
||||
ratio: 1.0,
|
||||
phase: 0.5,
|
||||
spacing: latency as f64 - MARGIN,
|
||||
@@ -280,11 +363,17 @@ impl VoicePitch {
|
||||
fn apply_params(&mut self, snap: bool) {
|
||||
let shift = self.pv.v("semitones") as f64 + self.pv.v("cents") as f64 / 100.0;
|
||||
self.ratio = 2f64.powf(shift / 12.0);
|
||||
self.follow_on = self.pv.v("formant_follow") >= 0.5;
|
||||
if snap {
|
||||
self.wet = self.target_wet();
|
||||
self.follow_mix = self.follow_target();
|
||||
}
|
||||
}
|
||||
|
||||
fn follow_target(&self) -> f64 {
|
||||
if self.follow_on { 1.0 } else { 0.0 }
|
||||
}
|
||||
|
||||
fn target_wet(&self) -> f64 {
|
||||
if self.ratio == 1.0 { 0.0 } else { 1.0 }
|
||||
}
|
||||
@@ -341,12 +430,13 @@ impl VoicePitch {
|
||||
impl AudioEffect for VoicePitch {
|
||||
param_plumbing!("voice_pitch");
|
||||
fn latency(&self) -> usize {
|
||||
self.latency
|
||||
self.latency + if self.follow_on { self.follow.n } else { 0 }
|
||||
}
|
||||
fn tail_samples(&self) -> usize {
|
||||
// A tap reads up to `latency + max_spacing` samples back and the cubic read two samples
|
||||
// more, which is twice the latency in all.
|
||||
self.latency
|
||||
// more, which is twice the latency in all. Keep Formants spreads a frame over up to the
|
||||
// formant stage's size more. A render drains `latency() + tail_samples()` samples.
|
||||
self.latency + if self.follow_on { self.follow.n } else { 0 }
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|v| *v = 0.0));
|
||||
@@ -355,23 +445,43 @@ impl AudioEffect for VoicePitch {
|
||||
self.phase = 0.5;
|
||||
self.spacing = self.max_spacing;
|
||||
self.wet = self.target_wet();
|
||||
self.follow.reset();
|
||||
self.follow_mix = self.follow_target();
|
||||
}
|
||||
fn process(&mut self, channels: &mut [&mut [f32]]) {
|
||||
let len = block_len(channels);
|
||||
let ch = channels.len().min(self.lines.len());
|
||||
let ch = self.lines.len();
|
||||
let dry_at = self.mask + 1 - self.latency;
|
||||
let follow_target = self.follow_target();
|
||||
// The formant stage moves the envelope by the inverse of the pitch ratio.
|
||||
let back = (1.0 / self.ratio) as f32;
|
||||
for i in 0..len {
|
||||
let mut sum = 0.0f32;
|
||||
for (line, io) in self.lines.iter_mut().zip(channels.iter()) {
|
||||
// A non-finite sample is stored as silence, so it never reaches the output.
|
||||
let x = flush32(io[i]);
|
||||
for (c, line) in self.lines.iter_mut().enumerate() {
|
||||
// A non-finite sample is stored as silence, so it never reaches the output. A
|
||||
// channel the block leaves out is stored as silence too while its line advances,
|
||||
// so after a gap of at least `latency() + tail_samples()` samples it holds none of
|
||||
// its earlier audio; after a shorter gap, audio still in the line can sound.
|
||||
let x = channels.get(c).map_or(0.0, |io| flush32(io[i]));
|
||||
line[self.pos] = x;
|
||||
sum += x;
|
||||
self.tracker.measure(c, x);
|
||||
}
|
||||
let first = self.lines[0][self.pos];
|
||||
self.tracker.push(sum / ch as f32, first);
|
||||
let single = self.lines[self.tracker.channel][self.pos];
|
||||
self.tracker.push(sum / ch as f32, single);
|
||||
let t = self.advance();
|
||||
for (line, io) in self.lines.iter().zip(channels.iter_mut()) {
|
||||
let mix = if self.follow_mix < follow_target {
|
||||
(self.follow_mix + self.wet_step).min(follow_target)
|
||||
} else {
|
||||
(self.follow_mix - self.wet_step).max(follow_target)
|
||||
};
|
||||
self.follow_mix = mix;
|
||||
// While Keep Formants is off and faded out, the stage's frames copy the shifted voice,
|
||||
// so switching it on crossfades from a delayed copy instead of from silence.
|
||||
let warp = if mix > 0.0 { back } else { 1.0 };
|
||||
// A channel the block leaves out still reads its line into the formant stage, so the
|
||||
// audio its line holds reaches the stage on time; only its output is dropped.
|
||||
for (c, line) in self.lines.iter().enumerate() {
|
||||
let dry = line[(self.pos + dry_at) & self.mask] as f64;
|
||||
let y = if t.wet == 0.0 {
|
||||
dry
|
||||
@@ -380,13 +490,290 @@ impl AudioEffect for VoicePitch {
|
||||
t.gain_a * read(line, self.mask, self.pos, t.delay_a) + (1.0 - t.gain_a) * read(line, self.mask, self.pos, t.delay_b);
|
||||
t.wet * shifted + (1.0 - t.wet) * dry
|
||||
};
|
||||
io[i] = y.clamp(-f32::MAX as f64, f32::MAX as f64) as f32;
|
||||
let y = y.clamp(-f32::MAX as f64, f32::MAX as f64);
|
||||
let z = self.follow.tick(c, y as f32, warp);
|
||||
// The stage's output is `n` samples later than `y`, so a switch fades one out
|
||||
// before the other comes in instead of mixing them.
|
||||
let out = if mix < 0.5 { (1.0 - 2.0 * mix) * y } else { (2.0 * mix - 1.0) * z as f64 };
|
||||
if let Some(io) = channels.get_mut(c) {
|
||||
io[i] = out.clamp(-f32::MAX as f64, f32::MAX as f64) as f32;
|
||||
}
|
||||
}
|
||||
self.pos = (self.pos + 1) & self.mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spectral envelope of the recent input from linear prediction, and the warp that moves it.
|
||||
/// Every buffer is sized at creation.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Envelope {
|
||||
fft: Fft,
|
||||
/// Hann window over the analyzed history.
|
||||
window: Vec<f64>,
|
||||
/// Gaussian lag window, one value per autocorrelation lag (`order + 1`).
|
||||
lags: Vec<f64>,
|
||||
frame: Vec<f64>,
|
||||
r: Vec<f64>,
|
||||
/// Predictor coefficients, `a[0] = 1`.
|
||||
a: Vec<f64>,
|
||||
prev: Vec<f64>,
|
||||
re: Vec<f32>,
|
||||
im: Vec<f32>,
|
||||
/// Natural log of the envelope's magnitude, bins 0..=n/2 of the STFT.
|
||||
log: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Envelope {
|
||||
/// An envelope for STFT frames of `n` points, read from the last `2 n` samples.
|
||||
fn new(n: usize, sample_rate: f32) -> Self {
|
||||
let order = ((sample_rate / 1000.0).round() as usize + 2).clamp(MIN_ORDER, MAX_ORDER);
|
||||
let w = 2 * n;
|
||||
let window = (0..w).map(|i| 0.5 - 0.5 * (2.0 * PI * (i as f64 + 0.5) / w as f64).cos()).collect();
|
||||
let lags = (0..=order)
|
||||
.map(|i| {
|
||||
let x = 2.0 * PI * LAG_HZ * i as f64 / sample_rate as f64;
|
||||
(-0.5 * x * x).exp()
|
||||
})
|
||||
.collect();
|
||||
Envelope {
|
||||
fft: Fft::new(n),
|
||||
window,
|
||||
lags,
|
||||
frame: vec![0.0; w],
|
||||
r: vec![0.0; order + 1],
|
||||
a: vec![0.0; order + 1],
|
||||
prev: vec![0.0; order + 1],
|
||||
re: vec![0.0; n],
|
||||
im: vec![0.0; n],
|
||||
log: vec![0.0; n / 2 + 1],
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the envelope of the newest `2 n` samples of `history`. Returns `false` for silence,
|
||||
/// which has no envelope.
|
||||
fn measure(&mut self, history: &History) -> bool {
|
||||
let mask = history.ring.len() - 1;
|
||||
for (i, (v, w)) in self.frame.iter_mut().zip(&self.window).enumerate() {
|
||||
*v = history.ring[(history.pos + i) & mask] as f64 * w;
|
||||
}
|
||||
let len = self.frame.len();
|
||||
self.r[0] = dot(&self.frame, &self.frame) * self.lags[0];
|
||||
if !(self.r[0] > 0.0 && self.r[0].is_finite()) {
|
||||
return false;
|
||||
}
|
||||
for (lag, (r, w)) in self.r.iter_mut().zip(&self.lags).enumerate().skip(1) {
|
||||
*r = dot(&self.frame[..len - lag], &self.frame[lag..]) * w;
|
||||
}
|
||||
self.r[0] *= 1.0 + WHITE;
|
||||
levinson(&self.r, &mut self.a, &mut self.prev);
|
||||
// The envelope is 1 / |A| on the bins of the STFT.
|
||||
self.re.fill(0.0);
|
||||
self.im.fill(0.0);
|
||||
for (v, a) in self.re.iter_mut().zip(&self.a) {
|
||||
*v = *a as f32;
|
||||
}
|
||||
self.fft.forward(&mut self.re, &mut self.im);
|
||||
for (l, (re, im)) in self.log.iter_mut().zip(self.re.iter().zip(&self.im)) {
|
||||
*l = (-0.5 * (*re as f64 * *re as f64 + *im as f64 * *im as f64 + 1e-30).ln()) as f32;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Multiplies the half spectrum `re`/`im` (bins 0..=n/2) by the envelope read at `bin /
|
||||
/// ratio` over the envelope at the bin, so the envelope moves up by `ratio` and the
|
||||
/// harmonics stay. A frame with a non-finite bin is replaced with silence.
|
||||
fn warp(&self, re: &mut [f32], im: &mut [f32], ratio: f32) {
|
||||
let half = self.log.len();
|
||||
let (re, im) = (&mut re[..half], &mut im[..half]);
|
||||
if !re.iter().chain(im.iter()).fold(true, |ok, v| ok & v.is_finite()) {
|
||||
re.fill(0.0);
|
||||
im.fill(0.0);
|
||||
return;
|
||||
}
|
||||
let last = (half - 1) as f32;
|
||||
for k in 0..half {
|
||||
let src = (k as f32 / ratio).min(last);
|
||||
let i = src as usize;
|
||||
let e = match self.log.get(i + 1) {
|
||||
Some(next) => self.log[i] + (src - i as f32) * (next - self.log[i]),
|
||||
None => self.log[i],
|
||||
};
|
||||
let g = ((e - self.log[k]) as f64).min(MAX_BOOST).exp() as f32;
|
||||
re[k] *= g;
|
||||
im[k] *= g;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dot product of two slices of the same length, in four running sums so it vectorizes.
|
||||
fn dot(a: &[f64], b: &[f64]) -> f64 {
|
||||
let mut sums = [0.0f64; 4];
|
||||
let ((ca, ra), (cb, rb)) = (a.as_chunks::<4>(), b.as_chunks::<4>());
|
||||
for (x, y) in ca.iter().zip(cb) {
|
||||
for ((s, x), y) in sums.iter_mut().zip(x).zip(y) {
|
||||
*s += x * y;
|
||||
}
|
||||
}
|
||||
let rest: f64 = ra.iter().zip(rb).map(|(x, y)| x * y).sum();
|
||||
(sums[0] + sums[1]) + (sums[2] + sums[3]) + rest
|
||||
}
|
||||
|
||||
/// Levinson-Durbin recursion: the predictor `a` (`a[0] = 1`) of the autocorrelation `r`. It
|
||||
/// stops at the first reflection coefficient that would make the predictor unstable.
|
||||
fn levinson(r: &[f64], a: &mut [f64], prev: &mut [f64]) {
|
||||
a.fill(0.0);
|
||||
a[0] = 1.0;
|
||||
let mut err = r[0];
|
||||
for i in 1..a.len() {
|
||||
let acc = r[i] + (1..i).map(|j| a[j] * r[i - j]).sum::<f64>();
|
||||
let k = -acc / err;
|
||||
// NaN (from a zero error) also stops the recursion.
|
||||
if k.is_nan() || k.abs() >= 1.0 {
|
||||
return;
|
||||
}
|
||||
prev[..i].copy_from_slice(&a[..i]);
|
||||
for j in 1..i {
|
||||
a[j] = prev[j] + k * prev[i - j];
|
||||
}
|
||||
a[i] = k;
|
||||
err *= 1.0 - k * k;
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest samples of one channel, for the envelope.
|
||||
#[derive(Clone, Debug)]
|
||||
struct History {
|
||||
ring: Vec<f32>,
|
||||
/// Where the next sample goes, which is also the oldest sample.
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl History {
|
||||
fn push(&mut self, x: f32) {
|
||||
self.ring[self.pos] = x;
|
||||
self.pos = (self.pos + 1) & (self.ring.len() - 1);
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ring.fill(0.0);
|
||||
self.pos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// STFT stage that moves each channel's envelope, fed one sample at a time: the formant
|
||||
/// shifter, and the formant stage of `voice_pitch`'s Keep Formants.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Stage {
|
||||
n: usize,
|
||||
hop: usize,
|
||||
scale: f32,
|
||||
spec: Spectral,
|
||||
stft: Vec<StftChannel>,
|
||||
history: Vec<History>,
|
||||
env: Envelope,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
fn new(sample_rate: f32, channels: usize) -> Self {
|
||||
let n = formant_size(sample_rate);
|
||||
Stage {
|
||||
n,
|
||||
hop: n / 4,
|
||||
// √Hann on both sides is Hann, which sums to 2 at a hop of n/4; the inverse FFT is
|
||||
// unscaled.
|
||||
scale: 1.0 / (2 * n) as f32,
|
||||
spec: Spectral::new(n, true),
|
||||
stft: vec![StftChannel::new(n); channels],
|
||||
history: vec![History { ring: vec![0.0; 2 * n], pos: 0 }; channels],
|
||||
env: Envelope::new(n, sample_rate),
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.stft.iter_mut().for_each(StftChannel::reset);
|
||||
self.history.iter_mut().for_each(History::reset);
|
||||
}
|
||||
|
||||
/// Pushes one sample of a channel and returns the stage's output for it, `n` samples later.
|
||||
/// A frame moves the envelope by `ratio`, which can spread a sound over the frame, so the
|
||||
/// output can go on for up to `n` samples more (the tail). At a ratio of 1, and for silence, a frame only
|
||||
/// windows and adds its input, which needs no FFT.
|
||||
fn tick(&mut self, channel: usize, x: f32, ratio: f32) -> f32 {
|
||||
let Stage { n, hop, scale, spec, stft, history, env } = self;
|
||||
let half = *n / 2 + 1;
|
||||
history[channel].push(x);
|
||||
let history = &history[channel];
|
||||
let z = stft[channel].tick(x, *hop, &mut |input, out| {
|
||||
if ratio != 1.0 && env.measure(history) {
|
||||
spec.analyze(input);
|
||||
env.warp(&mut spec.re[..half], &mut spec.im[..half], ratio);
|
||||
spec.synthesize_add(out, *scale);
|
||||
} else {
|
||||
for ((o, x), w) in out.iter_mut().zip(input).zip(&spec.window) {
|
||||
*o += x * w * w * 0.5;
|
||||
}
|
||||
}
|
||||
});
|
||||
// A huge finite input can overflow the inverse FFT.
|
||||
flush32(z)
|
||||
}
|
||||
}
|
||||
|
||||
/// Formant shifter for a live voice: moves the spectral envelope by -12 to +12 semitones (a ratio
|
||||
/// of 0.5 to 2) and keeps the harmonics. Its latency is the STFT size, 512 samples (10.7 ms) at
|
||||
/// 48 kHz.
|
||||
pub struct VoiceFormant {
|
||||
pv: ParamValues,
|
||||
stage: Stage,
|
||||
ratio: f32,
|
||||
}
|
||||
|
||||
impl VoiceFormant {
|
||||
pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("semitones", "Formant Shift", -12.0, 12.0, 0.0, Unit::Semitones)];
|
||||
|
||||
pub fn new(sample_rate: f32, channels: usize) -> Self {
|
||||
let sample_rate = crate::sane_sample_rate(sample_rate);
|
||||
let mut s = VoiceFormant { pv: ParamValues::new(Self::PARAMS), stage: Stage::new(sample_rate, crate::sane_channels(channels)), ratio: 1.0 };
|
||||
s.apply_params(true);
|
||||
s
|
||||
}
|
||||
|
||||
fn apply_params(&mut self, _snap: bool) {
|
||||
self.ratio = 2f32.powf(self.pv.v("semitones") / 12.0);
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioEffect for VoiceFormant {
|
||||
param_plumbing!("voice_formant");
|
||||
fn latency(&self) -> usize {
|
||||
self.stage.n
|
||||
}
|
||||
fn tail_samples(&self) -> usize {
|
||||
self.stage.n
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.stage.reset();
|
||||
}
|
||||
fn process(&mut self, channels: &mut [&mut [f32]]) {
|
||||
let len = block_len(channels);
|
||||
for i in 0..len {
|
||||
for c in 0..self.stage.stft.len() {
|
||||
// A non-finite sample is taken as silence, so it never reaches the output. A
|
||||
// channel the block leaves out is fed silence while its state advances, so after
|
||||
// a gap of at least `latency() + tail_samples()` samples it holds none of its
|
||||
// earlier audio; after a shorter gap, audio still pending can sound.
|
||||
match channels.get_mut(c) {
|
||||
Some(io) => io[i] = self.stage.tick(c, flush32(io[i]), self.ratio),
|
||||
None => {
|
||||
self.stage.tick(c, 0.0, self.ratio);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -455,6 +842,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With a silent first channel, a voice on the other two channels in opposite polarity is
|
||||
/// still tracked from one of them and crossfades without beating.
|
||||
#[test]
|
||||
fn opposite_polarity_beside_a_silent_first_channel_is_still_tracked() {
|
||||
let mut p = VoicePitch::new(SR, 3);
|
||||
assert!(p.set_param("semitones", 7.0));
|
||||
p.reset();
|
||||
let n = SR as usize * 2;
|
||||
let mut silent = vec![0.0f32; n];
|
||||
let mut l = sine(220.0, 0.5, SR as f64, n, 0.0);
|
||||
let mut r: Vec<f32> = l.iter().map(|v| -v).collect();
|
||||
p.process(&mut [&mut silent, &mut l, &mut r]);
|
||||
assert!(silent.iter().all(|v| *v == 0.0));
|
||||
assert!(l.iter().zip(&r).all(|(a, b)| *a == -*b));
|
||||
let rest = beside_tone_db(&l, 220.0 * 2f64.powf(7.0 / 12.0));
|
||||
assert!(rest < -40.0, "{rest:.1} dB beside the tone");
|
||||
}
|
||||
|
||||
/// A voice whose two channels have opposite polarity, which cancel in their mean, is still
|
||||
/// tracked and crossfades without beating.
|
||||
#[test]
|
||||
@@ -557,18 +962,357 @@ mod tests {
|
||||
assert!(db(rms(tail) / (0.5 / std::f64::consts::SQRT_2)).abs() < 1.0, "level {}", rms(tail));
|
||||
}
|
||||
|
||||
/// Two-pole resonance magnitude at `f`, 1 at `center`.
|
||||
fn resonance(f: f64, center: f64, bandwidth: f64) -> f64 {
|
||||
center * bandwidth / ((center * center - f * f).powi(2) + (f * bandwidth).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
/// A vowel: harmonics of `f0` up to 6 kHz shaped by two formants (`f1` with an 80 Hz
|
||||
/// bandwidth, `f2` with 120 Hz and half the level) over a floor 34 dB down.
|
||||
fn vowel(f0: f64, f1: f64, f2: f64, sr: f64, n: usize) -> Vec<f32> {
|
||||
let harmonics: Vec<(f64, f64)> = (1..)
|
||||
.map(|k| k as f64 * f0)
|
||||
.take_while(|f| *f < 6000.0)
|
||||
.map(|f| (f, 0.02 + resonance(f, f1, 80.0) + 0.5 * resonance(f, f2, 120.0)))
|
||||
.collect();
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let t = i as f64 / sr;
|
||||
(0.08 * harmonics.iter().map(|(f, a)| a * (2.0 * std::f64::consts::PI * f * t).sin()).sum::<f64>()) as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The envelope peak of `y` between `lo` and `hi` Hz, read from the amplitudes of the
|
||||
/// harmonics of `f0` with a parabola through the strongest one and its neighbors (in dB).
|
||||
fn envelope_peak(y: &[f32], f0: f64, lo: f64, hi: f64, sr: f64) -> f64 {
|
||||
let amp = |k: usize| tone_amplitude(y, k as f64 * f0, sr).max(1e-12).ln();
|
||||
let ks = (lo / f0).ceil() as usize..=(hi / f0).floor() as usize;
|
||||
let k = ks.max_by(|a, b| amp(*a).total_cmp(&(*b))).unwrap_or(1);
|
||||
let (a, b, c) = (amp(k - 1), amp(k), amp(k + 1));
|
||||
let denom = a - 2.0 * b + c;
|
||||
let shift = if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 };
|
||||
(k as f64 + shift) * f0
|
||||
}
|
||||
|
||||
/// The second of `y` after its first half second, at the rate `sr`.
|
||||
fn settled_at(y: &[f32], sr: f64) -> &[f32] {
|
||||
&y[sr as usize / 2..sr as usize * 3 / 2]
|
||||
}
|
||||
|
||||
/// The two formants of the vowel test signal (600 and 2000 Hz) in `y`, each looked for within
|
||||
/// a window moved by `ratio`, with `y`'s harmonics at multiples of `f0`.
|
||||
fn formants(y: &[f32], f0: f64, ratio: f64, sr: f64) -> (f64, f64) {
|
||||
let tail = settled_at(y, sr);
|
||||
(envelope_peak(tail, f0, 400.0 * ratio, 1000.0 * ratio, sr), envelope_peak(tail, f0, 1400.0 * ratio, 3000.0 * ratio, sr))
|
||||
}
|
||||
|
||||
/// Level of everything off the harmonics of `f0` in `y`'s settled second, against the whole,
|
||||
/// in dB.
|
||||
fn off_harmonics_db(y: &[f32], f0: f64, sr: f64) -> f64 {
|
||||
let tail = settled_at(y, sr);
|
||||
let total = rms(tail).powi(2);
|
||||
let on: f64 = (1..).map(|k| k as f64 * f0).take_while(|f| *f < sr / 2.0 - f0).map(|f| tone_amplitude(tail, f, sr).powi(2) / 2.0).sum();
|
||||
10.0 * ((total - on).max(1e-30) / total).log10()
|
||||
}
|
||||
|
||||
/// A formant shift moves both formants of a vowel by the ratio, within a tenth of the move for
|
||||
/// the first and 5% for the second, while every partial stays on the harmonics of the
|
||||
/// unchanged fundamental. Checked at three voice pitches and three sample rates.
|
||||
#[test]
|
||||
fn a_formant_shift_moves_the_envelope_and_keeps_the_harmonics() {
|
||||
for sr in [44_100.0, 48_000.0, 96_000.0] {
|
||||
for f0 in [110.0, 150.0, 220.0] {
|
||||
let x = vowel(f0, 600.0, 2000.0, sr, sr as usize * 2);
|
||||
let (p1, p2) = formants(&x, f0, 1.0, sr);
|
||||
for semis in [-4.0f32, 4.0] {
|
||||
let mut f = VoiceFormant::new(sr as f32, 1);
|
||||
assert!(f.set_param("semitones", semis));
|
||||
let mut y = x.clone();
|
||||
f.process(&mut [&mut y]);
|
||||
let r = 2f64.powf(semis as f64 / 12.0);
|
||||
let (q1, q2) = formants(&y, f0, r, sr);
|
||||
let at = format!("{sr} Hz, f0 {f0}, {semis:+} st: formants {p1:.0} and {p2:.0} moved to {q1:.0} and {q2:.0}");
|
||||
assert!((q1 / (p1 * r) - 1.0).abs() < 0.12, "{at}");
|
||||
assert!((q2 / (p2 * r) - 1.0).abs() < 0.05, "{at}");
|
||||
let off = off_harmonics_db(&y, f0, sr);
|
||||
assert!(off < -30.0, "{at}: {off:.1} dB off the harmonics");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep Formants: the pitch moves up a fourth, and the formants of the vowel stay where they
|
||||
/// were (where without it they move with the pitch).
|
||||
#[test]
|
||||
fn keep_formants_holds_the_envelope_while_the_pitch_moves() {
|
||||
let (sr, f0) = (SR as f64, 150.0);
|
||||
let x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2);
|
||||
let (p1, p2) = formants(&x, f0, 1.0, sr);
|
||||
let r = 2f64.powf(5.0 / 12.0);
|
||||
for keep in [false, true] {
|
||||
let mut p = shifter(5.0, 0.0);
|
||||
assert!(p.set_param("formant_follow", if keep { 1.0 } else { 0.0 }));
|
||||
p.reset();
|
||||
let y = run(&mut p, &x);
|
||||
let want = if keep { 1.0 } else { r };
|
||||
let (q1, q2) = formants(&y, f0 * r, want, sr);
|
||||
let at = format!("keep {keep}: formants {p1:.0} and {p2:.0} read {q1:.0} and {q2:.0}");
|
||||
assert!((q1 / (p1 * want) - 1.0).abs() < 0.12, "{at}");
|
||||
assert!((q2 / (p2 * want) - 1.0).abs() < 0.05, "{at}");
|
||||
assert!(cents(peak_hz(settled(&y), f0 * r * 0.98, f0 * r * 1.02), f0 * r).abs() < 2.0, "keep {keep}: pitch");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep Formants adds the formant shifter's latency to the pitch shifter's while it is on, at
|
||||
/// each rate.
|
||||
#[test]
|
||||
fn the_latency_reports_the_formant_stage() {
|
||||
for sr in [44_100.0, 48_000.0, 96_000.0] {
|
||||
let n = VoiceFormant::new(sr, 2).latency();
|
||||
assert!(n > 0, "{sr}");
|
||||
let mut p = VoicePitch::new(sr, 2);
|
||||
let base = p.latency();
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
assert_eq!(p.latency(), base + n, "{sr}");
|
||||
assert!(p.set_param("formant_follow", 0.0));
|
||||
assert_eq!(p.latency(), base, "{sr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// After a burst of noise ends, the formant shifter and the pitch shifter with Keep Formants
|
||||
/// fall silent within `latency + tail_samples`, so an offline render that drains that long
|
||||
/// keeps all of the output.
|
||||
#[test]
|
||||
fn formant_output_ends_within_the_reported_tail() {
|
||||
let (n, at, len) = (12_000, 1_777, 1_000);
|
||||
let mut rng = Rng::new(17);
|
||||
let mut x = vec![0.0f32; n];
|
||||
x[at..at + len].iter_mut().for_each(|v| *v = 0.5 * rng.uniform());
|
||||
let mut f = VoiceFormant::new(SR, 1);
|
||||
assert!(f.set_param("semitones", 7.0));
|
||||
let mut p = shifter(-5.0, 0.0);
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
p.reset();
|
||||
let fxs: [&mut dyn AudioEffect; 2] = [&mut f, &mut p];
|
||||
for fx in fxs {
|
||||
let mut y = x.clone();
|
||||
fx.process(&mut [&mut y]);
|
||||
let end = at + len + fx.latency() + fx.tail_samples();
|
||||
assert!(y[end..].iter().all(|v| *v == 0.0), "{}: output after {end}", fx.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Switching Keep Formants on fades the shifter's own output out over 10 ms and then fades the
|
||||
/// formant stage's output, 512 samples later, in over 10 ms: the two never sound together,
|
||||
/// so their different delays cannot comb-filter the voice. Checked at a shift of 0, where the
|
||||
/// stage passes the voice unchanged.
|
||||
#[test]
|
||||
fn switching_keep_formants_fades_through_silence() {
|
||||
let x = vowel(170.0, 650.0, 1900.0, SR as f64, 12_000);
|
||||
let at = 4_000;
|
||||
let mut plain = shifter(0.0, 0.0);
|
||||
let y = run(&mut plain, &x);
|
||||
let mut p = shifter(0.0, 0.0);
|
||||
let mut out = x.clone();
|
||||
p.process(&mut [&mut out[..at]]);
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
p.process(&mut [&mut out[at..]]);
|
||||
let n = p.follow.n;
|
||||
let step = 1.0 / (SR as f64 * BYPASS_MS as f64 / 1000.0);
|
||||
for i in at..x.len() {
|
||||
let m = ((i - at + 1) as f64 * step).min(1.0);
|
||||
let want = if m < 0.5 { (1.0 - 2.0 * m) * y[i] as f64 } else { (2.0 * m - 1.0) * y[i - n] as f64 };
|
||||
assert!((out[i] as f64 - want).abs() < 1e-4, "sample {i}: {} against {want}", out[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The formant shifter with a shift change part way, and the pitch shifter with Keep Formants
|
||||
/// switched on and off part way, give the same output however the stream is cut into blocks.
|
||||
#[test]
|
||||
fn formant_output_does_not_depend_on_how_the_stream_is_cut() {
|
||||
let n = 40_000;
|
||||
let x = vowel(130.0, 700.0, 1800.0, SR as f64, n);
|
||||
let changes: [(usize, &str, f32); 3] = [(9_001, "semitones", 3.0), (17_321, "formant_follow", 1.0), (29_999, "formant_follow", 0.0)];
|
||||
let run_cut = |make: &dyn Fn() -> Box<dyn AudioEffect>, sizes: &mut dyn FnMut() -> usize| {
|
||||
let mut fx = make();
|
||||
let mut y = x.clone();
|
||||
let mut pos = 0;
|
||||
while pos < n {
|
||||
for (at, id, v) in changes {
|
||||
if pos == at {
|
||||
fx.set_param(id, v);
|
||||
}
|
||||
}
|
||||
let next = changes.iter().map(|c| c.0).find(|at| *at > pos).unwrap_or(n);
|
||||
let len = sizes().min(next - pos);
|
||||
fx.process(&mut [&mut y[pos..pos + len]]);
|
||||
pos += len;
|
||||
}
|
||||
y
|
||||
};
|
||||
let makers: [&dyn Fn() -> Box<dyn AudioEffect>; 2] = [
|
||||
&|| {
|
||||
let mut f = VoiceFormant::new(SR, 1);
|
||||
f.set_param("semitones", -5.0);
|
||||
Box::new(f)
|
||||
},
|
||||
&|| Box::new(shifter(-3.0, 0.0)),
|
||||
];
|
||||
for make in makers {
|
||||
let whole = run_cut(make, &mut || usize::MAX);
|
||||
let mut rng = Rng::new(13);
|
||||
let cut = run_cut(make, &mut || (rng.next_u64() % 700) as usize);
|
||||
assert!(whole.iter().zip(&cut).all(|(a, b)| a.to_bits() == b.to_bits()));
|
||||
assert!(whole.iter().any(|v| v.abs() > 0.05));
|
||||
}
|
||||
}
|
||||
|
||||
/// NaN, infinite and the largest finite samples in a vowel give finite output from the formant
|
||||
/// shifter and from Keep Formants, and the formants are still moved afterwards.
|
||||
#[test]
|
||||
fn formant_stage_output_stays_finite() {
|
||||
let (sr, f0) = (SR as f64, 150.0);
|
||||
let mut x = vowel(f0, 600.0, 2000.0, sr, SR as usize * 2);
|
||||
let (p1, p2) = formants(&x, f0, 1.0, sr);
|
||||
for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -f32::MAX].into_iter().enumerate() {
|
||||
x[3000 + i * 1500] = bad;
|
||||
x[3001 + i * 1500] = bad;
|
||||
}
|
||||
let mut f = VoiceFormant::new(SR, 2);
|
||||
assert!(f.set_param("semitones", 4.0));
|
||||
let (mut l, mut r) = (x.clone(), x.clone());
|
||||
f.process(&mut [&mut l, &mut r]);
|
||||
assert!(l.iter().chain(&r).all(|v| v.is_finite()));
|
||||
let ratio = 2f64.powf(4.0 / 12.0);
|
||||
let (q1, _) = formants(&l, f0, ratio, sr);
|
||||
assert!((q1 / (p1 * ratio) - 1.0).abs() < 0.12, "{q1}");
|
||||
let mut p = shifter(-7.0, 0.0);
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
let y = run(&mut p, &x);
|
||||
assert!(y.iter().all(|v| v.is_finite()));
|
||||
assert!(rms(settled(&y)) > 0.01);
|
||||
let shifted_f0 = f0 * 2f64.powf(-7.0 / 12.0);
|
||||
let (q1, q2) = formants(&y, shifted_f0, 1.0, sr);
|
||||
assert!((q1 / p1 - 1.0).abs() < 0.12, "Keep Formants: {p1} read {q1}");
|
||||
assert!((q2 / p2 - 1.0).abs() < 0.05, "Keep Formants: {p2} read {q2}");
|
||||
}
|
||||
|
||||
/// A block that leaves channels out feeds them silence, so when they come back without a
|
||||
/// reset, after a gap at least as long as the latency and the tail, none of their earlier
|
||||
/// audio sounds. Checked for the formant shifter and for the pitch shifter with and without
|
||||
/// Keep Formants.
|
||||
#[test]
|
||||
fn channels_left_out_of_a_block_come_back_silent() {
|
||||
let mut rng = Rng::new(19);
|
||||
let noise: Vec<f32> = (0..4_000).map(|_| 0.5 * rng.uniform()).collect();
|
||||
let mut f = VoiceFormant::new(SR, 3);
|
||||
assert!(f.set_param("semitones", 4.0));
|
||||
let mut plain = VoicePitch::new(SR, 3);
|
||||
assert!(plain.set_param("semitones", 5.0));
|
||||
plain.reset();
|
||||
let mut keep = VoicePitch::new(SR, 3);
|
||||
assert!(keep.set_param("semitones", 5.0) && keep.set_param("formant_follow", 1.0));
|
||||
keep.reset();
|
||||
let fxs: [&mut dyn AudioEffect; 3] = [&mut f, &mut plain, &mut keep];
|
||||
for fx in fxs {
|
||||
assert!(fx.latency() + fx.tail_samples() <= noise.len(), "{}: the gap is shorter than the latency and the tail", fx.id());
|
||||
let (mut a, mut b, mut c) = (noise.clone(), noise.clone(), noise.clone());
|
||||
fx.process(&mut [&mut a, &mut b, &mut c]);
|
||||
let mut a = noise.clone();
|
||||
fx.process(&mut [&mut a]);
|
||||
let (mut a, mut b, mut c) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000], vec![0.0f32; 4_000]);
|
||||
fx.process(&mut [&mut a, &mut b, &mut c]);
|
||||
assert!(b.iter().chain(&c).all(|v| *v == 0.0), "{}: earlier audio came back", fx.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// With Keep Formants on, a channel left out of a short block while its line still holds an
|
||||
/// impulse passes that impulse to the formant stage, so after it comes back its output matches
|
||||
/// a channel that was never left out.
|
||||
#[test]
|
||||
fn a_short_gap_keeps_the_formant_stage_fed() {
|
||||
for semitones in [0.0, 5.0] {
|
||||
let mut p = VoicePitch::new(SR, 2);
|
||||
assert!(p.set_param("semitones", semitones) && p.set_param("formant_follow", 1.0));
|
||||
p.reset();
|
||||
let (mut a, mut b) = (vec![0.0f32; 480], vec![0.0f32; 480]);
|
||||
a[0] = 1.0;
|
||||
b[0] = 1.0;
|
||||
p.process(&mut [&mut a, &mut b]);
|
||||
// The impulse leaves the delay line during samples 480 to 735, while `b` is left out.
|
||||
let mut a = vec![0.0f32; 256];
|
||||
p.process(&mut [&mut a]);
|
||||
let (mut a, mut b) = (vec![0.0f32; 2_000], vec![0.0f32; 2_000]);
|
||||
p.process(&mut [&mut a, &mut b]);
|
||||
assert!(a.iter().any(|v| v.abs() > 0.01), "{semitones}: the impulse never came out");
|
||||
assert_eq!(a, b, "{semitones}: the left-out channel lost the impulse");
|
||||
}
|
||||
}
|
||||
|
||||
/// A block that leaves a channel out gives the same output, once the channel is back, as a
|
||||
/// block that holds silence for it: with Keep Formants on, an impulse just before the block
|
||||
/// still sounds afterward.
|
||||
#[test]
|
||||
fn a_channel_left_out_of_a_block_runs_as_silence() {
|
||||
let mut out = Vec::new();
|
||||
for omit in [false, true] {
|
||||
let mut p = VoicePitch::new(SR, 2);
|
||||
assert!(p.set_param("formant_follow", 1.0));
|
||||
p.reset();
|
||||
let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]);
|
||||
r[479] = 1.0;
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
let (mut l, mut r) = (vec![0.0f32; 480], vec![0.0f32; 480]);
|
||||
if omit {
|
||||
p.process(&mut [&mut l]);
|
||||
} else {
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
}
|
||||
let (mut l, mut r) = (vec![0.0f32; 4_000], vec![0.0f32; 4_000]);
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
assert!(r.iter().any(|v| *v != 0.0), "omit {omit}: the impulse did not sound");
|
||||
out.push((l, r));
|
||||
}
|
||||
assert!(out[0] == out[1], "leaving the channel out changed the output");
|
||||
}
|
||||
|
||||
/// Leaving a silent third channel out of a block does not change the pitch the tracker finds,
|
||||
/// so a shifted voice comes out the same on the channels that remain.
|
||||
#[test]
|
||||
fn a_silent_channel_left_out_keeps_the_tracked_pitch() {
|
||||
let n = SR as usize;
|
||||
let (low, high) = (sine(187.5, 0.2, SR as f64, n, 0.0), sine(375.0, 0.24, SR as f64, n, 0.0));
|
||||
let left: Vec<f32> = low.iter().zip(&high).map(|(a, b)| a + b).collect();
|
||||
let right: Vec<f32> = low.iter().zip(&high).map(|(a, b)| -a + b).collect();
|
||||
let mut out = Vec::new();
|
||||
for omit in [false, true] {
|
||||
let mut p = VoicePitch::new(SR, 3);
|
||||
assert!(p.set_param("semitones", 5.0));
|
||||
p.reset();
|
||||
let (mut l, mut r, mut s) = (left.clone(), right.clone(), vec![0.0f32; n]);
|
||||
if omit {
|
||||
p.process(&mut [&mut l, &mut r]);
|
||||
} else {
|
||||
p.process(&mut [&mut l, &mut r, &mut s]);
|
||||
}
|
||||
out.push((l, r));
|
||||
}
|
||||
assert!(out[0] == out[1], "leaving a silent channel out changed the tracked pitch");
|
||||
}
|
||||
|
||||
/// The tracker finds a voice's period down to 70 Hz and reports nothing for silence.
|
||||
#[test]
|
||||
fn the_tracker_reaches_70_hz() {
|
||||
for f in [72.0, 110.0, 440.0, 950.0] {
|
||||
let mut t = Tracker::new(SR);
|
||||
let mut t = Tracker::new(SR, 1);
|
||||
for v in sine(f, 0.3, SR as f64, SR as usize / 4, 0.0) {
|
||||
t.push(v, v);
|
||||
}
|
||||
let period = t.period.unwrap_or(0.0);
|
||||
assert!((SR as f64 / period / f - 1.0).abs() < 0.005, "{f} Hz read as {} Hz", SR as f64 / period);
|
||||
}
|
||||
let mut t = Tracker::new(SR);
|
||||
let mut t = Tracker::new(SR, 1);
|
||||
(0..SR as usize / 4).for_each(|_| t.push(0.0, 0.0));
|
||||
assert!(t.period.is_none());
|
||||
}
|
||||
|
||||
@@ -171,8 +171,10 @@ pub trait AudioEffect: Send {
|
||||
/// Parameter descriptions (same as the registry entry's).
|
||||
fn params(&self) -> &'static [ParamSpec];
|
||||
/// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids.
|
||||
/// Takes effect from the next processed sample. Gains, mix amounts and equalizer bands move to
|
||||
/// the new value smoothly; the crate documentation lists which other parameters change at once.
|
||||
/// Updates the target immediately. Sample-based effects use the target from the next processed
|
||||
/// sample. Frame-based effects may apply it at the next frame callback while earlier output
|
||||
/// remains queued. Gains, mix amounts and equalizer bands move to the new value smoothly; the
|
||||
/// crate documentation lists which other parameters change at once.
|
||||
fn set_param(&mut self, id: &str, value: f32) -> bool;
|
||||
/// Current (target) value of a parameter.
|
||||
fn param(&self, id: &str) -> Option<f32>;
|
||||
@@ -182,7 +184,11 @@ pub trait AudioEffect: Send {
|
||||
/// Process one block in place. All channel slices must have the same length (the shortest
|
||||
/// length is used otherwise). Zero-length blocks are allowed.
|
||||
fn process(&mut self, channels: &mut [&mut [f32]]);
|
||||
/// Processing latency in samples (look-ahead / STFT delay) for delay compensation.
|
||||
/// Processing latency in samples (look-ahead / STFT delay) for delay compensation. It does
|
||||
/// not change with the parameters, except for `voice_pitch`'s `formant_follow` (Keep
|
||||
/// Formants), which adds the formant stage's latency while it is on. The value changes as
|
||||
/// soon as the switch changes, while the output crossfades between the two delays over the
|
||||
/// next 20 ms, so during that fade the output does not match the reported latency.
|
||||
fn latency(&self) -> usize {
|
||||
0
|
||||
}
|
||||
@@ -197,7 +203,13 @@ pub trait AudioEffect: Send {
|
||||
None
|
||||
}
|
||||
/// How long the output keeps sounding after the input stops, in samples (reverb and delay
|
||||
/// tails), so an offline render can run past the end of its input.
|
||||
/// tails), so an offline render can run past the end of its input. The count starts after
|
||||
/// the latency: a render that keeps the tail runs `latency() + tail_samples()` samples past
|
||||
/// the end of its input. An effect whose output decays without reaching zero (a feedback
|
||||
/// delay, a resonator) reports where the decay falls below a cutoff, 60 dB under its start
|
||||
/// for the feedback delays and resonators, so quieter output can still follow that point.
|
||||
/// Those effects also cap the tail they report at 60 s, which is what a feedback of 1 or more
|
||||
/// reports.
|
||||
fn tail_samples(&self) -> usize {
|
||||
0
|
||||
}
|
||||
@@ -460,6 +472,37 @@ pub(crate) mod testutil {
|
||||
}
|
||||
}
|
||||
|
||||
/// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope),
|
||||
/// noise bursts (consonants) and pauses.
|
||||
pub fn speechy(sr: f64, secs: f64, seed: u64) -> Vec<f32> {
|
||||
let n = (sr * secs) as usize;
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut i = 0usize;
|
||||
while i < n {
|
||||
let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize;
|
||||
let kind = rng.uniform();
|
||||
let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5);
|
||||
let glide = 1.0 + 0.3 * rng.uniform() as f64;
|
||||
let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5);
|
||||
for k in 0..len.min(n - i) {
|
||||
let t = k as f64 / sr;
|
||||
let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32;
|
||||
let v = if kind > 0.3 {
|
||||
let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64);
|
||||
(1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::<f32>()
|
||||
} else if kind > -0.4 {
|
||||
rng.uniform()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
out[i + k] = v * env * amp;
|
||||
}
|
||||
i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec<f32> {
|
||||
(0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect()
|
||||
}
|
||||
|
||||
@@ -354,38 +354,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) -
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::Rng;
|
||||
|
||||
/// Speech-like test signal: voiced syllables (harmonics of a gliding pitch under an envelope),
|
||||
/// noise bursts (consonants) and pauses.
|
||||
fn speechy(sr: f64, secs: f64, seed: u64) -> Vec<f32> {
|
||||
let n = (sr * secs) as usize;
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut i = 0usize;
|
||||
while i < n {
|
||||
let len = ((0.08 + 0.25 * (rng.uniform() * 0.5 + 0.5) as f64) * sr) as usize;
|
||||
let kind = rng.uniform();
|
||||
let f0 = 110.0 + 120.0 * (rng.uniform() as f64 * 0.5 + 0.5);
|
||||
let glide = 1.0 + 0.3 * rng.uniform() as f64;
|
||||
let amp = 0.2 + 0.3 * (rng.uniform() * 0.5 + 0.5);
|
||||
for k in 0..len.min(n - i) {
|
||||
let t = k as f64 / sr;
|
||||
let env = (std::f64::consts::PI * k as f64 / len as f64).sin() as f32;
|
||||
let v = if kind > 0.3 {
|
||||
let f = f0 * (1.0 + (glide - 1.0) * k as f64 / len as f64);
|
||||
(1..8).map(|h| ((2.0 * std::f64::consts::PI * f * h as f64 * t).sin() / h as f64) as f32).sum::<f32>()
|
||||
} else if kind > -0.4 {
|
||||
rng.uniform()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
out[i + k] = v * env * amp;
|
||||
}
|
||||
i += len + ((rng.uniform() * 0.5 + 0.5) * 0.15 * sr as f32) as usize;
|
||||
}
|
||||
out
|
||||
}
|
||||
use crate::testutil::{Rng, speechy};
|
||||
|
||||
/// `x` delayed by `delay` samples (fractional: windowed-sinc interpolation), scaled by `gain`,
|
||||
/// optionally colored by a zero-phase low-pass (`[k, 1-2k, k]`, so the delay stays exact), with
|
||||
|
||||
@@ -31,7 +31,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia |
|
||||
| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` |
|
||||
| `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`, `wav_float_header_with_bwf`; `repair_wav` (size fields of a WAV left unfinished by a crash); `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
|
||||
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
@@ -218,8 +218,10 @@ target, call `reset()`, decode from there, and drop the output before the target
|
||||
The codec modules are also usable on their own. `aac::Decoder`, `opus::Decoder` and
|
||||
`vorbis::decoder::Decoder` return the codec's channel order; `aac::wav_order(channel_config)`,
|
||||
`opus::wav_order(channels)` and `vorbis::wav_order(channels)` map it to WAV order, and
|
||||
`vorbis::layout(channels)` gives the speakers of the result. `ac3::Decoder` and `mpa::Decoder`
|
||||
output WAV order.
|
||||
`vorbis::layout(channels)` gives the speakers of the result. `opus::wav_order` applies only to
|
||||
mapping family 1. Family 0 is mono or stereo, which is already in WAV order. For other families,
|
||||
`TrackDecoder` assigns no conventional speaker mapping and leaves channels in stream order.
|
||||
`ac3::Decoder` and `mpa::Decoder` output WAV order.
|
||||
|
||||
### Encode a file
|
||||
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
//! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar
|
||||
//! `f32` in WAV channel order.
|
||||
//! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also
|
||||
//! gives [`wav_float_header`]), FLAC (feature `flac-encode`), AAC-LC and ALAC in M4A
|
||||
//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! gives [`wav_float_header`], [`wav_float_header_with_bwf`] and [`repair_wav`]), FLAC (feature
|
||||
//! `flac-encode`), AAC-LC and ALAC in M4A (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3
|
||||
//! streams (`mp3-encode`, `ac3-encode`, `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder.
|
||||
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
|
||||
@@ -209,8 +209,6 @@ pub use track::{LOOKAHEAD_PACKETS, TrackDecoder};
|
||||
feature = "eac3-encode"
|
||||
))]
|
||||
pub use write::FileEncoder;
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::wav_float_header;
|
||||
#[cfg(any(
|
||||
feature = "pcm-encode",
|
||||
feature = "flac-encode",
|
||||
@@ -223,6 +221,8 @@ pub use write::wav_float_header;
|
||||
))]
|
||||
pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{WavRepair, repair_wav, wav_float_header, wav_float_header_with_bwf};
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header};
|
||||
|
||||
/// Errors from probing, decoding and encoding.
|
||||
|
||||
@@ -3,12 +3,9 @@
|
||||
|
||||
use super::source::Src;
|
||||
use crate::pcm::{PcmKind, le_u16, le_u32, le_u64, tag};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioError, AudioInfo, BwfInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
|
||||
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
|
||||
/// Parsed WAV layout (no sample data decoded yet).
|
||||
pub(crate) struct WavLayout {
|
||||
pub info: AudioInfo,
|
||||
@@ -359,7 +356,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result<WavParse> {
|
||||
ixml_time = ixml_time_reference(&small(IXML_MAX as u64));
|
||||
}
|
||||
}
|
||||
b"ds64" => ds64_data = le_u64(&small(64), 8),
|
||||
// The sizes come from the first `ds64` chunk that holds them.
|
||||
b"ds64" if ds64_data.is_none() => ds64_data = le_u64(&small(64), 8),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,9 @@ pub struct Header {
|
||||
impl Header {
|
||||
/// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow.
|
||||
pub fn frame_bytes(&self) -> usize {
|
||||
if !matches!(self.channels, 2 | 4 | 6 | 8) {
|
||||
return 0;
|
||||
}
|
||||
let pair_bytes = match self.bits {
|
||||
16 => 5,
|
||||
20 => 6,
|
||||
@@ -243,6 +246,17 @@ mod tests {
|
||||
assert_eq!(h.frame_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_rejects_unsupported_channels() {
|
||||
for bits in [16, 20, 24] {
|
||||
for channels in [0, 1, 3, 5, 7, 9, 10, usize::MAX] {
|
||||
let header = Header { channels, channel_id: 0, bits, alignment: 0, audio_bytes: 0 };
|
||||
assert!(Encoder::new(channels, bits).is_err());
|
||||
assert_eq!(header.frame_bytes(), 0, "{channels} channels, {bits} bits");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_rejects_unsupported_depth() {
|
||||
let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 };
|
||||
|
||||
@@ -5,3 +5,5 @@ pub(crate) const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
|
||||
pub(crate) const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
|
||||
/// Tail of the KSDATAFORMAT_SUBTYPE_* GUIDs (bytes 2..16); bytes 0..2 hold the format tag.
|
||||
pub(crate) const GUID_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71];
|
||||
/// Tail of the Ambisonic subtype GUIDs {0000000x-0721-11D3-8644-C8C1CA000000}: PCM (x = 1) and float (x = 3) as well.
|
||||
pub(crate) const AMBISONIC_TAIL: [u8; 14] = [0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00];
|
||||
@@ -449,8 +449,99 @@ impl EncodeOptions {
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result<Vec<u8>> {
|
||||
float_header(sample_rate, channels, None, frames)
|
||||
}
|
||||
|
||||
/// [`wav_float_header`] with a BWF `bext` chunk holding `bwf` before the format chunk. The length
|
||||
/// still doesn't depend on `frames`, so the header is rewritten in place the same way.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_audio::{BwfInfo, wav_float_header_with_bwf};
|
||||
///
|
||||
/// let bwf = BwfInfo::default().with_originator("Recorder").with_time_reference(48_000 * 3_600);
|
||||
/// let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap();
|
||||
/// let samples = [0.25f32, -0.25, 0.5, -0.5];
|
||||
/// file.extend(samples.iter().flat_map(|s| s.to_le_bytes()));
|
||||
/// let header = wav_float_header_with_bwf(48_000, 2, 2, &bwf).unwrap();
|
||||
/// file[..header.len()].copy_from_slice(&header);
|
||||
/// assert!(header.windows(4).any(|id| id == b"bext"));
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn wav_float_header_with_bwf(sample_rate: u32, channels: u16, frames: u64, bwf: &crate::BwfInfo) -> Result<Vec<u8>> {
|
||||
float_header(sample_rate, channels, Some(bwf), frames)
|
||||
}
|
||||
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
fn float_header(sample_rate: u32, channels: u16, bwf: Option<&crate::BwfInfo>, frames: u64) -> Result<Vec<u8>> {
|
||||
if channels == 0 || sample_rate == 0 {
|
||||
return Err(AudioError::Encode("a WAV needs channels and a sample rate".into()));
|
||||
}
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false)
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), bwf, None, frames, false)
|
||||
}
|
||||
|
||||
/// What [`repair_wav`] wrote into a file.
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WavRepair {
|
||||
/// The whole frames the data chunk holds.
|
||||
pub frames: u64,
|
||||
/// The length of the repaired file. Bytes past it are a partial last frame; truncate the
|
||||
/// file to this length (`File::set_len`) to drop them.
|
||||
pub len: u64,
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a PCM or float WAV whose writer stopped before finishing it, such
|
||||
/// as a recorder's file after a crash, for the whole frames the file holds. The file must end in
|
||||
/// its data chunk: everything after the data chunk's header counts as samples, whatever its size
|
||||
/// field says.
|
||||
///
|
||||
/// It writes these fields and leaves every other byte before the samples as it is, `fmt `, `bext`
|
||||
/// and unknown chunks included:
|
||||
///
|
||||
/// - the RIFF size and the data chunk's size (both `0xFFFF_FFFF` in an RF64 file);
|
||||
/// - the frame count, the first field of the first `fact` chunk (`0xFFFF_FFFF` past `u32::MAX` frames);
|
||||
/// - in an RF64 file, the RIFF size, data size and frame count at the start of the first `ds64` chunk;
|
||||
/// - the pad byte after an odd data length.
|
||||
///
|
||||
/// A RIFF file that grew past 4 GiB becomes RF64 when it starts with the 28-byte `JUNK` chunk that
|
||||
/// [`FileEncoder`] and [`wav_float_header`] write: `RIFF` becomes `RF64` and that `JUNK` chunk
|
||||
/// becomes a `ds64` chunk with an empty table. A RIFF file whose 28-byte chunk there already has the
|
||||
/// `ds64` id, left by an earlier repair that stopped before writing `RF64`, becomes RF64 the same way.
|
||||
///
|
||||
/// Errors:
|
||||
///
|
||||
/// - [`AudioError::Malformed`] when `file` is not a RIFF or RF64 WAVE file, has no data chunk within
|
||||
/// its first 100,000 chunks, has its data chunk before its `fmt ` chunk, has a `fmt ` chunk shorter
|
||||
/// than 16 bytes or cut short by the end of the file, has 0 channels or 0 bits, has a block size
|
||||
/// other than the channels times the bytes per sample, has an extensible `fmt ` chunk with a cbSize
|
||||
/// below 22 or more valid bits than bits per sample, or is RF64 without a `ds64` chunk or with a
|
||||
/// first `ds64` chunk of 16 to 27 bytes (the WAV reader takes the data size from that chunk).
|
||||
/// - [`AudioError::Unsupported`] for a format other than PCM and IEEE float, an extensible format
|
||||
/// whose subformat is neither, a sample width the WAV reader does not decode (PCM above 32 bits,
|
||||
/// float other than 32 or 64 bits), and unfinished 8-bit mono data of even length (its last byte
|
||||
/// may be a sample or a pad byte).
|
||||
/// - [`AudioError::TooLarge`] for a RIFF file past 4 GiB that does not start with that `JUNK` or
|
||||
/// `ds64` chunk.
|
||||
/// - [`AudioError::Io`] when reading, writing or seeking `file` fails.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_audio::{repair_wav, wav_float_header};
|
||||
/// use std::io::Cursor;
|
||||
///
|
||||
/// // A recorder wrote the header for 0 frames, then 2 frames and part of a third, then stopped.
|
||||
/// let mut bytes = wav_float_header(48_000, 2, 0).unwrap();
|
||||
/// bytes.extend([0.25f32, -0.25, 0.5, -0.5, 0.75].iter().flat_map(|s| s.to_le_bytes()));
|
||||
/// let mut file = Cursor::new(bytes);
|
||||
/// let repaired = repair_wav(&mut file).unwrap();
|
||||
/// assert_eq!(repaired.frames, 2);
|
||||
/// let mut bytes = file.into_inner();
|
||||
/// bytes.truncate(repaired.len as usize);
|
||||
/// let header = wav_float_header(48_000, 2, 2).unwrap();
|
||||
/// assert_eq!(bytes[..header.len()], header[..]);
|
||||
/// ```
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
pub fn repair_wav<F: std::io::Read + Write + Seek>(file: &mut F) -> Result<WavRepair> {
|
||||
let (frames, len) = wav::repair(file)?;
|
||||
Ok(WavRepair { frames, len })
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
//! specification, `bext` per EBU Tech 3285, `ds64` per EBU Tech 3306).
|
||||
|
||||
use super::pcm::{Quantizer, sample_format, validate_buffer, validate_layout, write_interleaved};
|
||||
use crate::wav::{GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::wav::{AMBISONIC_TAIL, GUID_TAIL, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM};
|
||||
use crate::{AudioBuffer, AudioError, BitDepth, BwfInfo, Result};
|
||||
use std::io::{Cursor, Seek, SeekFrom, Write};
|
||||
use std::io::{Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
|
||||
|
||||
const BEXT_MIN_LEN: usize = 602;
|
||||
|
||||
@@ -239,3 +239,175 @@ pub(crate) fn header(
|
||||
head.extend_from_slice(&(if rf64 { u32::MAX } else { data_len as u32 }).to_le_bytes());
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
/// Where the size fields of a WAV sit, from a walk of its chunks up to `data`.
|
||||
struct Layout {
|
||||
rf64: bool,
|
||||
/// The body of the `ds64` chunk of an RF64 file, or in a RIFF file the body of the 28-byte
|
||||
/// `JUNK` or `ds64` chunk right after `WAVE` that can become one.
|
||||
ds64: Option<u64>,
|
||||
junk: bool,
|
||||
fact: Option<u64>,
|
||||
block_align: u64,
|
||||
data: u64,
|
||||
}
|
||||
|
||||
fn read_at<F: Read + Seek>(file: &mut F, pos: u64, buf: &mut [u8]) -> Result<bool> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
match file.read_exact(buf) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(e) if e.kind() == ErrorKind::UnexpectedEof => Ok(false),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_at<F: Write + Seek>(file: &mut F, pos: u64, bytes: &[u8]) -> Result<()> {
|
||||
file.seek(SeekFrom::Start(pos))?;
|
||||
file.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The block size of a PCM or float `fmt ` chunk body at `pos` of `size` bytes.
|
||||
fn pcm_block_align<F: Read + Seek>(file: &mut F, pos: u64, size: u32) -> Result<u64> {
|
||||
let mut fmt = [0u8; 40];
|
||||
let n = if size >= 40 { 40 } else { 16 };
|
||||
if size < 16 || !read_at(file, pos, &mut fmt[..n])? {
|
||||
return Err(AudioError::Malformed("WAV fmt chunk is cut short".into()));
|
||||
}
|
||||
let field = |at: usize| u16::from_le_bytes([fmt[at], fmt[at + 1]]);
|
||||
let mut tag = field(0);
|
||||
if tag == WAVE_FORMAT_EXTENSIBLE && n == 40 {
|
||||
// The extensible fields the reader checks.
|
||||
if field(16) < 22 || field(18) > field(14) {
|
||||
return Err(AudioError::Malformed("WAVE_FORMAT_EXTENSIBLE fmt chunk has a cbSize below 22 or too many valid bits".into()));
|
||||
}
|
||||
if fmt[26..] == GUID_TAIL || fmt[26..] == AMBISONIC_TAIL {
|
||||
tag = field(24);
|
||||
}
|
||||
}
|
||||
if tag != WAVE_FORMAT_PCM && tag != WAVE_FORMAT_IEEE_FLOAT {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x}")));
|
||||
}
|
||||
let (channels, align, bits) = (field(2), field(12), field(14));
|
||||
if channels == 0 || bits == 0 || u32::from(align) != u32::from(channels) * u32::from(bits.div_ceil(8)) {
|
||||
return Err(AudioError::Malformed(format!("WAV block size {align} does not fit {channels} channels of {bits} bits")));
|
||||
}
|
||||
// The widths the WAV reader decodes.
|
||||
if !matches!((tag, bits), (WAVE_FORMAT_PCM, 1..=32) | (WAVE_FORMAT_IEEE_FLOAT, 32 | 64)) {
|
||||
return Err(AudioError::Unsupported(format!("repairing a WAV of format tag {tag:#06x} with {bits} bits per sample")));
|
||||
}
|
||||
Ok(u64::from(align))
|
||||
}
|
||||
|
||||
fn layout<F: Read + Seek>(file: &mut F, len: u64) -> Result<Layout> {
|
||||
let mut riff = [0u8; 12];
|
||||
if !read_at(file, 0, &mut riff)? || !(riff.starts_with(b"RIFF") || riff.starts_with(b"RF64")) || &riff[8..] != b"WAVE" {
|
||||
return Err(AudioError::Malformed("not a WAV file".into()));
|
||||
}
|
||||
let rf64 = riff.starts_with(b"RF64");
|
||||
let (mut ds64, mut junk, mut fact, mut block_align) = (None, false, None, None);
|
||||
let mut pos = 12u64;
|
||||
let mut chunk = [0u8; 8];
|
||||
// The same bound as the reader's, so a file of tiny chunks can't spin forever.
|
||||
for _ in 0..100_000 {
|
||||
if pos >= len || !read_at(file, pos, &mut chunk)? {
|
||||
break;
|
||||
}
|
||||
let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
|
||||
let body = pos + 8;
|
||||
match &chunk[..4] {
|
||||
b"data" => {
|
||||
let block_align = block_align.ok_or_else(|| AudioError::Malformed("WAV data chunk before its fmt chunk".into()))?;
|
||||
return Ok(Layout { rf64, ds64, junk, fact, block_align, data: body });
|
||||
}
|
||||
// The first `ds64` and `fact` chunks take the sizes; later ones are left as they are.
|
||||
// The WAV reader takes the data size from the first `ds64` chunk of 16 bytes or more.
|
||||
b"ds64" if rf64 && size >= 16 && ds64.is_none() => {
|
||||
if size < 28 {
|
||||
return Err(AudioError::Malformed("RF64 ds64 chunk is shorter than 28 bytes".into()));
|
||||
}
|
||||
ds64 = Some(body);
|
||||
}
|
||||
// A `ds64` id here in a RIFF file is a promotion that stopped before the RF64 id.
|
||||
b"JUNK" | b"ds64" if !rf64 && pos == 12 && size == 28 => (ds64, junk) = (Some(body), true),
|
||||
b"fact" if size >= 4 && fact.is_none() => fact = Some(body),
|
||||
b"fmt " => block_align = Some(pcm_block_align(file, body, size)?),
|
||||
_ => {}
|
||||
}
|
||||
pos = body + u64::from(size) + u64::from(size & 1);
|
||||
}
|
||||
Err(AudioError::Malformed("WAV has no data chunk".into()))
|
||||
}
|
||||
|
||||
/// The data size the header records: the `ds64` field of an RF64 file, else the data chunk's.
|
||||
fn stored_data_len<F: Read + Seek>(file: &mut F, l: &Layout) -> Result<Option<u64>> {
|
||||
let mut size = [0u8; 8];
|
||||
Ok(match (l.rf64, l.ds64) {
|
||||
(true, Some(at)) => read_at(file, at + 8, &mut size)?.then(|| u64::from_le_bytes(size)),
|
||||
(true, None) => None,
|
||||
(false, _) => read_at(file, l.data - 4, &mut size[..4])?
|
||||
.then(|| u32::from_le_bytes([size[0], size[1], size[2], size[3]]))
|
||||
.filter(|&s| s != u32::MAX)
|
||||
.map(u64::from),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrites the size fields of a WAV that ends in its data chunk for the whole frames it holds.
|
||||
/// Returns the frame count and the length the file should have; bytes past it are a partial frame.
|
||||
pub(crate) fn repair<F: Read + Write + Seek>(file: &mut F) -> Result<(u64, u64)> {
|
||||
let len = file.seek(SeekFrom::End(0))?;
|
||||
let l = layout(file, len)?;
|
||||
let held = len.saturating_sub(l.data);
|
||||
// A finished file's own size, which also tells its pad byte from a frame of one byte.
|
||||
let stored = stored_data_len(file, &l)?.filter(|&s| s % l.block_align == 0 && s.checked_add(s & 1) == Some(held));
|
||||
if stored.is_none() && l.block_align == 1 && held > 0 && held % 2 == 0 {
|
||||
// The last byte may be a sample or the pad byte after an odd count of them.
|
||||
return Err(AudioError::Unsupported("repairing 8-bit mono WAV data of even length: a pad byte reads as a sample".into()));
|
||||
}
|
||||
let frames = stored.unwrap_or(held) / l.block_align;
|
||||
let data_len = frames * l.block_align;
|
||||
let pad = data_len & 1;
|
||||
let new_len = l.data + data_len + pad;
|
||||
let riff_len = new_len - 8;
|
||||
let rf64 = l.rf64 || u32::try_from(riff_len).is_err();
|
||||
let ds64 = match (rf64, l.ds64) {
|
||||
(false, _) => None,
|
||||
(true, Some(at)) if l.rf64 || l.junk => Some(at),
|
||||
(true, _) if l.rf64 => return Err(AudioError::Malformed("RF64 file has no ds64 chunk".into())),
|
||||
(true, _) => return Err(AudioError::TooLarge("WAV past 4 GiB has no room for a ds64 chunk".into())),
|
||||
};
|
||||
if let Some(at) = l.fact {
|
||||
write_at(file, at, &u32::try_from(frames).unwrap_or(u32::MAX).to_le_bytes())?;
|
||||
}
|
||||
match ds64 {
|
||||
Some(at) => {
|
||||
let mut body = Vec::with_capacity(28);
|
||||
body.extend_from_slice(&riff_len.to_le_bytes());
|
||||
body.extend_from_slice(&data_len.to_le_bytes());
|
||||
body.extend_from_slice(&frames.to_le_bytes());
|
||||
if !l.rf64 {
|
||||
// The `JUNK` chunk's last 4 bytes become the table length: no table entries.
|
||||
body.extend_from_slice(&0u32.to_le_bytes());
|
||||
}
|
||||
write_at(file, at, &body)?;
|
||||
if !l.rf64 {
|
||||
write_at(file, at - 8, b"ds64")?;
|
||||
write_at(file, 0, b"RF64")?;
|
||||
}
|
||||
write_at(file, l.data - 4, &u32::MAX.to_le_bytes())?;
|
||||
write_at(file, 4, &u32::MAX.to_le_bytes())?;
|
||||
}
|
||||
None => {
|
||||
write_at(file, l.data - 4, &(data_len as u32).to_le_bytes())?;
|
||||
write_at(file, 4, &(riff_len as u32).to_le_bytes())?;
|
||||
}
|
||||
}
|
||||
// The pad byte goes last: until it is written, 8-bit mono data keeps an odd length that a
|
||||
// repeated repair can count.
|
||||
if pad == 1 {
|
||||
write_at(file, l.data + data_len, &[0])?;
|
||||
}
|
||||
file.seek(SeekFrom::Start(new_len))?;
|
||||
file.flush()?;
|
||||
Ok((frames, new_len))
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe};
|
||||
use craft_audio::{
|
||||
AudioBuffer, BitDepth, BwfInfo, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe, wav_float_header,
|
||||
wav_float_header_with_bwf,
|
||||
};
|
||||
|
||||
fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer {
|
||||
let mut b = AudioBuffer::new(sr, channels as u16, frames);
|
||||
@@ -64,3 +67,335 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that stopped growing before its header was rewritten: the header for 0 frames, the
|
||||
/// samples of `buf`, then `extra` bytes of a frame that was never finished.
|
||||
fn unfinished_wav(buf: &AudioBuffer, opts: &EncodeOptions, extra: usize) -> (Vec<u8>, Vec<u8>) {
|
||||
let finished = encode(buf, opts).unwrap();
|
||||
let mut file = encode(&AudioBuffer::new(buf.sample_rate, buf.num_channels(), 0), opts).unwrap();
|
||||
let head = file.len();
|
||||
let sample_bytes = match opts.bit_depth {
|
||||
BitDepth::Int16 => 2,
|
||||
BitDepth::Int24 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
let data_len = buf.frames() * usize::from(buf.num_channels()) * sample_bytes;
|
||||
file.extend_from_slice(&finished[head..head + data_len]);
|
||||
file.extend(std::iter::repeat_n(0x55, extra));
|
||||
(file, finished)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_rewrites_the_sizes_of_an_unfinished_file() {
|
||||
let bwf = BwfInfo::default().with_description("take 3").with_time_reference(48_000 * 3600);
|
||||
let cases = [
|
||||
(sine(48_000, 2, 1_000), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone()), 5),
|
||||
// 3 bytes a frame and an odd frame count: the data needs a pad byte.
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf.clone()), 2),
|
||||
(sine(44_100, 1, 999), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_bwf(bwf), 0),
|
||||
(sine(48_000, 6, 300), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true), 11),
|
||||
(sine(48_000, 2, 0), EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16), 3),
|
||||
];
|
||||
for (buf, opts, extra) in cases {
|
||||
let (file, finished) = unfinished_wav(&buf, &opts, extra);
|
||||
assert_ne!(file, finished);
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repaired.frames, buf.frames() as u64);
|
||||
let mut file = file.into_inner();
|
||||
assert!(file.len() as u64 >= repaired.len);
|
||||
file.truncate(repaired.len as usize);
|
||||
assert_eq!(file, finished, "{opts:?}");
|
||||
// A finished file stays as it is.
|
||||
let mut again = std::io::Cursor::new(file.clone());
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired);
|
||||
assert_eq!(again.into_inner(), file);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file whose data is all zeros past `head`, `len` bytes long, without holding them in memory.
|
||||
struct SparseWav {
|
||||
head: Vec<u8>,
|
||||
len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl std::io::Read for SparseWav {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = (self.len.saturating_sub(self.pos)).min(buf.len() as u64) as usize;
|
||||
for (i, b) in buf[..n].iter_mut().enumerate() {
|
||||
*b = self.head.get(self.pos as usize + i).copied().unwrap_or(0);
|
||||
}
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for SparseWav {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let end = self.pos as usize + buf.len();
|
||||
if end <= self.head.len() {
|
||||
self.head[self.pos as usize..end].copy_from_slice(buf);
|
||||
} else {
|
||||
assert!(buf.iter().all(|&b| b == 0), "only padding is written past the header");
|
||||
}
|
||||
self.pos += buf.len() as u64;
|
||||
self.len = self.len.max(self.pos);
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for SparseWav {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.pos = match to {
|
||||
std::io::SeekFrom::Start(p) => p,
|
||||
std::io::SeekFrom::End(d) => self.len.checked_add_signed(d).unwrap(),
|
||||
std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).unwrap(),
|
||||
};
|
||||
Ok(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_turns_a_file_past_4_gib_into_rf64() {
|
||||
let frames = 600_000_000u64; // 4.8 GB of stereo float
|
||||
let head = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let len = head.len() as u64 + frames * 8 + 3;
|
||||
let mut file = SparseWav { head: head.clone(), len, pos: 0 };
|
||||
let repaired = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((repaired.frames, repaired.len), (frames, len - 3));
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A JUNK chunk holding other bytes becomes a ds64 chunk with an empty table.
|
||||
let mut dirty = head.clone();
|
||||
assert_eq!(&dirty[12..16], b"JUNK");
|
||||
dirty[20..48].fill(0xAA);
|
||||
let mut file = SparseWav { head: dirty, len, pos: 0 };
|
||||
craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// A repair that stopped after naming the ds64 chunk but before writing RF64 finishes next time.
|
||||
let mut half = head.clone();
|
||||
half[12..16].copy_from_slice(b"ds64");
|
||||
let mut file = SparseWav { head: half, len, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap(), repaired);
|
||||
assert_eq!(file.head, wav_float_header(48_000, 2, frames).unwrap());
|
||||
|
||||
// In a RIFF file only the chunk right after WAVE becomes ds64; a later ds64 chunk is left as it is.
|
||||
let at = head.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"ds64"[..], &28u32.to_le_bytes(), &[0xBB; 28]].concat();
|
||||
let mut two = head.clone();
|
||||
two.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: two, len: len + 36, pos: 0 };
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, frames);
|
||||
assert_eq!((&file.head[..4], &file.head[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// In an RF64 file the ds64 chunk right after WAVE takes the sizes; a later ds64 chunk is left as it is.
|
||||
let finished = wav_float_header(48_000, 2, frames).unwrap();
|
||||
assert_eq!((&finished[..4], &finished[12..16]), (&b"RF64"[..], &b"ds64"[..]));
|
||||
let mut stale = finished.clone();
|
||||
stale[20..44].fill(0);
|
||||
stale.splice(at..at, later.iter().copied());
|
||||
let mut file = SparseWav { head: stale, len: len + 36, pos: 0 };
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!((r.frames, r.len), (frames, len + 33));
|
||||
let field = |at: usize| u64::from_le_bytes(file.head[at..at + 8].try_into().unwrap());
|
||||
assert_eq!((field(20), field(28), field(36)), (len + 25, frames * 8, frames));
|
||||
assert_eq!(file.head[at..at + 36], later[..]);
|
||||
|
||||
// A RIFF file with no JUNK chunk to turn into ds64 cannot grow past 4 GiB.
|
||||
let bare = craft_audio::pcm_wav_header(0, 2, 48_000, 16);
|
||||
assert_eq!(&bare[12..16], b"fmt ");
|
||||
let len = bare.len() as u64 + (1u64 << 32);
|
||||
let mut file = SparseWav { head: bare, len, pos: 0 };
|
||||
assert!(matches!(craft_audio::repair_wav(&mut file), Err(craft_audio::AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_writes_the_frame_count_into_the_first_fact_chunk() {
|
||||
let mut file = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let fact = file.windows(4).position(|w| w == b"fact").unwrap() + 8;
|
||||
let at = file.windows(4).position(|w| w == b"data").unwrap();
|
||||
let later: Vec<u8> = [&b"fact"[..], &4u32.to_le_bytes(), &[0xCC; 4]].concat();
|
||||
file.splice(at..at, later.iter().copied());
|
||||
file.extend(std::iter::repeat_n(0, 100 * 8));
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
assert_eq!(craft_audio::repair_wav(&mut file).unwrap().frames, 100);
|
||||
let file = file.into_inner();
|
||||
assert_eq!(file[fact..fact + 4], 100u32.to_le_bytes());
|
||||
assert_eq!(file[at..at + 12], later[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rf64_data_size_comes_from_the_ds64_chunk_after_wave() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16).with_force_rf64(true);
|
||||
let wav = encode(&sine(48_000, 2, 300), &opts).unwrap();
|
||||
assert_eq!(&wav[12..16], b"ds64");
|
||||
// A later ds64 chunk that gives the data 4 bytes, one frame.
|
||||
let mut body = [0u8; 28];
|
||||
body[8..16].copy_from_slice(&4u64.to_le_bytes());
|
||||
let later = [&b"ds64"[..], &28u32.to_le_bytes(), &body].concat();
|
||||
let at = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
let mut two = wav.clone();
|
||||
two.splice(at..at, later);
|
||||
let (info, buf) = decode(&two, Some("wav")).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (300, 300));
|
||||
|
||||
// A 16-byte first ds64 chunk gives the reader the data size, so repair does not use the later one.
|
||||
let mut short = two;
|
||||
short[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short[28..36].copy_from_slice(&4u64.to_le_bytes());
|
||||
short[36..44].copy_from_slice(&[&b"JUNK"[..], &4u32.to_le_bytes()].concat());
|
||||
assert_eq!(decode(&short, Some("wav")).unwrap().1.frames(), 1);
|
||||
let repaired = craft_audio::repair_wav(&mut std::io::Cursor::new(short));
|
||||
assert!(matches!(repaired, Err(craft_audio::AudioError::Malformed(_))), "{repaired:?}");
|
||||
}
|
||||
|
||||
/// A file whose writes fail once `writes` of them have gone through.
|
||||
struct FailingWrites {
|
||||
file: std::io::Cursor<Vec<u8>>,
|
||||
writes: usize,
|
||||
}
|
||||
|
||||
impl std::io::Read for FailingWrites {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
std::io::Read::read(&mut self.file, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Write for FailingWrites {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if self.writes == 0 {
|
||||
return Err(std::io::Error::other("disk full"));
|
||||
}
|
||||
self.writes -= 1;
|
||||
std::io::Write::write(&mut self.file, buf)
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::io::Seek for FailingWrites {
|
||||
fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
std::io::Seek::seek(&mut self.file, to)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_runs_again_after_a_write_error() {
|
||||
let mut u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
u8_mono.extend([0x80; 3]);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24);
|
||||
let (int24, _) = unfinished_wav(&sine(44_100, 1, 999), &opts, 2);
|
||||
for (file, frames) in [(u8_mono, 3), (int24, 999)] {
|
||||
let mut whole = std::io::Cursor::new(file.clone());
|
||||
let repaired = craft_audio::repair_wav(&mut whole).unwrap();
|
||||
assert_eq!(repaired.frames, frames);
|
||||
for writes in 0.. {
|
||||
let mut failing = FailingWrites { file: std::io::Cursor::new(file.clone()), writes };
|
||||
if craft_audio::repair_wav(&mut failing).is_ok() {
|
||||
break;
|
||||
}
|
||||
let mut again = failing.file;
|
||||
assert_eq!(craft_audio::repair_wav(&mut again).unwrap(), repaired, "stopped after {writes} writes");
|
||||
assert_eq!(again.into_inner(), *whole.get_ref(), "stopped after {writes} writes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_wav_refuses_what_it_cannot_repair() {
|
||||
use craft_audio::AudioError;
|
||||
let repair = |bytes: Vec<u8>| craft_audio::repair_wav(&mut std::io::Cursor::new(bytes));
|
||||
let wav = encode(&sine(48_000, 1, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16)).unwrap();
|
||||
assert!(matches!(repair(b"not a wave file at all".to_vec()), Err(AudioError::Malformed(_))));
|
||||
// Every cut inside the header is an error, not a panic.
|
||||
let data = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
for cut in 0..data + 8 {
|
||||
assert!(repair(wav[..cut].to_vec()).is_err(), "cut at {cut}");
|
||||
}
|
||||
// A compressed format (format tag 2, Microsoft ADPCM) has no fixed frame size to count by.
|
||||
let fmt = wav.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
let mut adpcm = wav.clone();
|
||||
adpcm[fmt..fmt + 2].copy_from_slice(&2u16.to_le_bytes());
|
||||
assert!(matches!(repair(adpcm), Err(AudioError::Unsupported(_))));
|
||||
// The chunk walk stops, as the reader's does, after 100,000 chunks.
|
||||
let mut many = wav[..12].to_vec();
|
||||
many.extend(b"JUNK\0\0\0\0".repeat(100_001));
|
||||
many.extend_from_slice(&wav[12..]);
|
||||
assert!(matches!(repair(many), Err(AudioError::Malformed(_))));
|
||||
// 8-bit mono: an even data length could end in a sample or in the pad after an odd count.
|
||||
let u8_mono = craft_audio::pcm_wav_header(0, 1, 8_000, 8);
|
||||
for (samples, ok) in [(3, true), (4, false)] {
|
||||
let mut file = u8_mono.clone();
|
||||
file.extend(std::iter::repeat_n(0x80, samples));
|
||||
assert_eq!(repair(file.clone()).map(|r| r.frames).ok(), ok.then_some(3), "{samples} bytes");
|
||||
if ok {
|
||||
// Once repaired, the size settles it.
|
||||
let mut file = std::io::Cursor::new(file);
|
||||
let r = craft_audio::repair_wav(&mut file).unwrap();
|
||||
assert_eq!(repair(file.into_inner()).unwrap(), r);
|
||||
}
|
||||
}
|
||||
// A block size that is not channels × sample bytes would count the wrong frames.
|
||||
let mut odd_align = wav.clone();
|
||||
odd_align[fmt + 12..fmt + 14].copy_from_slice(&4u16.to_le_bytes());
|
||||
assert!(matches!(repair(odd_align), Err(AudioError::Malformed(_))));
|
||||
// Widths the reader does not decode: 16-bit float and 40-bit PCM, each with a block size that fits.
|
||||
let mut float16 = wav.clone();
|
||||
float16[fmt..fmt + 2].copy_from_slice(&3u16.to_le_bytes());
|
||||
let mut pcm40 = wav.clone();
|
||||
pcm40[fmt + 12..fmt + 16].copy_from_slice(&[5, 0, 40, 0]);
|
||||
for bad in [float16, pcm40] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Unsupported(_))));
|
||||
}
|
||||
// An extensible file whose subformat is PCM's tag under another GUID is not PCM.
|
||||
let ext = encode(&sine(48_000, 2, 100), &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24)).unwrap();
|
||||
let fmt = ext.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
|
||||
assert!(repair(ext.clone()).is_ok());
|
||||
let mut other_guid = ext.clone();
|
||||
other_guid[fmt + 39] ^= 0xFF;
|
||||
assert!(matches!(repair(other_guid), Err(AudioError::Unsupported(_))));
|
||||
// Extensible fields the reader refuses: a cbSize below 22 and more valid bits than the sample holds.
|
||||
let mut short_cb = ext.clone();
|
||||
short_cb[fmt + 16..fmt + 18].copy_from_slice(&21u16.to_le_bytes());
|
||||
let mut wide_valid = ext.clone();
|
||||
wide_valid[fmt + 18..fmt + 20].copy_from_slice(&25u16.to_le_bytes());
|
||||
for bad in [short_cb, wide_valid] {
|
||||
assert!(craft_audio::decode(&bad, Some("wav")).is_err());
|
||||
assert!(matches!(repair(bad), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
// The Ambisonic PCM subformat {00000001-0721-11D3-8644-C8C1CA000000}, which the reader reads as PCM.
|
||||
let mut ambisonic = ext;
|
||||
ambisonic[fmt + 26..fmt + 40].copy_from_slice(&[0x00, 0x00, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00]);
|
||||
assert_eq!(repair(ambisonic).unwrap().frames, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_wav_header_with_bwf_keeps_its_bext_as_the_file_grows() {
|
||||
let take = sine(48_000, 2, 1_000);
|
||||
let bwf = BwfInfo::default()
|
||||
.with_description("take 3")
|
||||
.with_originator("recorder")
|
||||
.with_origination("2026-11-20", "18:30:00")
|
||||
.with_time_reference(48_000 * 66_600);
|
||||
let mut file = wav_float_header_with_bwf(48_000, 2, 0, &bwf).unwrap();
|
||||
let len = file.len();
|
||||
assert!(len > wav_float_header(48_000, 2, 0).unwrap().len());
|
||||
file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes()));
|
||||
file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 600, &bwf).unwrap());
|
||||
let (info, decoded) = decode(&file, None).unwrap();
|
||||
assert_eq!((info.bwf.as_ref(), decoded.frames()), (Some(&bwf), 600));
|
||||
file[..len].copy_from_slice(&wav_float_header_with_bwf(48_000, 2, 1_000, &bwf).unwrap());
|
||||
let opts = EncodeOptions::default().with_bit_depth(BitDepth::Float32).with_bwf(bwf.clone());
|
||||
assert_eq!(file, encode(&take, &opts).unwrap());
|
||||
let big = wav_float_header_with_bwf(48_000, 2, 600_000_000, &bwf).unwrap();
|
||||
assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len));
|
||||
assert!(wav_float_header_with_bwf(48_000, 0, 0, &bwf).is_err());
|
||||
}
|
||||
@@ -103,10 +103,8 @@ fn an_unasked_line_makes_the_connection_unusable_before_sending() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).unwrap();
|
||||
assert!(client.is_usable(), "an idle connection with nothing pending is usable");
|
||||
said.send(()).unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while client.is_usable() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
// A blocking peek (under the client's read timeout) returns once the line has arrived.
|
||||
assert!(client.stream.peek(&mut [0]).unwrap() > 0, "the unasked line arrived");
|
||||
assert!(!client.is_usable(), "the unasked line makes the connection unusable");
|
||||
assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()));
|
||||
assert!(client.is_broken(), "the unusable connection is closed");
|
||||
|
||||
@@ -487,20 +487,40 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> {
|
||||
stream.set_write_timeout(Some(IO_TIMEOUT))
|
||||
}
|
||||
|
||||
/// The time an [`AuthDeadlineStream`] reads its deadline against: [`Instant::now`] in a server, or a time a test sets
|
||||
/// by hand.
|
||||
pub type DeadlineClock = std::sync::Arc<dyn Fn() -> Instant + Send + Sync>;
|
||||
|
||||
/// The real clock, [`Instant::now`].
|
||||
pub fn real_clock() -> DeadlineClock {
|
||||
std::sync::Arc::new(Instant::now)
|
||||
}
|
||||
|
||||
/// A read wrapper that fails once [`AUTH_DEADLINE`] passes without [`Self::authenticated`] being
|
||||
/// called, whatever the client sends meanwhile; after that only [`IO_TIMEOUT`] applies.
|
||||
#[derive(Debug)]
|
||||
pub struct AuthDeadlineStream {
|
||||
inner: std::net::TcpStream,
|
||||
deadline: Option<std::time::Instant>,
|
||||
clock: DeadlineClock,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AuthDeadlineStream {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AuthDeadlineStream").field("inner", &self.inner).field("deadline", &self.deadline).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthDeadlineStream {
|
||||
/// Wraps `inner`; reads fail once `auth_deadline` has passed unauthenticated.
|
||||
pub fn new(inner: std::net::TcpStream, auth_deadline: Duration) -> Self {
|
||||
Self::with_clock(inner, auth_deadline, real_clock())
|
||||
}
|
||||
|
||||
/// [`Self::new`] with the deadline read against `clock` instead of the real clock.
|
||||
pub fn with_clock(inner: std::net::TcpStream, auth_deadline: Duration, clock: DeadlineClock) -> Self {
|
||||
// A limit too large to represent expires at once rather than never.
|
||||
let now = Instant::now();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)) }
|
||||
let now = clock();
|
||||
Self { inner, deadline: Some(now.checked_add(auth_deadline).unwrap_or(now)), clock }
|
||||
}
|
||||
|
||||
/// The handshake succeeded: lift the deadline and restore the idle timeout.
|
||||
@@ -513,7 +533,7 @@ impl AuthDeadlineStream {
|
||||
impl std::io::Read for AuthDeadlineStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(deadline) = self.deadline {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let left = deadline.saturating_duration_since((self.clock)());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time"));
|
||||
}
|
||||
|
||||
@@ -170,6 +170,37 @@ fn server_token_sources_and_validation() {
|
||||
);
|
||||
}
|
||||
|
||||
// An unauthenticated connection's reads succeed while its deadline is ahead, however much it sends, and fail once the
|
||||
// deadline has passed even with input waiting; after `authenticated` the deadline no longer applies.
|
||||
#[trial]
|
||||
fn the_authentication_deadline_holds_whatever_the_client_sends() {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (server, _) = listener.accept().unwrap();
|
||||
server.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let start = Instant::now();
|
||||
let at = std::sync::Arc::new(std::sync::Mutex::new(start));
|
||||
let read_at = std::sync::Arc::clone(&at);
|
||||
let clock: DeadlineClock = std::sync::Arc::new(move || *read_at.lock().unwrap());
|
||||
let mut stream = AuthDeadlineStream::with_clock(server.try_clone().unwrap(), Duration::from_secs(10), clock);
|
||||
let mut byte = [0];
|
||||
// Blank lines and partial frames, each read while the deadline is ahead.
|
||||
for (step, sent) in [b"\n", b" ", b"{", b"\n"].into_iter().enumerate() {
|
||||
*at.lock().unwrap() = start + Duration::from_secs(3 * step as u64);
|
||||
client.write_all(sent).unwrap();
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "read {step} is before the deadline");
|
||||
}
|
||||
*at.lock().unwrap() = start + Duration::from_secs(10);
|
||||
client.write_all(b"\n").unwrap();
|
||||
let late = stream.read(&mut byte).unwrap_err();
|
||||
assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "the input sent did not move the deadline: {late}");
|
||||
|
||||
stream.authenticated().unwrap();
|
||||
*at.lock().unwrap() = start + Duration::from_secs(60);
|
||||
assert_eq!(stream.read(&mut byte).unwrap(), 1, "an authenticated connection reads past the deadline");
|
||||
}
|
||||
|
||||
// A token file create that runs out of time fails with its own error, even when it left a file at
|
||||
// the path: that file is not read as another process's. A create that another process beat to the
|
||||
// path reads that process's token.
|
||||
|
||||
@@ -16,8 +16,8 @@ use serde_json::{Value, json};
|
||||
use crate::control::{ControlRequest, REPLY_DEADLINE};
|
||||
use crate::protocol::write_reply;
|
||||
use crate::security::{
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
|
||||
read_bounded_line, repeat_auth_reply,
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, DeadlineClock, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake,
|
||||
configure_stream, read_bounded_line, real_clock, repeat_auth_reply,
|
||||
};
|
||||
|
||||
/// A running control server. Dropping it stops accepting connections and returns once the port is
|
||||
@@ -72,6 +72,36 @@ pub fn serve_with_deadline(
|
||||
host: WindowHost,
|
||||
auth_deadline: Duration,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
serve_with(listener, token, host, ServeOptions { auth_deadline, ..ServeOptions::default() })
|
||||
}
|
||||
|
||||
/// What a test sets on a server [`serve_with`] starts.
|
||||
#[doc(hidden)]
|
||||
pub struct ServeOptions {
|
||||
/// How long a connection has to authenticate ([`AUTH_DEADLINE`] in [`serve`]).
|
||||
pub auth_deadline: Duration,
|
||||
/// The clock the authentication deadline is read against.
|
||||
pub clock: DeadlineClock,
|
||||
/// Sent `()` each time a connection has ended: its request sender is dropped and its place under
|
||||
/// [`MAX_CONNECTIONS`] is free again.
|
||||
pub ended: Option<Sender<()>>,
|
||||
}
|
||||
|
||||
impl Default for ServeOptions {
|
||||
fn default() -> Self {
|
||||
Self { auth_deadline: AUTH_DEADLINE, clock: real_clock(), ended: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// [`serve`] with the authentication deadline, its clock and a signal for each ended connection set by a test.
|
||||
#[doc(hidden)]
|
||||
pub fn serve_with(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
host: WindowHost,
|
||||
options: ServeOptions,
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
let ServeOptions { auth_deadline, clock, ended } = options;
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let addr = listener.local_addr()?;
|
||||
// `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept
|
||||
@@ -95,13 +125,19 @@ pub fn serve_with_deadline(
|
||||
let tx = tx.clone();
|
||||
let host = host.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let clock = Arc::clone(&clock);
|
||||
let ended = ended.clone();
|
||||
std::thread::spawn(move || {
|
||||
serve_connection(stream, &token, &tx, &host, auth_deadline);
|
||||
serve_connection(stream, &token, &tx, &host, auth_deadline, clock);
|
||||
drop(tx);
|
||||
// What the last client held down would otherwise stay held with no one left to
|
||||
// release it; while another connection is live, its input is left alone.
|
||||
if permit.release() {
|
||||
host.end_injection();
|
||||
}
|
||||
if let Some(ended) = ended {
|
||||
let _ = ended.send(());
|
||||
}
|
||||
});
|
||||
}
|
||||
})?;
|
||||
@@ -110,12 +146,12 @@ pub fn serve_with_deadline(
|
||||
|
||||
/// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of
|
||||
/// connecting, however much it sends meanwhile; after that only the idle timeout applies.
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration) {
|
||||
fn serve_connection(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration, clock: DeadlineClock) {
|
||||
if configure_stream(&stream).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::with_clock(read, auth_deadline, clock));
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::agents::AgentLinkStatus;
|
||||
@@ -17,7 +17,6 @@ use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::testing::Fixture;
|
||||
use craft_ui::testing::trial;
|
||||
@@ -29,16 +28,40 @@ fn temp_dir(tag: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir")
|
||||
}
|
||||
|
||||
/// Waits up to five seconds for `done`.
|
||||
fn wait_for(mut done: impl FnMut() -> bool) -> bool {
|
||||
let started = motion::now();
|
||||
while !done() {
|
||||
if started.elapsed() > Duration::from_secs(5) {
|
||||
return false;
|
||||
/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns once the thread has
|
||||
/// finished it and waits for the next.
|
||||
struct Ticks {
|
||||
tick: mpsc::SyncSender<()>,
|
||||
waiting: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
impl Ticks {
|
||||
/// The clock and the `tick` to give [`AgentSwitch::watch_with`].
|
||||
fn new() -> (Self, impl FnMut() -> bool + Send + 'static) {
|
||||
let (tick, ticks) = mpsc::sync_channel(0);
|
||||
let (waits, waiting) = mpsc::channel();
|
||||
let wait = move || {
|
||||
let _ = waits.send(());
|
||||
ticks.recv().is_ok()
|
||||
};
|
||||
(Self { tick, waiting }, wait)
|
||||
}
|
||||
|
||||
/// Blocks until the watch thread waits for its next poll; `false` once the thread has ended.
|
||||
fn waiting(&self) -> bool {
|
||||
// A hang guard only: the thread answers at once, so the limit is never reached by a run that works.
|
||||
match self.waiting.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => false,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"),
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
|
||||
/// Runs one poll; `false` when the thread ended in it instead of waiting for the next one.
|
||||
fn poll(&self) -> bool {
|
||||
self.tick.send(()).unwrap();
|
||||
self.waiting()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent.
|
||||
@@ -52,8 +75,8 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() {
|
||||
assert!(!AgentSwitch::fixed(false, true).allows(false));
|
||||
}
|
||||
|
||||
/// The switch follows the launcher's list within a poll, wakes the app once per change rather than once per poll, and
|
||||
/// its thread ends once the last clone is dropped.
|
||||
/// The switch follows the launcher's list at the next poll, wakes the app once per change rather than once per poll,
|
||||
/// and its thread ends at the first poll after the last clone is dropped.
|
||||
#[trial]
|
||||
fn the_switch_wakes_once_per_change() {
|
||||
let launcher = Arc::new(AtomicBool::new(false));
|
||||
@@ -72,28 +95,35 @@ fn the_switch_wakes_once_per_change() {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let (ticks, tick) = Ticks::new();
|
||||
let switch = AgentSwitch::watch_with(true, probe, tick, wake);
|
||||
let clone = switch.clone();
|
||||
assert!(ticks.waiting());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start");
|
||||
|
||||
launcher.store(true, Ordering::Relaxed);
|
||||
assert!(wait_for(|| clone.launcher()), "the switch follows the launcher");
|
||||
assert!(ticks.poll());
|
||||
assert!(clone.launcher(), "the switch follows the launcher");
|
||||
assert!(switch.allows(false));
|
||||
// Many polls with nothing changed.
|
||||
let polled = probes.load(Ordering::Relaxed);
|
||||
assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10));
|
||||
for _ in 0..10 {
|
||||
assert!(ticks.poll());
|
||||
}
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll");
|
||||
launcher.store(false, Ordering::Relaxed);
|
||||
assert!(wait_for(|| !switch.launcher()));
|
||||
assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2));
|
||||
assert!(ticks.poll());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll");
|
||||
|
||||
drop(switch);
|
||||
assert!(ticks.poll(), "a clone keeps the watch");
|
||||
drop(clone);
|
||||
// The thread sees the switch gone at its next poll and stops probing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let after_drop = probes.load(Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch");
|
||||
// The thread probes once more, sees the switch gone and ends, so nothing probes after it.
|
||||
assert!(!ticks.poll(), "the watch ended with the last switch");
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
/// A published connection reads back in its documented shape, and only the process that wrote it removes it.
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_automation::client::ControlClient;
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error};
|
||||
use craft_automation::protocol::MAX_RESPONSE_BYTES;
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
use craft_automation::server;
|
||||
use craft_automation::server::{self, ServeOptions};
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::testing::trial;
|
||||
@@ -101,39 +102,90 @@ fn host() -> WindowHost {
|
||||
/// sent is dispatched.
|
||||
#[trial]
|
||||
fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
// A short deadline, so the test does not wait out the real one.
|
||||
let deadline = Duration::from_millis(400);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bound");
|
||||
let (rx, server) = server::serve_with_deadline(listener, TOKEN.into(), host(), deadline).expect("started");
|
||||
// Blank lines and partial frames, one byte every 20 ms: each read succeeds long before the idle timeout.
|
||||
let start = motion::now();
|
||||
let at = Arc::new(Mutex::new(start));
|
||||
let read_at = Arc::clone(&at);
|
||||
let (ended, connection_ended) = channel();
|
||||
// Each read of the clock is announced, so the test moves it only after the connection has set its deadline.
|
||||
let (read, clock_read) = channel();
|
||||
let clock = Arc::new(move || {
|
||||
let now = *read_at.lock().expect("the clock");
|
||||
let _ = read.send(());
|
||||
now
|
||||
});
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(10), clock, ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
let started = motion::now();
|
||||
let mut closed = false;
|
||||
for i in 0..1000 {
|
||||
let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " };
|
||||
if stream.write_all(byte).is_err() {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let served = started.elapsed();
|
||||
assert!(closed, "the trickle did not keep the connection open");
|
||||
assert!(served < deadline + Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
clock_read.recv_timeout(Duration::from_secs(5)).expect("the connection set its deadline");
|
||||
// Blank lines and the start of a line, sent while the deadline is ahead: none is a frame the handshake refuses.
|
||||
stream.write_all(b"\n \n ").expect("written");
|
||||
*at.lock().expect("the clock") = start + Duration::from_secs(10);
|
||||
// The server may already have closed when this is written; if not, it wakes the server's read.
|
||||
let _ = stream.write_all(b" ");
|
||||
assert!(is_closed(&mut reader), "the input sent did not keep the connection open past the deadline");
|
||||
assert!(nothing_more_dispatched(&rx, server, &connection_ended, 1), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error.
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, or an error other than a timeout.
|
||||
/// A server that closes with input still unread makes the kernel send a reset, so the read fails with
|
||||
/// `ConnectionReset` or `ConnectionAborted` instead of returning the end of the stream (mostly on Windows).
|
||||
fn is_closed(reader: &mut impl BufRead) -> bool {
|
||||
let mut line = String::new();
|
||||
matches!(reader.read_line(&mut line), Ok(0))
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(read) => read == 0,
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader whose every read fails with the given error kind.
|
||||
struct Failing(std::io::ErrorKind);
|
||||
|
||||
impl std::io::Read for Failing {
|
||||
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reset or aborted connection counts as closed; a read timeout does not.
|
||||
#[trial]
|
||||
fn a_reset_connection_counts_as_closed() {
|
||||
use std::io::ErrorKind::{ConnectionAborted, ConnectionReset, TimedOut, WouldBlock};
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionReset))), "a reset is a close");
|
||||
assert!(is_closed(&mut BufReader::new(Failing(ConnectionAborted))), "an abort is a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(TimedOut))), "a timeout is not a close");
|
||||
assert!(!is_closed(&mut BufReader::new(Failing(WouldBlock))), "a timeout is not a close");
|
||||
}
|
||||
|
||||
/// A server whose `ended` receiver gets `()` each time one of its connections has ended. Its clock stands still, so no
|
||||
/// connection reaches the authentication deadline: only the client or a refusal ends one. The frozen clock does not
|
||||
/// stop the socket's read timeout, which runs on real time and is the time left to the deadline capped at the idle
|
||||
/// timeout. The deadline is a minute, so a waiting connection's read times out after the 30-second idle timeout
|
||||
/// instead of after 10 seconds.
|
||||
fn serve_counting_ends() -> (Receiver<ControlRequest>, server::Listening, Receiver<()>) {
|
||||
let (ended, connection_ended) = channel();
|
||||
let start = motion::now();
|
||||
let options = ServeOptions { auth_deadline: Duration::from_secs(60), clock: Arc::new(move || start), ended: Some(ended) };
|
||||
let (rx, server) = server::serve_with(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), options).expect("started");
|
||||
(rx, server, connection_ended)
|
||||
}
|
||||
|
||||
/// Stops `server` and waits for its `connections` connections to end, so the request receiver `rx` is disconnected
|
||||
/// once every request that reached it has been taken: `rx` then answers whether anything more was dispatched.
|
||||
fn nothing_more_dispatched(rx: &Receiver<ControlRequest>, server: server::Listening, ended: &Receiver<()>, connections: usize) -> bool {
|
||||
drop(server);
|
||||
for _ in 0..connections {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a connection ended");
|
||||
}
|
||||
rx.recv_timeout(Duration::from_secs(5)).err() == Some(RecvTimeoutError::Disconnected)
|
||||
}
|
||||
|
||||
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
|
||||
/// the open ones ends, its place serves a new connection.
|
||||
#[trial]
|
||||
fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let connect = || {
|
||||
let stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
@@ -150,20 +202,14 @@ fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
|
||||
drop(open.pop());
|
||||
// The server frees the place when it reads the close; a new connection is served once it has.
|
||||
let started = motion::now();
|
||||
let served = loop {
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let reply = read_json(&mut reader).expect("a reply");
|
||||
if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) {
|
||||
break reply;
|
||||
}
|
||||
assert_eq!(reply["error"], "connection limit reached", "{reply}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("the closed connection ended");
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let served = read_json(&mut reader).expect("a reply");
|
||||
assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
drop((stream, reader));
|
||||
drop(open);
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, MAX_CONNECTIONS), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the
|
||||
@@ -191,9 +237,8 @@ fn a_refused_first_frame_closes_the_connection() {
|
||||
/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app.
|
||||
#[trial]
|
||||
fn a_browser_post_never_reaches_the_app() {
|
||||
// Far longer than the trial, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60))
|
||||
.expect("started");
|
||||
// The server's clock stands still, so the close comes from the refusal, not the deadline.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
@@ -211,7 +256,8 @@ fn a_browser_post_never_reaches_the_app() {
|
||||
Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut),
|
||||
};
|
||||
assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "nothing reached the app");
|
||||
}
|
||||
|
||||
/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed.
|
||||
@@ -325,19 +371,19 @@ fn the_documented_capture_client_sends_setup_steps_and_capture() {
|
||||
let mut client = ControlClient::connect(addr, TOKEN).expect("connected");
|
||||
capture_state(&mut client, &client_doc, &client_doc["states"][0], "new")
|
||||
});
|
||||
let mut channel = ControlChannel::new(requests);
|
||||
// Each request is waited for as it arrives and then taken through the channel, as the app's frame takes it.
|
||||
let (forward, forwarded) = channel();
|
||||
let mut channel = ControlChannel::new(forwarded);
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
let started = motion::now();
|
||||
while seen.len() < 4 && started.elapsed() < Duration::from_secs(10) {
|
||||
while let Some(req) = channel.next_request() {
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
while seen.len() < 4 {
|
||||
forward.send(requests.recv_timeout(Duration::from_secs(10)).expect("a request")).expect("forwarded");
|
||||
let req = channel.next_request().expect("the forwarded request is dispatched");
|
||||
seen.push(format!("{} {}", req.method, req.params));
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::from_result(Ok(json!({"path": req.params["path"], "width": 1280, "height": 800}))),
|
||||
_ => Reply::from_result(Ok(Value::Null)),
|
||||
};
|
||||
channel.settle(req, reply, None, 0.0);
|
||||
}
|
||||
let reply = client.join().expect("client ran").expect("the capture replied");
|
||||
assert_eq!(
|
||||
@@ -440,12 +486,12 @@ fn a_repeated_auth_is_answered_already_authenticated_without_dispatching() {
|
||||
/// and shut its end down) still reaches the app and is answered: a client cannot know it was dropped.
|
||||
#[trial]
|
||||
fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("the request reached the app");
|
||||
assert_eq!(req.method, "test.once");
|
||||
req.reply.send(json!({"ok": true, "result": "once"})).expect("replied");
|
||||
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "it ran exactly once");
|
||||
rx
|
||||
});
|
||||
let (mut stream, mut reader) = authenticated(server.addr);
|
||||
stream.write_all(json!({"id": 3, "method": "test.once"}).to_string().as_bytes()).expect("written");
|
||||
@@ -454,7 +500,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
assert_eq!((&reply["id"], &reply["result"]), (&json!(3), &json!("once")));
|
||||
let mut rest = String::new();
|
||||
assert_eq!(reader.read_line(&mut rest).expect("closed, not timed out"), 0, "closed after the last request: {rest:?}");
|
||||
handler.join().expect("handler ran");
|
||||
let rx = handler.join().expect("handler ran");
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1), "it ran exactly once");
|
||||
}
|
||||
|
||||
/// Ported from WordCraft (#7317). Connections that never authenticate cannot fill the server: past the limit a new
|
||||
@@ -462,9 +509,8 @@ fn a_complete_json_request_at_eof_can_reach_the_app() {
|
||||
#[trial]
|
||||
fn idle_unauthenticated_connections_are_limited() {
|
||||
use craft_automation::security::MAX_CONNECTIONS;
|
||||
// Far longer than the trial, so only the limit refuses.
|
||||
let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60))
|
||||
.expect("started");
|
||||
// The server's clock stands still, so only the limit refuses.
|
||||
let (rx, server, ended) = serve_counting_ends();
|
||||
let idle: Vec<TcpStream> = (0..MAX_CONNECTIONS).map(|_| TcpStream::connect(server.addr).expect("connected")).collect();
|
||||
// Admission is counted by the accept thread: it is done once the next connection is answered.
|
||||
let refused = |addr| {
|
||||
@@ -477,18 +523,14 @@ fn idle_unauthenticated_connections_are_limited() {
|
||||
assert!(reply["error"].as_str().is_some_and(|e| e.contains("limit")), "{reply}");
|
||||
drop(idle);
|
||||
// The freed slots go back as the closed connections are noticed.
|
||||
let started = motion::now();
|
||||
loop {
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
// A refused connection may already be closed when the request is written (Windows resets it).
|
||||
let auth = json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}});
|
||||
if writeln!(stream, "{auth}").is_ok() && read_json(&mut reader).is_some_and(|r| r["ok"] == true) {
|
||||
break;
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "no slot came back");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
ended.recv_timeout(Duration::from_secs(5)).expect("a closed connection ended");
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["ok"], true, "a freed slot is admitted again");
|
||||
drop((stream, reader));
|
||||
assert!(nothing_more_dispatched(&rx, server, &ended, 1));
|
||||
}
|
||||
@@ -101,10 +101,12 @@ impl RulerUnits {
|
||||
(position - zero) * self.per_doc
|
||||
}
|
||||
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers;
|
||||
/// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a
|
||||
/// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them
|
||||
/// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler).
|
||||
/// The least and most decimals a ruler writes a tick of labelled step `step` with.
|
||||
///
|
||||
/// Whole ticks are whole numbers; a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under
|
||||
/// [`TickLabels::Distance`] a smaller step takes at least two (PhotoCraft's `0.50`), more when it has them
|
||||
/// (0.025), and every tick takes them all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a
|
||||
/// sixteenth-inch ruler).
|
||||
pub fn label_decimals(&self, step: f64) -> RangeInclusive<usize> {
|
||||
let most = match self.ticks {
|
||||
Ticks::Decimal { whole: true } => 0,
|
||||
|
||||
@@ -449,8 +449,9 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = column.groups.remove(group);
|
||||
let part = !column.groups.is_empty();
|
||||
let id = self.drop_if_empty(&place);
|
||||
return Ok(Moving { id, ..Moving::taken(taken, source) });
|
||||
return Ok(Moving { id, part, ..Moving::taken(taken, source) });
|
||||
};
|
||||
if let Some(Node::Stack { entries }) = self.node_of_mut(&place)
|
||||
&& entries.len() > 1
|
||||
@@ -478,14 +479,14 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving { column: taken, id: None })
|
||||
Ok(Moving { column: taken, id: None, part: false })
|
||||
}
|
||||
Some(PanelPlace::Floating { window, .. }) => {
|
||||
if window >= self.floating.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = self.floating.remove(window);
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) })
|
||||
Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false })
|
||||
}
|
||||
Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement),
|
||||
}
|
||||
@@ -500,7 +501,8 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating,
|
||||
/// keeps the moving column's state; groups that join a column take that column's.
|
||||
/// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column
|
||||
/// take that column's.
|
||||
/// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]).
|
||||
pub(super) fn insert_moving(&mut self, moving: Moving<P>, to: Target<P>, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> {
|
||||
let mut moving = moving;
|
||||
@@ -517,7 +519,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
Some(id) => id,
|
||||
None => self.fresh_window_id(),
|
||||
};
|
||||
let window = Floating::new(id, Column { width: None, ..moving.column }, rect);
|
||||
let window = Floating::new(id, moving.into_window_column(), rect);
|
||||
let edge = edge.filter(|_| window.column.iconic);
|
||||
self.floating.push(Floating { edge, ..window });
|
||||
Ok(())
|
||||
|
||||
@@ -330,12 +330,14 @@ pub(super) enum Unit {
|
||||
}
|
||||
|
||||
/// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or
|
||||
/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they
|
||||
/// join keeps its own.
|
||||
/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a
|
||||
/// collapsed column stays icons); a column they join keeps its own.
|
||||
pub(super) struct Moving<P> {
|
||||
pub column: Column<P>,
|
||||
/// The id of a floating window whose last group is in transit, which a new window keeps.
|
||||
pub id: Option<u64>,
|
||||
/// Panels stay in the column the groups left, so a new column made of them is expanded.
|
||||
pub part: bool,
|
||||
}
|
||||
|
||||
impl<P> Moving<P> {
|
||||
@@ -344,14 +346,26 @@ impl<P> Moving<P> {
|
||||
Self::taken(group, Column::new(Vec::new()))
|
||||
}
|
||||
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]).
|
||||
/// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column.
|
||||
pub(super) fn taken(group: Group<P>, source: Column<P>) -> Self {
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None }
|
||||
Self { column: Column { groups: vec![group], ..source }, id: None, part: false }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width.
|
||||
/// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it.
|
||||
pub(super) fn panel(panel: P, source: (Column<P>, bool)) -> Self {
|
||||
let (column, part) = source;
|
||||
Self { part, ..Self::taken(Group::new(vec![panel], 0), column) }
|
||||
}
|
||||
|
||||
/// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_window_column(self) -> Column<P> {
|
||||
Column { width: None, iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
|
||||
/// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and
|
||||
/// expanded when it is part of a collapsed one.
|
||||
pub(super) fn into_column(self, width: Option<f32>) -> Column<P> {
|
||||
Column { width: self.column.width.or(width), ..self.column }
|
||||
Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
let source = self.source_of(&panel);
|
||||
// A panel the layout does not hold opens in the new window.
|
||||
let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None });
|
||||
let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) };
|
||||
let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) };
|
||||
self.insert_moving(moving, Target::Float { rect, edge: None }, canvas)
|
||||
}
|
||||
Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel),
|
||||
@@ -72,7 +72,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
let entry = StackEntry { panel, open: true, height: None };
|
||||
if let Some(anchor) = anchor {
|
||||
self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas)
|
||||
} else if self.root.is_none() {
|
||||
self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 });
|
||||
Ok(())
|
||||
@@ -89,7 +89,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
{
|
||||
return Err(DockError::MissingTarget);
|
||||
}
|
||||
self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas)
|
||||
self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas)
|
||||
}
|
||||
Action::MoveFloating { panel, rect, edge } => {
|
||||
if !valid_rect(rect) {
|
||||
@@ -142,7 +142,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
to => {
|
||||
let source = self.source_of(&panel);
|
||||
let entry = self.take(&panel).ok_or(DockError::MissingPanel)?;
|
||||
self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas)
|
||||
self.insert_moving(Moving::panel(entry.panel, source), to, canvas)
|
||||
}
|
||||
},
|
||||
Action::Restore { panel, location } => {
|
||||
@@ -256,9 +256,11 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
}
|
||||
|
||||
/// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel
|
||||
/// outside a column or absent.
|
||||
pub(super) fn source_of(&self, panel: &P) -> Column<P> {
|
||||
self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place))
|
||||
/// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]).
|
||||
pub(super) fn source_of(&self, panel: &P) -> (Column<P>, bool) {
|
||||
let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) };
|
||||
let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel));
|
||||
(self.source_column(&place), part)
|
||||
}
|
||||
|
||||
/// The accordion entry of `panel` in the docked tree.
|
||||
@@ -327,7 +329,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
pub(super) fn insert(
|
||||
&mut self,
|
||||
entry: StackEntry<P>,
|
||||
source: Column<P>,
|
||||
source: (Column<P>, bool),
|
||||
anchor: &P,
|
||||
placement: DockPlacement<P>,
|
||||
canvas: &dyn Fn(&P) -> bool,
|
||||
@@ -338,8 +340,7 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
.filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_)))
|
||||
.map(<[bool]>::to_vec)
|
||||
else {
|
||||
let moving = Moving::taken(Group::new(vec![entry.panel], 0), source);
|
||||
return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas);
|
||||
};
|
||||
let root = self.root.as_mut().ok_or(DockError::MissingTarget)?;
|
||||
if let DockPlacement::Split(zone) = placement
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
/// The longest step motion integrates, in seconds, so a stalled pass never jumps the view.
|
||||
pub const FRAME_STEP_MAX: f64 = 0.1;
|
||||
|
||||
/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the
|
||||
/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number.
|
||||
/// The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`.
|
||||
///
|
||||
/// `dt` is the time between two readings of the caller's pass clock; where it is not a number, the step is 0.
|
||||
pub fn frame_step(dt: f64) -> f64 {
|
||||
if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 }
|
||||
}
|
||||
@@ -148,8 +148,9 @@ impl CropBox {
|
||||
(w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0)))
|
||||
}
|
||||
|
||||
/// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is
|
||||
/// not a number counts as one unit).
|
||||
/// Whether both sides are at least `min`, and never under one document unit whatever `min` says.
|
||||
///
|
||||
/// A `min` that is not a number counts as one unit.
|
||||
pub fn size_ok(&self, min: f64) -> bool {
|
||||
let min = min.max(MIN_FRAME);
|
||||
self.rect.width() >= min && self.rect.height() >= min
|
||||
@@ -544,7 +545,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9;
|
||||
const PHI: f64 = 1.0 + INV_PHI;
|
||||
|
||||
/// The composition guide drawn inside a crop frame, in Photoshop's menu order.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum CropGuide {
|
||||
@@ -727,7 +728,7 @@ fn golden_spiral() -> Vec<[f64; 2]> {
|
||||
}
|
||||
|
||||
/// When the guide shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum GuideShow {
|
||||
|
||||
@@ -310,7 +310,7 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
|
||||
assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window");
|
||||
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
moved.apply(Action::move_column(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap();
|
||||
let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap();
|
||||
assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near");
|
||||
let mut moved = columns();
|
||||
@@ -356,10 +356,21 @@ fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width()
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own");
|
||||
|
||||
let source = Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_width(300.0).with_iconic(true);
|
||||
let target = Column::new(vec![g(&[7], 0)]).with_iconic(true);
|
||||
let mut layout = Layout::new(
|
||||
Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::dock(DockEdge::Start, vec![target]), Node::dock(DockEdge::End, vec![source]))),
|
||||
vec![],
|
||||
);
|
||||
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
|
||||
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from a collapsed column of its own width keeps its flyout width");
|
||||
}
|
||||
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a
|
||||
/// column float in its state; groups joining a column, docked or floating, take that column's state.
|
||||
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; a whole column
|
||||
/// leaving floats in its state, and part of a collapsed column floats expanded; groups joining a column, docked or
|
||||
/// floating, take that column's state.
|
||||
#[test]
|
||||
fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() {
|
||||
let mut layout = columns();
|
||||
@@ -369,15 +380,24 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides
|
||||
layout.apply(Action::set_iconic(6, false)).unwrap();
|
||||
assert_eq!(layout.panel_state(&6), PanelState::Front);
|
||||
|
||||
for action in [
|
||||
Action::move_column(3, Target::float(window())),
|
||||
Action::move_group(3, Target::float(window())),
|
||||
Action::move_panel(3, Target::float(window())),
|
||||
] {
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_column(3, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "the whole collapsed column floats as icons");
|
||||
for action in [Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] {
|
||||
let mut moved = columns();
|
||||
moved.apply(action.clone()).unwrap();
|
||||
assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons");
|
||||
assert!(floats(&moved, 3) && !column_of(&moved, 3).iconic, "{action:?} out of a column with another group floats expanded");
|
||||
assert!(column_of(&moved, 4).iconic, "the column it left stays collapsed");
|
||||
moved.apply(Action::move_group(4, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 4) && column_of(&moved, 4).iconic, "the column's last group floats as icons");
|
||||
}
|
||||
let mut tabbed = Layout::new(None, vec![Floating::new(102, Column::new(vec![g(&[3, 4, 5], 0)]).with_iconic(true), window())]);
|
||||
tabbed.apply(Action::move_panel(3, Target::float(window()))).unwrap();
|
||||
assert!(!column_of(&tabbed, 3).iconic, "a tab out of a collapsed column's only group floats expanded");
|
||||
tabbed.apply(Action::move_panel(5, Target::new_dock(DockEdge::End))).unwrap();
|
||||
assert!(!column_of(&tabbed, 5).iconic, "a tab out of a collapsed column docks expanded");
|
||||
tabbed.apply(Action::move_panel(4, Target::new_dock(DockEdge::Start))).unwrap();
|
||||
assert!(column_of(&tabbed, 4).iconic, "the column's last panel docks as icons");
|
||||
let mut moved = columns();
|
||||
moved.apply(Action::move_group(2, Target::float(window()))).unwrap();
|
||||
assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded");
|
||||
|
||||
@@ -146,10 +146,10 @@ pub fn parse(text: &str) -> Result<Document> {
|
||||
Some(end_bracket) => stripped[end_bracket + 1..].trim_start(),
|
||||
None => trimmed_rem,
|
||||
}
|
||||
} else if let Some(space_idx) = trimmed_rem.find(' ') {
|
||||
let first_token = &trimmed_rem[..space_idx];
|
||||
} else if let Some(separator) = trimmed_rem.find(char::is_whitespace) {
|
||||
let first_token = &trimmed_rem[..separator];
|
||||
if first_token.starts_with('D') && first_token[1..].chars().all(|c| c.is_ascii_digit()) {
|
||||
trimmed_rem[space_idx + 1..].trim_start()
|
||||
trimmed_rem[separator..].trim_start()
|
||||
} else {
|
||||
trimmed_rem
|
||||
}
|
||||
@@ -218,6 +218,13 @@ mod tests {
|
||||
assert_eq!(written, jss);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_after_directive_keeps_only_the_subtitle_text() {
|
||||
let doc = parse("0:00:01.00 0:00:03.00 D0\tFirst\tline\n").unwrap();
|
||||
assert_eq!(doc.cues.len(), 1);
|
||||
assert_eq!(doc.cues[0].text, "First\tline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_bracketed_directive() {
|
||||
let jss = "#TimeRes 100\n0:00:01.00 0:00:03.00 [Style1] Bracketed style text\n";
|
||||
|
||||
@@ -351,7 +351,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option<Format> {
|
||||
if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) {
|
||||
return Some(Format::SubViewer);
|
||||
}
|
||||
if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) {
|
||||
if !first_lines.is_empty()
|
||||
&& head.lines().map(str::trim_start).filter(|line| !line.trim().is_empty()).take(3).all(|line| vplayer::split_line(line).is_some())
|
||||
{
|
||||
return Some(Format::VPlayer);
|
||||
}
|
||||
if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) {
|
||||
|
||||
+91
-20
@@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option<FrameRate>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caption text as the tag parser sees it: one byte at a time, counted in tests.
|
||||
mod reader {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Calls to [`Reader::byte`] on this thread (tests: the tag parser's work is linear in the text).
|
||||
pub(super) static READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The bytes of a caption text, read only through [`Reader::byte`].
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn new(bytes: &'a [u8]) -> Self {
|
||||
Self { bytes }
|
||||
}
|
||||
|
||||
/// The byte at `index`, or `None` past the end.
|
||||
pub(super) fn byte(self, index: usize) -> Option<u8> {
|
||||
#[cfg(test)]
|
||||
READS.with(|r| r.set(r.get().saturating_add(1)));
|
||||
self.bytes.get(index).copied()
|
||||
}
|
||||
|
||||
/// The bytes from `start` to the end, each read through [`Reader::byte`].
|
||||
pub(super) fn suffix(self, start: usize) -> Suffix<'a> {
|
||||
Suffix { reader: self, next: start }
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator returned by [`Reader::suffix`].
|
||||
pub(super) struct Suffix<'a> {
|
||||
reader: Reader<'a>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Iterator for Suffix<'_> {
|
||||
type Item = u8;
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let c = self.reader.byte(self.next)?;
|
||||
self.next = self.next.saturating_add(1);
|
||||
Some(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use reader::Reader;
|
||||
|
||||
/// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned.
|
||||
#[derive(Default)]
|
||||
struct QuoteCache {
|
||||
@@ -121,7 +172,7 @@ struct QuoteCache {
|
||||
|
||||
impl QuoteCache {
|
||||
/// Index of the next `quote` byte at or after `from`.
|
||||
fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option<usize> {
|
||||
fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option<usize> {
|
||||
let slot = usize::from(quote == b'\'');
|
||||
if let Some((searched, result)) = self.found[slot]
|
||||
&& searched <= from
|
||||
@@ -129,7 +180,7 @@ impl QuoteCache {
|
||||
{
|
||||
return result;
|
||||
}
|
||||
let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i);
|
||||
let result = bytes.suffix(from).position(|c| c == quote).map(|i| from + i);
|
||||
self.found[slot] = Some((from, result));
|
||||
result
|
||||
}
|
||||
@@ -139,42 +190,42 @@ impl QuoteCache {
|
||||
/// letters/digits starting with a letter immediately after, then whitespace-separated
|
||||
/// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted
|
||||
/// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag.
|
||||
fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
fn parse_tag(bytes: Reader<'_>, start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> {
|
||||
let mut i = start + 1;
|
||||
let closing = bytes.get(i) == Some(&b'/');
|
||||
let closing = bytes.byte(i) == Some(b'/');
|
||||
if closing {
|
||||
i += 1;
|
||||
}
|
||||
let name_start = i;
|
||||
if !bytes.get(i)?.is_ascii_alphabetic() {
|
||||
if !bytes.byte(i)?.is_ascii_alphabetic() {
|
||||
return None;
|
||||
}
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) {
|
||||
let mut name = String::new();
|
||||
while let Some(c) = bytes.byte(i).filter(u8::is_ascii_alphanumeric) {
|
||||
name.push(char::from(c.to_ascii_lowercase()));
|
||||
i += 1;
|
||||
}
|
||||
let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase();
|
||||
loop {
|
||||
let ws_start = i;
|
||||
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
i += 1;
|
||||
}
|
||||
match bytes.get(i)? {
|
||||
match bytes.byte(i)? {
|
||||
b'>' => return Some((i + 1, closing, name)),
|
||||
// self-closing: no markup
|
||||
b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())),
|
||||
b'/' if !closing && bytes.byte(i + 1) == Some(b'>') => return Some((i + 2, closing, String::new())),
|
||||
_ => {}
|
||||
}
|
||||
if i == ws_start {
|
||||
return None;
|
||||
}
|
||||
let key_start = i;
|
||||
while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
while bytes.byte(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) {
|
||||
i += 1;
|
||||
}
|
||||
if i == key_start || bytes.get(i) != Some(&b'=') {
|
||||
if i == key_start || bytes.byte(i) != Some(b'=') {
|
||||
return None;
|
||||
}
|
||||
let quote = *bytes.get(i + 1)?;
|
||||
let quote = bytes.byte(i + 1)?;
|
||||
if quote != b'"' && quote != b'\'' {
|
||||
return None;
|
||||
}
|
||||
@@ -204,10 +255,11 @@ fn inline(text: &str) -> String {
|
||||
};
|
||||
let mut rest = text;
|
||||
let mut cache = QuoteCache::default();
|
||||
let bytes = Reader::new(text.as_bytes());
|
||||
while !rest.is_empty() {
|
||||
// Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "a<b and c>d" are text.
|
||||
if rest.starts_with('<')
|
||||
&& let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache)
|
||||
&& let Some((end, closing, name)) = parse_tag(bytes, text.len() - rest.len(), &mut cache)
|
||||
{
|
||||
let attr = match name.as_str() {
|
||||
"i" => Some("tts:fontStyle=\"italic\""),
|
||||
@@ -1171,15 +1223,34 @@ mod tests {
|
||||
assert_eq!(out, "<span tts:fontStyle=\"italic\">x</span>");
|
||||
}
|
||||
|
||||
/// `inline(text)` and the number of bytes the tag parser read for it.
|
||||
fn inline_cost(text: &str) -> (String, usize) {
|
||||
reader::READS.with(|r| r.set(0));
|
||||
let out = inline(text);
|
||||
(out, reader::READS.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// The tag parser reads each byte of `text` a bounded number of times, and twice the text costs about twice the work.
|
||||
fn assert_linear(make: impl Fn(usize) -> String, escaped: impl Fn(usize) -> String) {
|
||||
let (out, small) = inline_cost(&make(50_000));
|
||||
assert_eq!(out, escaped(50_000));
|
||||
let text = make(100_000);
|
||||
let (out, large) = inline_cost(&text);
|
||||
assert_eq!(out, escaped(100_000));
|
||||
assert!(large <= 3 * text.len(), "{large} byte reads in a text of {}", text.len());
|
||||
assert!(large < 3 * small, "twice the text, {small} then {large} byte reads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclosed_angle_brackets_are_escaped_in_one_pass() {
|
||||
// Every `<` used to search the rest of the text for a `>`, which made this quadratic.
|
||||
let text = "<".repeat(200_000);
|
||||
let started = std::time::Instant::now();
|
||||
let out = inline(&text);
|
||||
assert_eq!(out, "<".repeat(200_000));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert_linear(|n| "<".repeat(n), |n| "<".repeat(n));
|
||||
// A tag before the unclosed tail is still markup; the tail stays literal text.
|
||||
assert_eq!(inline("<i>a</i> 1 < 2"), "<span tts:fontStyle=\"italic\">a</span> 1 < 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_unmatched_angle_brackets_before_one_gt_are_read_once() {
|
||||
assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n)));
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ pub fn parse(text: &str) -> Result<Document> {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
match split_line(line.trim()) {
|
||||
match split_line(line.trim_start()) {
|
||||
Some((t, raw)) => {
|
||||
let lines: Vec<String> = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect();
|
||||
starts.push((t, lines.join("\n")));
|
||||
@@ -121,6 +121,38 @@ pub fn write(doc: &Document) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_clearing_lines_keep_each_separator() {
|
||||
for separator in [":", "=", " "] {
|
||||
for indent in ["", " \t"] {
|
||||
let input = format!("{indent}00:00:01{separator} hello \n{indent}00:00:02{separator} \n");
|
||||
assert_eq!(crate::detect(input.as_bytes(), None), Some(crate::Format::VPlayer), "{input:?}");
|
||||
let doc = parse(&input).unwrap();
|
||||
assert_eq!(doc.cues.len(), 1, "{input:?}");
|
||||
assert_eq!(doc.cues[0].text, "hello", "{input:?}");
|
||||
assert_eq!(doc.cues[0].end, ms_to_tick(2000), "{input:?}");
|
||||
assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_keeps_clearing_lines_at_each_sampled_position() {
|
||||
for separator in [":", "=", " "] {
|
||||
for at in 0..3 {
|
||||
let mut lines = ["00:00:01=one".to_owned(), "00:00:02=two".to_owned(), "00:00:03=three".to_owned()];
|
||||
lines[at] = format!(" \t00:00:0{}{separator} \t", at + 1);
|
||||
let input = format!("\u{feff}\n \t\n{}\n", lines.join("\n"));
|
||||
let format = crate::detect(input.as_bytes(), None).unwrap();
|
||||
assert_eq!(format, crate::Format::VPlayer, "{input:?}");
|
||||
let document = crate::parse(input.as_bytes(), format).unwrap();
|
||||
assert_eq!(document.cues.len(), 2, "{input:?}");
|
||||
assert!(document.warnings.is_empty(), "{:?}", document.warnings);
|
||||
}
|
||||
}
|
||||
assert_eq!(crate::detect(b"00:00:01 hello\n00:00:02\n", None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_duration_cue_preserves_positive_duration_on_write_and_read() {
|
||||
let mut doc = Document::default();
|
||||
|
||||
@@ -66,11 +66,10 @@ fn whitespace_after_lt_is_literal_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The work for this text is checked in `ttml.rs`'s `many_unmatched_angle_brackets_before_one_gt_are_read_once`.
|
||||
#[test]
|
||||
fn many_unmatched_lt_is_fast() {
|
||||
fn many_unmatched_lt_stay_text() {
|
||||
let input = format!("{}>", "<".repeat(256_000));
|
||||
let start = std::time::Instant::now();
|
||||
let text = export(&input, Format::Ttml);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed());
|
||||
assert!(text.contains(&format!("{}>", "<".repeat(256_000))));
|
||||
}
|
||||
+22
-11
@@ -2,7 +2,7 @@
|
||||
|
||||
The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15
|
||||
files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer
|
||||
(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each
|
||||
(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each
|
||||
field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a
|
||||
cited id has no row here.
|
||||
|
||||
@@ -56,9 +56,16 @@ Sources:
|
||||
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs,
|
||||
was read for the order of fields that the notes do not spell out (the table entries, the rendering
|
||||
attributes and the curve body); no code was copied from it
|
||||
- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h`
|
||||
and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`,
|
||||
https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp,
|
||||
https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h
|
||||
and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h,
|
||||
read for the header's offsets, the index chunks and the fields of a color entry; no code was
|
||||
copied from it
|
||||
|
||||
Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks
|
||||
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
|
||||
confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows;
|
||||
listed so it can be checked against a file, with what the reader does when it is wrong). The
|
||||
"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test
|
||||
files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and
|
||||
@@ -129,7 +136,7 @@ file is committed.
|
||||
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
|
||||
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
|
||||
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
|
||||
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
|
||||
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
|
||||
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
|
||||
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample |
|
||||
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
|
||||
@@ -148,24 +155,26 @@ file is committed.
|
||||
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
|
||||
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
|
||||
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
|
||||
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
|
||||
|
||||
## Written fields
|
||||
|
||||
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
|
||||
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
|
||||
the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the
|
||||
index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in
|
||||
their page, layer and group records, and the bounds they keep in layer and group records are not
|
||||
written: no public source describes
|
||||
them, and the reader finds every chunk by its id and walks the instructions in order.
|
||||
the synthetic test files of `src/synth_cmx.rs` set it.
|
||||
|
||||
| Field written | Rows | Status |
|
||||
|---|---|---|
|
||||
| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample |
|
||||
| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) |
|
||||
| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) |
|
||||
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
|
||||
| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) |
|
||||
| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) |
|
||||
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
|
||||
| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) |
|
||||
| `rlst` for each page: its layers' numbers | R77 | sample |
|
||||
| Table counts and field lists | R55 | sample |
|
||||
| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) |
|
||||
| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) |
|
||||
| `rpen` field 1: the width | R57 | public-notes |
|
||||
| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own |
|
||||
@@ -177,9 +186,11 @@ them, and the reader finds every chunk by its id and walks the instructions in o
|
||||
| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample |
|
||||
| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) |
|
||||
| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) |
|
||||
| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample |
|
||||
| Begin page, field 4: the page's width and height | R61 | public-notes |
|
||||
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) |
|
||||
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) |
|
||||
| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes |
|
||||
| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) |
|
||||
| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) |
|
||||
| End layer, group and page with no fields | R60 | own (the bodies are not read) |
|
||||
| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) |
|
||||
| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) |
|
||||
+15
-8
@@ -107,12 +107,17 @@ corners, not stretched ones. Hidden layers, groups and shapes, guide and grid la
|
||||
and master layers are left out; opacity, blend modes, fill rules and locked states are not
|
||||
written, desktop layers are written as drawing layers, and a spot color with no name opens as a
|
||||
process color; every use of a named spot color takes the look of its use at the strongest tint
|
||||
among the uses whose look is known.
|
||||
among the uses whose look is known. Each color entry holds the color twice: as the property list
|
||||
`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In
|
||||
those fields a spot color is written as its look at its tint, and the registration color as 100
|
||||
percent cyan, magenta, yellow and black.
|
||||
|
||||
`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width
|
||||
past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than
|
||||
65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a
|
||||
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks,
|
||||
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit
|
||||
of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one
|
||||
group, more chunks,
|
||||
objects, coordinates or dashes than a read within the limits takes, a file longer than their input
|
||||
size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes
|
||||
rounded to whole outline widths, nonzero fills that may fill differently, names that open
|
||||
@@ -120,12 +125,14 @@ shortened, spot colors at a tint too low to keep their look, with no name or wit
|
||||
(written black), uses of one ink with different looks, and what was left out or written opaque,
|
||||
unclipped or unlocked.
|
||||
|
||||
The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
|
||||
inside page, layer and group records, and the bounds inside layer and group records are not
|
||||
written, so a reader must find the chunks by their ids and walk the instructions in order, as
|
||||
`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page
|
||||
when it has none. `PROVENANCE.md`'s "Written
|
||||
fields" table lists every field the `.cmx` writer sets.
|
||||
The file holds an index, so that a reader that finds the tables and pages through it, rather than
|
||||
by their chunk ids, opens it: the header gives where the master index starts, the index list
|
||||
(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page,
|
||||
layer and group records give their instruction counts. A page's record also gives where its
|
||||
end-page instruction starts, and a group's record gives where the instruction after its end-group
|
||||
instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or
|
||||
of the page when it has none. The header repeats the first page's edges and instruction count.
|
||||
`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets.
|
||||
|
||||
## Writing
|
||||
|
||||
|
||||
+347
-67
@@ -2,8 +2,8 @@
|
||||
//! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and
|
||||
//! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for
|
||||
//! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines
|
||||
//! (R63). `PROVENANCE.md`'s "Written fields" lists every field the writer sets and where its layout
|
||||
//! comes from.
|
||||
//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written
|
||||
//! fields" lists every field the writer sets and where its layout comes from.
|
||||
//!
|
||||
//! Rectangles and ellipses are written as curves. A clipping container is written as a group of
|
||||
//! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes,
|
||||
@@ -130,28 +130,58 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
|
||||
children.push(c);
|
||||
Ok(())
|
||||
};
|
||||
add(chunk(b"cont", &cont())?)?;
|
||||
for (n, page) in drawing.pages.iter().enumerate() {
|
||||
add(w.page(n, page.size.or(drawing.page_size), &page.layers)?)?;
|
||||
// The header's index offset is set once the index is placed.
|
||||
add(chunk(b"cont", &cont(0, PageHead::default()))?)?;
|
||||
// Each page chunk and its reference list, with where they start in the file and the start and
|
||||
// name of each of the page's layers.
|
||||
let mut pages = Vec::new();
|
||||
let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> {
|
||||
let at = w.file_bytes;
|
||||
let (c, written, head) = w.page(n, size, layers)?;
|
||||
add(c)?;
|
||||
let refs = w.file_bytes;
|
||||
let r = chunk(b"rlst", &reference_list(written.len()))?;
|
||||
w.check_bytes(r.len())?;
|
||||
w.file_bytes += r.len();
|
||||
add(r)?;
|
||||
pages.push(PageAt { at, refs, layers: written, head });
|
||||
Ok(())
|
||||
};
|
||||
for (n, p) in drawing.pages.iter().enumerate() {
|
||||
page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?;
|
||||
}
|
||||
// A drawing with no pages but a page size is written as one empty page of that size.
|
||||
if drawing.pages.is_empty() && drawing.page_size.is_some() {
|
||||
add(w.page(0, drawing.page_size, &[])?)?;
|
||||
page(&mut w, 0, drawing.page_size, &[])?;
|
||||
}
|
||||
// The reader also counts every chunk (`cont`, the pages and the seven tables), every table entry
|
||||
// and the one arrowhead pair.
|
||||
let pages = if drawing.pages.is_empty() { usize::from(drawing.page_size.is_some()) } else { drawing.pages.len() };
|
||||
// The reader leaves out a list as deep as its depth limit, and the index is a list.
|
||||
if w.limits.depth == 0 {
|
||||
return Err(Error::Limit("nesting depth"));
|
||||
}
|
||||
// The reader also counts every chunk (`cont`, each page and its reference list, the seven
|
||||
// tables, and the index list with its three chunks and a layer table for each page), every
|
||||
// table entry and the one arrowhead pair.
|
||||
let t = &w.tables;
|
||||
let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1;
|
||||
w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + pages + 7 + entries);
|
||||
let index_chunks = pages.len().saturating_add(4);
|
||||
w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks);
|
||||
w.read_cost.check(&w.limits)?;
|
||||
// Where each table chunk starts, by its id.
|
||||
let mut tables = Vec::new();
|
||||
let mut at = w.file_bytes;
|
||||
for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? {
|
||||
let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?;
|
||||
tables.push((id, at));
|
||||
at = at.saturating_add(c.len());
|
||||
add(c)?;
|
||||
}
|
||||
let (list, ixmr) = index(at, &pages, &tables)?;
|
||||
add(list)?;
|
||||
let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?;
|
||||
if total > w.limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
}
|
||||
children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?;
|
||||
bytes.extend(b"RIFF");
|
||||
@@ -190,16 +220,124 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
}
|
||||
|
||||
/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64
|
||||
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files; the rest are zeros.
|
||||
fn cont() -> Vec<u8> {
|
||||
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file
|
||||
/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the
|
||||
/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and
|
||||
/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros.
|
||||
fn cont(ixmr: u32, first: PageHead) -> Vec<u8> {
|
||||
let mut c = vec![0u8; 180];
|
||||
c[48] = b'2';
|
||||
c[52] = b'4';
|
||||
c[54] = b'2';
|
||||
c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes());
|
||||
c[84..88].copy_from_slice(&ixmr.to_le_bytes());
|
||||
c[88..96].fill(0xFF);
|
||||
for (i, v) in first.edges.iter().enumerate() {
|
||||
c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
c[112..116].copy_from_slice(&first.instructions.to_le_bytes());
|
||||
c
|
||||
}
|
||||
|
||||
/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom
|
||||
/// edges and its instruction count, begin and end page included.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct PageHead {
|
||||
edges: [i32; 4],
|
||||
instructions: u32,
|
||||
}
|
||||
|
||||
/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name.
|
||||
type LayerAt = (usize, Vec<u8>);
|
||||
|
||||
/// Where a page's chunks start in the file, and its layers.
|
||||
struct PageAt {
|
||||
at: usize,
|
||||
/// The page's reference list `rlst`.
|
||||
refs: usize,
|
||||
layers: Vec<LayerAt>,
|
||||
/// What the header repeats of its begin-page record.
|
||||
head: PageHead,
|
||||
}
|
||||
|
||||
/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16
|
||||
/// values 2 and 9 and its number.
|
||||
fn reference_list(layers: usize) -> Vec<u8> {
|
||||
let mut r = (layers as u16).to_le_bytes().to_vec();
|
||||
for n in 1..=layers {
|
||||
r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// A file offset as the u32 the index stores.
|
||||
fn offset(at: usize) -> Result<u32, Error> {
|
||||
u32::try_from(at).map_err(|_| Error::Limit("chunk size"))
|
||||
}
|
||||
|
||||
/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each
|
||||
/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with
|
||||
/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id.
|
||||
fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec<u8>, u32), Error> {
|
||||
let mut body = b"indx".to_vec();
|
||||
// Where the next chunk of the list starts.
|
||||
let next = |body: &Vec<u8>| at.saturating_add(8).saturating_add(body.len());
|
||||
let mut layer_tables = Vec::with_capacity(pages.len());
|
||||
for (n, p) in pages.iter().enumerate() {
|
||||
layer_tables.push(next(&body));
|
||||
// The layer count and the page number, then for each layer the size of its record before
|
||||
// the 0xFFFFFFFF that ends it, its begin-layer instruction and its name.
|
||||
let mut t = (p.layers.len() as u16).to_le_bytes().to_vec();
|
||||
t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes());
|
||||
for (start, name) in &p.layers {
|
||||
t.extend(((8 + name.len()) as u16).to_le_bytes());
|
||||
t.extend(offset(*start)?.to_le_bytes());
|
||||
t.extend((name.len() as u16).to_le_bytes());
|
||||
t.extend(name);
|
||||
t.extend(u32::MAX.to_le_bytes());
|
||||
}
|
||||
body.extend(chunk(b"ixlr", &t)?);
|
||||
}
|
||||
// The table of layer tables: their count, the size of each record, the type 3 and the offsets.
|
||||
let ixtl = next(&body);
|
||||
let mut t = (pages.len() as u16).to_le_bytes().to_vec();
|
||||
t.extend(4u16.to_le_bytes());
|
||||
t.extend(3u16.to_le_bytes());
|
||||
for l in &layer_tables {
|
||||
t.extend(offset(*l)?.to_le_bytes());
|
||||
}
|
||||
body.extend(chunk(b"ixtl", &t)?);
|
||||
// The page index: the page count, then for each page the size of its record, its page chunk,
|
||||
// its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference
|
||||
// list.
|
||||
let ixpg = next(&body);
|
||||
let mut t = (pages.len() as u16).to_le_bytes().to_vec();
|
||||
for (p, l) in pages.iter().zip(&layer_tables) {
|
||||
t.extend(16u16.to_le_bytes());
|
||||
for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] {
|
||||
t.extend(v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
body.extend(chunk(b"ixpg", &t)?);
|
||||
// The master index: the values 1 and 24, the entry count, then an id and an offset for itself,
|
||||
// the page index, the table of layer tables and each table.
|
||||
let ixmr = next(&body);
|
||||
let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)];
|
||||
let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)];
|
||||
for (id, n) in ids {
|
||||
if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) {
|
||||
entries.push((n, *start));
|
||||
}
|
||||
}
|
||||
let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat();
|
||||
for (n, start) in entries {
|
||||
t.extend(n.to_le_bytes());
|
||||
t.extend(offset(start)?.to_le_bytes());
|
||||
}
|
||||
body.extend(chunk(b"ixmr", &t)?);
|
||||
Ok((chunk(b"LIST", &body)?, offset(ixmr)?))
|
||||
}
|
||||
|
||||
/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the
|
||||
/// data does not fit the length.
|
||||
fn field(tag: u8, data: &[u8]) -> Option<Vec<u8>> {
|
||||
@@ -397,9 +535,25 @@ fn color_key(c: &Color) -> ColorKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32
|
||||
/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the
|
||||
/// values; R14), and for a named color part 3, a u32 count and UTF-16 units.
|
||||
/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5,
|
||||
/// then four value bytes. A spot color is written as its look at its tint in red, green and blue,
|
||||
/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the
|
||||
/// models of these fields hold neither.
|
||||
fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) {
|
||||
let [v0, v1, v2, v3] = k.values;
|
||||
match k.model {
|
||||
2 => (2, [v0, v1, v2, v3]),
|
||||
// Red, green and blue, where the color record holds blue, green and red.
|
||||
5 | 21 => (5, [v2, v1, v0, 0]),
|
||||
9 => (9, [v0, 0, 0, 0]),
|
||||
_ => (2, [100; 4]),
|
||||
}
|
||||
}
|
||||
|
||||
/// A color entry (R56): field 1 the model and the palette, field 2 the values, as
|
||||
/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8
|
||||
/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes,
|
||||
/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units.
|
||||
fn color_entry(k: &ColorKey) -> Result<Vec<u8>, Error> {
|
||||
let mut list = vec![1u8];
|
||||
list.extend(12u32.to_le_bytes());
|
||||
@@ -416,7 +570,9 @@ fn color_entry(k: &ColorKey) -> Result<Vec<u8>, Error> {
|
||||
}
|
||||
let mut rec = (list.len() as u32).to_le_bytes().to_vec();
|
||||
rec.extend(list);
|
||||
Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?]))
|
||||
let (model, values) = older_fields(k);
|
||||
let size = || Error::Limit("table entry size");
|
||||
Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?]))
|
||||
}
|
||||
|
||||
/// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file.
|
||||
@@ -462,8 +618,14 @@ struct Writer {
|
||||
looks: HashMap<String, [f32; 3]>,
|
||||
/// The comparisons [`may_fill_differently`] may still make.
|
||||
crossing_budget: u64,
|
||||
/// The groups open where the next instruction is written.
|
||||
open_groups: usize,
|
||||
/// The groups open where the next instruction is written, outermost first.
|
||||
open_groups: Vec<OpenGroup>,
|
||||
/// The instructions written on the current page, its begin-page instruction included.
|
||||
instructions: usize,
|
||||
/// For each group closed on the current page, where its end offset goes in the page's
|
||||
/// instructions after the begin-page instruction, and the offset there, both counted from the
|
||||
/// end of the begin-page instruction.
|
||||
group_ends: Vec<(usize, usize)>,
|
||||
/// The smallest and largest x and y the curves written on the current page reach, in
|
||||
/// coordinate units.
|
||||
bounds: Option<[i32; 4]>,
|
||||
@@ -585,10 +747,17 @@ impl Writer {
|
||||
self.tables.colors.index(key)
|
||||
}
|
||||
|
||||
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60).
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<Vec<u8>, Error> {
|
||||
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60),
|
||||
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and
|
||||
/// what the header repeats of the begin-page record. The chunk starts at the file offset
|
||||
/// [`Writer::file_bytes`] gives.
|
||||
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>, PageHead), Error> {
|
||||
let mut out = Vec::new();
|
||||
self.bounds = None;
|
||||
self.instructions = 1;
|
||||
self.group_ends.clear();
|
||||
// Where each layer's begin-layer instruction starts in `out`, and its 8-bit name.
|
||||
let mut starts = Vec::new();
|
||||
// The model holds layers and objects front to back; the file lists them back to front.
|
||||
let mut written = 0;
|
||||
for layer in layers.iter().rev() {
|
||||
@@ -604,19 +773,43 @@ impl Writer {
|
||||
// The reader also stops a layer's name at its first NUL and takes a blank name as none.
|
||||
let name = &layer.name;
|
||||
self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty());
|
||||
out.extend(instr(BEGIN_LAYER, &layer_fields(n, written, &layer.name)?));
|
||||
let body = layer_fields(n, written, &layer.name)?;
|
||||
let begin = instr(BEGIN_LAYER, &body);
|
||||
// The layer's instruction count goes at bytes 8 to 12 of field 1, after the
|
||||
// instruction's header and the field's tag and length.
|
||||
let count_at = out.len() + begin.len() - body.len() + 3 + 8;
|
||||
let first = self.instructions;
|
||||
starts.push((out.len(), narrow_name(&layer.name)));
|
||||
out.extend(begin);
|
||||
self.instructions += 1;
|
||||
written += 1;
|
||||
self.objects(&layer.objects, &mut out)?;
|
||||
out.extend(instr(END_LAYER, &[]));
|
||||
self.instructions += 1;
|
||||
put_u32(&mut out, count_at, self.instructions - first)?;
|
||||
self.read_cost.chunks += 2;
|
||||
self.read_cost.check(&self.limits)?;
|
||||
self.check_bytes(out.len())?;
|
||||
}
|
||||
let end = out.len();
|
||||
out.extend(instr(END_PAGE, &[]));
|
||||
self.instructions += 1;
|
||||
// The begin and end page instructions.
|
||||
self.read_cost.chunks += 2;
|
||||
self.read_cost.check(&self.limits)?;
|
||||
let begin = begin_page(n, size, self.bounds.take())?;
|
||||
let bounds = self.bounds.take();
|
||||
let begin_len = begin_page(n, size, bounds, PageTail::default())?.len();
|
||||
// The page's instructions after the begin-page instruction start here in the file.
|
||||
let base = self.file_bytes.saturating_add(8).saturating_add(begin_len);
|
||||
let tail = PageTail {
|
||||
end: offset(base.saturating_add(end))?,
|
||||
layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?,
|
||||
instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?,
|
||||
};
|
||||
for (at, end) in std::mem::take(&mut self.group_ends) {
|
||||
put_u32(&mut out, at, base.saturating_add(end))?;
|
||||
}
|
||||
let begin = begin_page(n, size, bounds, tail)?;
|
||||
if u32::try_from(begin.len() + out.len()).is_err() {
|
||||
return Err(Error::Limit("chunk size"));
|
||||
}
|
||||
@@ -624,8 +817,9 @@ impl Writer {
|
||||
page.extend(out);
|
||||
let c = chunk(b"page", &page)?;
|
||||
self.check_bytes(c.len())?;
|
||||
let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect();
|
||||
self.file_bytes += c.len();
|
||||
Ok(c)
|
||||
Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions }))
|
||||
}
|
||||
|
||||
/// An [`Error::Limit`] when the file would be longer than the input size of the limits with
|
||||
@@ -657,7 +851,7 @@ impl Writer {
|
||||
self.shape(&s, out)?;
|
||||
}
|
||||
if ends {
|
||||
self.end_group(out);
|
||||
self.end_group(out)?;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
@@ -699,20 +893,55 @@ impl Writer {
|
||||
/// Begin a group. A group inside as many groups as the reader opens (the depth of the
|
||||
/// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds.
|
||||
fn begin_group(&mut self, out: &mut Vec<u8>) -> Result<(), Error> {
|
||||
if self.open_groups >= self.limits.depth {
|
||||
if self.open_groups.len() >= self.limits.depth {
|
||||
return Err(Error::Limit("nesting depth"));
|
||||
}
|
||||
self.open_groups += 1;
|
||||
if let Some(parent) = self.open_groups.last_mut() {
|
||||
parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?;
|
||||
}
|
||||
self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None });
|
||||
out.extend(group());
|
||||
self.instructions += 1;
|
||||
self.read_cost.chunks += 1;
|
||||
self.read_cost.objects += 1;
|
||||
self.read_cost.check(&self.limits)
|
||||
}
|
||||
|
||||
fn end_group(&mut self, out: &mut Vec<u8>) {
|
||||
self.open_groups = self.open_groups.saturating_sub(1);
|
||||
/// End the innermost open group, and fill in its begin-group record (R77): the edges of its
|
||||
/// curves (all 0 when it has none), the groups directly inside it, its instructions from begin
|
||||
/// to end, and where the instruction after its end starts, which [`Writer::page`] places in
|
||||
/// the file.
|
||||
fn end_group(&mut self, out: &mut Vec<u8>) -> Result<(), Error> {
|
||||
out.extend(instr(END_GROUP, &[]));
|
||||
self.instructions += 1;
|
||||
self.read_cost.chunks += 1;
|
||||
let Some(g) = self.open_groups.pop() else { return Ok(()) };
|
||||
if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) {
|
||||
parent.bounds = Some(match parent.bounds {
|
||||
Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])],
|
||||
None => b,
|
||||
});
|
||||
}
|
||||
// Field 1's data starts after the instruction's 4-byte header and the field's tag and
|
||||
// length.
|
||||
let data = g.at + 4 + 3;
|
||||
let [x0, y0, x1, y1] = g.bounds.unwrap_or_default();
|
||||
for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() {
|
||||
out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes());
|
||||
put_u32(out, data + 18, self.instructions - g.first)?;
|
||||
self.group_ends.push((data + 22, out.len()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost
|
||||
/// open group's edges.
|
||||
fn reach(&mut self, e: [i32; 4]) {
|
||||
for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() {
|
||||
let b = b.get_or_insert(e);
|
||||
*b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])];
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape as one curve, or as a group of curves when its path holds more than
|
||||
@@ -802,9 +1031,7 @@ impl Writer {
|
||||
_ => [p.x, p.y, p.x, p.y],
|
||||
};
|
||||
// Within the anchors and control points, which are i32, so the casts keep them.
|
||||
let (x0, y0, x1, y1) = (x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32);
|
||||
let b = self.bounds.get_or_insert([x0, y0, x1, y1]);
|
||||
*b = [b[0].min(x0), b[1].min(y0), b[2].max(x1), b[3].max(y1)];
|
||||
self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]);
|
||||
}
|
||||
g.extend(c.iter().map(|(_, t)| *t));
|
||||
bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?);
|
||||
@@ -815,10 +1042,11 @@ impl Writer {
|
||||
let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()]));
|
||||
self.check_bytes(out.len().saturating_add(i.len()))?;
|
||||
out.extend(i);
|
||||
self.instructions += 1;
|
||||
}
|
||||
}
|
||||
if curves.len() > 1 {
|
||||
self.end_group(out);
|
||||
self.end_group(out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -912,41 +1140,61 @@ impl Writer {
|
||||
}
|
||||
}
|
||||
|
||||
/// A group open where the next instruction is written.
|
||||
struct OpenGroup {
|
||||
/// Where its begin-group instruction starts in the page's instructions after the begin-page
|
||||
/// instruction.
|
||||
at: usize,
|
||||
/// The page's instructions written before it.
|
||||
first: usize,
|
||||
/// The groups directly inside it so far.
|
||||
groups: u16,
|
||||
/// The smallest and largest x and y its curves reach so far, in coordinate units.
|
||||
bounds: Option<[i32; 4]>,
|
||||
}
|
||||
|
||||
/// What begin page keeps of the rest of the page (R77).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct PageTail {
|
||||
/// The file offset of the end-page instruction.
|
||||
end: u32,
|
||||
/// The layers on the page.
|
||||
layers: u16,
|
||||
/// The page's instructions, begin and end page included.
|
||||
instructions: u32,
|
||||
}
|
||||
|
||||
/// Write `v` as a u32 at `at` of `out`.
|
||||
fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> {
|
||||
let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?;
|
||||
out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left,
|
||||
/// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y),
|
||||
/// or of the page around its center when it has no art; field 4 its width and height. Without a
|
||||
/// size the edges are all 0, which the reader takes as no size.
|
||||
fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<Vec<u8>, Error> {
|
||||
/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and
|
||||
/// height. Without a size the edges are all 0, which the reader takes as no size.
|
||||
fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result<Vec<u8>, Error> {
|
||||
let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?;
|
||||
let mut d = number.to_le_bytes().to_vec();
|
||||
d.extend(0u32.to_le_bytes());
|
||||
let mut list = Vec::new();
|
||||
let mut size_field = None;
|
||||
let mut edges = [0i32; 4];
|
||||
if let Some((w, h)) = size {
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
let edges = page_edges(size, bounds)?;
|
||||
let size_field = match size {
|
||||
Some((w, h)) => {
|
||||
let mut s = width_units(w)?.to_le_bytes().to_vec();
|
||||
s.extend(width_units(h)?.to_le_bytes());
|
||||
Some(s)
|
||||
}
|
||||
edges = match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
};
|
||||
let mut s = wu.to_le_bytes().to_vec();
|
||||
s.extend(hu.to_le_bytes());
|
||||
size_field = Some(s);
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
for v in edges {
|
||||
d.extend(v.to_le_bytes());
|
||||
}
|
||||
d.extend(tail.end.to_le_bytes());
|
||||
d.extend(tail.layers.to_le_bytes());
|
||||
d.extend(tail.instructions.to_le_bytes());
|
||||
list.push(field(1, &d).ok_or(Error::Limit("page size"))?);
|
||||
if let Some(s) = size_field {
|
||||
list.push(field(4, &s).ok_or(Error::Limit("page size"))?);
|
||||
@@ -954,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> R
|
||||
Ok(instr(BEGIN_PAGE, &fields(&list)))
|
||||
}
|
||||
|
||||
/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches
|
||||
/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`].
|
||||
fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> {
|
||||
let Some((w, h)) = size else { return Ok([0; 4]) };
|
||||
// A negative or NaN side counts as 0.
|
||||
let (wu, hu) = (width_units(w)?, width_units(h)?);
|
||||
// A side that rounds to nothing would make the reader drop the page's whole size.
|
||||
if wu == 0 || hu == 0 {
|
||||
return Err(Error::Limit("page size"));
|
||||
}
|
||||
Ok(match bounds {
|
||||
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
|
||||
None => {
|
||||
// The page around its center; an odd size keeps its extra unit on the left and
|
||||
// bottom, where the edge reaches -2^31.
|
||||
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
|
||||
let (w, h) = (i64::from(wu), i64::from(hu));
|
||||
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it.
|
||||
fn windows_1252_byte(c: char) -> u8 {
|
||||
match u8::try_from(u32::from(c)) {
|
||||
@@ -962,16 +1232,26 @@ fn windows_1252_byte(c: char) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 8 zero
|
||||
/// bytes, then the name as a u16 count and 8-bit characters (Windows-1252: characters the code
|
||||
/// page has no byte for are written as `?`); field 4 the name as a u32 count and UTF-16 units.
|
||||
/// `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers is an
|
||||
/// [`Error::Limit`].
|
||||
/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written
|
||||
/// empty, so it opens with no name.
|
||||
fn blank_name(name: &str) -> bool {
|
||||
name.split('\0').next().unwrap_or_default().trim().is_empty()
|
||||
}
|
||||
|
||||
/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no
|
||||
/// byte for are written as `?`).
|
||||
fn narrow_name(name: &str) -> Vec<u8> {
|
||||
if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() }
|
||||
}
|
||||
|
||||
/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero
|
||||
/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a
|
||||
/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16
|
||||
/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers
|
||||
/// is an [`Error::Limit`].
|
||||
fn layer_fields(page: usize, n: usize, name: &str) -> Result<Vec<u8>, Error> {
|
||||
// A blank name, up to the first NUL where the reader stops, is written empty in both fields,
|
||||
// so it opens with no name.
|
||||
let blank = name.split('\0').next().unwrap_or_default().trim().is_empty();
|
||||
let narrow: Vec<u8> = if blank { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() };
|
||||
let blank = blank_name(name);
|
||||
let narrow = narrow_name(name);
|
||||
let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?;
|
||||
let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?;
|
||||
let mut d = page.to_le_bytes().to_vec();
|
||||
@@ -987,7 +1267,7 @@ fn layer_fields(page: usize, n: usize, name: &str) -> Result<Vec<u8>, Error> {
|
||||
Ok(fields(&[f1, f4]))
|
||||
}
|
||||
|
||||
/// Begin a group: field 1 of 26 zero bytes, as the test files of `synth_cmx` hold.
|
||||
/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77).
|
||||
fn group() -> Vec<u8> {
|
||||
instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()]))
|
||||
}
|
||||
|
||||
+15
-7
@@ -133,8 +133,9 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
/// width, or a page side that rounds to 0;
|
||||
/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash
|
||||
/// patterns or outlines, or a dash pattern of more than 32,765 lengths;
|
||||
/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or
|
||||
/// dashes than a read within `limits` takes;
|
||||
/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out
|
||||
/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects,
|
||||
/// coordinates or dashes than a read within `limits` takes;
|
||||
/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds.
|
||||
///
|
||||
/// [`Written`] reports what the file holds differently from the drawing; its fields name each
|
||||
@@ -142,11 +143,18 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
/// written with round corners of its radii times the square root of the scales' product, not with
|
||||
/// stretched corners, and is not reported.
|
||||
///
|
||||
/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
|
||||
/// inside page, layer and group records, and the bounds inside layer and group records are not
|
||||
/// written, so a reader must find the chunks by their ids and walk the instructions in order, as
|
||||
/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the
|
||||
/// page when it has none.
|
||||
/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the
|
||||
/// model and value fields that other readers read. In those fields a spot color is written as its
|
||||
/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black.
|
||||
///
|
||||
/// The file holds an index, so that a reader that finds the tables and pages through it, rather
|
||||
/// than by their chunk ids, opens it: the header gives where the master index starts, the index
|
||||
/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the
|
||||
/// page, layer and group records give their instruction counts. A page's record also gives where
|
||||
/// its end-page instruction starts, and a group's record gives where the instruction after its
|
||||
/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of
|
||||
/// its curves, or of the page when it has none. The header repeats the first page's edges and
|
||||
/// instruction count.
|
||||
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
|
||||
cmx_write::write(drawing, limits)
|
||||
}
|
||||
@@ -283,9 +283,15 @@ fn pages_are_numbered_in_their_order() {
|
||||
assert_eq!(numbers, [1, 2]);
|
||||
}
|
||||
|
||||
/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag,
|
||||
/// a u16 length counting the 3 header bytes, the data; 0xff after the last field).
|
||||
/// Field 1 of each entry of the table chunk `id`.
|
||||
fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
|
||||
table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect()
|
||||
}
|
||||
|
||||
/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and
|
||||
/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header
|
||||
/// bytes, the data; 0xff after the last field).
|
||||
fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<(u8, usize, Vec<u8>)>> {
|
||||
let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8;
|
||||
// The chunk's body runs for the size after its id.
|
||||
let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize;
|
||||
@@ -294,7 +300,7 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
|
||||
let mut p = at + 2;
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..count {
|
||||
let mut first = None;
|
||||
let mut entry = Vec::new();
|
||||
loop {
|
||||
assert!(p < end, "entry runs past the {id:?} chunk at {p}");
|
||||
if bytes[p] == 0xff {
|
||||
@@ -304,13 +310,11 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
|
||||
let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]]));
|
||||
// A length shorter than its header, or past the chunk, would stop the walk.
|
||||
assert!(len >= 3 && p + len <= end, "field at {p} has length {len}");
|
||||
if bytes[p] == 1 {
|
||||
first = Some(bytes[p + 3..p + len].to_vec());
|
||||
}
|
||||
entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec()));
|
||||
p += len;
|
||||
}
|
||||
p += 1;
|
||||
out.push(first.expect("field 1"));
|
||||
out.push(entry);
|
||||
}
|
||||
// The size counts the u16 count and the entries; the pad byte comes after it.
|
||||
assert_eq!(p, end, "{id:?} chunk has bytes left after its entries");
|
||||
@@ -348,6 +352,61 @@ fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() {
|
||||
assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_are_also_written_in_the_model_and_value_fields() {
|
||||
let colors = [
|
||||
Color::Rgb([1.0, 0.2, 0.0]),
|
||||
Color::Cmyk([0.6, 0.0, 0.13, 0.05]),
|
||||
Color::Gray(0.75),
|
||||
Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) },
|
||||
Color::Registration,
|
||||
];
|
||||
let objects = colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None))))
|
||||
.collect();
|
||||
let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]);
|
||||
let mut bytes = write_cmx(&d).unwrap().bytes;
|
||||
let entries = table_fields(&bytes, b"rclr");
|
||||
// Each entry holds the model and the palette 5 in field 1 and four values in field 2, before
|
||||
// the property list of field 10.
|
||||
let mut older: Vec<(Vec<u8>, Vec<u8>)> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::<Vec<_>>(), [1, 2, 10]);
|
||||
(e[0].2.clone(), e[1].2.clone())
|
||||
})
|
||||
.collect();
|
||||
older.sort();
|
||||
let mut want = vec![
|
||||
// Red, green and blue.
|
||||
(vec![5, 5], vec![255, 51, 0, 0]),
|
||||
// Cyan, magenta, yellow and black in percent.
|
||||
(vec![2, 5], vec![60, 0, 13, 5]),
|
||||
// Gray, 255 white.
|
||||
(vec![9, 5], vec![64, 0, 0, 0]),
|
||||
// The spot color's look at its tint of 40 percent.
|
||||
(vec![5, 5], vec![153, 194, 235, 0]),
|
||||
// The registration color as every ink at 100 percent.
|
||||
(vec![2, 5], vec![100, 100, 100, 100]),
|
||||
];
|
||||
want.sort();
|
||||
assert_eq!(older, want);
|
||||
// With field 10 retagged, the reader takes each color from fields 1 and 2.
|
||||
for e in &entries {
|
||||
bytes[e[2].1] = 11;
|
||||
}
|
||||
let back = read_cmx(&bytes, Limits::default()).unwrap();
|
||||
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
|
||||
let fills: Vec<Color> = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect();
|
||||
let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])];
|
||||
assert_eq!(fills.len(), opened.len());
|
||||
for (got, want) in fills.iter().zip(&opened) {
|
||||
assert!(near_color(got, want), "{got:?} for {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() {
|
||||
let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]);
|
||||
@@ -657,7 +716,7 @@ fn a_page_without_a_size_still_writes_its_four_edges() {
|
||||
// The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length.
|
||||
assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9);
|
||||
let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]]));
|
||||
assert_eq!(len - 3, 2 + 4 + 16, "the page number, the flags and four edges");
|
||||
assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -950,6 +1009,277 @@ fn layers_give_their_page_and_their_number() {
|
||||
assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]);
|
||||
}
|
||||
|
||||
fn u16_at(b: &[u8], at: usize) -> usize {
|
||||
usize::from(u16::from_le_bytes([b[at], b[at + 1]]))
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], at: usize) -> usize {
|
||||
u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize
|
||||
}
|
||||
|
||||
/// The id of each chunk of a written file by where it starts, those inside lists included.
|
||||
fn chunk_ids(b: &[u8]) -> std::collections::HashMap<usize, [u8; 4]> {
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
let mut stack = vec![(12, b.len())];
|
||||
while let Some((mut at, end)) = stack.pop() {
|
||||
while at + 8 <= end {
|
||||
let id: [u8; 4] = b[at..at + 4].try_into().unwrap();
|
||||
let size = u32_at(b, at + 4);
|
||||
ids.insert(at, id);
|
||||
if id == *b"LIST" {
|
||||
stack.push((at + 12, at + 8 + size));
|
||||
}
|
||||
at += 8 + size + size % 2;
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where
|
||||
/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test.
|
||||
fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> {
|
||||
let mut out = Vec::new();
|
||||
while b[at] != 0xff {
|
||||
let len = u16_at(b, at + 1);
|
||||
assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}");
|
||||
out.push((b[at], at + 3));
|
||||
at += len;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a field of length 0")]
|
||||
fn a_field_of_length_0_fails_the_check() {
|
||||
field_starts(&[1, 0, 0, 0xff], 0, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a field of length 9")]
|
||||
fn a_field_past_its_instruction_fails_the_check() {
|
||||
field_starts(&[1, 9, 0, 0, 0xff], 0, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_and_the_records_give_where_everything_is() {
|
||||
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
|
||||
let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() };
|
||||
let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() };
|
||||
let pages = vec![
|
||||
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] },
|
||||
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] },
|
||||
];
|
||||
let b = write_cmx(&drawing(pages)).unwrap().bytes;
|
||||
let page_entries = page_index(&b);
|
||||
let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]);
|
||||
let (seen_layers, groups) = page_records(&b, &page_entries);
|
||||
assert_eq!(seen_layers, layer_starts);
|
||||
// The inner group: itself and a curve; the outer: two curves and the inner group.
|
||||
assert_eq!(groups, [(0, 3), (1, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_repeats_the_first_pages_edges_and_instruction_count() {
|
||||
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
|
||||
let pages = vec![
|
||||
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] },
|
||||
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] },
|
||||
];
|
||||
let b = write_cmx(&drawing(pages)).unwrap().bytes;
|
||||
let cont = 12 + 8;
|
||||
let chunk = page_index(&b)[0][0];
|
||||
let page = chunk + 8;
|
||||
// Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count
|
||||
// and the instruction count.
|
||||
let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4)));
|
||||
assert_eq!(fields[0].0, 1);
|
||||
let f1 = fields[0].1;
|
||||
assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]);
|
||||
// The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down.
|
||||
let edges: Vec<i32> = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect();
|
||||
let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32;
|
||||
assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]);
|
||||
// Begin and end page, two begin and end layers and three curves.
|
||||
assert_eq!(u32_at(&b, cont + 112), 9);
|
||||
assert_eq!(u32_at(&b, f1 + 28), 9);
|
||||
// A drawing without pages leaves them 0.
|
||||
let b = write_cmx(&drawing(Vec::new())).unwrap().bytes;
|
||||
assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0));
|
||||
}
|
||||
|
||||
/// The page index of a written file of two pages, each entry's page chunk, layer table, picture
|
||||
/// and reference list, checked through the header and the master index.
|
||||
fn page_index(b: &[u8]) -> Vec<[usize; 4]> {
|
||||
let ids = chunk_ids(b);
|
||||
let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default();
|
||||
// The header names the master index, and no information list or picture.
|
||||
let cont = 12 + 8;
|
||||
let ixmr = u32_at(b, cont + 84);
|
||||
assert_eq!(id(ixmr), "ixmr");
|
||||
assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize));
|
||||
// The master index names itself, the page index, the table of layer tables and each table.
|
||||
let m = ixmr + 8;
|
||||
assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24));
|
||||
let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect();
|
||||
let want =
|
||||
[(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")];
|
||||
assert_eq!(entries, want.map(|(n, s)| (n, s.to_string())));
|
||||
let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap());
|
||||
// The page index: each page chunk, its layer table, no picture and its reference list.
|
||||
let pg = at_of(2) + 8;
|
||||
assert_eq!(u16_at(b, pg), 2);
|
||||
let page_entries: Vec<[usize; 4]> = (0..2)
|
||||
.map(|i| {
|
||||
let e = pg + 2 + 18 * i;
|
||||
assert_eq!(u16_at(b, e), 16);
|
||||
[0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k))
|
||||
})
|
||||
.collect();
|
||||
for [page, layers, picture, refs] in &page_entries {
|
||||
assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into()));
|
||||
}
|
||||
// The table of layer tables lists each page's.
|
||||
let tl = at_of(3) + 8;
|
||||
assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]);
|
||||
assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]);
|
||||
page_entries
|
||||
}
|
||||
|
||||
/// Where each layer table of `page_entries` says the layers named `names` start, checking each
|
||||
/// table and each reference list: a layer table holds its count, the page number, then each
|
||||
/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and
|
||||
/// the number of each layer.
|
||||
fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec<usize> {
|
||||
let mut layer_starts = Vec::new();
|
||||
for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() {
|
||||
let t = entry[1] + 8;
|
||||
assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1));
|
||||
let mut at = t + 4;
|
||||
for name in *names {
|
||||
let size = u16_at(b, at);
|
||||
let start = u32_at(b, at + 2);
|
||||
let len = u16_at(b, at + 6);
|
||||
assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes()));
|
||||
assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize);
|
||||
assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction");
|
||||
layer_starts.push(start);
|
||||
at += size + 4;
|
||||
}
|
||||
let r = entry[3] + 8;
|
||||
let refs: Vec<usize> = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect();
|
||||
let want: Vec<usize> = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect();
|
||||
assert_eq!(refs, want);
|
||||
}
|
||||
layer_starts
|
||||
}
|
||||
|
||||
/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the
|
||||
/// instructions before it, the records found directly inside it and the edges of its curves.
|
||||
type Open = (usize, usize, usize, usize, Option<[i32; 4]>);
|
||||
|
||||
/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at`
|
||||
/// after `count` instructions of its page: begin page where the page ends, its layers and its
|
||||
/// instructions; begin layer its instructions; begin group the edges of its curves, then its
|
||||
/// groups and instructions, which are returned, and where the instruction after it starts.
|
||||
fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> {
|
||||
let (opened, f1, before, inside, edges) = open;
|
||||
assert_eq!(opened + 1, code);
|
||||
let instructions = count - before;
|
||||
match code {
|
||||
10 => {
|
||||
assert_eq!(u32_at(b, f1 + 22), at, "where the page ends");
|
||||
assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers");
|
||||
assert_eq!(u32_at(b, f1 + 28), instructions);
|
||||
None
|
||||
}
|
||||
12 => {
|
||||
assert_eq!(u32_at(b, f1 + 8), instructions);
|
||||
None
|
||||
}
|
||||
_ => {
|
||||
let [x0, y0, x1, y1] = edges.unwrap();
|
||||
let stored: Vec<i32> = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect();
|
||||
assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom");
|
||||
assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends");
|
||||
Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and
|
||||
/// begin-group records, and give where each begin-layer instruction starts and each group's
|
||||
/// groups and instructions, in the order the groups end.
|
||||
fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec<usize>, Vec<(usize, usize)>) {
|
||||
let mut seen_layers = Vec::new();
|
||||
let mut groups = Vec::new();
|
||||
for entry in page_entries {
|
||||
let end = entry[0] + 8 + u32_at(b, entry[0] + 4);
|
||||
let mut at = entry[0] + 8;
|
||||
let mut open: Vec<Open> = Vec::new();
|
||||
let mut count = 0;
|
||||
while at < end {
|
||||
let size = instruction_size(b, at, end);
|
||||
let code = u16_at(b, at + 2);
|
||||
count += 1;
|
||||
match code {
|
||||
9 | 11 | 13 => {
|
||||
let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1;
|
||||
if code == 11 {
|
||||
seen_layers.push(at);
|
||||
}
|
||||
// A page counts its layers and a group the groups directly inside it.
|
||||
if code != 9 {
|
||||
open.last_mut().unwrap().3 += 1;
|
||||
}
|
||||
open.push((code, f1, count - 1, 0, None));
|
||||
}
|
||||
67 => {
|
||||
let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1;
|
||||
for i in 0..u16_at(b, f2) {
|
||||
let p = f2 + 2 + 8 * i;
|
||||
let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32);
|
||||
for o in open.iter_mut().filter(|o| o.0 == 13) {
|
||||
let e = o.4.get_or_insert([x, y, x, y]);
|
||||
*e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)];
|
||||
}
|
||||
}
|
||||
}
|
||||
10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)),
|
||||
_ => {}
|
||||
}
|
||||
at += size;
|
||||
}
|
||||
}
|
||||
(seen_layers, groups)
|
||||
}
|
||||
|
||||
/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold
|
||||
/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or
|
||||
/// one past `end` fails the test.
|
||||
fn instruction_size(b: &[u8], at: usize, end: usize) -> usize {
|
||||
let size = u16_at(b, at);
|
||||
assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}");
|
||||
size
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "an instruction of size 0")]
|
||||
fn an_instruction_of_size_0_fails_the_check() {
|
||||
instruction_size(&[0, 0, 67, 0], 0, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "an instruction of size 65535")]
|
||||
fn a_long_instruction_fails_the_check() {
|
||||
instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "an instruction of size 8")]
|
||||
fn an_instruction_past_its_page_fails_the_check() {
|
||||
instruction_size(&[8, 0, 67, 0], 0, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uniform_fill_names_the_screen_the_file_holds() {
|
||||
let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes;
|
||||
|
||||
@@ -10,9 +10,8 @@ fn opts() -> TransformOptions {
|
||||
TransformOptions::default()
|
||||
}
|
||||
|
||||
/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it.
|
||||
fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 {
|
||||
let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap();
|
||||
/// L* of a CMYK colour, measured by the prebuilt transform.
|
||||
fn lightness(t: &Transform, cmyk: [f32; 4]) -> f32 {
|
||||
let mut lab = [0.0f32; 3];
|
||||
t.eval(&cmyk, &mut lab).unwrap();
|
||||
lab[0] * 100.0
|
||||
@@ -70,18 +69,22 @@ fn the_destination_black_matches_the_source_lightness() {
|
||||
for intent in [Intent::RelativeColorimetric, Intent::Perceptual] {
|
||||
for bpc in [true, false] {
|
||||
let o = TransformOptions { intent, bpc, ..opts() };
|
||||
let coated_lab = Transform::with_options(coated(), Builtin::LabD50.profile(), o).unwrap();
|
||||
let fogra_lab = Transform::with_options(fogra(), Builtin::LabD50.profile(), o).unwrap();
|
||||
// Both directions for one setting; the other settings in the forward one.
|
||||
let directions = if intent == Intent::RelativeColorimetric && bpc { 2 } else { 1 };
|
||||
for (src, dst) in [(coated(), fogra()), (fogra(), coated())].into_iter().take(directions) {
|
||||
for (src, dst, src_lab, dst_lab) in
|
||||
[(coated(), fogra(), &coated_lab, &fogra_lab), (fogra(), coated(), &fogra_lab, &coated_lab)].into_iter().take(directions)
|
||||
{
|
||||
let bp = BlackPreserving::new(src, dst, o).unwrap();
|
||||
let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]);
|
||||
let dst_black = lightness(dst_lab, [0.0, 0.0, 0.0, 1.0]);
|
||||
for k in [0.1f32, 0.5, 0.9, 1.0] {
|
||||
let want = lightness(src, o, [0.0, 0.0, 0.0, k]);
|
||||
let want = lightness(src_lab, [0.0, 0.0, 0.0, k]);
|
||||
if want <= dst_black {
|
||||
assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1");
|
||||
continue;
|
||||
}
|
||||
let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]);
|
||||
let got = lightness(dst_lab, [0.0, 0.0, 0.0, bp.map_k(k)]);
|
||||
assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}");
|
||||
}
|
||||
assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper");
|
||||
|
||||
+29
-6
@@ -361,17 +361,35 @@ fn edge_index(t: &[f32], start: bool) -> f32 {
|
||||
if start {
|
||||
let v = t[0];
|
||||
// The first value that differs, given they do so from there on.
|
||||
let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7);
|
||||
let first_other = t.partition_point(|x| {
|
||||
count_edge_read();
|
||||
(*x - v).abs() <= 1e-7
|
||||
});
|
||||
let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) };
|
||||
i as f32 / (n - 1) as f32
|
||||
} else {
|
||||
let v = t[n - 1];
|
||||
// The start of the trailing run equal to the last value.
|
||||
let i = t.partition_point(|x| (*x - v).abs() > 1e-7);
|
||||
let i = t.partition_point(|x| {
|
||||
count_edge_read();
|
||||
(*x - v).abs() > 1e-7
|
||||
});
|
||||
i as f32 / (n - 1) as f32
|
||||
}
|
||||
}
|
||||
|
||||
// Each table entry `edge_index` reads on this thread.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static EDGE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_edge_read() {
|
||||
#[cfg(test)]
|
||||
EDGE_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -381,13 +399,18 @@ mod tests {
|
||||
// Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls.
|
||||
let mut t = vec![0.0f32; 4_000_000];
|
||||
t.push(1.0);
|
||||
// Bisection reads one entry per halving of the table, and a scan reads the whole run.
|
||||
let per_call = t.len().ilog2() as usize + 2;
|
||||
let c = Curve::Table(t);
|
||||
let started = std::time::Instant::now();
|
||||
let mut last = 0.0;
|
||||
for _ in 0..200_000 {
|
||||
EDGE_READS.with(|reads| reads.set(0));
|
||||
let mut last = c.eval_inverse(0.0);
|
||||
let one_call = EDGE_READS.with(std::cell::Cell::get);
|
||||
assert!(one_call <= per_call, "one inversion read {one_call} entries");
|
||||
for _ in 1..200_000 {
|
||||
last = c.eval_inverse(0.0);
|
||||
}
|
||||
assert!(last > 0.99, "the flat start ends at the last zero: {last}");
|
||||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||||
let total = EDGE_READS.with(std::cell::Cell::get);
|
||||
assert!(total <= 200_000 * per_call, "200,000 inversions read {total} entries");
|
||||
}
|
||||
}
|
||||
@@ -901,7 +901,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn oklab_profile_has_three_tables() {
|
||||
let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() };
|
||||
let p = CmykParams { grid_a2b: 3, grid_b2a: 3, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() };
|
||||
let profile = cmyk_profile(&p).unwrap();
|
||||
let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") };
|
||||
assert!(b0 != b1 && b0 != b2, "perceptual shares a table");
|
||||
|
||||
@@ -7,3 +7,8 @@ Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, sample
|
||||
Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`).
|
||||
|
||||
The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`.
|
||||
|
||||
`ColorPanel::edited` can supply a colour's native components. Editing one channel preserves the other components,
|
||||
even when the host renders the colour through a different working-space transform. Current host components take
|
||||
precedence over the panel's remembered values. Canceling a channel gesture restores the host's complete opening
|
||||
colour, including its display colour, alpha and native components.
|
||||
@@ -4,7 +4,7 @@ use craft_behavior::{Metrics, Mixed, PartKey, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, Outcome, PaintUi, PartsCx, Props as _, Role};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, WellFill};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TypeRole};
|
||||
use egui::{CornerRadius, Rect, Response, Vec2, pos2};
|
||||
@@ -83,6 +83,7 @@ pub struct CompareSwatch<'a> {
|
||||
new: Mixed<Srgba>,
|
||||
current: Mixed<Srgba>,
|
||||
warnings: &'a [ColorWarning],
|
||||
no_current: bool,
|
||||
restore: bool,
|
||||
warning: Option<usize>,
|
||||
}
|
||||
@@ -90,7 +91,23 @@ pub struct CompareSwatch<'a> {
|
||||
impl<'a> CompareSwatch<'a> {
|
||||
/// A block named `label` ("New color", the new half's name) showing `new` over `current`.
|
||||
pub fn new(label: impl Into<Label>, new: impl Into<Mixed<Srgba>>, current: impl Into<Mixed<Srgba>>) -> Self {
|
||||
CompareSwatch { common: Common::new(), new: new.into(), current: current.into(), warnings: &[], restore: false, warning: None }.label(label)
|
||||
CompareSwatch {
|
||||
common: Common::new(),
|
||||
new: new.into(),
|
||||
current: current.into(),
|
||||
warnings: &[],
|
||||
no_current: false,
|
||||
restore: false,
|
||||
warning: None,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
|
||||
/// The current half has no colour to show or restore (the target is unset or Automatic): it draws the sunken
|
||||
/// "no colour" diagonal, not a colour or the mixed mark, and is not a button.
|
||||
pub fn no_current(mut self, on: bool) -> Self {
|
||||
self.no_current = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The warnings in the column after the block, top to bottom.
|
||||
@@ -157,18 +174,22 @@ impl Component for CompareSwatch<'_> {
|
||||
let restore = cx.env.words::<ColorPickerWords>().restore.as_str().to_owned();
|
||||
let flow = craft_behavior::Flow::new(rect, cx.flow.is_rtl());
|
||||
let (_, _, current) = halves(rect, cx.style, caption_of(rect.height(), cx.style));
|
||||
cx.part(CURRENT, flow.to_physical(current)).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(restore);
|
||||
if !self.no_current {
|
||||
cx.part(CURRENT, flow.to_physical(current)).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(restore);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
self.restore = cx.part_activated(CURRENT).is_some();
|
||||
self.restore = !self.no_current && cx.part_activated(CURRENT).is_some();
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
if let Some(color) = self.new.same() {
|
||||
access.value(color.to_hex());
|
||||
}
|
||||
access.node(CURRENT, Role::BUTTON).name = Name::Text(cx.env.words::<ColorPickerWords>().restore.as_str().to_owned());
|
||||
if !self.no_current {
|
||||
access.node(CURRENT, Role::BUTTON).name = Name::Text(cx.env.words::<ColorPickerWords>().restore.as_str().to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
@@ -184,7 +205,8 @@ impl Component for CompareSwatch<'_> {
|
||||
(flow.to_physical(block), flow.to_physical(new), flow.to_physical(current), flow.to_physical(above), flow.to_physical(under));
|
||||
let _ = ui.child("new_caption", above, caption_text(words.new_caption.as_str()));
|
||||
ui.draw().swatch_well(new, CornerRadius::ZERO, self.new.same().copied());
|
||||
ui.draw().swatch_well(current, CornerRadius::ZERO, self.current.same().copied());
|
||||
let current_fill = if self.no_current { WellFill::None } else { self.current.same().copied().into() };
|
||||
ui.draw().swatch_well(current, CornerRadius::ZERO, current_fill);
|
||||
let _ = ui.child("current_caption", under, caption_text(words.current_caption.as_str()));
|
||||
ui.draw().stroke(&PaintShape::Rect(block, CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
|
||||
// The warnings column: each chip its icon over its swatch, the first level with the block's top.
|
||||
|
||||
@@ -61,7 +61,7 @@ craft_ui::words! {
|
||||
}
|
||||
|
||||
/// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SampleSize {
|
||||
@@ -115,7 +115,7 @@ impl SampleSize {
|
||||
}
|
||||
|
||||
/// Which layers the eyedropper reads: Photoshop's Sample list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SampleSource {
|
||||
@@ -172,7 +172,7 @@ impl SampleSource {
|
||||
}
|
||||
|
||||
/// The Eyedropper's options bar values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperOptions {
|
||||
|
||||
@@ -845,7 +845,7 @@ impl<P: Clone + Send + Sync + 'static> Component for GradientBar<'_, P> {
|
||||
let edge_of = |m: StopRef| {
|
||||
if self.selected_marker == Some(m) {
|
||||
style.selected
|
||||
} else if !dragging && cx.hover_pos(part_of(m)).is_some() {
|
||||
} else if !dragging && cx.part_if_declared(part_of(m)).is_some_and(|result| result.hovered) {
|
||||
style.hovered
|
||||
} else {
|
||||
cx.resolve(&style.edge)
|
||||
|
||||
@@ -19,7 +19,7 @@ use std::sync::Arc;
|
||||
use super::picker::{ChannelRow, ChannelRule};
|
||||
use super::{ColorDisc, DiscHit, DiscLook, DiscRadius};
|
||||
use crate::harmony::{Guide, GuideOptions, Harmony, Variation};
|
||||
use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput};
|
||||
use craft_ui::choice::{CellMarks, SwatchSpacing, SwatchTable, SwatchTableOutput};
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -503,6 +503,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
.multiple(true)
|
||||
.per_row(columns)
|
||||
.span(true)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.marks(move |&at| CellMarks::default().edge(at % columns == centre))
|
||||
.selection(Bind::bound(&mut selection));
|
||||
let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui);
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::AreaMode;
|
||||
use craft_behavior::{EditEvent, EditEvents, Metrics, PartKey, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPUP_PAD, PaintUi, PartsCx,
|
||||
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPOVER_PAD, PaintUi, PartsCx,
|
||||
Pattern, Props as _, Role, Show as _, ShowContainer as _, pad_of,
|
||||
};
|
||||
use craft_ui::popover::Popover;
|
||||
@@ -77,7 +77,7 @@ fn start_point(geometry: Geometry, start: Option<Srgba>) -> Pos2 {
|
||||
/// The popover's top left, so that the start colour's point in the area sits at `at`.
|
||||
fn origin(tokens: &UiTokens, at: Pos2, start: Option<Srgba>) -> Pos2 {
|
||||
let point = start_point(Geometry::of(tokens), start);
|
||||
let pad = pad_of(tokens, POPUP_PAD);
|
||||
let pad = pad_of(tokens, POPOVER_PAD);
|
||||
pos2(at.x - pad - point.x, at.y - pad - point.y)
|
||||
}
|
||||
|
||||
|
||||
@@ -68,14 +68,14 @@ pub use paint_chip::{
|
||||
PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords,
|
||||
};
|
||||
pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well};
|
||||
pub use palette::{SwatchPalette, SwatchPaletteOutput};
|
||||
pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput};
|
||||
pub use panel::{
|
||||
ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp,
|
||||
ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow,
|
||||
};
|
||||
pub use picker::{
|
||||
ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor,
|
||||
ScreenPickGesture, TrackRamp,
|
||||
ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords,
|
||||
PickedColor, ScreenPickGesture, TrackRamp,
|
||||
};
|
||||
pub use picker_dialog::{
|
||||
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary,
|
||||
|
||||
@@ -280,6 +280,7 @@ struct Shown {
|
||||
picture: Option<ImagePreview>,
|
||||
/// A recent colour or a swatch was picked: its colour, before the paint's alpha is applied.
|
||||
picked: Option<Srgba>,
|
||||
swatch_color: Option<SwatchColor>,
|
||||
/// The Color Picker… button was pressed.
|
||||
full_picker: bool,
|
||||
}
|
||||
@@ -297,6 +298,8 @@ pub struct PaintChipOutput {
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
/// A click, Enter or Space on a chip without a popover: the modifiers held.
|
||||
pub clicked: Option<Mods>,
|
||||
/// Original palette colour when a library swatch was picked.
|
||||
pub swatch_color: Option<SwatchColor>,
|
||||
}
|
||||
|
||||
impl Outcome for PaintChipOutput {
|
||||
@@ -440,6 +443,7 @@ pub struct PaintChip<'a> {
|
||||
pick_color: Option<ColorRequest>,
|
||||
/// The modifiers of this pass's click on a chip without a popover.
|
||||
clicked: Option<Mods>,
|
||||
swatch_color: Option<SwatchColor>,
|
||||
}
|
||||
|
||||
impl<'a> PaintChip<'a> {
|
||||
@@ -466,6 +470,7 @@ impl<'a> PaintChip<'a> {
|
||||
chip_size: PaintChipSize::Regular,
|
||||
pick_color: None,
|
||||
clicked: None,
|
||||
swatch_color: None,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
@@ -729,6 +734,7 @@ impl Component for PaintChip<'_> {
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
shown.picked = Some(color.to_srgb(cmyk));
|
||||
shown.swatch_color = Some(**color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -753,6 +759,7 @@ impl Component for PaintChip<'_> {
|
||||
let next = self.switched(kind, solid);
|
||||
cx.set(next);
|
||||
} else if let (Some(rgb), Some(current)) = (shown.picked, solid_now) {
|
||||
self.swatch_color = shown.swatch_color;
|
||||
// A recent colour or a swatch keeps the paint's alpha.
|
||||
cx.set(Paint::Solid(Srgba { a: current.a, ..rgb }));
|
||||
} else {
|
||||
@@ -797,7 +804,13 @@ impl Component for PaintChip<'_> {
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> PaintChipOutput {
|
||||
PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick, pick_color: self.pick_color, clicked: self.clicked }
|
||||
PaintChipOutput {
|
||||
edit: cx.edit_response(),
|
||||
screen_pick: self.screen_pick,
|
||||
pick_color: self.pick_color,
|
||||
clicked: self.clicked,
|
||||
swatch_color: self.swatch_color,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput {
|
||||
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
|
||||
/// The recent row and the Other… cell do not report a swatch index.
|
||||
pub picked_swatch: Option<usize>,
|
||||
/// The cell `picked` came from, so a host can tell apart cells that show the same color.
|
||||
pub cell: Option<PaletteCell>,
|
||||
}
|
||||
|
||||
/// A cell of a [`SwatchPalette`] by its place in the host's lists.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaletteCell {
|
||||
/// The swatch at this index of the palette's swatches.
|
||||
Swatch(usize),
|
||||
/// The color at this index of the recent row's colors.
|
||||
Recent(usize),
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPaletteOutput {
|
||||
@@ -112,8 +124,8 @@ impl PaletteColor<'_> {
|
||||
/// What the body picked in its pass.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Pick {
|
||||
/// A swatch or a recent colour.
|
||||
Color { color: Srgba, swatch: Option<usize> },
|
||||
/// A swatch or a recent color, and its cell.
|
||||
Color(Srgba, PaletteCell),
|
||||
/// The Other… cell.
|
||||
Other,
|
||||
}
|
||||
@@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
|
||||
// on its release, so only the activation files the request: one request for one click.
|
||||
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
|
||||
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
|
||||
Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))),
|
||||
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
|
||||
});
|
||||
}
|
||||
@@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> {
|
||||
.space(SpaceAction::ActivateLead)
|
||||
.selection(Bind::bound(&mut current))
|
||||
.show_all(ui);
|
||||
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
|
||||
pick = Some(Pick::Color { color: *picked, swatch: None });
|
||||
if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) {
|
||||
pick = Some(Pick::Color(*picked, PaletteCell::Recent(at)));
|
||||
}
|
||||
}
|
||||
Some((before, pick))
|
||||
@@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> {
|
||||
let key = other.as_ref().map(|(key, _)| key.clone())?;
|
||||
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
|
||||
}
|
||||
Pick::Color { color: after, swatch } => {
|
||||
Pick::Color(after, cell) => {
|
||||
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
|
||||
let edit = (!unchanged).then(|| {
|
||||
color.write(cx, before, after, name.as_str());
|
||||
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
|
||||
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
|
||||
});
|
||||
Some((Some(after), edit, None, swatch))
|
||||
Some((Some(after), edit, None, Some(cell)))
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatten();
|
||||
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
|
||||
let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None));
|
||||
let picked_swatch = match cell {
|
||||
Some(PaletteCell::Swatch(at)) => Some(at),
|
||||
_ => None,
|
||||
};
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell }
|
||||
}
|
||||
}
|
||||
+102
-16
@@ -5,7 +5,7 @@
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvent, GesturePhase, IconId, Mixed};
|
||||
use craft_behavior::{EditEvent, GestureId, GesturePhase, IconId, Mixed};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Srgba};
|
||||
use craft_ui::buttons::IconButton;
|
||||
@@ -245,7 +245,8 @@ pub struct ColorPanelState {
|
||||
pub hide_options: bool,
|
||||
/// The FillStroke layout shows the Recent Colors slot.
|
||||
pub recent_colors: bool,
|
||||
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255.
|
||||
/// The R, G and B rows count percents, 0 to 100, in place of 0 to 255; Web Color's rows keep 0 to 255. A double
|
||||
/// click on a units cell ([`ColorPanel::rgb_units_cell`]) switches it.
|
||||
pub rgb_percent: bool,
|
||||
}
|
||||
|
||||
@@ -414,6 +415,8 @@ struct Kept {
|
||||
tracks: Vec<(&'static str, usize, ModelValues)>,
|
||||
/// A channel gesture is running.
|
||||
dragging: bool,
|
||||
/// The host's complete colour before a model gesture, independent of the panel's transform.
|
||||
opening: Option<(GestureId, PanelTarget, PickedColor)>,
|
||||
/// The ramp gesture in progress picks for the colour not edited.
|
||||
other: bool,
|
||||
}
|
||||
@@ -444,12 +447,14 @@ pub struct ColorPanel<'a> {
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
rgb: Option<&'a dyn ColorModel>,
|
||||
dynamic: bool,
|
||||
rgb_units: bool,
|
||||
layout: ColorPanelLayout,
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
buttons: Option<[Label; 2]>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -474,6 +479,7 @@ struct Inputs<'a> {
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -486,12 +492,14 @@ impl<'a> ColorPanel<'a> {
|
||||
cmyk: None,
|
||||
rgb: None,
|
||||
dynamic: true,
|
||||
rgb_units: false,
|
||||
layout: ColorPanelLayout::default(),
|
||||
wells: None,
|
||||
buttons: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: None,
|
||||
recent_models: &[],
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -518,6 +526,14 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A units cell right of each R, G and B field (not Web Color's): a double click on it switches
|
||||
/// [`ColorPanelState::rgb_percent`]. The cell has no keyboard stop, so a host that turns it on offers the same
|
||||
/// switch as a command that writes `rgb_percent`. Off by default.
|
||||
pub fn rgb_units_cell(mut self, on: bool) -> Self {
|
||||
self.rgb_units = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// How the panel arranges its body; the Photoshop foreground and background arrangement by default.
|
||||
pub fn layout(mut self, layout: ColorPanelLayout) -> Self {
|
||||
self.layout = layout;
|
||||
@@ -541,6 +557,8 @@ impl<'a> ColorPanel<'a> {
|
||||
|
||||
/// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited
|
||||
/// well's colour by default.
|
||||
/// Explicit components take precedence over remembered values for their model, including when the host uses a
|
||||
/// different working-space transform to render the colour.
|
||||
pub fn edited(mut self, color: Option<PickedColor>) -> Self {
|
||||
self.edited = Some(color);
|
||||
self
|
||||
@@ -559,6 +577,15 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has
|
||||
/// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip
|
||||
/// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of
|
||||
/// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing.
|
||||
pub fn recent_models(mut self, models: &'a [Option<ModelValues>]) -> Self {
|
||||
self.recent_models = models;
|
||||
self
|
||||
}
|
||||
|
||||
/// The payload a Recent Colors chip drags.
|
||||
pub fn recent_payload<P: Send + Sync + 'static>(mut self, map: impl Fn(usize) -> Option<P> + Send + Sync + 'static) -> Self {
|
||||
self.recent_setup = Some(recent_setup(map));
|
||||
@@ -573,7 +600,23 @@ impl<'a> ColorPanel<'a> {
|
||||
|
||||
/// Shows the panel and returns this pass's edits and requests.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
|
||||
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self;
|
||||
let ColorPanel {
|
||||
state,
|
||||
colors,
|
||||
cmyk,
|
||||
rgb,
|
||||
dynamic,
|
||||
rgb_units,
|
||||
layout,
|
||||
wells,
|
||||
buttons,
|
||||
edited,
|
||||
shown: rows,
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup,
|
||||
gamut,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
|
||||
let mut held = Held::new(state);
|
||||
@@ -605,6 +648,7 @@ impl<'a> ColorPanel<'a> {
|
||||
rgb,
|
||||
gamut: &gamut,
|
||||
dynamic,
|
||||
rgb_units,
|
||||
words: &words,
|
||||
dialog: &dialog,
|
||||
inputs: Inputs {
|
||||
@@ -613,6 +657,7 @@ impl<'a> ColorPanel<'a> {
|
||||
edited: edited.as_ref(),
|
||||
shown: rows.as_ref().unwrap_or(&default_rows),
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup: recent_setup.as_ref(),
|
||||
},
|
||||
now: before,
|
||||
@@ -904,6 +949,8 @@ struct Body<'a> {
|
||||
rgb: &'a dyn ColorModel,
|
||||
gamut: &'a Gamut<'a>,
|
||||
dynamic: bool,
|
||||
/// The R, G and B rows have units cells ([`ColorPanel::rgb_units_cell`]).
|
||||
rgb_units: bool,
|
||||
words: &'a ColorPanelWords,
|
||||
dialog: &'a ColorPickerDialogWords,
|
||||
/// The state as this pass leaves it.
|
||||
@@ -1052,12 +1099,11 @@ impl Body<'_> {
|
||||
/// The model's values for the edited colour, unrounded: an edit of one channel leaves the others as they are.
|
||||
fn values(&self, model: &dyn ColorModel) -> ModelValues {
|
||||
let color = self.color();
|
||||
// The host's own values of the colour (typed CMYK, a working space's numbers) stand when they give the colour.
|
||||
let given = self.picked().and_then(|picked| picked.model);
|
||||
let kept = self.kept.values[self.target.index()]
|
||||
.iter()
|
||||
.chain(given.as_ref())
|
||||
.find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color));
|
||||
// Current host values are authoritative: its working-space transform may differ from the panel's.
|
||||
if let Some(values) = self.picked().and_then(|picked| picked.model).filter(|values| values.model == model.id()) {
|
||||
return finite_values(values);
|
||||
}
|
||||
let kept = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color));
|
||||
finite_values(kept.copied().unwrap_or_else(|| self.read(model, color)))
|
||||
}
|
||||
|
||||
@@ -1096,11 +1142,39 @@ impl Body<'_> {
|
||||
fn model_event(&mut self, model: &dyn ColorModel, event: EditEvent<ModelValues>) {
|
||||
let event = event.map(finite_values);
|
||||
self.kept.dragging = matches!(event.phase(), Some(GesturePhase::Begin | GesturePhase::Update));
|
||||
if let EditEvent::Begin { id, .. } = &event {
|
||||
self.kept.opening = self.picked().copied().map(|picked| (*id, self.target, picked));
|
||||
}
|
||||
if let Some(values) = event.value() {
|
||||
self.remember(model, *values);
|
||||
}
|
||||
let alpha = self.color().a;
|
||||
let event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) });
|
||||
let mut event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) });
|
||||
let opening = self.kept.opening.filter(|(id, target, _)| Some(*id) == event.id() && *target == self.target).map(|(_, _, picked)| picked);
|
||||
match &mut event {
|
||||
EditEvent::Begin { before, .. } | EditEvent::Commit { before, .. } => {
|
||||
if let (Mixed::Same(value), Some(picked)) = (before, opening) {
|
||||
*value = picked;
|
||||
}
|
||||
}
|
||||
EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => {
|
||||
if let Some(picked) = opening {
|
||||
*value = picked;
|
||||
if let Some(values) = picked.model.filter(|values| values.model == model.id()) {
|
||||
self.remember(model, values);
|
||||
}
|
||||
}
|
||||
}
|
||||
EditEvent::Set { before: Mixed::Same(value), .. } => {
|
||||
if let Some(picked) = self.picked() {
|
||||
*value = *picked;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if matches!(event.phase(), Some(GesturePhase::Commit | GesturePhase::Cancel) | None) {
|
||||
self.kept.opening = None;
|
||||
}
|
||||
self.push(self.target, event);
|
||||
}
|
||||
|
||||
@@ -1128,15 +1202,18 @@ impl Body<'_> {
|
||||
self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot);
|
||||
self.kept.tracks.push((slot.0, slot.1, current));
|
||||
}
|
||||
// The R, G and B rows are not Web Color's. The units are read once, so a double click on one units cell
|
||||
// switches all three rows together, from the next pass.
|
||||
let rgb = !web && model.id() == self.rgb.id();
|
||||
let rgb_percent = self.now.rgb_percent;
|
||||
for (i, ch) in model.channels().iter().enumerate() {
|
||||
let mut rule = ChannelRule::of(ch);
|
||||
if web {
|
||||
rule.step = WEB_STEP;
|
||||
}
|
||||
// The R, G and B rows count percents of the channel's range; an edit goes back through `scale`.
|
||||
// PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow`
|
||||
// (color-w2) reports no signal for its units cell, so the panel cannot read it.
|
||||
let percent = self.now.rgb_percent && model.id() == self.rgb.id();
|
||||
// With `rgb_percent` the R, G and B rows count percents of the channel's range; an edit goes back through
|
||||
// `scale`.
|
||||
let percent = rgb && rgb_percent;
|
||||
let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 };
|
||||
let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) };
|
||||
if percent {
|
||||
@@ -1152,8 +1229,17 @@ impl Body<'_> {
|
||||
// The field shows the channel's places, as Photoshop's; the edits start from the unrounded values.
|
||||
let places = 10f64.powi(i32::from(rule.decimals));
|
||||
let shown = (f64::from(current.values[i]) * scale * places).round() / places;
|
||||
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui);
|
||||
for event in row.into_iter().flat_map(|row| row.events) {
|
||||
let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track);
|
||||
let edit = if rgb && self.rgb_units {
|
||||
let row = row.show_with_units(ui);
|
||||
if row.units_double_clicked {
|
||||
self.now.rgb_percent = !rgb_percent;
|
||||
}
|
||||
row.edit
|
||||
} else {
|
||||
row.show(ui)
|
||||
};
|
||||
for event in edit.into_iter().flat_map(|row| row.events) {
|
||||
self.channel_event(model, current, i, event.map(|x| x / scale));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers.
|
||||
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::{ModelValues, Srgba};
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
@@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette};
|
||||
use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette};
|
||||
|
||||
impl Body<'_> {
|
||||
/// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the
|
||||
@@ -156,8 +156,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it.
|
||||
/// The caption shows while the host's list is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
@@ -174,13 +174,34 @@ impl Body<'_> {
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
palette = setup(palette);
|
||||
}
|
||||
if let Some(event) = palette.show(ui).edit
|
||||
let out = palette.show(ui);
|
||||
let values = match out.cell {
|
||||
Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(),
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(color), Some(values)) = (out.picked, values) {
|
||||
self.set_in_model(color, values);
|
||||
} else if let Some(event) = out.edit
|
||||
&& let Some(color) = event.value()
|
||||
{
|
||||
self.set_color(self.target, *color);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's
|
||||
/// color already has those values and shows that color.
|
||||
fn set_in_model(&mut self, color: Srgba, values: ModelValues) {
|
||||
let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()]));
|
||||
let after = PickedColor::in_model(color.with_alpha(before.color.a), values);
|
||||
if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() {
|
||||
return;
|
||||
}
|
||||
// The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue).
|
||||
self.kept.values[self.target.index()].retain(|v| v.model != values.model);
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None));
|
||||
}
|
||||
|
||||
/// Sets `target`'s colour to `color`, keeping its alpha.
|
||||
fn set_color(&mut self, target: PanelTarget, color: Srgba) {
|
||||
let before = self.colors[target.index()];
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use craft_behavior::{Axis, Sense};
|
||||
use craft_behavior::press::MULTI_CLICK_TIME;
|
||||
use craft_behavior::{Axis, Metrics, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{Channel, ColorModel, Srgba};
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
|
||||
Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role,
|
||||
Show as _, ShowContainer as _, SideLabel, Sizing,
|
||||
};
|
||||
use craft_ui::form::{Field, SliderField, SliderFieldLayout};
|
||||
use craft_ui::form::{Field, FieldDecimals, SliderField, SliderFieldLayout};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::runtime::memory::sub;
|
||||
use craft_ui::runtime::pointer;
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use craft_ui::value_drag::{SliderThumb, TrackFace};
|
||||
use egui::{Color32, CornerRadius, Ui, Vec2};
|
||||
@@ -145,7 +150,8 @@ impl Component for TrackRamp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The slider and number field of a channel, over `value`, with `track` colours on the groove.
|
||||
/// The slider and number field of a channel, over `value`, with `track` colours on the groove. The field shows the
|
||||
/// decimals the rule declares, a percent channel too ("67", not the percent look's "66.7").
|
||||
pub(crate) fn channel_slider<'a>(
|
||||
name: Label,
|
||||
value: Bind<'a, f64>,
|
||||
@@ -153,7 +159,7 @@ pub(crate) fn channel_slider<'a>(
|
||||
unit: ChannelUnit,
|
||||
track: Option<(Vec<Srgba>, bool)>,
|
||||
) -> SliderField<'a> {
|
||||
let field = SliderField::new(name, value, rule.range.clone()).step(rule.step);
|
||||
let field = SliderField::new(name, value, rule.range.clone()).step(rule.step).field_decimals(FieldDecimals::Fixed(usize::from(rule.decimals)));
|
||||
let field = match unit {
|
||||
ChannelUnit::None => field,
|
||||
ChannelUnit::Percent => field.unit_kind(UnitKind::Percent),
|
||||
@@ -168,7 +174,8 @@ pub(crate) fn channel_slider<'a>(
|
||||
|
||||
/// One channel on one line, as Photoshop's Color panel draws it: the label at the start (the channel's short label
|
||||
/// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its
|
||||
/// track, and the number field with its unit at the end, as wide as its widest value.
|
||||
/// track, and the number field with its unit at the end, as wide as its widest value, showing the channel's declared
|
||||
/// decimals.
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct ChannelRow<'a> {
|
||||
label: Label,
|
||||
@@ -183,6 +190,15 @@ pub struct ChannelRow<'a> {
|
||||
marks: &'a [f64],
|
||||
}
|
||||
|
||||
/// What [`ChannelRow::show_with_units`] reports.
|
||||
#[non_exhaustive]
|
||||
pub struct ChannelRowOutput {
|
||||
/// The edit of the slider or the field, `None` when the row did not run.
|
||||
pub edit: Option<EditResponse<f64>>,
|
||||
/// The units cell was double-clicked in this pass: the host switches the units the row counts in.
|
||||
pub units_double_clicked: bool,
|
||||
}
|
||||
|
||||
impl<'a> ChannelRow<'a> {
|
||||
/// A row named `label` over `value`, ruled by `rule`.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
|
||||
@@ -223,22 +239,139 @@ impl<'a> ChannelRow<'a> {
|
||||
|
||||
/// Shows the row; the edit of the slider or the field, `None` when the row did not run.
|
||||
pub fn show(self, ui: &mut Ui) -> Option<EditResponse<f64>> {
|
||||
self.show_row(ui, false).edit
|
||||
}
|
||||
|
||||
/// Shows the row with a blank units cell after the number field, for a row whose host can switch the units the
|
||||
/// value counts in: the edit of the slider or the field, and whether the cell was double-clicked. The cell is
|
||||
/// highlighted under the pointer and takes no keyboard focus, so the host offers the same switch as a command; in
|
||||
/// a disabled container it does not report a double click. The slider gives up the cell's width, so the row keeps
|
||||
/// its width.
|
||||
pub fn show_with_units(self, ui: &mut Ui) -> ChannelRowOutput {
|
||||
self.show_row(ui, true)
|
||||
}
|
||||
|
||||
fn show_row(self, ui: &mut Ui, units_cell: bool) -> ChannelRowOutput {
|
||||
let ChannelRow { label, short, mut value, rule, track, checker, unit, marks } = self;
|
||||
let side = match short {
|
||||
Some(short) => SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short)))),
|
||||
None => SideLabel::new(),
|
||||
};
|
||||
Field::new(label.clone())
|
||||
.side(side.scrub(true))
|
||||
.show(ui, |ui, _| {
|
||||
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
|
||||
.marks(marks)
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.field_sizing(Sizing::Content)
|
||||
.thumb(SliderThumb::Triangle)
|
||||
.show(ui)
|
||||
.edit
|
||||
})
|
||||
.inner
|
||||
let mut field = |ui: &mut Ui| {
|
||||
Field::new(label.clone())
|
||||
.side(side.clone().scrub(true))
|
||||
.show(ui, |ui, _| {
|
||||
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
|
||||
.marks(marks)
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.field_sizing(Sizing::Content)
|
||||
.thumb(SliderThumb::Triangle)
|
||||
.show(ui)
|
||||
.edit
|
||||
})
|
||||
.inner
|
||||
};
|
||||
if !units_cell {
|
||||
return ChannelRowOutput { edit: field(ui), units_double_clicked: false };
|
||||
}
|
||||
let shown = Row::new().fill_width().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let edit = field(ui);
|
||||
let cell = UnitsCell::new().show(ui);
|
||||
(edit, cell.double_clicked)
|
||||
});
|
||||
let (edit, units_double_clicked) = shown.inner.unwrap_or((None, false));
|
||||
ChannelRowOutput { edit, units_double_clicked }
|
||||
}
|
||||
}
|
||||
|
||||
/// The units cell's one part, which takes the pointer.
|
||||
const UNITS: PartKey = PartKey::new("units");
|
||||
|
||||
/// The style of a units cell: its size.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct UnitsCellStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The cell's size: `size.icon.glyph_sm` wide, a control high, so it fills the row's line.
|
||||
size: Vec2,
|
||||
}
|
||||
|
||||
/// The blank cell after a channel row's number field ([`ChannelRow::show_with_units`]): highlighted under the pointer, it
|
||||
/// reports a double click. It has no keyboard stop and no node: the host's command that switches the units is its
|
||||
/// keyboard path.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(sample = UnitsCell::new)]
|
||||
struct UnitsCell {
|
||||
#[common]
|
||||
common: Common,
|
||||
double_clicked: bool,
|
||||
}
|
||||
|
||||
impl UnitsCell {
|
||||
fn new() -> Self {
|
||||
UnitsCell { common: Common::new(), double_clicked: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a units cell reports: its response and whether it was double-clicked in this pass.
|
||||
struct UnitsCellOutput {
|
||||
response: egui::Response,
|
||||
double_clicked: bool,
|
||||
}
|
||||
|
||||
impl Outcome for UnitsCellOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &egui::Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for UnitsCell {
|
||||
const ROLE: Role = Role::None;
|
||||
const OVERLAYS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
type Style = UnitsCellStyle;
|
||||
type Output = UnitsCellOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: UnitsCellStyleKey) -> UnitsCellStyle {
|
||||
UnitsCellStyle { metrics: Metrics::new(), size: Vec2::new(cx.tokens.size.icon.glyph_sm, cx.control().height) }
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
cx.style.size
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.part(UNITS, rect).sense(Sense::CLICK).state_layer().pointer_only("the host's command switches the units");
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let first = sub(cx.core.id, "units-first-click");
|
||||
// A press off the cell ends the cell's click run, even when it starts a new count that the next click on the
|
||||
// cell continues.
|
||||
if pointer::frame(&cx.response.ctx).press.is_some_and(|press| !cx.response.rect.contains(press.origin)) {
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = None;
|
||||
}
|
||||
let PressPhase::Release { start, click: true, .. } = cx.part(UNITS).press.phase else { return };
|
||||
// The click count also counts a press just beside the cell, on the number field, so a click is the second of a
|
||||
// double click only when the click just before it, by the count, was a click on this cell.
|
||||
let earlier = *cx.core.memory.shown::<Option<(f64, u32)>>(first);
|
||||
let follows = earlier.is_some_and(|(time, clicks)| start.clicks == clicks + 1 && start.time - time <= MULTI_CLICK_TIME);
|
||||
if start.clicks >= 2 && follows {
|
||||
self.double_clicked = true;
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = None;
|
||||
} else {
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = Some((start.time, start.clicks));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> UnitsCellOutput {
|
||||
UnitsCellOutput { response: cx.response.clone(), double_clicked: self.double_clicked }
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ pub(super) struct Body<'a> {
|
||||
/// Compact only: the host gave a compare colour, so the compare block stands beside the area (Word's Colors
|
||||
/// dialog's New over Current). The Full layout always shows it.
|
||||
pub compare: bool,
|
||||
/// The compare block's current half shows no colour.
|
||||
pub no_current: bool,
|
||||
pub alpha: bool,
|
||||
pub dynamic_tracks: bool,
|
||||
pub eyedropper: bool,
|
||||
|
||||
@@ -92,7 +92,10 @@ impl<'a> Body<'a> {
|
||||
Mixed::Same(current) => Mixed::Same(current.color),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
let shown = CompareSwatch::new(words.new_color.as_str().to_owned(), pass.shows(pass.shown.color), current).warnings(&self.warnings).show(ui);
|
||||
let shown = CompareSwatch::new(words.new_color.as_str().to_owned(), pass.shows(pass.shown.color), current)
|
||||
.warnings(&self.warnings)
|
||||
.no_current(self.no_current)
|
||||
.show(ui);
|
||||
if shown.restore
|
||||
&& let Mixed::Same(current) = pass.compare
|
||||
{
|
||||
|
||||
@@ -21,7 +21,7 @@ use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::{AreaMode, ColorWarning};
|
||||
pub(crate) use channel::channel_name;
|
||||
pub use channel::{ChannelRow, ChannelRule, ChannelUnit, TrackRamp};
|
||||
pub use channel::{ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, TrackRamp};
|
||||
pub(crate) use full::TWO_COLUMNS;
|
||||
pub use value::ColorConstraint;
|
||||
use value::Rules;
|
||||
@@ -303,6 +303,10 @@ pub struct ColorPicker<'a> {
|
||||
/// picker's first show.
|
||||
#[prop(into)]
|
||||
compare: Option<Mixed<PickedColor>>,
|
||||
/// The compare block's current half shows no colour (the "no colour" diagonal) and is not a restore button; the
|
||||
/// host has no colour to go back to.
|
||||
#[prop]
|
||||
compare_none: bool,
|
||||
warnings: Vec<ColorWarning>,
|
||||
/// Applied to every colour before it is reported, after Only Web Colors' snap.
|
||||
#[prop(func = "Fn(Srgba) -> Srgba")]
|
||||
@@ -330,6 +334,7 @@ impl<'a> ColorPicker<'a> {
|
||||
eyedropper: false,
|
||||
eyedropper_busy: false,
|
||||
compare: None,
|
||||
compare_none: false,
|
||||
warnings: Vec::new(),
|
||||
constrain: None,
|
||||
sampled: None,
|
||||
@@ -388,6 +393,7 @@ impl<'a> ColorPicker<'a> {
|
||||
eyedropper,
|
||||
eyedropper_busy,
|
||||
compare,
|
||||
compare_none,
|
||||
warnings,
|
||||
constrain,
|
||||
sampled,
|
||||
@@ -401,6 +407,7 @@ impl<'a> ColorPicker<'a> {
|
||||
models: models.clone(),
|
||||
warnings,
|
||||
compare: compare.is_some(),
|
||||
no_current: compare_none,
|
||||
alpha,
|
||||
dynamic_tracks,
|
||||
eyedropper,
|
||||
|
||||
@@ -23,8 +23,9 @@ use craft_ui::contract::{
|
||||
use craft_ui::dialog::{
|
||||
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout::{CellAlign, GridFit};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
|
||||
use craft_ui::pickers::Select;
|
||||
@@ -41,7 +42,7 @@ use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::picker::TWO_COLUMNS;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerWords, ColorWarning, CompareSwatch, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
|
||||
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
|
||||
|
||||
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
|
||||
@@ -65,6 +66,7 @@ craft_ui::words! {
|
||||
custom_tab: "colorPickerDialog.customTab" = "Custom";
|
||||
standard_colors: "colorPickerDialog.standardColors" = "Standard colors";
|
||||
greys: "colorPickerDialog.greys" = "Shades of gray";
|
||||
colors_heading: "colorPickerDialog.colorsHeading" = "Colors:";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,6 +239,8 @@ pub struct ColorPickerDialog {
|
||||
/// The colour as it stands; `None` until the first pick when the dialog opened without one.
|
||||
current: Option<PickedColor>,
|
||||
compare: bool,
|
||||
/// [`no_current`](Self::no_current).
|
||||
no_current: bool,
|
||||
remember: bool,
|
||||
add_to_swatches: bool,
|
||||
cmyk: Option<CmykConverter>,
|
||||
@@ -273,6 +277,8 @@ struct TabbedBody<'a> {
|
||||
words: &'a ColorPickerDialogWords,
|
||||
standard: Option<&'a StandardColors>,
|
||||
compare: Option<Mixed<PickedColor>>,
|
||||
/// The compare block's current half shows no colour and restores nothing.
|
||||
no_current: bool,
|
||||
}
|
||||
|
||||
/// The built-in models `on` takes, the host's working RGB in place of the built-in RGB.
|
||||
@@ -318,27 +324,48 @@ impl TabbedBody<'_> {
|
||||
let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice()));
|
||||
let current = held.same().map(|picked| picked.color);
|
||||
let mut pick = None;
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
|
||||
.arrangement(SwatchArrangement::Honeycomb)
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(cells, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = honeycomb.selected {
|
||||
pick = cells.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
let row = SwatchTable::new(self.words.greys.clone(), greys)
|
||||
.per_row(greys.len().max(1))
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(greys, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = row.selected {
|
||||
pick = greys.get(at).map(|(_, color)| *color);
|
||||
let mut restore = None;
|
||||
// The compare block stands beside the honeycomb, as it does beside the Custom page's area.
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Text::new(self.words.colors_heading.clone()).show(ui);
|
||||
let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells)
|
||||
.arrangement(SwatchArrangement::Honeycomb)
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(cells, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = honeycomb.selected {
|
||||
pick = cells.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
let row = SwatchTable::new(self.words.greys.clone(), greys)
|
||||
.per_row(greys.len().max(1))
|
||||
.tips(true)
|
||||
.selection(Bind::given(chosen(greys, current)))
|
||||
.show_all(ui);
|
||||
if let Some(at) = row.selected {
|
||||
pick = greys.get(at).map(|(_, color)| *color);
|
||||
}
|
||||
});
|
||||
if let Some(compare) = self.compare {
|
||||
let new = held.same().map_or(Mixed::Mixed, |picked| Mixed::Same(picked.color));
|
||||
let current = match compare {
|
||||
Mixed::Same(current) => Mixed::Same(current.color),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
let label = Env::of(ui).words::<ColorPickerWords>().new_color.clone();
|
||||
if CompareSwatch::new(label, new, current).no_current(self.no_current).show(ui).restore
|
||||
&& let Mixed::Same(current) = compare
|
||||
{
|
||||
restore = Some(current);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(color) = pick {
|
||||
*held = Mixed::Same(PickedColor::rgb(color));
|
||||
}
|
||||
if let Some(current) = restore {
|
||||
*held = Mixed::Same(current);
|
||||
}
|
||||
}
|
||||
|
||||
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
|
||||
@@ -350,8 +377,9 @@ impl TabbedBody<'_> {
|
||||
.models(models)
|
||||
.shown_model(Bind::bound(&mut model));
|
||||
if let Some(compare) = self.compare {
|
||||
picker = picker.compare(compare);
|
||||
picker = picker.compare(compare).compare_none(self.no_current);
|
||||
}
|
||||
Text::new(self.words.colors_heading.clone()).show(ui);
|
||||
let _ = picker.show(ui);
|
||||
memory.model = model.map(str::to_owned);
|
||||
}
|
||||
@@ -393,6 +421,7 @@ impl ColorPickerDialog {
|
||||
opening,
|
||||
current: opening,
|
||||
compare: true,
|
||||
no_current: false,
|
||||
remember: true,
|
||||
add_to_swatches: true,
|
||||
cmyk: None,
|
||||
@@ -482,6 +511,20 @@ impl ColorPickerDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// The target has no colour to return to (unset or Automatic): the compare block's current half shows the "no
|
||||
/// colour" diagonal and is not a restore button, while the dialog still opens on the colour it was given and
|
||||
/// Reset returns to it.
|
||||
#[must_use]
|
||||
pub fn no_current(mut self) -> ColorPickerDialog {
|
||||
self.no_current = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the compare block has no current colour ([`no_current`](Self::no_current)).
|
||||
pub fn has_no_current(&self) -> bool {
|
||||
self.no_current
|
||||
}
|
||||
|
||||
/// Whether the field's component and Only Web Colors are recalled on open and stored on OK
|
||||
/// ([`ColorPickerMemory`]); on by default. A picker opened by a feature that wants its own start turns it off.
|
||||
#[must_use]
|
||||
@@ -754,7 +797,20 @@ impl StackDialog for ColorPickerDialog {
|
||||
// Word's Colors dialog.
|
||||
let place = if full { ButtonPlace::Body } else { ButtonPlace::Side };
|
||||
let Self {
|
||||
current, opening, compare, memory, screen_busy, sample, pending_screen, open, layout, standard, swatches: view, working_rgb, ..
|
||||
current,
|
||||
opening,
|
||||
compare,
|
||||
no_current,
|
||||
memory,
|
||||
screen_busy,
|
||||
sample,
|
||||
pending_screen,
|
||||
open,
|
||||
layout,
|
||||
standard,
|
||||
swatches: view,
|
||||
working_rgb,
|
||||
..
|
||||
} = self;
|
||||
let working_rgb = working_rgb.as_deref().map(|model| model as &dyn ColorModel);
|
||||
let mut held: Mixed<PickedColor> = current.map_or(Mixed::Mixed, Mixed::Same);
|
||||
@@ -776,7 +832,14 @@ impl StackDialog for ColorPickerDialog {
|
||||
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
|
||||
}
|
||||
if *layout == ColorPickerDialogLayout::Tabbed {
|
||||
let body = TabbedBody { title: &title, working_rgb, words: &words, standard: standard.as_ref(), compare: compare_with };
|
||||
let body = TabbedBody {
|
||||
title: &title,
|
||||
working_rgb,
|
||||
words: &words,
|
||||
standard: standard.as_ref(),
|
||||
compare: compare_with,
|
||||
no_current: *no_current,
|
||||
};
|
||||
body.show(ui, &mut *memory, &mut held);
|
||||
return;
|
||||
}
|
||||
@@ -815,6 +878,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
if let Some(compare) = compare_with {
|
||||
picker = picker.compare(compare);
|
||||
}
|
||||
picker = picker.compare_none(*no_current);
|
||||
if let Some(gesture) = picker.show(ui).screen_pick {
|
||||
*pending_screen = Some(gesture);
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ impl Component for CaptureView<'_> {
|
||||
.get_or_put(ctx, self.key, Revision::default(), || ColorImage::from_rgba_unmultiplied(image.size.map(|n| n as usize), &image.rgba));
|
||||
let whole = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0));
|
||||
ui.draw().texture(cx.rect, texture.id, whole);
|
||||
let Some(pointer) = cx.response.hover_pos().filter(|at| cx.rect.contains(*at)) else { return };
|
||||
let Some(pointer) = craft_ui::runtime::pointer::hover_point_in(ctx, cx.rect) else { return };
|
||||
let Some((x, y)) = self.pixel(cx.rect, pointer) else { return };
|
||||
self.loupe(ui, cx, pointer, (x, y));
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ pub struct SwatchesPanel<'a> {
|
||||
search: bool,
|
||||
row_icons: Option<RowIconsFn<'a>>,
|
||||
select: SelectMode,
|
||||
drops: Vec<DropMaker<'a>>,
|
||||
report_invalid_renames: bool,
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
@@ -131,8 +131,8 @@ impl<'a> SwatchesPanel<'a> {
|
||||
search: true,
|
||||
row_icons: None,
|
||||
select: SelectMode::Single,
|
||||
drops: Vec::new(),
|
||||
report_invalid_renames: false,
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
@@ -211,12 +211,12 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees;
|
||||
/// the drop comes back as `PresetEvent::Dropped`.
|
||||
/// Adds a target for host payloads of type `P` at `place` where `accepts` agrees.
|
||||
/// Each drop comes back as `PresetEvent::Dropped`.
|
||||
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
|
||||
// The body can run more than once a pass, and a `PresetDrop` is used up by the browser: it is built per run.
|
||||
let accepts = Rc::new(accepts);
|
||||
self.takes_drop = Some(Box::new(move || {
|
||||
self.drops.push(Box::new(move || {
|
||||
let accepts = Rc::clone(&accepts);
|
||||
PresetDrop::new::<P>(place, move |payload: &P, at: &DropAt<SwatchKey>| accepts(payload, at))
|
||||
}));
|
||||
@@ -270,8 +270,8 @@ impl<'a> SwatchesPanel<'a> {
|
||||
search,
|
||||
row_icons,
|
||||
select,
|
||||
drops,
|
||||
report_invalid_renames,
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
@@ -331,7 +331,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
if let Some(items) = &row_items {
|
||||
browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key));
|
||||
}
|
||||
if let Some(make) = &takes_drop {
|
||||
for make in &drops {
|
||||
browser = browser.takes_drop(make());
|
||||
}
|
||||
for add in &payloads {
|
||||
|
||||
@@ -210,7 +210,7 @@ fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>>
|
||||
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
|
||||
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
|
||||
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
|
||||
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
|
||||
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules, 0).show_at(ui, area, |ui, _| {
|
||||
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
|
||||
});
|
||||
let _ = craft_ui::buttons::Button::new("After").show(ui);
|
||||
|
||||
@@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel,
|
||||
SwatchesState, SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
@@ -38,6 +38,7 @@ type Edits = Rc<RefCell<Vec<(PanelTarget, EditEvent<PickedColor>)>>>;
|
||||
/// The Color panel on a state and two colours the test can change, collecting what it reports.
|
||||
struct PanelRig {
|
||||
fixture: Fixture,
|
||||
state: Rc<RefCell<ColorPanelState>>,
|
||||
colors: Rc<Cell<[Srgba; 2]>>,
|
||||
edits: Edits,
|
||||
}
|
||||
@@ -48,15 +49,19 @@ impl PanelRig {
|
||||
}
|
||||
|
||||
fn in_room(mode: ColorPanelMode, room: Vec2) -> Self {
|
||||
let start = ColorPanelState { mode, ..Default::default() };
|
||||
Self::with_state(ColorPanelState { mode, ..Default::default() }, room, true)
|
||||
}
|
||||
|
||||
/// The panel from `start`, with the RGB units cells where `units` is set.
|
||||
fn with_state(start: ColorPanelState, room: Vec2, units: bool) -> Self {
|
||||
let state = Rc::new(RefCell::new(start));
|
||||
let colors = Rc::new(Cell::new([RED, BLUE]));
|
||||
type Shared = (Edits, Rc<RefCell<Vec<ColorRequest>>>, Rc<RefCell<Vec<PanelTarget>>>);
|
||||
let (edits, opened, added): Shared = Default::default();
|
||||
let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added);
|
||||
let (s, c, e, o, a) = (state.clone(), colors.clone(), edits.clone(), opened, added);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = *s.borrow();
|
||||
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui);
|
||||
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).rgb_units_cell(units).show(ui);
|
||||
*s.borrow_mut() = current;
|
||||
e.borrow_mut().extend(shown.edits);
|
||||
o.borrow_mut().extend(shown.pick_color);
|
||||
@@ -64,7 +69,7 @@ impl PanelRig {
|
||||
});
|
||||
fixture.room(room);
|
||||
fixture.settle();
|
||||
PanelRig { fixture, colors, edits }
|
||||
PanelRig { fixture, state, colors, edits }
|
||||
}
|
||||
|
||||
fn set_colors(&mut self, colors: [Srgba; 2]) {
|
||||
@@ -197,6 +202,237 @@ fn a_channel_step_keeps_the_other_channels_unrounded() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A point in the units cell right of `field`, on its line.
|
||||
fn right_of(field: &craft_ui::testing::Target) -> egui::Pos2 {
|
||||
egui::pos2(field.rect.right() + 6.0, field.rect.center().y)
|
||||
}
|
||||
|
||||
/// The number fields' values, top to bottom, and the end of the first one's range.
|
||||
fn field_values(fixture: &Fixture) -> (Vec<f64>, f64) {
|
||||
let tree = fixture.tree();
|
||||
let fields = fixture.by_role(Role::SPIN_BUTTON);
|
||||
let numbers: Vec<_> = fields.iter().map(|field| tree.numeric_of(field.node).expect("a field's value and range")).collect();
|
||||
let values = numbers.iter().map(|number| number.value.expect("a field's value")).collect();
|
||||
(values, *numbers[0].range.end())
|
||||
}
|
||||
|
||||
/// A double click right of the R, G or B field switches all three rows between 0 to 255 and percent, and the next one
|
||||
/// switches them back. The colour does not change.
|
||||
#[trial]
|
||||
fn a_double_click_right_of_an_rgb_field_switches_the_rgb_units() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
rig.set_colors([Srgba::rgb(1.0, 0.5, 0.0), BLUE]);
|
||||
let (bytes, end) = field_values(&rig.fixture);
|
||||
assert!(!rig.state.borrow().rgb_percent && end > 100.0, "the rows start at 0 to 255 ({bytes:?}, to {end})");
|
||||
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click right of R switches to percent");
|
||||
let (percents, end) = field_values(&rig.fixture);
|
||||
assert_eq!(end, 100.0, "the fields count to 100 %");
|
||||
for (percent, byte) in percents.iter().zip(&bytes) {
|
||||
assert!((percent - byte / 2.55).abs() < 0.51, "every row shows its percent ({percents:?}, {bytes:?})");
|
||||
}
|
||||
|
||||
rig.fixture.advance(1.0);
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[2]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a double click right of B switches back");
|
||||
assert_eq!(field_values(&rig.fixture).0, bytes, "the rows count 0 to 255 again");
|
||||
assert!(rig.edits.borrow().is_empty(), "switching the units changes no colour: {:?}", rig.edits.borrow());
|
||||
}
|
||||
|
||||
/// A single click right of an RGB field, and a double click on the field itself, leave the units as they are.
|
||||
#[trial]
|
||||
fn only_a_double_click_on_the_units_cell_switches_the_rgb_units() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
rig.fixture.click_at(right_of(&fields[1])).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a single click right of G switches nothing");
|
||||
rig.fixture.advance(1.0);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(1);
|
||||
rig.fixture.click(&field).click(&field).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "a double click on the G field switches nothing");
|
||||
}
|
||||
|
||||
/// A click at the right edge of an RGB field followed at once by a click on the units cell beside it is not a double
|
||||
/// click on the cell, though the two presses are close enough to count as one, nor are two clicks on the cell with a
|
||||
/// click on the field between them.
|
||||
#[trial]
|
||||
fn a_click_on_the_field_then_one_on_the_units_cell_switches_nothing() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
|
||||
let (edge, cell) = (egui::pos2(field.rect.right() - 0.4, field.rect.center().y), egui::pos2(field.rect.right() + 2.4, field.rect.center().y));
|
||||
rig.fixture.click_at(cell).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click at {cell:?} is on the units cell");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(edge).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a click on the field's edge and one on the cell switch nothing");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(cell).click_at(edge).click_at(cell).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "two clicks on the cell with one on the field between them switch nothing");
|
||||
}
|
||||
|
||||
/// Two clicks on the units cell with a click on the field between them switch nothing when the field click is too far
|
||||
/// from the first to continue its click run, and the second cell click is close enough to the field click to count as
|
||||
/// its second click.
|
||||
#[trial]
|
||||
fn a_field_click_that_starts_a_new_run_between_two_units_cell_clicks_switches_nothing() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::RgbSliders);
|
||||
let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0);
|
||||
let (top, bottom) = (field.rect.top() + 1.0, field.rect.bottom() - 1.0);
|
||||
let (first, edge, second) =
|
||||
(egui::pos2(field.rect.right() + 2.4, top), egui::pos2(field.rect.right() - 0.4, bottom), egui::pos2(field.rect.right() + 2.4, bottom));
|
||||
rig.fixture.click_at(second).click_at(second).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a double click at {second:?} is on the units cell");
|
||||
rig.fixture.advance(1.0);
|
||||
rig.fixture.click_at(first).click_at(edge).click_at(second).settle();
|
||||
assert!(rig.state.borrow().rgb_percent, "a field click that starts a new run between two cell clicks switches nothing");
|
||||
}
|
||||
|
||||
/// Rows of other modes have no units cell, nor do the RGB rows of a panel whose host did not ask for them, and Web
|
||||
/// Color keeps 0 to 255 while the RGB rows show percent.
|
||||
#[trial]
|
||||
fn rows_other_than_rgb_keep_their_units() {
|
||||
let rgb = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..Default::default() };
|
||||
let mut rigs = vec![("RGB without units cells".to_owned(), PanelRig::with_state(rgb, COLOR_ROOM, false))];
|
||||
for mode in [ColorPanelMode::CmykSliders, ColorPanelMode::HsbSliders, ColorPanelMode::WebColorSliders] {
|
||||
rigs.push((format!("{mode:?}"), PanelRig::new(mode)));
|
||||
}
|
||||
for (case, mut rig) in rigs {
|
||||
let fields = rig.fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
rig.fixture.click_at(at).click_at(at).settle();
|
||||
assert!(!rig.state.borrow().rgb_percent, "{case}: a double click right of a field switches nothing");
|
||||
}
|
||||
let start = ColorPanelState { mode: ColorPanelMode::WebColorSliders, rgb_percent: true, ..Default::default() };
|
||||
let rig = PanelRig::with_state(start, COLOR_ROOM, true);
|
||||
let (_, end) = field_values(&rig.fixture);
|
||||
assert!(end > 100.0, "Web Color counts 0 to 255 while the RGB rows show percent (to {end})");
|
||||
}
|
||||
|
||||
/// The FillStroke layout's RGB rows switch their units the same way, and not while a mixed selection disables them.
|
||||
#[trial]
|
||||
fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() {
|
||||
let state = Rc::new(RefCell::new(ColorPanelState::default()));
|
||||
let edited = Rc::new(Cell::new(Some(PickedColor::rgb(RED))));
|
||||
let (s, e) = (state.clone(), edited.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = *s.borrow();
|
||||
let _ = ColorPanel::new(Bind::bound(&mut current), [RED, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::RgbSliders))
|
||||
.rgb_units_cell(true)
|
||||
.edited(e.get())
|
||||
.show(ui);
|
||||
*s.borrow_mut() = current;
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let fields = fixture.by_role(Role::SPIN_BUTTON);
|
||||
let at = right_of(&fields[0]);
|
||||
fixture.click_at(at).click_at(at).settle();
|
||||
assert!(state.borrow().rgb_percent, "a double click right of R switches the FillStroke rows to percent");
|
||||
|
||||
edited.set(None);
|
||||
fixture.settle().advance(1.0);
|
||||
fixture.click_at(at).click_at(at).settle();
|
||||
assert!(state.borrow().rgb_percent, "with the rows disabled a double click switches nothing");
|
||||
}
|
||||
|
||||
/// A Color panel whose host supplies authoritative native CMYK components.
|
||||
fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc<RefCell<PickedColor>>, Edits) {
|
||||
let host = Rc::new(RefCell::new(picked));
|
||||
let edits: Edits = Default::default();
|
||||
let (color, output) = (host.clone(), edits.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let picked = *color.borrow();
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), [picked.color; 2])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(picked))
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::CmykSliders))
|
||||
.show(ui);
|
||||
for (_, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
*color.borrow_mut() = *picked;
|
||||
}
|
||||
}
|
||||
output.borrow_mut().extend(shown.edits);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
(fixture, host, edits)
|
||||
}
|
||||
|
||||
fn step_cyan(fixture: &mut Fixture) {
|
||||
let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider");
|
||||
fixture.access(AccessActionKind::Focus, &cyan).settle();
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
}
|
||||
|
||||
fn last_native_pick(edits: &Edits) -> PickedColor {
|
||||
edits.borrow().iter().rev().find_map(|(_, event)| event.value().copied()).expect("the channel edit")
|
||||
}
|
||||
|
||||
/// A host may render its native CMYK through a different working-space transform. Editing one ink still keeps
|
||||
/// the other explicit components, rather than deriving them from the rendered RGB.
|
||||
#[trial]
|
||||
fn a_channel_edit_keeps_native_host_components_with_a_different_transform() {
|
||||
let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::rgb(0.2, 0.4, 0.6), native);
|
||||
let (mut fixture, _, edits) = native_cmyk_panel(picked);
|
||||
step_cyan(&mut fixture);
|
||||
let after = last_native_pick(&edits).model.expect("native component values");
|
||||
assert!(after.values[0] > native.values[0], "Cyan changed");
|
||||
assert_eq!(&after.values[1..4], &native.values[1..4], "the other native inks stay exact");
|
||||
}
|
||||
|
||||
/// Fresh host components win over remembered components even when both still give the same display pixel.
|
||||
#[trial]
|
||||
fn fresh_host_components_replace_the_panels_remembered_components() {
|
||||
let model = craft_color_ui::CmykModel::new(craft_cms::convert::CmykConverter::coated().clone());
|
||||
let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(model.to_srgb(&native.values), native);
|
||||
let (mut fixture, host, edits) = native_cmyk_panel(picked);
|
||||
step_cyan(&mut fixture);
|
||||
let kept = last_native_pick(&edits);
|
||||
let mut fresh = kept.model.expect("remembered native values");
|
||||
fresh.values[1] += 0.001;
|
||||
assert!(model.to_srgb(&fresh.values).same_rgb8(kept.color), "the host update keeps the display pixel");
|
||||
*host.borrow_mut() = PickedColor::in_model(kept.color, fresh);
|
||||
fixture.settle();
|
||||
step_cyan(&mut fixture);
|
||||
let after = last_native_pick(&edits).model.expect("the next channel edit");
|
||||
assert!(after.values[0] > fresh.values[0], "Cyan changed again");
|
||||
assert_eq!(&after.values[1..4], &fresh.values[1..4], "fresh host inks replace the older cache");
|
||||
}
|
||||
|
||||
/// Cancel restores both the native inks and the host's display colour, even after the host applies live updates.
|
||||
#[trial]
|
||||
fn a_canceled_native_channel_drag_restores_the_hosts_original_color() {
|
||||
let native = craft_theme::ModelValues::new("cmyk", &[12.345, 45.678, 78.912, 23.456]);
|
||||
let picked = PickedColor::in_model(Srgba::new(0.2, 0.4, 0.6, 0.7), native);
|
||||
let (mut fixture, host, edits) = native_cmyk_panel(picked);
|
||||
let cyan = fixture.by_role(Role::SLIDER).into_iter().next().expect("the Cyan slider");
|
||||
fixture.drag_hold_at(cyan.center(), Vec2::new(25.0, 0.0)).settle();
|
||||
assert_ne!(*host.borrow(), picked, "the host applies the live channel preview");
|
||||
fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
let canceled = edits
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|(_, event)| match event {
|
||||
EditEvent::Cancel { before: Some(Mixed::Same(before)), .. } => Some(*before),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the channel drag cancels");
|
||||
assert_eq!(canceled, picked, "Cancel carries the host's exact opening colour and model");
|
||||
assert_eq!(*host.borrow(), picked, "the host restores the complete opening colour");
|
||||
fixture.release_at(cyan.center() + Vec2::new(25.0, 0.0)).settle();
|
||||
assert_eq!(*host.borrow(), picked, "release after Cancel cannot reapply the preview");
|
||||
}
|
||||
|
||||
/// The rect of the FillStroke spectrum in Web Color for a foreground of `color`.
|
||||
fn spectrum_rect(color: Srgba) -> egui::Rect {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
@@ -275,6 +511,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip
|
||||
/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has
|
||||
/// sets nothing.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_keeps_the_chips_model() {
|
||||
let chip = RECENT[0];
|
||||
let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]);
|
||||
let pick = |edited: PickedColor| {
|
||||
let edits: Edits = Default::default();
|
||||
let seen = Rc::clone(&edits);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(edited))
|
||||
.recent(&RECENT)
|
||||
.recent_models(&[Some(cmyk)])
|
||||
.show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
edits.take()
|
||||
};
|
||||
let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]);
|
||||
for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] {
|
||||
let edits = pick(edited);
|
||||
assert!(
|
||||
matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })]
|
||||
if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()),
|
||||
"one Set to the chip in CMYK from {edited:?}: {edits:?}"
|
||||
);
|
||||
}
|
||||
let edits = pick(PickedColor::in_model(chip, cmyk));
|
||||
assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}");
|
||||
}
|
||||
|
||||
/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey
|
||||
/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits.
|
||||
#[trial]
|
||||
fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() {
|
||||
let grey = Srgba::rgb(0.5, 0.5, 0.5);
|
||||
let chip = [grey];
|
||||
let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]);
|
||||
let host = Rc::new(RefCell::new(grey));
|
||||
let color = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let current = *color.borrow();
|
||||
let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() };
|
||||
let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE])
|
||||
.layout(ColorPanelLayout::FillStroke)
|
||||
.edited(Some(PickedColor::rgb(current)))
|
||||
.shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders))
|
||||
.recent(&chip)
|
||||
.recent_models(&[Some(chip_hsb)])
|
||||
.show(ui);
|
||||
for (_, event) in &shown.edits {
|
||||
if let Some(picked) = event.landed() {
|
||||
*color.borrow_mut() = picked.color;
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
for _ in 0..20 {
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
}
|
||||
let hue_value = |fixture: &mut Fixture| {
|
||||
let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider");
|
||||
fixture.access(AccessActionKind::Focus, &hue).settle();
|
||||
let id = fixture.focused().expect("the hue slider takes the focus");
|
||||
fixture.tree().value(id).expect("the hue slider reports its value").to_owned()
|
||||
};
|
||||
let stepped = hue_value(&mut fixture);
|
||||
assert_ne!(stepped, "0", "the steps moved the kept hue of the grey");
|
||||
let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}");
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
@@ -379,6 +697,7 @@ struct PaletteReports {
|
||||
edits: Vec<EditEvent<Srgba>>,
|
||||
requests: Vec<ColorRequest>,
|
||||
picked: Vec<Srgba>,
|
||||
cells: Vec<PaletteCell>,
|
||||
swatches: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -390,6 +709,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
|
||||
reports.edits.extend(shown.edit);
|
||||
reports.requests.extend(shown.pick_color);
|
||||
reports.picked.extend(shown.picked);
|
||||
reports.cells.extend(shown.cell);
|
||||
reports.swatches.extend(shown.picked_swatch);
|
||||
}
|
||||
|
||||
@@ -447,11 +767,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
taken.edits[0]
|
||||
);
|
||||
assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written");
|
||||
assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row");
|
||||
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
fixture.click(&violet).settle();
|
||||
let _ = std::mem::take(&mut *reports.borrow_mut());
|
||||
let taken = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba());
|
||||
assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch");
|
||||
// Past the double-click time, so the repeat is a single click of its own.
|
||||
fixture.advance(1.0);
|
||||
let violet = fixture.by_label("Violet").expect("violet");
|
||||
@@ -816,6 +1138,56 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
|
||||
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn swatches_keep_both_host_drop_places() {
|
||||
use craft_color_ui::palette::SwatchEntry;
|
||||
use craft_ui::contract::{DropAt, DropPlace, ListDrag, ShowCollection as _};
|
||||
use craft_ui::list::{List, ListRow};
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetView};
|
||||
use egui::{Pos2, Rect, UiBuilder};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Art;
|
||||
|
||||
const SWATCHES: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(300.0, 300.0) };
|
||||
const LAYERS: Rect = Rect { min: Pos2::new(320.0, 0.0), max: Pos2::new(460.0, 120.0) };
|
||||
let groups = vec![SwatchGroup {
|
||||
name: String::new(),
|
||||
entries: vec![SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0]))],
|
||||
}];
|
||||
let received = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = Rc::clone(&received);
|
||||
let mut state = SwatchesState::default();
|
||||
state.browser.view = PresetView::List;
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ui.scope_builder(UiBuilder::new().max_rect(LAYERS), |ui| {
|
||||
let ids = [7_u32];
|
||||
let source = craft_behavior::keyed(&ids, |id: &u32| *id);
|
||||
List::<u32>::new("Layers").drag_payload(|_: &ListDrag<u32>| Some(Art)).show_items(ui, &source, &mut |_, _| ListRow::new("Art"));
|
||||
});
|
||||
ui.scope_builder(UiBuilder::new().max_rect(SWATCHES), |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED)
|
||||
.takes_drop::<Art>(DropPlace::Between, |_, _| true)
|
||||
.takes_drop::<Art>(DropPlace::Onto, |_, _| true)
|
||||
.show(ui);
|
||||
seen.borrow_mut().extend(
|
||||
out.events
|
||||
.into_iter()
|
||||
.filter_map(|event| if let PresetEvent::Dropped { at, payload, .. } = event { payload.get::<Art>().map(|_| at) } else { None }),
|
||||
);
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(480.0, 320.0)).settle();
|
||||
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch").rect;
|
||||
let gap = Pos2::new(blue.center().x, blue.min.y + 2.0);
|
||||
for to in [gap, blue.center()] {
|
||||
let from = fixture.by_label("Art").expect("the layer row").center();
|
||||
fixture.drag_at(from, to - from).settle();
|
||||
}
|
||||
let blue = SwatchKey::Swatch("Blue".into());
|
||||
assert_eq!(*received.borrow(), [DropAt::gap(Some(blue.clone()), 1), DropAt::Onto(blue)]);
|
||||
}
|
||||
|
||||
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
|
||||
/// swatch of the same name opens no field, and Enter there renames nothing.
|
||||
#[trial]
|
||||
@@ -1079,3 +1451,23 @@ fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
|
||||
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation cells stand apart: each cell's left edge lies right of the cell before it on its row,
|
||||
/// and each row's top lies below the row above it.
|
||||
#[trial]
|
||||
fn the_color_guide_variation_cells_stand_apart() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
|
||||
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let grid = fixture.by_label("Variations").expect("the variations grid");
|
||||
let cells: Vec<egui::Rect> =
|
||||
fixture.tree().children_of(grid.node).into_iter().filter_map(|key| fixture.target(key)).map(|cell| cell.rect).collect();
|
||||
assert!(cells.len() >= 4, "the grid holds its cells: {cells:?}");
|
||||
let (first, next) = (cells[0], cells[1]);
|
||||
assert!((first.center().y - next.center().y).abs() < 0.5, "the first two cells share a row: {cells:?}");
|
||||
assert!(next.left() >= first.right() + 1.0, "a gap lies between two cells of a row: {first:?}, {next:?}");
|
||||
let below = cells.iter().find(|cell| cell.top() > first.center().y).expect("a second row of cells");
|
||||
assert!(below.top() >= first.bottom() + 1.0, "a gap lies between two rows: {first:?}, {below:?}");
|
||||
}
|
||||
@@ -5,12 +5,12 @@ use std::rc::Rc;
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color_ui::ui::{
|
||||
ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning,
|
||||
PickedColor, PickerLibrary, PickerSwatches,
|
||||
ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab,
|
||||
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches,
|
||||
};
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
|
||||
use craft_ui::contract::{Bind, Role, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, EditResponse, Role, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::Row;
|
||||
@@ -177,6 +177,45 @@ fn the_dialogs_rgb_fields_show_the_hosts_working_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChannelRow::show` returns the row's edit, and `show_with_units` returns the same edit with the units cell's
|
||||
/// double click, which typing into the field does not report.
|
||||
#[trial]
|
||||
fn a_channel_rows_show_returns_its_edit_and_show_with_units_adds_the_units_cell() {
|
||||
let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 };
|
||||
/// Each edit: the row, the value and whether the units cell was double-clicked.
|
||||
type Seen = Rc<RefCell<Vec<(&'static str, f64, bool)>>>;
|
||||
let got: Seen = Rc::default();
|
||||
let seen = Rc::clone(&got);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let edit: Option<EditResponse<f64>> = ChannelRow::new("Plain", Bind::given(40.0), rule.clone()).show(ui);
|
||||
for event in edit.into_iter().flat_map(|edit| edit.events) {
|
||||
if let Some(v) = event.value() {
|
||||
seen.borrow_mut().push(("Plain", *v, false));
|
||||
}
|
||||
}
|
||||
let row: ChannelRowOutput = ChannelRow::new("Units", Bind::given(40.0), rule.clone()).show_with_units(ui);
|
||||
for event in row.edit.into_iter().flat_map(|edit| edit.events) {
|
||||
if let Some(v) = event.value() {
|
||||
seen.borrow_mut().push(("Units", *v, row.units_double_clicked));
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(320.0, 200.0));
|
||||
fixture.idle(2);
|
||||
for (i, text) in [(0, "70"), (1, "20")] {
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().nth(i).unwrap_or_else(|| panic!("number field {i}"));
|
||||
fixture.click(&field);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
}
|
||||
let got = got.borrow();
|
||||
assert!(got.iter().any(|&(row, v, _)| row == "Plain" && v == 70.0), "show reports the typed value: {got:?}");
|
||||
assert!(got.iter().any(|&(row, v, _)| row == "Units" && v == 20.0), "show_with_units reports the typed value: {got:?}");
|
||||
assert!(got.iter().all(|&(_, _, clicked)| !clicked), "typing is not a double click on the units cell: {got:?}");
|
||||
}
|
||||
|
||||
/// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme.
|
||||
const LOOKS: [(Size, &str); 4] =
|
||||
[(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")];
|
||||
@@ -504,6 +543,33 @@ fn dialog_field(dialogs: &Rc<RefCell<DialogHost>>, name: &str) -> Option<serde_j
|
||||
dialogs.borrow().get::<ColorPickerDialog>().and_then(|dialog| dialog.json_fields()).and_then(|fields| fields.get(name).cloned())
|
||||
}
|
||||
|
||||
/// #7984: a dialog with no current colour shows the Colors heading and the compare block, its current half is not a
|
||||
/// restore button, and the dialog still opens on the colour it was given.
|
||||
#[trial]
|
||||
fn the_standard_page_without_a_current_colour_offers_no_restore() {
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "picker-test", name: "Picker test", version: "0" }).build()));
|
||||
let cells = vec![(Label::from("Standard 0"), Srgba::from_hex("#ff0000").expect("a colour"))];
|
||||
dialogs.borrow_mut().open(
|
||||
ColorPickerDialog::new("fill", "Fill", Srgba::from_hex("#000000").expect("a colour"))
|
||||
.layout(ColorPickerDialogLayout::Tabbed)
|
||||
.standard(cells, Vec::new())
|
||||
.no_current()
|
||||
.web_colors_remembered(false),
|
||||
);
|
||||
fixture.idle(6);
|
||||
assert!(fixture.by_label("Colors:").is_some(), "the honeycomb has its heading");
|
||||
assert!(fixture.by_label("New color").is_some(), "the compare block shows without a current colour");
|
||||
assert!(fixture.by_label("Restore current color").is_none(), "there is nothing to restore");
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#000000"), "the dialog opens on the colour it was given");
|
||||
fixture.click(&fixture.by_label("Standard 0").expect("a cell"));
|
||||
fixture.idle(4);
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#ff0000"));
|
||||
}
|
||||
|
||||
/// The current colour of the open dialog as `#rrggbb`.
|
||||
fn dialog_color(dialogs: &Rc<RefCell<DialogHost>>) -> Option<String> {
|
||||
dialogs.borrow().get::<ColorPickerDialog>().and_then(|dialog| dialog.current()).map(|picked| picked.color.to_hex())
|
||||
@@ -538,6 +604,7 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
|
||||
fixture.idle(6);
|
||||
assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")), "the dialog opens on the tab it was given");
|
||||
assert!(fixture.by_label("Hex color").is_some(), "the Custom page shows the compact picker");
|
||||
assert!(fixture.by_label("Colors:").is_some(), "and the Colors heading over it");
|
||||
assert!(fixture.by_label("Standard 0").is_none(), "and not the honeycomb");
|
||||
assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::Value::Null), "no model is picked yet");
|
||||
assert!(fixture.by_label("Red").is_none(), "the first model (HSB) shows no red channel");
|
||||
@@ -558,6 +625,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() {
|
||||
fixture.click(&cell);
|
||||
fixture.idle(4);
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour");
|
||||
// #7984: the Standard page shows the compare block too, and its current half restores the opening colour.
|
||||
assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block");
|
||||
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
|
||||
fixture.click(&restore);
|
||||
fixture.idle(4);
|
||||
assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour");
|
||||
let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells");
|
||||
fixture.click(&cell);
|
||||
fixture.idle(4);
|
||||
|
||||
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx), "OK answers");
|
||||
let answered = dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex());
|
||||
@@ -609,3 +685,33 @@ fn a_request_for_the_swatches_opens_the_picker_on_its_swatch_view() {
|
||||
assert!(shows_swatches(request().on_swatches()), "the swatch view shows the library's cells");
|
||||
assert!(!shows_swatches(request()), "without it the picker opens on the Color Models");
|
||||
}
|
||||
|
||||
/// The number a Compact picker's channel field named `channel` paints, the picker showing HSB `values`.
|
||||
fn compact_field_number(values: [f32; 3], channel: &str) -> String {
|
||||
let hsb = ModelValues::new(HsbModel.id(), &values);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut color = PickedColor::in_model(HsbModel.to_srgb(&hsb.values), hsb);
|
||||
let models: [&dyn ColorModel; 2] = [&HsbModel, &RgbModel];
|
||||
let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Compact).models(models).show(ui);
|
||||
});
|
||||
fixture.room(vec2(600.0, 700.0));
|
||||
fixture.settle();
|
||||
let tree = fixture.tree();
|
||||
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|t| tree.name_of(t.node) == Some(channel));
|
||||
let field = field.unwrap_or_else(|| panic!("the picker shows a {channel} field")).rect;
|
||||
let texts = fixture.texts();
|
||||
let number = texts.iter().find(|run| field.contains(run.rect.center()) && run.text.starts_with(|c: char| c.is_ascii_digit()));
|
||||
number
|
||||
.unwrap_or_else(|| panic!("the {channel} field shows its value: {:?}", texts.iter().map(|r| r.text.to_string()).collect::<Vec<_>>()))
|
||||
.text
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// A Compact picker's channel rows, which the Color panel and the harmony brightness row share, show the decimals their
|
||||
/// channel declares, a percent channel too: HSB saturation declares none, so 66.7 % reads "67", not the percent look's
|
||||
/// "66.7".
|
||||
#[trial]
|
||||
fn the_compact_pickers_percent_channels_show_the_decimals_they_declare() {
|
||||
assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Saturation"), "67");
|
||||
assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Hue"), "210", "a degree channel keeps its whole degrees");
|
||||
}
|
||||
@@ -13,3 +13,7 @@ workspace = true
|
||||
[dependencies]
|
||||
serde_json = { workspace = true }
|
||||
subtle = "2"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The session token: 32 random bytes from the operating system (MIT OR Apache-2.0).
|
||||
getrandom = "0.3"
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Authenticated JSON-lines request framing and dispatch for local control services.
|
||||
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::Cell;
|
||||
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::time::{Duration, Instant};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
/// Whether a session token has the control protocol's 64 hexadecimal character form.
|
||||
@@ -9,6 +12,15 @@ pub fn valid_token(token: &str) -> bool {
|
||||
token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// A new session token that [`valid_token`] accepts: 32 bytes from the operating system's random
|
||||
/// source, as lowercase hexadecimal. `None` when the system cannot supply random bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn new_token() -> Option<String> {
|
||||
let mut bytes = [0u8; 32];
|
||||
getrandom::fill(&mut bytes).ok()?;
|
||||
Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Encode one client request, including its terminating newline.
|
||||
pub fn request_line(id: u64, token: Option<&str>, method: &str, params: &Value) -> String {
|
||||
format!("{}\n", json!({"id": id, "token": token, "method": method, "params": params}))
|
||||
@@ -103,9 +115,112 @@ pub fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usiz
|
||||
/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is
|
||||
/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and
|
||||
/// returns the reply object (the request's `id` is added here).
|
||||
pub fn serve_lines<R: Read, W: Write>(read: R, mut out: W, token: &str, max_line: usize, mut handle: impl FnMut(String, Value) -> Option<Value>) {
|
||||
let mut reader = BufReader::new(read);
|
||||
pub fn serve_lines<R: Read, W: Write>(read: R, out: W, token: &str, max_line: usize, handle: impl FnMut(String, Value) -> Option<Value>) {
|
||||
serve(BufReader::new(read), out, token, max_line, |_| Ok(()), |_| false, handle);
|
||||
}
|
||||
|
||||
/// Serve one TCP connection as [`serve_lines`] does, but give the peer `first_request` from now
|
||||
/// to send its first authenticated request. Until then every read shares that one deadline, so
|
||||
/// blank lines or a line sent a byte at a time do not extend it; when it passes, the connection
|
||||
/// closes without a reply and nothing is dispatched. After the first authenticated request, each
|
||||
/// read waits at most `idle` (`None` waits without limit). A `first_request` too long for the
|
||||
/// clock to represent waits without limit. The connection is closed when this returns.
|
||||
///
|
||||
/// Returns an `InvalidInput` error, before reading anything, when `first_request` or `idle` is
|
||||
/// zero, and any error from setting the socket's read timeout.
|
||||
pub fn serve_tcp(
|
||||
stream: TcpStream,
|
||||
token: &str,
|
||||
max_line: usize,
|
||||
first_request: Duration,
|
||||
idle: Option<Duration>,
|
||||
handle: impl FnMut(String, Value) -> Option<Value>,
|
||||
) -> std::io::Result<()> {
|
||||
if first_request.is_zero() || idle.is_some_and(|d| d.is_zero()) {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "control wait times must be longer than zero"));
|
||||
}
|
||||
let deadline = Instant::now().checked_add(first_request);
|
||||
if deadline.is_none() {
|
||||
// No deadline to apply on each read: clear any read timeout the stream already has.
|
||||
stream.set_read_timeout(None)?;
|
||||
}
|
||||
let timeout_error = Cell::new(None);
|
||||
let input = FirstRequestDeadline { socket: &stream, deadline, timeout_error: &timeout_error };
|
||||
serve(
|
||||
BufReader::new(input),
|
||||
&stream,
|
||||
token,
|
||||
max_line,
|
||||
|input: &mut FirstRequestDeadline<'_>| input.admit(idle),
|
||||
FirstRequestDeadline::expired,
|
||||
handle,
|
||||
);
|
||||
timeout_error.take().map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
/// A TCP connection's input whose reads share one deadline until the peer is admitted.
|
||||
struct FirstRequestDeadline<'a> {
|
||||
socket: &'a TcpStream,
|
||||
deadline: Option<Instant>,
|
||||
/// The error from setting the socket's read timeout, which [`serve_tcp`] returns.
|
||||
timeout_error: &'a Cell<Option<std::io::Error>>,
|
||||
}
|
||||
|
||||
impl FirstRequestDeadline<'_> {
|
||||
fn set_timeout(&self, timeout: Option<Duration>) -> std::io::Result<()> {
|
||||
self.socket.set_read_timeout(timeout).map_err(|e| {
|
||||
let kind = e.kind();
|
||||
self.timeout_error.set(Some(e));
|
||||
kind.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// The peer sent an authenticated request: from now on each read waits at most `idle`. A
|
||||
/// request admitted after the first-request deadline returns `TimedOut` instead, and the
|
||||
/// deadline stays in place.
|
||||
fn admit(&mut self, idle: Option<Duration>) -> std::io::Result<()> {
|
||||
if self.expired() {
|
||||
return Err(std::io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
self.deadline = None;
|
||||
self.set_timeout(idle)
|
||||
}
|
||||
|
||||
/// Whether the first-request deadline has passed and no request was admitted before it.
|
||||
fn expired(&self) -> bool {
|
||||
self.deadline.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for FirstRequestDeadline<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(deadline) = self.deadline {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
self.set_timeout(Some(left))?;
|
||||
}
|
||||
let mut socket = self.socket;
|
||||
socket.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// The request loop of [`serve_lines`] and [`serve_tcp`]: `admit` runs once, on the input, after
|
||||
/// the first authenticated request and before it is dispatched; an error from it closes the
|
||||
/// connection. Before the first request is admitted, a rejection closes the connection without a
|
||||
/// reply when `expired` returns true for the input.
|
||||
fn serve<R: Read, W: Write>(
|
||||
mut reader: BufReader<R>,
|
||||
mut out: W,
|
||||
token: &str,
|
||||
max_line: usize,
|
||||
mut admit: impl FnMut(&mut R) -> std::io::Result<()>,
|
||||
expired: impl Fn(&R) -> bool,
|
||||
mut handle: impl FnMut(String, Value) -> Option<Value>,
|
||||
) {
|
||||
let mut buf = Vec::new();
|
||||
let mut admitted = false;
|
||||
loop {
|
||||
let reject = match read_bounded_line(&mut reader, &mut buf, max_line) {
|
||||
Ok(false) => return,
|
||||
@@ -117,6 +232,12 @@ pub fn serve_lines<R: Read, W: Write>(read: R, mut out: W, token: &str, max_line
|
||||
Line::Blank => continue,
|
||||
Line::Reject(e) => e,
|
||||
Line::Request { id, method, params } => {
|
||||
if !admitted {
|
||||
if admit(reader.get_mut()).is_err() {
|
||||
return;
|
||||
}
|
||||
admitted = true;
|
||||
}
|
||||
let Some(mut r) = handle(method, params) else { return };
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
@@ -128,6 +249,9 @@ pub fn serve_lines<R: Read, W: Write>(read: R, mut out: W, token: &str, max_line
|
||||
}
|
||||
},
|
||||
};
|
||||
if !admitted && expired(reader.get_ref()) {
|
||||
return;
|
||||
}
|
||||
let _ = write_line(&mut out, &json!({"ok": false, "error": reject}));
|
||||
return;
|
||||
}
|
||||
@@ -249,6 +373,19 @@ mod tests {
|
||||
assert!(!valid_token(&"g".repeat(64)));
|
||||
}
|
||||
#[test]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_tokens_are_valid_and_distinct() {
|
||||
let first = new_token().unwrap();
|
||||
let second = new_token().unwrap();
|
||||
assert!(valid_token(&first));
|
||||
assert!(valid_token(&second));
|
||||
assert_ne!(first, second);
|
||||
let input = request_line(1, Some(&first), "status", &json!({}));
|
||||
let mut output = Vec::new();
|
||||
serve_lines(input.as_bytes(), &mut output, &first, 4096, |_, _| Some(json!({"ok": true})));
|
||||
assert_eq!(serde_json::from_slice::<Value>(&output).unwrap(), json!({"ok": true, "id": 1}));
|
||||
}
|
||||
#[test]
|
||||
fn authenticates_each_request_and_closes_after_failure() {
|
||||
let input =
|
||||
b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n{\"id\":2,\"method\":\"second\"}\n{\"method\":\"third\",\"token\":\"secret\"}\n";
|
||||
@@ -263,6 +400,115 @@ mod tests {
|
||||
assert_eq!(lines[0], json!({"ok": true, "id": 1}));
|
||||
assert_eq!(lines[1]["error"], "control authentication failed; closing the connection");
|
||||
}
|
||||
/// The serving thread: what `serve_tcp` returned and the methods it dispatched.
|
||||
type Server = std::thread::JoinHandle<(std::io::Result<()>, Vec<String>)>;
|
||||
/// A loopback connection whose client sent `input` before `serve_tcp` starts serving it on
|
||||
/// another thread, so the server has read everything the client sends when a wait runs out.
|
||||
fn tcp_session(input: &[u8], first_request: Duration, idle: Option<Duration>) -> (TcpStream, Server) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
// Guards the test against a server that never closes; the assertions do not depend on it.
|
||||
client.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
|
||||
client.write_all(input).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut calls = Vec::new();
|
||||
let result = serve_tcp(stream, "secret", 1024, first_request, idle, |method, _| {
|
||||
calls.push(method);
|
||||
Some(json!({"ok": true}))
|
||||
});
|
||||
(result, calls)
|
||||
});
|
||||
(client, server)
|
||||
}
|
||||
#[test]
|
||||
fn tcp_peer_without_a_request_loses_the_connection() {
|
||||
let (mut client, server) = tcp_session(b"\n{\"method\":", Duration::from_millis(50), None);
|
||||
let mut rest = Vec::new();
|
||||
client.read_to_end(&mut rest).expect("the server closes the connection");
|
||||
assert!(rest.is_empty());
|
||||
let (result, calls) = server.join().unwrap();
|
||||
assert!(result.is_ok());
|
||||
assert!(calls.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn tcp_input_waiting_after_the_deadline_is_not_read() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
client.write_all(b"\n\n").unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let timeout_error = Cell::new(None);
|
||||
let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error };
|
||||
assert_eq!(input.read(&mut [0; 8]).unwrap_err().kind(), std::io::ErrorKind::TimedOut);
|
||||
assert!(timeout_error.take().is_none());
|
||||
}
|
||||
#[test]
|
||||
fn tcp_request_read_after_the_deadline_is_not_admitted() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let timeout_error = Cell::new(None);
|
||||
let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error };
|
||||
assert_eq!(input.admit(None).unwrap_err().kind(), std::io::ErrorKind::TimedOut);
|
||||
assert!(input.deadline.is_some());
|
||||
assert!(timeout_error.take().is_none());
|
||||
}
|
||||
#[test]
|
||||
fn rejection_read_after_the_deadline_gets_no_reply() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let timeout_error = Cell::new(None);
|
||||
let mut input = FirstRequestDeadline { socket: &stream, deadline: Some(Instant::now()), timeout_error: &timeout_error };
|
||||
assert!(input.expired());
|
||||
input.deadline = None;
|
||||
assert!(!input.expired());
|
||||
let long = format!("{}\n", "x".repeat(100));
|
||||
for line in [&b"{broken}\n"[..], &b"{\"method\":\"x\",\"token\":\"wrong\"}\n"[..], long.as_bytes()] {
|
||||
let mut out = Vec::new();
|
||||
serve(BufReader::new(line), &mut out, "secret", 64, |_| Ok(()), |_| true, |_, _| panic!("must not dispatch"));
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn tcp_peer_waits_idle_time_after_its_first_request() {
|
||||
let input = b"{\"id\":1,\"method\":\"first\",\"token\":\"secret\"}\n";
|
||||
let (mut client, server) = tcp_session(input, Duration::from_secs(600), Some(Duration::from_millis(50)));
|
||||
let mut rest = Vec::new();
|
||||
client.read_to_end(&mut rest).expect("the server closes the idle connection");
|
||||
assert_eq!(serde_json::from_slice::<Value>(&rest).unwrap(), json!({"ok": true, "id": 1}));
|
||||
let (result, calls) = server.join().unwrap();
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(calls, ["first"]);
|
||||
}
|
||||
#[test]
|
||||
fn tcp_peer_sending_blank_lines_still_loses_the_connection_at_the_deadline() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let server =
|
||||
std::thread::spawn(move || serve_tcp(stream, "secret", 1024, Duration::from_millis(200), None, |_, _| panic!("must not dispatch")));
|
||||
// Every read finds a new line, so a deadline that restarted on each read would never expire.
|
||||
// The loop ends when the server closes the connection; the guard only stops a hung test.
|
||||
client.set_write_timeout(Some(Duration::from_secs(30))).unwrap();
|
||||
let guard = Instant::now() + Duration::from_secs(30);
|
||||
while client.write_all(b"\n").is_ok() {
|
||||
assert!(Instant::now() < guard, "the server kept reading past the first-request deadline");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(Instant::now() < guard, "the server stopped reading but kept the connection open");
|
||||
assert!(server.join().unwrap().is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn tcp_rejects_zero_wait_times() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
for (first, idle) in [(Duration::ZERO, None), (Duration::from_secs(1), Some(Duration::ZERO))] {
|
||||
let err = serve_tcp(stream.try_clone().unwrap(), "secret", 1024, first, idle, |_, _| panic!("must not dispatch")).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn bounds_requests_and_preserves_last_unterminated_line() {
|
||||
let mut buf = Vec::new();
|
||||
|
||||
@@ -22,9 +22,8 @@ serde_json = { workspace = true }
|
||||
|
||||
# The loopback server is for desktop apps; the web app is driven through the page instead.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0).
|
||||
getrandom = "0.3"
|
||||
# The request-line reader and the reply's result, shared with servers built on it (MIT OR Apache-2.0, ours).
|
||||
# The request-line reader, the reply's result and the per-launch token generator, shared with servers
|
||||
# built on it (MIT OR Apache-2.0, ours).
|
||||
craft-control-protocol = { workspace = true }
|
||||
# The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours).
|
||||
craft-ai-agents = { workspace = true, optional = true }
|
||||
|
||||
@@ -147,6 +147,16 @@ pub struct LiveConfig<W, H> {
|
||||
pub launch_timeout: Duration,
|
||||
/// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s).
|
||||
pub poll: Duration,
|
||||
/// The clock the launch timeout is measured on ([`Instant::now`]).
|
||||
#[doc(hidden)]
|
||||
pub now: Box<dyn Fn() -> Instant + Send + Sync>,
|
||||
/// Waits one poll while a started app is looked for ([`std::thread::sleep`]).
|
||||
#[doc(hidden)]
|
||||
pub sleep: Box<dyn Fn(Duration) + Send + Sync>,
|
||||
/// Called by each [`Live::resolve`] once it has noted how many starts have finished, before it
|
||||
/// waits for the lookup.
|
||||
#[doc(hidden)]
|
||||
pub on_queued: Option<Box<dyn Fn() + Send + Sync>>,
|
||||
consent: ConsentFn,
|
||||
connect: ConnectFn<W>,
|
||||
headless: HeadlessFn<H>,
|
||||
@@ -173,6 +183,9 @@ impl<W, H> LiveConfig<W, H> {
|
||||
launch: None,
|
||||
launch_timeout: LAUNCH_TIMEOUT,
|
||||
poll: LAUNCH_POLL,
|
||||
now: Box::new(Instant::now),
|
||||
sleep: Box::new(std::thread::sleep),
|
||||
on_queued: None,
|
||||
consent: Box::new(consent),
|
||||
connect: Box::new(connect),
|
||||
headless: Box::new(headless),
|
||||
@@ -246,6 +259,9 @@ impl<W: Clone, H: Clone> Live<W, H> {
|
||||
/// result.
|
||||
pub fn resolve(&self) -> Result<Route<W, H>, String> {
|
||||
let queued_at = self.finished.load(Ordering::Acquire);
|
||||
if let Some(queued) = &self.cfg.on_queued {
|
||||
queued();
|
||||
}
|
||||
let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let consent = (self.cfg.consent)(&self.cfg.config_dir);
|
||||
// Allow Agent Control off refuses agents, as the app does: it doesn't listen then.
|
||||
@@ -310,15 +326,15 @@ impl<W: Clone, H: Clone> Live<W, H> {
|
||||
};
|
||||
launch().map_err(|e| format!("couldn't start {app}: {e}"))?;
|
||||
let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT);
|
||||
let started = Instant::now();
|
||||
let started = (self.cfg.now)();
|
||||
let deadline = started.checked_add(timeout).unwrap_or(started);
|
||||
let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1);
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
(self.cfg.sleep)(poll);
|
||||
if let Some(window) = self.find_app()? {
|
||||
return self.use_window(window);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
if (self.cfg.now)() >= deadline {
|
||||
return Err(format!(
|
||||
"{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.",
|
||||
timeout.as_secs()
|
||||
|
||||
@@ -44,7 +44,11 @@ impl AgentSwitch {
|
||||
if !flag {
|
||||
return Self::fixed(false, false);
|
||||
}
|
||||
Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake)
|
||||
let tick = || {
|
||||
std::thread::sleep(POLL);
|
||||
true
|
||||
};
|
||||
Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), tick, wake)
|
||||
}
|
||||
|
||||
/// A switch that never changes: tests, the web, an app without agents.
|
||||
@@ -52,14 +56,20 @@ impl AgentSwitch {
|
||||
Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) }
|
||||
}
|
||||
|
||||
/// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`.
|
||||
/// [`Self::watch`] with the flag given and `probe` asked once now. The watch thread then calls
|
||||
/// `tick`, which returns when the next poll is due ([`Self::watch`] sleeps [`POLL`]), and asks
|
||||
/// `probe` again; the watch ends when `tick` returns `false`.
|
||||
#[doc(hidden)]
|
||||
pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self {
|
||||
pub fn watch_with(
|
||||
mcp_flag: bool,
|
||||
probe: impl Fn() -> bool + Send + 'static,
|
||||
mut tick: impl FnMut() -> bool + Send + 'static,
|
||||
wake: impl Fn() + Send + 'static,
|
||||
) -> Self {
|
||||
let on = Arc::new(AtomicBool::new(probe()));
|
||||
let seen: Weak<AtomicBool> = Arc::downgrade(&on);
|
||||
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
while tick() {
|
||||
let now = probe();
|
||||
let Some(seen) = seen.upgrade() else { return };
|
||||
if seen.swap(now, Ordering::Relaxed) != now {
|
||||
|
||||
@@ -4,11 +4,12 @@ use super::*;
|
||||
use crate::ControlRequest;
|
||||
use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits};
|
||||
use socket2::{Domain, Socket, Type};
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::channel;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
@@ -51,22 +52,17 @@ impl Protocol for Probe {
|
||||
}
|
||||
}
|
||||
|
||||
/// The app on `port` (0: an ephemeral one) behind [`TOKEN`]: its window answers each request after
|
||||
/// `delay` with the request's method and parameters, and the server says a request is still
|
||||
/// running after `wait`.
|
||||
fn serve(port: u16, delay: Duration, wait: Duration) -> Stop {
|
||||
// A port just closed may take a moment to be free again on a loaded machine.
|
||||
let started = Instant::now();
|
||||
let mut bound = TcpListener::bind(("127.0.0.1", port));
|
||||
while bound.is_err() && started.elapsed() < Duration::from_secs(2) {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
bound = TcpListener::bind(("127.0.0.1", port));
|
||||
}
|
||||
let listener = bound.unwrap();
|
||||
/// The app on `listener` behind [`TOKEN`]: its window answers each request with the request's
|
||||
/// method and parameters. With a `gate`, it answers each request only once the gate is opened (a
|
||||
/// message, or the sender dropped), and the server says at once that the request is still running.
|
||||
fn serve(listener: TcpListener, gate: Option<Receiver<()>>) -> Stop {
|
||||
let wait = if gate.is_some() { Duration::ZERO } else { Duration::from_secs(10) };
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
std::thread::sleep(delay);
|
||||
if let Some(gate) = &gate {
|
||||
let _ = gate.recv();
|
||||
}
|
||||
let _ = req.reply.send(json!({"ok": true, "result": {"method": req.method, "params": req.params}}));
|
||||
}
|
||||
});
|
||||
@@ -75,6 +71,60 @@ fn serve(port: u16, delay: Duration, wait: Duration) -> Stop {
|
||||
hub.listen_stoppable(listener, TOKEN.into(), tx, false).unwrap()
|
||||
}
|
||||
|
||||
/// A listener on an ephemeral loopback port.
|
||||
fn any_port() -> TcpListener {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap()
|
||||
}
|
||||
|
||||
/// `port` bound as [`TcpListener::bind`] binds it, but not listening yet: the port stays held, and
|
||||
/// a connection to it is refused until [`listen`]. A listener just stopped may still hold the port
|
||||
/// on a loaded machine ([`Stop::stop`] waits at most a couple of seconds), so the bind is retried
|
||||
/// for up to two seconds.
|
||||
fn hold(port: u16) -> Socket {
|
||||
let started = Instant::now();
|
||||
hold_after(port, || {
|
||||
if started.elapsed() >= Duration::from_secs(2) {
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// [`hold`], calling `busy` each time the port is still taken; the bind is tried again while
|
||||
/// `busy` returns true.
|
||||
fn hold_after(port: u16, mut busy: impl FnMut() -> bool) -> Socket {
|
||||
let address = std::net::SocketAddr::from(([127, 0, 0, 1], port)).into();
|
||||
loop {
|
||||
let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap();
|
||||
#[cfg(not(windows))]
|
||||
socket.set_reuse_address(true).unwrap();
|
||||
match socket.bind(&address) {
|
||||
Ok(()) => return socket,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && busy() => {}
|
||||
Err(e) => panic!("binding 127.0.0.1:{port}: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn listen(socket: Socket) -> TcpListener {
|
||||
socket.listen(128).unwrap();
|
||||
socket.into()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Opened by [`open_gate`] when the client first reports a wait.
|
||||
static GATE: RefCell<Option<Sender<()>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// A client's progress report: the app said its request is still running, so its window may
|
||||
/// answer now.
|
||||
fn open_gate(_: &str) {
|
||||
if let Some(gate) = GATE.with(|g| g.borrow_mut().take()) {
|
||||
let _ = gate.send(());
|
||||
}
|
||||
}
|
||||
|
||||
fn addr(port: u16) -> String {
|
||||
format!("127.0.0.1:{port}")
|
||||
}
|
||||
@@ -91,7 +141,7 @@ fn reserve_non_listening_port() -> (Socket, u16) {
|
||||
|
||||
#[test]
|
||||
fn a_call_is_one_round_trip_with_the_token() {
|
||||
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
|
||||
let app = serve(any_port(), None);
|
||||
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
|
||||
assert!(!c.is_connected());
|
||||
let r = c.call(Request::new("document.inspect", json!({"a": 1}))).unwrap();
|
||||
@@ -109,7 +159,7 @@ fn a_call_is_one_round_trip_with_the_token() {
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_or_none_is_refused() {
|
||||
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
|
||||
let app = serve(any_port(), None);
|
||||
for token in [Some("fedcba9876543210fedcba9876543210"), None] {
|
||||
let mut c = Connection::new(APP, &addr(app.port()), token);
|
||||
match c.call(Request::new("document.inspect", json!({}))) {
|
||||
@@ -139,20 +189,36 @@ fn the_not_running_fixture_keeps_its_port_from_another_listener() {
|
||||
drop(reserved);
|
||||
}
|
||||
|
||||
/// A port a listener still holds is bound once that listener closes, not refused at the first try.
|
||||
#[test]
|
||||
fn holding_a_port_waits_for_the_listener_on_it_to_close() {
|
||||
let mut listener = Some(any_port());
|
||||
let port = listener.as_ref().unwrap().local_addr().unwrap().port();
|
||||
let mut tries = 0;
|
||||
let held = hold_after(port, || {
|
||||
tries += 1;
|
||||
listener.take().is_some()
|
||||
});
|
||||
assert_eq!(tries, 1, "the port was free while its listener was open");
|
||||
assert_eq!(held.local_addr().unwrap().as_socket().unwrap().port(), port);
|
||||
}
|
||||
|
||||
/// An app that goes away during a call is lost, not "not running"; the next call says it is not
|
||||
/// running, and once it runs again the next call reaches it.
|
||||
#[test]
|
||||
fn an_app_gone_during_a_call_is_lost_and_reached_again_once_back() {
|
||||
let app = serve(0, Duration::ZERO, Duration::from_secs(10));
|
||||
let app = serve(any_port(), None);
|
||||
let port = app.port();
|
||||
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
|
||||
c.call(Request::new("document.inspect", json!({}))).unwrap();
|
||||
app.stop();
|
||||
// Held, not listening, until the app is back, so no other listener takes the port meanwhile.
|
||||
let held = hold(port);
|
||||
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
|
||||
let CallError::Lost(m) = &e else { panic!("{e:?}") };
|
||||
assert!(m.contains("may have quit") && m.contains("Inspect the design") && m.contains(&format!("`probe --control {port}`")), "{m}");
|
||||
assert!(matches!(c.call(Request::new("document.inspect", json!({}))), Err(CallError::NotRunning(_))));
|
||||
let _back = serve(port, Duration::ZERO, Duration::from_secs(10));
|
||||
let _back = serve(listen(held), None);
|
||||
assert_eq!(c.call(Request::new("ui.view", json!({}))).unwrap()["method"], json!("ui.view"));
|
||||
}
|
||||
|
||||
@@ -178,10 +244,13 @@ fn a_connection_closed_without_a_reply_is_lost() {
|
||||
/// connection, and its own reply is the call's result.
|
||||
#[test]
|
||||
fn a_request_still_running_is_waited_for_through_pending() {
|
||||
let app = serve(0, Duration::from_millis(400), Duration::from_millis(50));
|
||||
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
|
||||
let (gate, held) = channel();
|
||||
let app = serve(any_port(), Some(held));
|
||||
GATE.with(|g| *g.borrow_mut() = Some(gate));
|
||||
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN)).with_progress(open_gate);
|
||||
c.set_waits(Waits { pending: Duration::from_secs(10), settle: Duration::from_secs(10), poll: Duration::from_millis(5) });
|
||||
let r = c.call(Request::new("solid.slow", json!({"n": 2}))).unwrap();
|
||||
assert!(GATE.with(|g| g.borrow().is_none()), "the app never said the request was still running");
|
||||
assert_eq!(r, json!({"method": "solid.slow", "params": {"n": 2}}));
|
||||
assert!(!c.has_outstanding());
|
||||
assert_eq!(c.pending(), json!({"pending": null}));
|
||||
@@ -190,15 +259,17 @@ fn a_request_still_running_is_waited_for_through_pending() {
|
||||
/// Past the wait, the call says the request is still running, and `pending` later has its end.
|
||||
#[test]
|
||||
fn a_request_still_running_past_the_wait_is_reported_and_its_end_kept() {
|
||||
let app = serve(0, Duration::from_millis(400), Duration::from_millis(20));
|
||||
let (gate, held) = channel();
|
||||
let app = serve(any_port(), Some(held));
|
||||
let mut c = Connection::new(APP, &addr(app.port()), Some(TOKEN));
|
||||
c.set_waits(Waits { pending: Duration::from_millis(30), settle: Duration::from_secs(10), poll: Duration::from_millis(5) });
|
||||
c.set_waits(Waits { pending: Duration::ZERO, settle: Duration::from_secs(10), poll: Duration::from_millis(5) });
|
||||
let mut slow = Request::new("solid.slow", json!({}));
|
||||
slow.what = "`solid.slow` (now)".into();
|
||||
let e = c.call(slow).unwrap_err();
|
||||
let CallError::StillRunning(m) = &e else { panic!("{e:?}") };
|
||||
assert!(m.starts_with(STILL_RUNNING) && m.contains("`solid.slow` (now)") && m.contains("will still apply"), "{m}");
|
||||
assert!(c.has_outstanding());
|
||||
gate.send(()).unwrap();
|
||||
let end = c.pending();
|
||||
assert_eq!(end["done"], json!(true), "{end}");
|
||||
assert_eq!(end["reply"]["result"]["method"], json!("solid.slow"), "{end}");
|
||||
|
||||
+240
-116
@@ -7,7 +7,7 @@ use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_control_protocol::ReadFailure;
|
||||
@@ -60,11 +60,16 @@ pub struct Hub {
|
||||
/// Longest request line accepted.
|
||||
max_line: usize,
|
||||
waits: Waits,
|
||||
clock: Clock,
|
||||
watch: &'static DocumentWatch,
|
||||
running: Arc<Running>,
|
||||
open: AtomicUsize,
|
||||
}
|
||||
|
||||
/// The time a connection's token deadline is measured on: [`Instant::now`], or a clock a test
|
||||
/// moves.
|
||||
pub type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
|
||||
|
||||
impl Hub {
|
||||
/// A server for `protocol`'s requests; `wake` makes the window look at its requests now.
|
||||
pub fn new(protocol: impl Protocol + 'static, wake: impl Fn() + Send + Sync + 'static, max_line: usize) -> Self {
|
||||
@@ -73,6 +78,7 @@ impl Hub {
|
||||
wake: Box::new(wake),
|
||||
max_line,
|
||||
waits: Waits::default(),
|
||||
clock: Arc::new(Instant::now),
|
||||
watch: &DOCUMENT_WATCH,
|
||||
running: Arc::new(Running::new()),
|
||||
open: AtomicUsize::new(0),
|
||||
@@ -85,6 +91,12 @@ impl Hub {
|
||||
self
|
||||
}
|
||||
|
||||
/// Another clock for the token deadline than [`Instant::now`] (tests).
|
||||
pub fn with_clock(mut self, clock: Clock) -> Self {
|
||||
self.clock = clock;
|
||||
self
|
||||
}
|
||||
|
||||
/// Another document watch than the app's [`DOCUMENT_WATCH`] (tests).
|
||||
pub fn with_watch(mut self, watch: &'static DocumentWatch) -> Self {
|
||||
self.watch = watch;
|
||||
@@ -187,12 +199,17 @@ impl Stop {
|
||||
}
|
||||
|
||||
/// Stop accepting, close the port and end every connection it accepted. Returns once the
|
||||
/// port is closed (at most a couple of seconds), so the same port can be bound again at once.
|
||||
/// port is closed, so the same port can be bound again at once. When no connection can be
|
||||
/// made to wake the listener, it waits at most two seconds for the port to close.
|
||||
pub fn stop(self) {
|
||||
self.shared.stopped.store(true, Ordering::SeqCst);
|
||||
// The listener waits in `accept`: a connection of our own wakes it to see the flag.
|
||||
let _ = TcpStream::connect_timeout(&self.addr, Duration::from_secs(1));
|
||||
let _ = self.closed.recv_timeout(Duration::from_secs(2));
|
||||
// The listener waits in `accept`: a connection of our own wakes it to see the flag. Once
|
||||
// that connection is made, the listener accepts it and ends however busy the machine is.
|
||||
if TcpStream::connect_timeout(&self.addr, Duration::from_secs(1)).is_ok() {
|
||||
let _ = self.closed.recv();
|
||||
} else {
|
||||
let _ = self.closed.recv_timeout(Duration::from_secs(2));
|
||||
}
|
||||
self.shared.close_all();
|
||||
}
|
||||
}
|
||||
@@ -209,12 +226,9 @@ const EVENT_GAP: Duration = Duration::from_millis(100);
|
||||
/// [`MAX_CONNECTIONS`] goes to someone else.
|
||||
const TOKEN_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A new random token: 32 bytes from the operating system, as hex.
|
||||
pub fn new_token() -> Option<String> {
|
||||
let mut bytes = [0u8; 32];
|
||||
getrandom::fill(&mut bytes).ok()?;
|
||||
Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
/// A new random token: 32 bytes from the operating system, as hex. The generator lives in
|
||||
/// [`craft_control_protocol`], so this crate and servers built on that crate make the same tokens.
|
||||
pub use craft_control_protocol::new_token;
|
||||
|
||||
/// One line without its newline (and a `\r` before it), or `None` at the end of the stream, read
|
||||
/// with [`craft_control_protocol::read_bounded_line`]. A line of more than `max` bytes, not
|
||||
@@ -283,7 +297,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader<ClientInput>, docs: &str)
|
||||
use std::io::Read;
|
||||
let _ = send(out, &unauthorized(docs));
|
||||
let _ = out.shutdown(std::net::Shutdown::Write);
|
||||
reader.get_mut().deadline = Some(Instant::now() + Duration::from_millis(500));
|
||||
let input = reader.get_mut();
|
||||
input.deadline = Some((input.clock)() + Duration::from_millis(500));
|
||||
let _ = std::io::copy(&mut reader.by_ref().take(64 * 1024), &mut std::io::sink());
|
||||
}
|
||||
|
||||
@@ -293,6 +308,8 @@ fn refuse(out: &mut TcpStream, reader: &mut BufReader<ClientInput>, docs: &str)
|
||||
struct ClientInput {
|
||||
socket: TcpStream,
|
||||
deadline: Option<Instant>,
|
||||
/// What the deadline is measured on.
|
||||
clock: Clock,
|
||||
}
|
||||
|
||||
impl ClientInput {
|
||||
@@ -306,7 +323,7 @@ impl ClientInput {
|
||||
impl std::io::Read for ClientInput {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(deadline) = self.deadline {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let left = deadline.saturating_duration_since((self.clock)());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
@@ -402,6 +419,8 @@ fn cancel(pending: &mut Option<Pending>, late: Option<Value>, id: Option<&Value>
|
||||
/// a running request.
|
||||
struct Running {
|
||||
list: Mutex<Vec<InFlight>>,
|
||||
/// Notified each time a request leaves the list.
|
||||
left: Condvar,
|
||||
connections: AtomicU64,
|
||||
keys: AtomicU64,
|
||||
}
|
||||
@@ -420,7 +439,7 @@ struct InFlight {
|
||||
|
||||
impl Running {
|
||||
fn new() -> Self {
|
||||
Running { list: Mutex::new(Vec::new()), connections: AtomicU64::new(0), keys: AtomicU64::new(0) }
|
||||
Running { list: Mutex::new(Vec::new()), left: Condvar::new(), connections: AtomicU64::new(0), keys: AtomicU64::new(0) }
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, Vec<InFlight>> {
|
||||
@@ -482,6 +501,7 @@ impl Drop for Listing {
|
||||
fn drop(&mut self) {
|
||||
let key = self.key;
|
||||
self.running.lock().retain(|e| e.key != key);
|
||||
self.running.left.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,7 +680,8 @@ impl Hub {
|
||||
let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(Instant::now() + waits.token) });
|
||||
let clock = Arc::clone(&self.clock);
|
||||
let mut reader = BufReader::new(ClientInput { socket: read, deadline: Some(clock() + waits.token), clock });
|
||||
let mut bad = 0usize;
|
||||
let mut authenticated = false;
|
||||
let mut pending: Option<Pending> = None;
|
||||
@@ -844,6 +865,52 @@ mod tests {
|
||||
Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_watch(watch))
|
||||
}
|
||||
|
||||
/// [`Plain`], except that only `slow` and `queued` take the short wait.
|
||||
struct Holding;
|
||||
|
||||
impl Protocol for Holding {
|
||||
fn summary(&self, method: &str, params: &Value) -> Summary {
|
||||
Summary { long: !matches!(method, "slow" | "queued"), ..Plain.summary(method, params) }
|
||||
}
|
||||
fn document(&self) -> &'static str {
|
||||
Plain.document()
|
||||
}
|
||||
fn change_event(&self) -> &'static str {
|
||||
Plain.change_event()
|
||||
}
|
||||
fn revision_method(&self) -> &'static str {
|
||||
Plain.revision_method()
|
||||
}
|
||||
fn docs(&self) -> &'static str {
|
||||
Plain.docs()
|
||||
}
|
||||
fn capabilities(&self) -> Value {
|
||||
Plain.capabilities()
|
||||
}
|
||||
}
|
||||
|
||||
/// A server for [`Holding`] whose test window holds `slow` and `queued` back: they time out at
|
||||
/// once, as neither has its reply yet, and every other request waits for its reply. The hour
|
||||
/// only stops a hung test.
|
||||
fn holding_hub() -> Arc<Hub> {
|
||||
let waits = Waits { short: Duration::ZERO, long: Duration::from_secs(3600), token: TOKEN_WAIT };
|
||||
Arc::new(Hub::new(Holding, || {}, MAX_LINE).with_waits(waits))
|
||||
}
|
||||
|
||||
/// Wait until `hub` lists no request in `control.running`. A request that timed out leaves the
|
||||
/// list once its connection's `control.pending` has its reply. Each wait ends when the list
|
||||
/// tells the test that a request left it; one that runs out its ten seconds fails the test,
|
||||
/// even if the list has emptied since without telling it.
|
||||
fn wait_until_nothing_runs(hub: &Hub) {
|
||||
let mut list = hub.running.lock();
|
||||
while !list.is_empty() {
|
||||
let (now, waited) = hub.running.left.wait_timeout(list, Duration::from_secs(10)).unwrap_or_else(PoisonError::into_inner);
|
||||
list = now;
|
||||
assert!(!waited.timed_out(), "no request was reported leaving the list");
|
||||
}
|
||||
assert!(list.is_empty(), "a request still runs");
|
||||
}
|
||||
|
||||
/// The channel never goes on the network: a listener on any address but loopback is refused,
|
||||
/// and nothing is served on it.
|
||||
#[test]
|
||||
@@ -863,55 +930,91 @@ mod tests {
|
||||
fn the_token_has_a_time_limit_and_an_authenticated_client_may_idle() {
|
||||
use std::io::Read;
|
||||
let token = "0123456789abcdef0123456789abcdef";
|
||||
let limit = Duration::from_millis(500);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
let waits = Waits { short: Duration::from_secs(10), long: Duration::from_secs(10), token: limit };
|
||||
let hub = hub(waits, &DOCUMENT_WATCH);
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let (tx, hub) = (tx.clone(), Arc::clone(&hub));
|
||||
std::thread::spawn(move || hub.serve(stream, token, tx, false));
|
||||
}
|
||||
});
|
||||
let open = || {
|
||||
let s = TcpStream::connect(addr).unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
|
||||
s
|
||||
};
|
||||
// Sends `drip` every 50 ms until the server closes; what it read, and when it closed.
|
||||
let closed_after = |drip: &[u8]| {
|
||||
let mut s = open();
|
||||
let limit = Duration::from_secs(3600);
|
||||
// A server for one connection, whose clock stands still until the test moves it with the
|
||||
// returned `at` (the time since the connection's deadline was set). It returns once that
|
||||
// deadline is set: the clock's first reading.
|
||||
let serve_one = |limit: Duration| {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
let start = Instant::now();
|
||||
s.set_read_timeout(Some(Duration::from_millis(50))).unwrap();
|
||||
let now = Arc::new(Mutex::new(start));
|
||||
let (read_tx, read) = channel::<()>();
|
||||
let clock: Clock = {
|
||||
let now = Arc::clone(&now);
|
||||
Arc::new(move || {
|
||||
let t = *now.lock().unwrap();
|
||||
// Told only once the time is read, so the test moves the clock after it.
|
||||
let _ = read_tx.send(());
|
||||
t
|
||||
})
|
||||
};
|
||||
let waits = Waits { short: Duration::from_secs(3600), long: Duration::from_secs(3600), token: limit };
|
||||
let hub = Arc::new(Hub::new(Plain, || {}, MAX_LINE).with_waits(waits).with_clock(clock));
|
||||
std::thread::spawn(move || {
|
||||
if let Some(stream) = listener.incoming().flatten().next() {
|
||||
hub.serve(stream, token, tx, false);
|
||||
}
|
||||
});
|
||||
let s = TcpStream::connect(addr).unwrap();
|
||||
// Only stops a hung test.
|
||||
s.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
|
||||
read.recv_timeout(Duration::from_secs(20)).expect("the connection's deadline is set");
|
||||
let at = move |after: Duration| *now.lock().unwrap() = start + after;
|
||||
(s, at)
|
||||
};
|
||||
// What the server sent until it closed the connection.
|
||||
let until_closed = |s: &mut TcpStream| {
|
||||
let mut got = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0u8; 256];
|
||||
match s.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => got.extend_from_slice(buf.get(..n).unwrap()),
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
|
||||
assert!(start.elapsed() < Duration::from_secs(20), "still open");
|
||||
let _ = s.write_all(drip);
|
||||
Err(e) => {
|
||||
assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "still open");
|
||||
break;
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
(got, start.elapsed())
|
||||
got
|
||||
};
|
||||
for drip in [&b""[..], b"\n", b"\r\n \n", b" ", b"{"] {
|
||||
let (got, took) = closed_after(drip);
|
||||
// A connection that sends nothing is closed when the limit runs out on the socket's own
|
||||
// read timeout, without a word.
|
||||
let (mut s, _) = serve_one(Duration::from_millis(100));
|
||||
let got = until_closed(&mut s);
|
||||
assert!(got.is_empty(), "a silent connection was answered: {}", String::from_utf8_lossy(&got));
|
||||
for drip in [&b"\n"[..], b"\r\n \n", b" ", b"{"] {
|
||||
// Once the limit has passed, the next thing sent closes the connection without a
|
||||
// word, however the time before it was filled.
|
||||
let (mut s, at) = serve_one(limit);
|
||||
s.write_all(drip).unwrap();
|
||||
at(limit / 2);
|
||||
s.write_all(drip).unwrap();
|
||||
at(limit);
|
||||
let _ = s.write_all(drip);
|
||||
let got = until_closed(&mut s);
|
||||
assert!(got.is_empty(), "{drip:?} was answered: {}", String::from_utf8_lossy(&got));
|
||||
assert!(took >= limit.saturating_sub(Duration::from_millis(50)), "{drip:?} closed after {took:?}");
|
||||
// Before the limit, the connection is still open: a request finished then is answered.
|
||||
// A `{` is the request's own first byte.
|
||||
let request = format!("{}\n", json!({"id": 1, "method": "ui.view", "token": token}));
|
||||
let rest = request.strip_prefix(std::str::from_utf8(drip).unwrap()).unwrap_or(&request);
|
||||
let (mut s, at) = serve_one(limit);
|
||||
s.write_all(drip).unwrap();
|
||||
at(limit - Duration::from_secs(60));
|
||||
s.write_all(rest.as_bytes()).unwrap();
|
||||
let mut l = String::new();
|
||||
BufReader::new(&s).read_line(&mut l).unwrap();
|
||||
assert!(serde_json::from_str::<Value>(&l).is_ok_and(|r| r["ok"] == true), "{drip:?} closed before the limit: {l}");
|
||||
}
|
||||
|
||||
let mut s = open();
|
||||
let (mut s, at) = serve_one(limit);
|
||||
let mut lines = BufReader::new(s.try_clone().unwrap());
|
||||
let mut ask = |line: Value| -> Value {
|
||||
writeln!(s, "{line}").unwrap();
|
||||
@@ -920,11 +1023,11 @@ mod tests {
|
||||
serde_json::from_str(&l).unwrap()
|
||||
};
|
||||
assert_eq!(ask(json!({"id": 1, "method": "ui.view", "token": token}))["ok"], true);
|
||||
std::thread::sleep(limit * 3);
|
||||
at(limit * 3);
|
||||
assert_eq!(ask(json!({"id": 2, "method": "ui.view"}))["ok"], true, "idle for longer than the limit");
|
||||
|
||||
// A wrong token is still answered, at once.
|
||||
let mut wrong = open();
|
||||
let (mut wrong, _) = serve_one(limit);
|
||||
writeln!(wrong, "{}", json!({"id": 1, "method": "ui.view", "token": "nope"})).unwrap();
|
||||
let mut l = String::new();
|
||||
BufReader::new(wrong).read_line(&mut l).unwrap();
|
||||
@@ -942,6 +1045,8 @@ mod tests {
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let (gate_tx, gate_rx) = channel::<()>();
|
||||
// `()` once the window has taken `slow` to run it.
|
||||
let (started_tx, started) = channel::<()>();
|
||||
let ran = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let seen = ran.clone();
|
||||
// A stand-in for the window thread: `queued` waits behind the others (never taken until
|
||||
@@ -958,6 +1063,7 @@ mod tests {
|
||||
}
|
||||
seen.lock().unwrap().push(req.method.clone());
|
||||
if req.method == "slow" {
|
||||
let _ = started_tx.send(());
|
||||
let _ = gate_rx.recv();
|
||||
}
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
@@ -970,11 +1076,11 @@ mod tests {
|
||||
}
|
||||
}
|
||||
});
|
||||
let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT };
|
||||
let hub = hub(waits, &DOCUMENT_WATCH);
|
||||
let hub = holding_hub();
|
||||
let server = Arc::clone(&hub);
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let (tx, hub) = (tx.clone(), Arc::clone(&hub));
|
||||
let (tx, hub) = (tx.clone(), Arc::clone(&server));
|
||||
std::thread::spawn(move || hub.serve(stream, token, tx, false));
|
||||
}
|
||||
});
|
||||
@@ -1007,6 +1113,8 @@ mod tests {
|
||||
// Already running in the app: it can't be, and it still answers.
|
||||
let r = ask(&mut a, json!({"id": 4, "method": "slow"}));
|
||||
assert_eq!(r["running"], true, "{r}");
|
||||
// The ten seconds only stop a hung test.
|
||||
started.recv_timeout(Duration::from_secs(10)).expect("the window took `slow`");
|
||||
let r = ask(&mut b, json!({"id": 2, "method": "control.cancel", "params": {"id": 4}}));
|
||||
assert!(r["ok"] == false && r["error"].as_str().is_some_and(|e| e.contains("its own requests")), "another connection's: {r}");
|
||||
let r = ask(&mut a, json!({"id": 5, "method": "control.cancel", "params": {"id": 99}}));
|
||||
@@ -1015,14 +1123,8 @@ mod tests {
|
||||
assert!(r["ok"] == false && r["cancellable"] == false, "{r}");
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.starts_with("cannot be cancelled") && e.contains("control.pending")), "{r}");
|
||||
gate_tx.send(()).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let r = loop {
|
||||
let r = ask(&mut a, json!({"id": 7, "method": "control.pending"}));
|
||||
if r["result"]["done"] == true || Instant::now() > deadline {
|
||||
break r;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
wait_until_nothing_runs(&hub);
|
||||
let r = ask(&mut a, json!({"id": 7, "method": "control.pending"}));
|
||||
assert_eq!(r["result"]["reply"]["result"], "slow", "{r}");
|
||||
let r = ask(&mut a, json!({"id": 8, "method": "control.cancel"}));
|
||||
assert!(r["ok"] == true && r["result"]["cancelled"].is_null(), "{r}");
|
||||
@@ -1052,11 +1154,11 @@ mod tests {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
let waits = Waits { short: Duration::from_millis(100), long: Duration::from_millis(100), token: TOKEN_WAIT };
|
||||
let hub = hub(waits, &DOCUMENT_WATCH);
|
||||
let hub = holding_hub();
|
||||
let server = Arc::clone(&hub);
|
||||
std::thread::spawn(move || {
|
||||
if let Some(stream) = listener.incoming().flatten().next() {
|
||||
hub.serve(stream, token, tx, false);
|
||||
server.serve(stream, token, tx, false);
|
||||
}
|
||||
});
|
||||
let s = TcpStream::connect(addr).unwrap();
|
||||
@@ -1076,14 +1178,8 @@ mod tests {
|
||||
let r = ask(json!({"id": 3, "method": "control.pending"}));
|
||||
assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(1), &json!(false)), "{r}");
|
||||
gate_tx.send(()).unwrap();
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
let r = loop {
|
||||
let r = ask(json!({"id": 4, "method": "control.pending"}));
|
||||
if r["result"]["done"] == true || std::time::Instant::now() > deadline {
|
||||
break r;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
wait_until_nothing_runs(&hub);
|
||||
let r = ask(json!({"id": 4, "method": "control.pending"}));
|
||||
assert_eq!(
|
||||
(&r["result"]["pending"], &r["result"]["done"], &r["result"]["reply"]["result"]),
|
||||
(&json!(1), &json!(true), &json!("slow")),
|
||||
@@ -1122,10 +1218,15 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let hub = hub(Waits::default(), &WATCH);
|
||||
// `()` each time a connection's own thread is done with it.
|
||||
let (ended_tx, ended) = channel::<()>();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let (tx, hub) = (tx.clone(), Arc::clone(&hub));
|
||||
std::thread::spawn(move || hub.serve(stream, token, tx, false));
|
||||
let (tx, hub, ended) = (tx.clone(), Arc::clone(&hub), ended_tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
hub.serve(stream, token, tx, false);
|
||||
let _ = ended.send(());
|
||||
});
|
||||
}
|
||||
});
|
||||
let open = || {
|
||||
@@ -1176,18 +1277,10 @@ mod tests {
|
||||
assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"}));
|
||||
writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap();
|
||||
assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing");
|
||||
// Closed, it is no longer counted. Each publish asks the events thread for one more line,
|
||||
// and its write to the closed connection is what retires the seat; that keeps the wait off
|
||||
// the connection's own thread, which anything else this process is doing may hold up past
|
||||
// the deadline (#7226).
|
||||
// Closed, it is no longer counted once its own thread is done with it (the quiet one is
|
||||
// still open). The ten seconds only stop a hung test.
|
||||
drop((out, lines));
|
||||
let mut revision = 11;
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while WATCH.subscribed() && Instant::now() < deadline {
|
||||
WATCH.publish("d-1", revision);
|
||||
revision += 1;
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended");
|
||||
assert!(!WATCH.subscribed());
|
||||
}
|
||||
|
||||
@@ -1215,10 +1308,12 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let hub = hub(Waits::default(), &WATCH);
|
||||
// `()` once the connection's own thread is done with it.
|
||||
let (ended_tx, ended) = channel::<()>();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let (tx, hub) = (tx.clone(), Arc::clone(&hub));
|
||||
std::thread::spawn(move || hub.serve(stream, token, tx, false));
|
||||
if let Some(stream) = listener.incoming().flatten().next() {
|
||||
hub.serve(stream, token, tx, false);
|
||||
let _ = ended_tx.send(());
|
||||
}
|
||||
});
|
||||
let s = TcpStream::connect(addr).unwrap();
|
||||
@@ -1231,18 +1326,47 @@ mod tests {
|
||||
let reply: Value = serde_json::from_str(&l).unwrap();
|
||||
assert!(reply["ok"] == true, "{reply}");
|
||||
assert!(WATCH.subscribed(), "the connection is subscribed");
|
||||
// Let the events thread settle into its wait: the design stands still, so it has nothing
|
||||
// to write, and only the end of the connection can retire it.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
// The client goes away without asking anything else.
|
||||
// The client goes away without asking anything else. The design stands still, so the
|
||||
// events thread has nothing to write: the seat must be gone when the connection's own
|
||||
// thread is done, not when the events thread next wakes. The ten seconds only stop a hung
|
||||
// test.
|
||||
drop((out, lines));
|
||||
let deadline = Instant::now() + Duration::from_millis(400);
|
||||
while WATCH.subscribed() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
ended.recv_timeout(Duration::from_secs(10)).expect("the closed connection ended");
|
||||
assert!(!WATCH.subscribed(), "a closed connection is not counted on the watch");
|
||||
}
|
||||
|
||||
/// #7226: the events thread leaves the watch at the first write its socket refuses, while the
|
||||
/// connection's own thread still holds the seat and has not seen the end of the stream.
|
||||
#[test]
|
||||
fn the_events_thread_leaves_the_watch_when_a_write_fails() {
|
||||
static WATCH: DocumentWatch = DocumentWatch::new();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (socket, _) = listener.accept().unwrap();
|
||||
// The socket takes no more writes, as one to a client that closed: the next line fails.
|
||||
socket.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let lines = Arc::new(Lines { socket, turn: Mutex::new(()) });
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
WATCH.publish("d-1", 3);
|
||||
let seat = Arc::new(Seat::new(WATCH.join()));
|
||||
// The connection's own thread, which keeps its share of the seat throughout.
|
||||
let held = Arc::clone(&seat);
|
||||
assert!(WATCH.subscribed(), "the connection is subscribed");
|
||||
// `()` once the events thread has ended.
|
||||
let (ended_tx, ended) = channel::<()>();
|
||||
let (l, s) = (Arc::clone(&lines), Arc::clone(&stop));
|
||||
std::thread::spawn(move || {
|
||||
send_events(&WATCH, "design.changed", &l, &s, ("d-1".to_string(), 3), seat);
|
||||
let _ = ended_tx.send(());
|
||||
});
|
||||
WATCH.publish("d-1", 4);
|
||||
// The ten seconds only stop a hung test.
|
||||
ended.recv_timeout(Duration::from_secs(10)).expect("the events thread ended at the failed write");
|
||||
assert!(!stop.load(Ordering::Relaxed), "nothing stopped the events thread but the write");
|
||||
assert!(!WATCH.subscribed(), "the seat left with the events thread");
|
||||
drop((held, client));
|
||||
}
|
||||
|
||||
/// The token is read from a request object without building the rest of it: other fields,
|
||||
/// however large or nested, are only skipped. Anything but an object with a string token is
|
||||
/// no token.
|
||||
@@ -1449,19 +1573,26 @@ mod tests {
|
||||
#[test]
|
||||
fn a_stopped_listener_closes_its_port_and_its_connections() {
|
||||
use std::io::Read;
|
||||
let token = "0123456789abcdef0123456789abcdef";
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (tx, _rx) = channel();
|
||||
let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, "0123456789abcdef0123456789abcdef".into(), tx, false).unwrap();
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "result": req.method}));
|
||||
}
|
||||
});
|
||||
let stop = hub(Waits::default(), &DOCUMENT_WATCH).listen_stoppable(listener, token.into(), tx, false).unwrap();
|
||||
assert_eq!(stop.port(), port);
|
||||
let mut client = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
client.set_read_timeout(Some(Duration::from_secs(4))).unwrap();
|
||||
// Wait until the server holds the connection, so stopping has one to close.
|
||||
let held = Instant::now();
|
||||
while stop.shared.lock().is_empty() && held.elapsed() < Duration::from_secs(4) {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let started = Instant::now();
|
||||
// Only stops a hung test.
|
||||
client.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
// Once its first request is answered, the server holds the connection, so stopping has one
|
||||
// to close. It has shown the token, so the token wait cannot end it: only stopping can.
|
||||
writeln!(client, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap();
|
||||
let mut l = String::new();
|
||||
BufReader::new(&client).read_line(&mut l).unwrap();
|
||||
assert!(serde_json::from_str::<Value>(&l).is_ok_and(|r| r["ok"] == true), "{l}");
|
||||
stop.stop();
|
||||
let mut byte = [0u8; 1];
|
||||
match client.read(&mut byte) {
|
||||
@@ -1470,15 +1601,8 @@ mod tests {
|
||||
assert!(!matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), "the connection ends, not waits: {e}")
|
||||
}
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(3), "before the token wait runs out");
|
||||
// The listener thread closes its socket when it notices the stop; on a loaded machine that can
|
||||
// take a moment after `stop()` returns. Wait for the port to be free, not for one instant.
|
||||
let freed = Instant::now();
|
||||
let mut bound = TcpListener::bind(("127.0.0.1", port));
|
||||
while bound.is_err() && freed.elapsed() < Duration::from_secs(2) {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
bound = TcpListener::bind(("127.0.0.1", port));
|
||||
}
|
||||
// `stop` returns once the port is closed.
|
||||
let bound = TcpListener::bind(("127.0.0.1", port));
|
||||
assert!(bound.is_ok(), "the port is free again: {:?}", bound.err());
|
||||
}
|
||||
}
|
||||
+128
-52
@@ -6,7 +6,7 @@
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_control::agents::{
|
||||
@@ -18,18 +18,6 @@ fn temp_dir(tag: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir")
|
||||
}
|
||||
|
||||
/// Waits up to five seconds for `done`.
|
||||
fn wait_for(mut done: impl FnMut() -> bool) -> bool {
|
||||
let started = Instant::now();
|
||||
while !done() {
|
||||
if started.elapsed() > Duration::from_secs(5) {
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// Writes `text` as an owner-only token file, as an app's own token writer does.
|
||||
@@ -65,19 +53,53 @@ fn with_the_flag_only_the_launchers_switch_lets_agents_in() {
|
||||
assert!(!AgentSwitch::fixed(false, true).allows(false));
|
||||
}
|
||||
|
||||
/// The switch follows the launcher's list within a poll, wakes the app once per change rather than
|
||||
/// once per poll, and its thread ends once the last clone is dropped.
|
||||
/// The watch thread's poll clock, driven by the test: [`Self::poll`] lets one poll run and returns
|
||||
/// once the thread has finished it and waits for the next.
|
||||
struct Ticks {
|
||||
tick: mpsc::SyncSender<()>,
|
||||
waiting: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
impl Ticks {
|
||||
/// The clock and the `tick` to give [`AgentSwitch::watch_with`].
|
||||
fn new() -> (Self, impl FnMut() -> bool + Send + 'static) {
|
||||
let (tick, ticks) = mpsc::sync_channel(0);
|
||||
let (waits, waiting) = mpsc::channel();
|
||||
let wait = move || {
|
||||
let _ = waits.send(());
|
||||
ticks.recv().is_ok()
|
||||
};
|
||||
(Self { tick, waiting }, wait)
|
||||
}
|
||||
|
||||
/// Blocks until the watch thread waits for its next poll; `false` once the thread has ended.
|
||||
fn waiting(&self) -> bool {
|
||||
// A hang guard only: the thread answers at once, so the limit is never reached by a run
|
||||
// that works.
|
||||
match self.waiting.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(()) => true,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => false,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the watch thread hung"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one poll; `false` when the thread ended in it instead of waiting for the next one.
|
||||
fn poll(&self) -> bool {
|
||||
self.tick.send(()).unwrap();
|
||||
self.waiting()
|
||||
}
|
||||
}
|
||||
|
||||
/// The switch follows the launcher's list at the next poll, wakes the app once per change rather
|
||||
/// than once per poll, and its thread ends at the first poll after the last clone is dropped.
|
||||
#[test]
|
||||
fn the_switch_wakes_once_per_change() {
|
||||
let launcher = Arc::new(AtomicBool::new(false));
|
||||
let probes = Arc::new(AtomicUsize::new(0));
|
||||
let wakes = Arc::new(AtomicUsize::new(0));
|
||||
// Held by the watch thread through its probe: gone once the thread has ended.
|
||||
let alive = Arc::new(());
|
||||
let probe = {
|
||||
let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone());
|
||||
let (launcher, probes) = (launcher.clone(), probes.clone());
|
||||
move || {
|
||||
let _ = &alive;
|
||||
probes.fetch_add(1, Ordering::Relaxed);
|
||||
launcher.load(Ordering::Relaxed)
|
||||
}
|
||||
@@ -88,26 +110,35 @@ fn the_switch_wakes_once_per_change() {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let (ticks, tick) = Ticks::new();
|
||||
let switch = AgentSwitch::watch_with(true, probe, tick, wake);
|
||||
let clone = switch.clone();
|
||||
assert!(ticks.waiting());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 1, "asked once at the start");
|
||||
|
||||
launcher.store(true, Ordering::Relaxed);
|
||||
assert!(wait_for(|| clone.launcher()), "the switch follows the launcher");
|
||||
assert!(ticks.poll());
|
||||
assert!(clone.launcher(), "the switch follows the launcher");
|
||||
assert!(switch.allows(false));
|
||||
let polled = probes.load(Ordering::Relaxed);
|
||||
assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10));
|
||||
// Many polls with nothing changed.
|
||||
for _ in 0..10 {
|
||||
assert!(ticks.poll());
|
||||
}
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 12, "one probe per poll");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 1, "one wake per change, not per poll");
|
||||
launcher.store(false, Ordering::Relaxed);
|
||||
assert!(wait_for(|| !switch.launcher()));
|
||||
assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2));
|
||||
assert!(ticks.poll());
|
||||
assert!(!switch.launcher());
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll");
|
||||
|
||||
drop(switch);
|
||||
assert!(ticks.poll(), "a clone keeps the watch");
|
||||
drop(clone);
|
||||
assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch");
|
||||
let after_end = probes.load(Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended");
|
||||
// The thread probes once more, sees the switch gone and ends, so nothing probes after it.
|
||||
assert!(!ticks.poll(), "the watch ended with the last switch");
|
||||
assert_eq!(probes.load(Ordering::Relaxed), 15, "one probe per poll, the last one before the watch ended");
|
||||
assert_eq!(wakes.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
// ---- The connection file ------------------------------------------------------------------------
|
||||
@@ -238,6 +269,21 @@ fn paths(p: &[&str]) -> Vec<PathBuf> {
|
||||
p.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
/// Gives `cfg`'s launch wait a clock that moves only when the wait sleeps: each sleep calls
|
||||
/// `gate`, then adds its length to the time and returns. Returns the lengths slept.
|
||||
fn virtual_clock(cfg: &mut LiveConfig<Window, HeadlessFolders>, gate: impl Fn() + Send + Sync + 'static) -> Arc<Mutex<Vec<Duration>>> {
|
||||
let slept = Arc::new(Mutex::new(Vec::new()));
|
||||
let start = Instant::now();
|
||||
let s = slept.clone();
|
||||
cfg.now = Box::new(move || start + s.lock().unwrap().iter().sum::<Duration>());
|
||||
let s = slept.clone();
|
||||
cfg.sleep = Box::new(move |d| {
|
||||
gate();
|
||||
s.lock().unwrap().push(d);
|
||||
});
|
||||
slept
|
||||
}
|
||||
|
||||
/// An app accepting agents takes the call; the same port, token and process keep the client, a
|
||||
/// restarted app (another process on the same port and token) gets a new one.
|
||||
#[test]
|
||||
@@ -444,8 +490,10 @@ fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() {
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
cfg.launch = Some(Box::new(|| Ok(())));
|
||||
cfg.launch_timeout = Duration::from_millis(40);
|
||||
let slept = virtual_clock(&mut cfg, || {});
|
||||
let err = TestLive::new(cfg).resolve().err().unwrap();
|
||||
assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}");
|
||||
assert_eq!(*slept.lock().unwrap(), [Duration::from_millis(5); 8], "the app is looked for every poll until the timeout");
|
||||
}
|
||||
|
||||
/// "Launch" starts the app once, also for calls that arrive together, and the calls go to its
|
||||
@@ -455,19 +503,24 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() {
|
||||
let dir = temp_dir("launch");
|
||||
let made = Arc::new(Made::default());
|
||||
let launches = Arc::new(AtomicUsize::new(0));
|
||||
let app: Arc<Mutex<Option<TcpListener>>> = Arc::new(Mutex::new(None));
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone());
|
||||
let (queued_tx, queued) = mpsc::channel();
|
||||
cfg.on_queued = Some(Box::new(move || {
|
||||
let _ = queued_tx.send(());
|
||||
}));
|
||||
let (launched_tx, launched) = mpsc::channel();
|
||||
let n = launches.clone();
|
||||
cfg.launch = Some(Box::new(move || {
|
||||
n.fetch_add(1, Ordering::Relaxed);
|
||||
let (d, slot) = (d.clone(), slot.clone());
|
||||
// The app takes a moment before it accepts agents.
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(60));
|
||||
*slot.lock().unwrap() = Some(publish(&d).0);
|
||||
});
|
||||
let _ = launched_tx.send(());
|
||||
Ok(())
|
||||
}));
|
||||
// The started app's first poll waits until the test has published the app.
|
||||
let (open, opened) = mpsc::channel::<()>();
|
||||
let opened = Mutex::new(opened);
|
||||
virtual_clock(&mut cfg, move || {
|
||||
let _ = opened.lock().unwrap().recv();
|
||||
});
|
||||
let live = Arc::new(TestLive::new(cfg));
|
||||
let calls: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
@@ -475,6 +528,13 @@ fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() {
|
||||
std::thread::spawn(move || window(live.resolve()))
|
||||
})
|
||||
.collect();
|
||||
// Every call is under way before the app is started and accepts agents.
|
||||
for _ in 0..4 {
|
||||
queued.recv().unwrap();
|
||||
}
|
||||
launched.recv().unwrap();
|
||||
let _app = publish(dir.path());
|
||||
drop(open);
|
||||
let ports: Vec<u16> = calls.into_iter().map(|c| c.join().unwrap().port).collect();
|
||||
assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call");
|
||||
assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}");
|
||||
@@ -489,26 +549,30 @@ fn calls_queued_behind_a_failed_start_share_its_error() {
|
||||
let made = Arc::new(Made::default());
|
||||
let launches = Arc::new(AtomicUsize::new(0));
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
let entered = Arc::new(AtomicUsize::new(0));
|
||||
let (n, e) = (launches.clone(), entered.clone());
|
||||
// The app is started but never accepts agents within the timeout. The start waits until every
|
||||
// call is under way and then a while longer, so a call that hasn't reached its lookup by the
|
||||
// time the start ends is very unlikely (there is no hook between the two).
|
||||
let (queued_tx, queued) = mpsc::channel();
|
||||
cfg.on_queued = Some(Box::new(move || {
|
||||
let _ = queued_tx.send(());
|
||||
}));
|
||||
let queued = Mutex::new(queued);
|
||||
let n = launches.clone();
|
||||
// The app is started but never accepts agents within the timeout. The first start returns only
|
||||
// once every call has queued behind it.
|
||||
cfg.launch = Some(Box::new(move || {
|
||||
n.fetch_add(1, Ordering::Relaxed);
|
||||
assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts");
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
if n.fetch_add(1, Ordering::Relaxed) == 0 {
|
||||
let queued = queued.lock().unwrap();
|
||||
for _ in 0..4 {
|
||||
queued.recv().unwrap();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
cfg.launch_timeout = Duration::from_millis(150);
|
||||
virtual_clock(&mut cfg, || {});
|
||||
let live = Arc::new(TestLive::new(cfg));
|
||||
let calls: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let (live, entered) = (live.clone(), entered.clone());
|
||||
std::thread::spawn(move || {
|
||||
entered.fetch_add(1, Ordering::Relaxed);
|
||||
live.resolve()
|
||||
})
|
||||
let live = live.clone();
|
||||
std::thread::spawn(move || live.resolve())
|
||||
})
|
||||
.collect();
|
||||
let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect();
|
||||
@@ -596,7 +660,19 @@ fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() {
|
||||
}));
|
||||
cfg.launch_timeout = Duration::MAX;
|
||||
cfg.poll = Duration::MAX;
|
||||
let started = Instant::now();
|
||||
let slept = virtual_clock(&mut cfg, || {});
|
||||
window(TestLive::new(cfg).resolve());
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
assert_eq!(*slept.lock().unwrap(), [Duration::from_secs(1)], "the poll is cut to a second");
|
||||
|
||||
// An app that never accepts agents: the wait ends after the longest launch timeout.
|
||||
let dir = temp_dir("huge-never");
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
cfg.launch = Some(Box::new(|| Ok(())));
|
||||
cfg.launch_timeout = Duration::MAX;
|
||||
cfg.poll = Duration::MAX;
|
||||
let slept = virtual_clock(&mut cfg, || {});
|
||||
let err = TestLive::new(cfg).resolve().err().unwrap();
|
||||
assert!(err.starts_with("Test didn't accept agents within 600 s of starting."), "{err}");
|
||||
let slept = slept.lock().unwrap();
|
||||
assert_eq!((slept.len(), slept.iter().max()), (600, Some(&Duration::from_secs(1))));
|
||||
}
|
||||
@@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true }
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-math = { workspace = true, optional = true }
|
||||
craft-mesh = { workspace = true, optional = true }
|
||||
craft-mesh-ops = { workspace = true, optional = true }
|
||||
craft-metadata = { workspace = true, optional = true }
|
||||
craft-metafile = { workspace = true, optional = true }
|
||||
craft-midi = { workspace = true, optional = true }
|
||||
@@ -138,6 +139,7 @@ craft-raster-codecs = { workspace = true, optional = true }
|
||||
craft-raw = { workspace = true, optional = true }
|
||||
craft-rtf = { workspace = true, optional = true }
|
||||
craft-scraft-format = { workspace = true, optional = true }
|
||||
craft-scopes = { workspace = true, optional = true }
|
||||
craft-sf2 = { workspace = true, optional = true }
|
||||
craft-sheet = { workspace = true, optional = true }
|
||||
craft-silhouette-studio = { workspace = true, optional = true }
|
||||
@@ -221,9 +223,11 @@ craft-geom = { workspace = true, optional = true }
|
||||
craft-suite-account = { workspace = true, optional = true }
|
||||
craft-xfa = { workspace = true, optional = true }
|
||||
craft-gpu = { workspace = true, optional = true }
|
||||
craft-gpu-device = { workspace = true, optional = true }
|
||||
craft-gpu-null = { workspace = true, optional = true }
|
||||
craft-gpu-providers = { workspace = true, optional = true }
|
||||
craft-gpu-wgpu = { workspace = true, optional = true }
|
||||
craft-gpu-yuv = { workspace = true, optional = true }
|
||||
craft-ipp = { workspace = true, optional = true }
|
||||
craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
@@ -532,6 +536,13 @@ gif-frames = ["gif", "craft-gif/frames"]
|
||||
gpu = ["dep:craft-gpu"]
|
||||
gpu-startup = ["gpu", "craft-gpu/startup"]
|
||||
|
||||
gpu-device = ["dep:craft-gpu-device"]
|
||||
gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"]
|
||||
gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"]
|
||||
gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"]
|
||||
gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"]
|
||||
gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"]
|
||||
|
||||
gpu-null = ["dep:craft-gpu-null"]
|
||||
|
||||
gpu-providers = ["dep:craft-gpu-providers"]
|
||||
@@ -543,6 +554,8 @@ gpu-wgpu-native-gles = ["gpu-wgpu", "craft-gpu-wgpu/native-gles"]
|
||||
gpu-wgpu-native-metal = ["gpu-wgpu", "craft-gpu-wgpu/native-metal"]
|
||||
gpu-wgpu-native-vulkan = ["gpu-wgpu", "craft-gpu-wgpu/native-vulkan"]
|
||||
|
||||
gpu-yuv = ["dep:craft-gpu-yuv"]
|
||||
|
||||
gridcraft-format = ["dep:craft-gridcraft-format"]
|
||||
|
||||
gzip = ["dep:craft-gzip"]
|
||||
@@ -663,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"]
|
||||
mesh-stl = ["mesh", "craft-mesh/stl"]
|
||||
mesh-threemf = ["mesh", "craft-mesh/threemf"]
|
||||
|
||||
mesh-ops = ["dep:craft-mesh-ops"]
|
||||
|
||||
metadata = ["dep:craft-metadata"]
|
||||
|
||||
metafile = ["dep:craft-metafile"]
|
||||
@@ -694,6 +709,8 @@ pages = ["dep:craft-pages", "keymap", "text"]
|
||||
palette = ["dep:craft-palette"]
|
||||
|
||||
pbr = ["dep:craft-pbr"]
|
||||
pbr-materialx = ["pbr", "craft-pbr/materialx"]
|
||||
pbr-mesh = ["pbr", "craft-pbr/mesh"]
|
||||
pbr-parallel = ["pbr", "craft-pbr/parallel"]
|
||||
|
||||
pcap = ["dep:craft-pcap"]
|
||||
@@ -810,6 +827,8 @@ rtf-outlook = ["rtf", "craft-rtf/outlook"]
|
||||
|
||||
sbs = ["dep:craft-sbs"]
|
||||
|
||||
scopes = ["dep:craft-scopes"]
|
||||
|
||||
score = ["dep:craft-score"]
|
||||
|
||||
scraft-format = ["dep:craft-scraft-format"]
|
||||
@@ -931,7 +950,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"]
|
||||
|
||||
texture = ["dep:craft-texture"]
|
||||
texture-dds = ["texture", "craft-texture/dds"]
|
||||
texture-decode = ["texture", "craft-texture/decode"]
|
||||
texture-exr = ["texture", "craft-texture/exr"]
|
||||
texture-hdr = ["texture", "craft-texture/hdr"]
|
||||
texture-parallel = ["texture", "craft-texture/parallel"]
|
||||
texture-png = ["texture", "craft-texture/png"]
|
||||
texture-tiff = ["texture", "craft-texture/tiff"]
|
||||
|
||||
tga = ["dep:craft-tga"]
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ craft = { workspace = true, features = ["ui", "color-ui", "draw", "imaging", "ke
|
||||
## Features
|
||||
|
||||
- One feature per crate, named after the crate without `craft-`: `color-ui` turns on `craft-color-ui` and re-exports it as `craft::color_ui`.
|
||||
- `gpu-yuv` enables the GPU YUV provider through `craft::gpu_yuv`.
|
||||
- `ui` turns on `craft-ui` (`craft::ui`), re-exports `egui` (`craft::egui`, the egui the library is built with) and forwards `ui` to every enabled crate.
|
||||
- `screen-testing` implies `ui` and forwards to every enabled crate.
|
||||
- Each crate feature is forwarded as `<crate>-<feature>` (`platform-appearance`, `text-hyphen`, `ui-window-frame`).
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564";
|
||||
pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -161,12 +161,16 @@ pub use craft_geom as geom;
|
||||
pub use craft_gif as gif;
|
||||
#[cfg(feature = "gpu")]
|
||||
pub use craft_gpu as gpu;
|
||||
#[cfg(feature = "gpu-device")]
|
||||
pub use craft_gpu_device as gpu_device;
|
||||
#[cfg(feature = "gpu-null")]
|
||||
pub use craft_gpu_null as gpu_null;
|
||||
#[cfg(feature = "gpu-providers")]
|
||||
pub use craft_gpu_providers as gpu_providers;
|
||||
#[cfg(feature = "gpu-wgpu")]
|
||||
pub use craft_gpu_wgpu as gpu_wgpu;
|
||||
#[cfg(feature = "gpu-yuv")]
|
||||
pub use craft_gpu_yuv as gpu_yuv;
|
||||
#[cfg(feature = "gridcraft-format")]
|
||||
pub use craft_gridcraft_format as gridcraft_format;
|
||||
#[cfg(feature = "gzip")]
|
||||
@@ -247,6 +251,8 @@ pub use craft_media_source as media_source;
|
||||
pub use craft_menu as menu;
|
||||
#[cfg(feature = "mesh")]
|
||||
pub use craft_mesh as mesh;
|
||||
#[cfg(feature = "mesh-ops")]
|
||||
pub use craft_mesh_ops as mesh_ops;
|
||||
#[cfg(feature = "metadata")]
|
||||
pub use craft_metadata as metadata;
|
||||
#[cfg(feature = "metafile")]
|
||||
@@ -331,6 +337,8 @@ pub use craft_review as review;
|
||||
pub use craft_rtf as rtf;
|
||||
#[cfg(feature = "sbs")]
|
||||
pub use craft_sbs as sbs;
|
||||
#[cfg(feature = "scopes")]
|
||||
pub use craft_scopes as scopes;
|
||||
#[cfg(feature = "score")]
|
||||
pub use craft_score as score;
|
||||
#[cfg(feature = "scraft-format")]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `contract/pointer`: drag and click queries and press-origin reads outside `runtime::egui`.
|
||||
//! `contract/pointer`: drag and click queries, press-origin reads and hover-position reads outside `runtime::egui`.
|
||||
|
||||
use crate::report::Finding;
|
||||
|
||||
@@ -7,6 +7,13 @@ use super::Cx;
|
||||
pub const ID: &str = "contract/pointer";
|
||||
|
||||
pub(super) fn check(cx: &Cx<'_>, out: &mut Vec<Finding>) {
|
||||
cx.flag_methods(
|
||||
out,
|
||||
ID,
|
||||
ID,
|
||||
"reads egui's pointer position; `Cx::hover_pos` and `pointer::hover_point_in` read it and mark what follows the pointer",
|
||||
|name, args| matches!(name, "pointer_hover_pos" | "pointer_latest_pos" | "pointer_interact_pos") || (name == "hover_pos" && args.count == 0),
|
||||
);
|
||||
cx.flag_methods(out, ID, ID, "reads egui's pointer state; the pointer frame carries presses and drags", |name, _| {
|
||||
matches!(
|
||||
name,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
fn f(r: &Response) {
|
||||
fn f(r: &Response, ctx: &Context) {
|
||||
if r.drag_started() || r.clicked() {}
|
||||
let _ = r.drag_delta();
|
||||
let _ = r.hover_pos();
|
||||
let _ = ctx.pointer_latest_pos();
|
||||
}
|
||||
@@ -228,7 +228,12 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("report.docx"), b"x").unwrap();
|
||||
|
||||
let (service, panels) = FileService::scripted(Wake::none(), [Answer::Unavailable("no portal".to_owned())]);
|
||||
// The service lists the real folder on its own threads and wakes the app when each listing is in.
|
||||
let (woke, wakes) = std::sync::mpsc::channel();
|
||||
let wake = Wake::new(move || {
|
||||
let _ = woke.send(());
|
||||
});
|
||||
let (service, panels) = FileService::scripted(wake, [Answer::Unavailable("no portal".to_owned())]);
|
||||
let panels = Rc::new(RefCell::new(panels));
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let (pumped, shown) = (panels.clone(), host.clone());
|
||||
@@ -236,18 +241,15 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() {
|
||||
pumped.borrow_mut().pump_with(&mut shown.borrow_mut(), NONE);
|
||||
shown.borrow_mut().run(ui);
|
||||
});
|
||||
// The service lists the real folder on its own threads: wait until the chooser is listed.
|
||||
let listed = |fixture: &mut Fixture| {
|
||||
for _ in 0..400 {
|
||||
fixture.idle(1);
|
||||
if fields(&host).get("listed") == Some(&Value::Bool(true)) {
|
||||
// The chooser lays out its listing in the next passes: a click reads where the controls rest.
|
||||
fixture.settle();
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
// A pass takes in the listings that are in; until the chooser is listed, the next pass waits for the next wake.
|
||||
let listed = |fixture: &mut Fixture| loop {
|
||||
fixture.idle(1);
|
||||
if fields(&host).get("listed") == Some(&Value::Bool(true)) {
|
||||
// The chooser lays out its listing in the next passes: a click reads where the controls rest.
|
||||
fixture.settle();
|
||||
return;
|
||||
}
|
||||
panic!("the chooser listed the folder");
|
||||
wakes.recv_timeout(Duration::from_secs(10)).expect("a finished listing wakes the app");
|
||||
};
|
||||
let click = |fixture: &mut Fixture, label: &str| {
|
||||
let target = fixture.by_label(label).unwrap_or_else(|| panic!("`{label}` is shown"));
|
||||
@@ -284,3 +286,26 @@ fn an_unavailable_or_forced_pick_opens_the_chooser_and_settles_its_answer() {
|
||||
assert!(!host.borrow().is_open::<FileChooser>(), "the chooser closed");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_empty_folder_says_there_are_no_items() {
|
||||
let fake = Arc::new(FakeDirectories::new().folder("/d/empty").folder("/d/full").file("/d/full/chapter.docx"));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let folders = || FolderCache::new(fake.clone(), jobs.clone(), Wake::none());
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
host.borrow_mut().open(FileChooser::new(PickRequest::open("document").directory("/d/empty").fallback(true), None, folders()));
|
||||
let shown = host.clone();
|
||||
let run_jobs = jobs.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
run_jobs.run_all();
|
||||
shown.borrow_mut().run(ui);
|
||||
});
|
||||
fixture.idle(10);
|
||||
assert!(fixture.by_label("No items to show.").is_some(), "empty-state hint shown");
|
||||
|
||||
let _ = host.borrow_mut().take::<FileChooser>();
|
||||
host.borrow_mut().open(FileChooser::new(PickRequest::open("document").directory("/d/full").fallback(true), None, folders()));
|
||||
fixture.idle(10);
|
||||
assert!(fixture.by_label("chapter.docx").is_some(), "the file is listed");
|
||||
assert!(fixture.by_label("No items to show.").is_none(), "the hint is gone");
|
||||
}
|
||||
@@ -277,7 +277,7 @@ fn members_into(nodes: &[Node], t: (f32, f32, f32, f32), depth: usize, b: &Build
|
||||
let float = Float { rot: sp.props.rot, flip_h: sp.flip_h(), flip_v: sp.flip_v(), ..Float::default() };
|
||||
let (w, h) = (fit(ew * sx).max(0.0), fit(eh * sy).max(0.0));
|
||||
if let Some(obj) = leaf(sp, w, h, float, b, pics) {
|
||||
out.push(GroupChild { x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj });
|
||||
out.push(GroupChild { link: None, x: fit(x0 + ox * sx), y: fit(y0 + oy * sy), obj });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) ->
|
||||
let mut doc = Document::new();
|
||||
// Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default
|
||||
// 15 would apply Word 2013+ justification and line-breaking rules to them.
|
||||
doc.settings.compat_mode = 11;
|
||||
doc.settings.compat_mode = Some(11);
|
||||
if let Some(core) = metadata::read(&comp) {
|
||||
doc.core = core;
|
||||
}
|
||||
@@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u
|
||||
let content = word6::content(word, &fib)?;
|
||||
let mut doc = Document::new();
|
||||
// Word opens these files in compatibility mode 11 too.
|
||||
doc.settings.compat_mode = 11;
|
||||
doc.settings.compat_mode = Some(11);
|
||||
if let Some(core) = metadata::read(comp) {
|
||||
doc.core = core;
|
||||
}
|
||||
|
||||
@@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() {
|
||||
let doc = read(&f).expect("opens");
|
||||
// Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and
|
||||
// line breaking.
|
||||
assert_eq!(doc.settings.compat_mode, 11);
|
||||
assert_eq!(doc.settings.compat_mode, Some(11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -462,7 +462,7 @@ fn a_floating_copy_is_charged_its_alt_text() {
|
||||
};
|
||||
let bare = crate::object_cost(&image(String::new()));
|
||||
assert_eq!(crate::object_cost(&image("€".repeat(4096))), bare + 3 * 4096);
|
||||
let member = |obj| craft_wordmodel::para::GroupChild { x: 0.0, y: 0.0, obj };
|
||||
let member = |obj| craft_wordmodel::para::GroupChild { link: None, x: 0.0, y: 0.0, obj };
|
||||
let group = InlineObject::Group {
|
||||
w: 1.0,
|
||||
h: 1.0,
|
||||
|
||||
@@ -105,6 +105,7 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel()
|
||||
assert_eq!((p.width, p.height, p.rgba.len()), (300, 260, 300 * 260 * 4));
|
||||
assert_eq!(rgba_at(&p, 0, 0), [0, 0, 7, 255]);
|
||||
assert_eq!(rgba_at(&p, 255, 3), [255, 3, 7, 255]);
|
||||
assert_eq!(rgba_at(&p, 255, 255), [255, 255, 7, 255]);
|
||||
assert_eq!(rgba_at(&p, 256, 0), [10, 20, 30, 40]);
|
||||
assert_eq!(rgba_at(&p, 0, 256), [10, 20, 30, 40]);
|
||||
assert_eq!(rgba_at(&p, 299, 259), [200, 100, 50, 128]);
|
||||
@@ -112,6 +113,18 @@ fn eight_bit_tiles_land_on_the_canvas_and_missing_tiles_hold_the_default_pixel()
|
||||
assert_eq!(p.mask, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_one_decoded_byte_over_its_size_is_refused() {
|
||||
let mut tile = solid(&[1, 2, 3, 4]);
|
||||
tile.push(0);
|
||||
let s = surface("Rgb", "U8", true, &[0; 4], &[(0, 0, &hash(&tile))]);
|
||||
let file = bundle(256, 256, "Rgb", &[layer(&raster(&s), None)], &[&tile]);
|
||||
assert!(matches!(
|
||||
pcraft_layer_rgba(&file, &[0], &Limits::default()),
|
||||
Err(craft_doc::Error::Malformed(message)) if message.contains("more than 262144 bytes")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_and_flipped_byte_is_an_error_not_a_panic() {
|
||||
let tile = solid(&[1, 2, 3, 4]);
|
||||
|
||||
@@ -27,6 +27,7 @@ unicode-bidi = "0.3"
|
||||
zeroize = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
craft-flow = { workspace = true }
|
||||
craft-cfb = { workspace = true }
|
||||
craft-testkit = { workspace = true }
|
||||
craft-opc = { workspace = true, features = ["test-support"] }
|
||||
|
||||
+26
-1
@@ -116,6 +116,10 @@ fn room(total: u64) -> u64 {
|
||||
/// Unpack a Flat OPC file into its parts, with a `[Content_Types].xml` made from the parts'
|
||||
/// content types (unless the file carries one).
|
||||
pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
unpack_within(bytes, MAX_PART_ELEMENTS)
|
||||
}
|
||||
|
||||
fn unpack_within(bytes: &[u8], part_elements: usize) -> Result<Package, DocxError> {
|
||||
let text = utf8_text(bytes);
|
||||
let src: &[u8] = text.as_ref();
|
||||
let mut r = NsReader::from_reader(src);
|
||||
@@ -150,7 +154,7 @@ pub(crate) fn unpack(bytes: &[u8]) -> Result<Package, DocxError> {
|
||||
}
|
||||
}
|
||||
elements += 1;
|
||||
if elements > MAX_PART_ELEMENTS {
|
||||
if elements > part_elements {
|
||||
return Err(DocxError::Limit("too many XML elements".into()));
|
||||
}
|
||||
let local = e.local_name().as_ref().to_vec();
|
||||
@@ -552,6 +556,27 @@ mod tests {
|
||||
assert_eq!(out.matches("xmlns:p").count(), 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part_element_budget_counts_parts_that_are_not_read() {
|
||||
assert_eq!(MAX_PART_ELEMENTS, 8_000_002);
|
||||
let cap = 100;
|
||||
let inline = |children| format!("<r>{}</r>", "<y/>".repeat(children));
|
||||
let part = |name: &str, xml: &str| format!("<pkg:part pkg:name=\"{name}\"><pkg:xmlData>{xml}</pkg:xmlData></pkg:part>");
|
||||
let package = |parts: &str| format!("<pkg:package xmlns:pkg=\"{PKG_NS}\">{parts}</pkg:package>");
|
||||
// The part, xmlData and r wrappers count too: 97 children make exactly 100.
|
||||
let xml = inline(97);
|
||||
let first = part("/word/unused.xml", &xml);
|
||||
let at_cap = unpack_within(package(&first).as_bytes(), cap).unwrap();
|
||||
assert_eq!(at_cap.get("word/unused.xml"), Some(xml.as_bytes()));
|
||||
let over = part("/word/unused.xml", &inline(98));
|
||||
assert!(matches!(unpack_within(package(&over).as_bytes(), cap), Err(DocxError::Limit(_))));
|
||||
// Each package child has its own allowance, even though neither part is read.
|
||||
let two = format!("{first}{}", part("/word/also-unused.xml", &xml));
|
||||
let reset = unpack_within(package(&two).as_bytes(), cap).unwrap();
|
||||
assert_eq!(reset.get("word/unused.xml"), Some(xml.as_bytes()));
|
||||
assert_eq!(reset.get("word/also-unused.xml"), Some(xml.as_bytes()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_is_capped_where_the_xml_tree_reader_stops() {
|
||||
let inline = |levels: usize| format!("{}<b/>{}", "<a>".repeat(levels), "</a>".repeat(levels));
|
||||
|
||||
@@ -76,6 +76,8 @@ pub(crate) struct Reader<'p> {
|
||||
revs: HashMap<(u8, String, String, Option<String>, Option<String>), u32>,
|
||||
/// Move ranges (`w:moveFromRangeStart` …) seen so far.
|
||||
pub moves: MoveCtx,
|
||||
/// Bytes of drawing hyperlink targets copied into this document.
|
||||
drawing_link_bytes: usize,
|
||||
media_by_path: HashMap<String, String>,
|
||||
hf_by_path: HashMap<String, u32>,
|
||||
/// Header/footer parts being read right now (see [`MAX_HF_DEPTH`]).
|
||||
@@ -178,6 +180,7 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize,
|
||||
pc: PropCtx::default(),
|
||||
revs: HashMap::new(),
|
||||
moves: MoveCtx::default(),
|
||||
drawing_link_bytes: 0,
|
||||
media_by_path: HashMap::new(),
|
||||
hf_by_path: HashMap::new(),
|
||||
hf_depth: 0,
|
||||
@@ -254,7 +257,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize,
|
||||
lenient("numbering", r.read_numbering(&p));
|
||||
}
|
||||
// Without a stated mode (or settings at all) Word lays a document out as Word 2007 did.
|
||||
r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE;
|
||||
// Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308).
|
||||
r.doc.settings.compat_mode = None;
|
||||
if let Some(p) = part(rt::SETTINGS) {
|
||||
lenient("settings", r.read_settings(&p));
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ impl Reader<'_> {
|
||||
})
|
||||
.and_then(|c| c.attr("w:val"));
|
||||
if let Some(m) = mode.and_then(u32_of) {
|
||||
s.compat_mode = m.clamp(11, 99);
|
||||
s.compat_mode = Some(m.clamp(11, 99));
|
||||
}
|
||||
s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off);
|
||||
s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off);
|
||||
|
||||
Loaded 100 of 1009 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user