mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
Merge craft-libs main and regenerate the contract catalog
This commit is contained in:
commit
7e7128ad21
916 files changed
+78862
-5683
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'
|
||||
|
||||
@@ -32,7 +32,9 @@ jobs:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
linux-env: WGPU_BACKEND=vulkan
|
||||
windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1
|
||||
env: CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
CRAFT_HOSTILE_DIVISOR=1
|
||||
setup-command: bash scripts/ci-test-inputs.sh
|
||||
command: |
|
||||
python scripts/test-full-validation.py
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Nightly full tests
|
||||
|
||||
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
|
||||
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
|
||||
# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The
|
||||
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
|
||||
on:
|
||||
schedule:
|
||||
@@ -26,7 +26,9 @@ jobs:
|
||||
packages: mesa-vulkan-drivers libvulkan1
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
linux-env: WGPU_BACKEND=vulkan
|
||||
env: CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
env: |
|
||||
CRAFT_PRINT_REQUIRE_QUEUE=0
|
||||
CRAFT_HOSTILE_DIVISOR=1
|
||||
setup-command: bash scripts/ci-test-inputs.sh
|
||||
cache-paths: .test-inputs/photocraft/corpus
|
||||
cache-key: photocraft-corpus
|
||||
|
||||
@@ -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`) |
|
||||
@@ -174,6 +175,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.
|
||||
|
||||
Generated
+110
-15
@@ -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,13 @@ dependencies = [
|
||||
name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tempfile",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4328,8 +4384,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 +4734,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 +4753,7 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
@@ -4928,9 +4991,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 +5724,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 +5780,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 +5815,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 +5834,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 +5853,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 +5873,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 +5886,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 +5963,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 +6036,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 +6062,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 +6872,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 +6889,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"
|
||||
@@ -8660,6 +8737,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 +15119,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 +15412,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"
|
||||
+18
-14
@@ -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,20 @@ 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" }
|
||||
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,10 @@ 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/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.
|
||||
|
||||
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.
|
||||
@@ -377,8 +391,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item
|
||||
means stays in each app.
|
||||
|
||||
- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional
|
||||
app menu. Unsaved-document decisions and save prompts stay in each app.
|
||||
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
|
||||
documents, the Quit menu item id and the unsaved-changes question one document at a time
|
||||
(`CloseGuard`). The prompt and the saving stay in each app.
|
||||
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
|
||||
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
|
||||
for a small neutral model (paragraphs, character formatting, outline levels, tables).
|
||||
@@ -411,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
|
||||
@@ -423,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,
|
||||
|
||||
+22
-1
@@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee
|
||||
|
||||
## Core Guarantees: Atomicity vs. Durability
|
||||
|
||||
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted.
|
||||
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted.
|
||||
2. **Durability & Ordering Boundaries**:
|
||||
- **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback).
|
||||
- **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced.
|
||||
@@ -63,6 +63,27 @@ let path = Path::new("export.png");
|
||||
write_new(path, b"png bytes...").expect("exclusive write");
|
||||
```
|
||||
|
||||
### Removing Orphaned Staging Files
|
||||
|
||||
```rust
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use craft_atomic::sweep_temp_files;
|
||||
|
||||
// Removes staging files in scenes/ that were last modified an hour or more ago.
|
||||
// Returns how many were removed.
|
||||
let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0);
|
||||
```
|
||||
|
||||
`sweep_temp_files` removes only regular files whose names have the staging form, never follows
|
||||
a symbolic link, and does not search subfolders. A save updates its staging file's modification
|
||||
time only while it writes bytes, not while it flushes or renames, and removing the staging file
|
||||
makes that save fail. Choose a minimum age longer than the longest time any save into the folder,
|
||||
by any process including the calling one, may go without writing, counting the final flush and
|
||||
rename. On Windows, a write may not update the modification time until the staging file's handle
|
||||
closes, so choose a minimum age longer than the longest whole save, from the staging file's
|
||||
creation through the rename. Entries that cannot be removed are left in place.
|
||||
|
||||
### Document Permissions and Private Data
|
||||
|
||||
The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`.
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
//! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs
|
||||
//! during staging or rename, the target remains unmodified and the staging file is removed in user space.
|
||||
//! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and
|
||||
//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the
|
||||
//! consuming application; the library does not perform background sweeping. The destination file itself is
|
||||
//! never corrupted.
|
||||
//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming
|
||||
//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging
|
||||
//! files. The destination file itself is never corrupted.
|
||||
//! - **Durability & Ordering Boundaries**:
|
||||
//! Data persistence across power failures involves two sync points:
|
||||
//! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage
|
||||
@@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String {
|
||||
format!(".{stem}.{pid}-{n}.craft_tmp")
|
||||
}
|
||||
|
||||
/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed.
|
||||
///
|
||||
/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a
|
||||
/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process
|
||||
/// id in the name is not used to decide, since the system reuses process ids. A save updates its
|
||||
/// staging file's modification time only while it writes bytes, not while it flushes or renames,
|
||||
/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest
|
||||
/// time any save into `dir`, by any process including the calling one, may go without writing,
|
||||
/// counting the final flush and rename. On Windows, a write may not update the modification time
|
||||
/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save,
|
||||
/// from the staging file's creation through the rename. Entries that cannot be read or removed are
|
||||
/// left in place. Subfolders are not searched.
|
||||
/// On `wasm32` this returns an `Unsupported` error.
|
||||
pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result<usize> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (dir, min_age);
|
||||
Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform"))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let now = std::time::SystemTime::now();
|
||||
let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?;
|
||||
let mut removed = 0;
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_str().is_some_and(is_temp_name) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
|
||||
let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age);
|
||||
if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem
|
||||
/// of at most [`TEMP_STEM_BYTES`] bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn is_temp_name(name: &str) -> bool {
|
||||
// Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed.
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'));
|
||||
let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else {
|
||||
return false;
|
||||
};
|
||||
let Some((pid, n)) = tail.split_once('-') else { return false };
|
||||
stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::<u32>().is_ok() && n.parse::<u64>().is_ok()
|
||||
}
|
||||
|
||||
/// The end of an error message: whether an original file was left as it was.
|
||||
fn unchanged(existed: bool) -> &'static str {
|
||||
if existed { "; the original file was not changed" } else { "" }
|
||||
|
||||
@@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() {
|
||||
let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[test]
|
||||
fn wasm_sweep_temp_files_returns_unsupported() {
|
||||
let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
|
||||
}
|
||||
|
||||
/// Writes the file `name` in `dir` and dates its modification time `age` in the past.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result<PathBuf> {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, b"interrupted save")?;
|
||||
File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_removes_only_old_staging_files() -> io::Result<()> {
|
||||
let d = TempDir::new("sweep_old");
|
||||
let other = std::process::id().wrapping_add(1);
|
||||
let hour = std::time::Duration::from_secs(3600);
|
||||
let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?;
|
||||
// A process id the system reused for this process does not protect an old orphan.
|
||||
let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?;
|
||||
let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?;
|
||||
let document = leftover(&d.0, "scene.json", 2 * hour)?;
|
||||
|
||||
assert_eq!(sweep_temp_files(&d.0, hour)?, 2);
|
||||
assert!(!orphan.exists() && !same_pid.exists());
|
||||
assert!(recent.exists() && document.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> {
|
||||
let d = TempDir::new("sweep_lookalike");
|
||||
let other = std::process::id().wrapping_add(1);
|
||||
let old = std::time::Duration::from_secs(7200);
|
||||
let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?;
|
||||
let kept = [
|
||||
leftover(&d.0, "notes.craft_tmp", old)?,
|
||||
leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?,
|
||||
leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?,
|
||||
leftover(&d.0, ".scene.json.-3.craft_tmp", old)?,
|
||||
leftover(&d.0, ".12-3.craft_tmp", old)?,
|
||||
leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?,
|
||||
leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?,
|
||||
// temp_name writes the process id and the counter without leading zeros.
|
||||
leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?,
|
||||
leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?,
|
||||
// temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name.
|
||||
leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?,
|
||||
];
|
||||
// The longest stem temp_name writes, in ASCII and in two-byte characters.
|
||||
let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?;
|
||||
let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?;
|
||||
let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp"));
|
||||
std::fs::create_dir(&folder)?;
|
||||
|
||||
assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3);
|
||||
assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists());
|
||||
assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed");
|
||||
assert!(folder.is_dir());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn sweep_of_a_missing_folder_is_an_error() {
|
||||
let d = TempDir::new("sweep_missing");
|
||||
let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind());
|
||||
assert_eq!(err, Some(io::ErrorKind::NotFound));
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -578,7 +578,17 @@ impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
moving.column.groups.iter_mut().for_each(|group| group.height = height);
|
||||
}
|
||||
let index = place.group_index().ok_or(DockError::InvalidPlacement)?;
|
||||
let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups;
|
||||
let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?;
|
||||
// Groups shown at a width of their own, in a floating window or an expanded column, keep it
|
||||
// as the flyout width of the collapsed column they join.
|
||||
if column.iconic
|
||||
&& !moving.column.iconic
|
||||
&& let Some(width) = moving.column.width
|
||||
{
|
||||
let flyout = (column.width != Some(width)).then_some(width);
|
||||
moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout);
|
||||
}
|
||||
let groups = &mut column.groups;
|
||||
let index = (index + usize::from(below)).min(groups.len());
|
||||
groups.splice(index..index, moving.column.groups);
|
||||
Ok(())
|
||||
|
||||
@@ -545,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 {
|
||||
@@ -728,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 {
|
||||
|
||||
@@ -82,7 +82,8 @@ impl Reader {
|
||||
self
|
||||
}
|
||||
|
||||
/// The digit-group separator, which the reader skips between digits.
|
||||
/// The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a
|
||||
/// decimal when it is the number's only separator and digits follow it.
|
||||
#[must_use]
|
||||
pub fn group(mut self, group: char) -> Self {
|
||||
self.group = Some(group);
|
||||
@@ -250,11 +251,6 @@ impl Parse<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the group separator at `at` is followed by exactly three digits.
|
||||
fn three_digits_after(&self, at: usize) -> bool {
|
||||
self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3
|
||||
}
|
||||
|
||||
fn number(&mut self) -> Result<f64, NotAValue> {
|
||||
let mut text = String::new();
|
||||
let mut seen_decimal = false;
|
||||
@@ -264,7 +260,16 @@ impl Parse<'_> {
|
||||
} else if c == self.reader.decimal && !seen_decimal {
|
||||
seen_decimal = true;
|
||||
text.push('.');
|
||||
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) {
|
||||
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() {
|
||||
let after = &self.chars[self.at + 1..];
|
||||
let digits = after.iter().take_while(|c| digit(**c).is_some()).count();
|
||||
let only_mark = after.get(digits).is_none_or(|&next| next != c && next != self.reader.decimal);
|
||||
if text == "0" && matches!(c, '.' | ',') && digits > 0 && only_mark {
|
||||
seen_decimal = true;
|
||||
text.push('.');
|
||||
} else if digits != 3 {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
@@ -281,6 +286,28 @@ impl Parse<'_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_single_group_mark_after_zero_reads_as_a_decimal() {
|
||||
for (decimal, group) in [('.', ','), (',', '.')] {
|
||||
let reader = Reader::new().decimal(decimal).group(group).unit("cm", 2.0);
|
||||
for (text, want) in [
|
||||
(format!("0{group}125+2"), 2.125),
|
||||
(format!("2x0{group}125"), 0.25),
|
||||
(format!("-0{group}25 cm"), -0.5),
|
||||
(format!("٠{group}١٢٥"), 0.125),
|
||||
(format!("1{group}125"), 1125.0),
|
||||
(format!("1{group}234{decimal}5"), 1234.5),
|
||||
(format!("0{group}123{group}456"), 123456.0),
|
||||
(format!("0{group}125{decimal}5"), 125.5),
|
||||
] {
|
||||
assert_eq!(reader.read(&text, None), Ok(want), "{text}");
|
||||
}
|
||||
assert_eq!(reader.read(&format!("0{group}"), None), Err(NotAValue));
|
||||
}
|
||||
let swiss = Reader::new().group('\'');
|
||||
assert_eq!(swiss.read("0'125", None), Ok(125.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expressions_units_and_relative_input_read_through_one_grammar() {
|
||||
let reader = Reader::new().decimal(',').group('.').unit("in", 72.0).unit("pt", 1.0);
|
||||
|
||||
@@ -66,6 +66,15 @@ pub struct Wheel {
|
||||
pub lines: Vec2,
|
||||
/// Zoom factor; 1 for none.
|
||||
pub zoom: f32,
|
||||
/// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the
|
||||
/// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line
|
||||
/// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line
|
||||
/// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that
|
||||
/// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier.
|
||||
pub zoom_lines: Vec2,
|
||||
/// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture;
|
||||
/// another taker's share gathers only itself, as with `gathered`.
|
||||
pub zoom_gathered: Vec2,
|
||||
/// The modifiers held.
|
||||
pub mods: Mods,
|
||||
/// The unit the device reported.
|
||||
@@ -224,6 +233,8 @@ impl Wheel {
|
||||
scroll,
|
||||
lines: Vec2::ZERO,
|
||||
zoom: 1.0,
|
||||
zoom_lines: Vec2::ZERO,
|
||||
zoom_gathered: Vec2::ZERO,
|
||||
mods,
|
||||
unit,
|
||||
phase,
|
||||
@@ -245,6 +256,13 @@ impl Wheel {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`).
|
||||
#[must_use]
|
||||
pub const fn zoom_lines(mut self, lines: Vec2) -> Self {
|
||||
self.zoom_lines = lines;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same gesture with the two-finger touch zoom factor `zoom`.
|
||||
pub const fn touch_zoom(mut self, zoom: f32) -> Self {
|
||||
self.touch_zoom = zoom;
|
||||
@@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool {
|
||||
|
||||
/// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values.
|
||||
fn pinches(wheel: &Wheel) -> bool {
|
||||
wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO
|
||||
wheel.zoom != 1.0
|
||||
|| wheel.zoom_lines != Vec2::ZERO
|
||||
|| wheel.touch_zoom != 1.0
|
||||
|| wheel.rotation != 0.0
|
||||
|| wheel.touch_rotation != 0.0
|
||||
|| wheel.touch_pan != Vec2::ZERO
|
||||
}
|
||||
|
||||
/// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region
|
||||
/// never reads one.
|
||||
const fn scroll_only(wheel: Wheel) -> Wheel {
|
||||
Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel }
|
||||
Wheel {
|
||||
zoom: 1.0,
|
||||
zoom_lines: Vec2::ZERO,
|
||||
zoom_gathered: Vec2::ZERO,
|
||||
touch_zoom: 1.0,
|
||||
rotation: 0.0,
|
||||
touch_rotation: 0.0,
|
||||
touch_pan: Vec2::ZERO,
|
||||
zooms: false,
|
||||
..wheel
|
||||
}
|
||||
}
|
||||
|
||||
/// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes
|
||||
@@ -715,6 +748,7 @@ fn split_at<O: Copy + PartialEq>(
|
||||
Some((_, share)) => {
|
||||
share.scroll += part.scroll;
|
||||
share.zoom *= part.zoom;
|
||||
share.zoom_lines += part.zoom_lines;
|
||||
share.touch_zoom *= part.touch_zoom;
|
||||
share.rotation += part.rotation;
|
||||
share.touch_rotation += part.touch_rotation;
|
||||
|
||||
@@ -319,6 +319,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
|
||||
assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect");
|
||||
}
|
||||
|
||||
/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's
|
||||
/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group
|
||||
/// moved between collapsed columns keeps its own flyout width.
|
||||
#[test]
|
||||
fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() {
|
||||
let flyout = |layout: &Layout<u32>, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width;
|
||||
|
||||
let mut layout = columns();
|
||||
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap();
|
||||
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic);
|
||||
assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width");
|
||||
|
||||
layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap();
|
||||
layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap();
|
||||
layout.apply(Action::set_iconic(6, false)).unwrap();
|
||||
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap();
|
||||
layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with");
|
||||
|
||||
let mut layout = columns();
|
||||
layout.apply(Action::resize_column(2, 260.0)).unwrap();
|
||||
layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width");
|
||||
|
||||
let mut layout = columns();
|
||||
layout.apply(Action::resize_column(3, 300.0)).unwrap();
|
||||
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
|
||||
assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column");
|
||||
|
||||
let mut layout = columns();
|
||||
let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]);
|
||||
let Some(root) = layout.root.take() else { panic!("no root") };
|
||||
layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root));
|
||||
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");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-cdr"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings, and a .cmx writer in the layouts it reads"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# Where each layout comes from
|
||||
|
||||
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. Code cites a row by its id
|
||||
(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here.
|
||||
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 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.
|
||||
|
||||
Sources:
|
||||
|
||||
@@ -54,10 +56,20 @@ 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;
|
||||
listed so it can be checked against a file, with what the reader does when it is wrong).
|
||||
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
|
||||
the synthetic test files do not set, chosen by the writer).
|
||||
|
||||
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
|
||||
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
|
||||
@@ -124,9 +136,9 @@ 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 | sample |
|
||||
| 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) |
|
||||
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
|
||||
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
|
||||
@@ -142,3 +154,43 @@ file is committed.
|
||||
| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) |
|
||||
| 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.
|
||||
|
||||
| Field written | Rows | Status |
|
||||
|---|---|---|
|
||||
| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample |
|
||||
| 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 |
|
||||
| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes |
|
||||
| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes |
|
||||
| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample |
|
||||
| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample |
|
||||
| `rota`: one pair of 0 | R59 | sample |
|
||||
| `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 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, 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) |
|
||||
+39
-2
@@ -97,6 +97,43 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h
|
||||
path is left out and the objects it clips are read without it. Files in big-endian byte order and
|
||||
files with 16-bit coordinates are refused.
|
||||
|
||||
`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx`
|
||||
reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their
|
||||
sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file
|
||||
holds differently from the drawing is reported, as below. Rectangles and ellipses are
|
||||
written as curves, and a clipping container as a group of its fill, the objects it clips
|
||||
(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round
|
||||
corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines
|
||||
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. 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, 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
|
||||
shortened, spot colors at a tint too low to keep their look, with no name or with no known look
|
||||
(written black), uses of one ink with different looks, and what was left out or written opaque,
|
||||
unclipped or unlocked.
|
||||
|
||||
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
|
||||
|
||||
`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member,
|
||||
@@ -157,8 +194,8 @@ degree of its angle.
|
||||
|
||||
## Provenance
|
||||
|
||||
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer
|
||||
needs, with their public sources and status.
|
||||
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writers
|
||||
need, with their public sources and status.
|
||||
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
|
||||
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
|
||||
`synth` feature); no third-party file is committed.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+42
-2
@@ -11,7 +11,7 @@
|
||||
//! panic.
|
||||
//!
|
||||
//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the
|
||||
//! reader reads it. Nothing here writes `.cmx` files.
|
||||
//! reader reads it. [`write_cmx`] writes `.cmx` files in the layouts the reader reads.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -20,6 +20,7 @@ use std::fmt;
|
||||
mod build;
|
||||
mod bytes;
|
||||
mod cmx;
|
||||
mod cmx_write;
|
||||
mod geometry;
|
||||
mod inline;
|
||||
mod layout;
|
||||
@@ -38,6 +39,7 @@ mod wl;
|
||||
mod write;
|
||||
mod zip;
|
||||
|
||||
pub use cmx_write::{MAX_CURVE_POINTS, Written};
|
||||
pub use limits::Limits;
|
||||
pub use model::{Drawing, Warning};
|
||||
pub use preview::{Preview, PreviewFormat, preview};
|
||||
@@ -66,7 +68,8 @@ pub enum Error {
|
||||
Version(u16),
|
||||
/// A container structure that doesn't parse.
|
||||
Damaged(&'static str),
|
||||
/// Past one of the [`Limits`].
|
||||
/// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an
|
||||
/// outline width that is negative or NaN.
|
||||
Limit(&'static str),
|
||||
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
|
||||
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a
|
||||
@@ -118,3 +121,40 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
|
||||
let mut budget = limits::Budget::new(limits);
|
||||
cmx::drawing(bytes, &mut budget)
|
||||
}
|
||||
|
||||
/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts
|
||||
/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and
|
||||
/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them;
|
||||
/// what the file holds differently from the drawing, such as a name the reader shortens, is
|
||||
/// reported in [`Written`].
|
||||
///
|
||||
/// It fails with [`Error::Limit`], and writes nothing, for:
|
||||
/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline
|
||||
/// 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`, 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
|
||||
/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is
|
||||
/// written with round corners of its radii times the square root of the scales' product, not with
|
||||
/// stretched corners, and is not reported.
|
||||
///
|
||||
/// 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)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4;
|
||||
const MAX_OUTLINE_RECORDS: usize = 16;
|
||||
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
|
||||
/// a layer's.
|
||||
const MAX_NAME: usize = 256;
|
||||
pub(crate) const MAX_NAME: usize = 256;
|
||||
|
||||
/// A header field: u16 in short files, u32 otherwise.
|
||||
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
|
||||
@@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option<f32> {
|
||||
}
|
||||
|
||||
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
|
||||
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
|
||||
pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
|
||||
if tint <= 0.0 {
|
||||
return rgb;
|
||||
}
|
||||
@@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option<u64>) -> String {
|
||||
|
||||
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
|
||||
/// are Latin-1.
|
||||
const CP1252_HIGH: [char; 32] = [
|
||||
pub(crate) const CP1252_HIGH: [char; 32] = [
|
||||
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
|
||||
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
|
||||
];
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@
|
||||
|
||||
mod bench;
|
||||
mod cmx;
|
||||
mod cmx_write;
|
||||
mod provenance;
|
||||
mod read;
|
||||
mod write;
|
||||
@@ -282,6 +282,58 @@ fn a_late_reply_from_before_sign_out_is_dropped() {
|
||||
);
|
||||
}
|
||||
|
||||
/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it
|
||||
/// before a request the next frame sends. A provider that still holds the session answers that
|
||||
/// request with the departed account, and the window must not show that account or its files.
|
||||
#[test]
|
||||
fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() {
|
||||
let (mut app, held, _log) = two_tabs();
|
||||
start(&mut app);
|
||||
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
|
||||
post.send(Event::Account(Ok(account("Previous Person"))));
|
||||
held.take(|j| matches!(j, Job::List(_))).unwrap();
|
||||
drain(&mut app, &egui::Context::default());
|
||||
sign_out(&mut app);
|
||||
start(&mut app);
|
||||
// Whatever the frame asked is answered as a provider that has not yet ended the session would.
|
||||
while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) {
|
||||
match job {
|
||||
Job::Account => post.send(Event::Account(Ok(account("Previous Person")))),
|
||||
Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
drain(&mut app, &egui::Context::default());
|
||||
let r = report(&app);
|
||||
assert!(
|
||||
r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty),
|
||||
"signed out, yet account={} entries={}",
|
||||
r["account"],
|
||||
r["entries"]
|
||||
);
|
||||
sign_in(&mut app);
|
||||
let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap();
|
||||
post.send(Event::Account(Ok(account("Ada"))));
|
||||
drain(&mut app, &egui::Context::default());
|
||||
start(&mut app);
|
||||
assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again");
|
||||
}
|
||||
|
||||
/// Save As while signed out has no account to land in. A provider that has not ended the session
|
||||
/// yet would create the file in the account that is leaving.
|
||||
#[test]
|
||||
fn save_as_after_sign_out_is_refused_until_the_next_sign_in() {
|
||||
let (mut app, held, _log) = two_tabs();
|
||||
start(&mut app);
|
||||
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
|
||||
post.send(Event::Account(Ok(account("Previous Person"))));
|
||||
drain(&mut app, &egui::Context::default());
|
||||
sign_out(&mut app);
|
||||
let refused = save_as(&mut app, "", "Plan");
|
||||
assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}");
|
||||
assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out");
|
||||
}
|
||||
|
||||
/// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The
|
||||
/// second click, with a name, must still copy the conflicted document A, not the active tab B.
|
||||
#[test]
|
||||
|
||||
@@ -191,6 +191,11 @@ pub struct CloudFiles {
|
||||
pub account_fault: Option<Fault>,
|
||||
/// The account is asked for once per run. A frame never asks again.
|
||||
asked_account: bool,
|
||||
/// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the
|
||||
/// pages ask the service nothing. [`Job::SignOut`] has no answer and no
|
||||
/// order against a later job, so a provider that still holds the session
|
||||
/// could answer an account or listing request with the departed account.
|
||||
signed_out: bool,
|
||||
/// The folder being browsed. Shared by the Open and Save As pages, which
|
||||
/// are never on screen together.
|
||||
pub mine: Folder,
|
||||
@@ -249,6 +254,7 @@ impl CloudFiles {
|
||||
account: None,
|
||||
account_fault: None,
|
||||
asked_account: false,
|
||||
signed_out: false,
|
||||
mine: Folder::default(),
|
||||
shared: Folder::default(),
|
||||
source: Source::default(),
|
||||
@@ -344,8 +350,10 @@ pub fn submit<A: CloudApp>(app: &A, job: Job) {
|
||||
}
|
||||
|
||||
/// Asks who is signed in, once per run, and lists the root folder.
|
||||
///
|
||||
/// After [`sign_out`] it asks nothing until the next [`sign_in`].
|
||||
pub fn start<A: CloudApp>(app: &mut A) {
|
||||
if !available(app) {
|
||||
if !available(app) || app.cloud().signed_out {
|
||||
return;
|
||||
}
|
||||
if !app.cloud().asked_account {
|
||||
@@ -375,6 +383,7 @@ pub fn sign_in<A: CloudApp>(app: &mut A) {
|
||||
// would then be swallowed by the guard that stops a frame asking twice. A
|
||||
// button that does nothing the second time reads as a broken button.
|
||||
cloud.asked_account = true;
|
||||
cloud.signed_out = false;
|
||||
cloud.link = None;
|
||||
cloud.status = Some(working);
|
||||
// A new session. A job the previous one left outstanding may never
|
||||
@@ -402,6 +411,10 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
|
||||
cloud.account = None;
|
||||
cloud.account_fault = None;
|
||||
cloud.asked_account = false;
|
||||
// File › Open and Save As call `start` on every frame. Without this, the
|
||||
// next frame would ask who is signed in and list the root folder while
|
||||
// the sign-out may still be on its way.
|
||||
cloud.signed_out = true;
|
||||
cloud.link = None;
|
||||
cloud.mine = Folder::default();
|
||||
cloud.shared = Folder::default();
|
||||
@@ -413,8 +426,13 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
|
||||
// that never heard back does not refuse every one after it forever.
|
||||
cloud.account_generation.fetch_add(1, Ordering::Relaxed);
|
||||
cloud.busy = None;
|
||||
cloud.sharing_save = false;
|
||||
cloud.relist_after_sign_in = false;
|
||||
cloud.save_as_target = None;
|
||||
// Sharing went with the account: Share is not offered on the old
|
||||
// account's answer, and a sheet open on one of its documents closes. The
|
||||
// next sign-in asks the provider again.
|
||||
app.sharing().signed_out();
|
||||
submit(app, Job::SignOut);
|
||||
}
|
||||
|
||||
@@ -630,6 +648,9 @@ pub fn save_as<A: CloudApp>(app: &mut A, folder: &str, name: &str) -> Result<Jso
|
||||
if app.cloud().relist_after_sign_in {
|
||||
return Err("wait for the sign-in to finish".to_owned());
|
||||
}
|
||||
if app.cloud().signed_out {
|
||||
return Err(app.tr("Sign in to save to the cloud"));
|
||||
}
|
||||
// A document that does not exist yet has no content type to read. The
|
||||
// name a person just typed is the whole of what was asked for.
|
||||
let bytes = app.encode(uid, Destination::new(&name))?;
|
||||
|
||||
@@ -42,6 +42,11 @@ fn header<A: CloudApp>(app: &mut A, ui: &mut Ui) {
|
||||
let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() };
|
||||
dim(ui, &style, &line);
|
||||
}
|
||||
// Nothing is asked after a sign-out, so there is nothing to wait for.
|
||||
(None, None) if app.cloud().signed_out => {
|
||||
let signed_out = app.tr("Signed out");
|
||||
dim(ui, &style, &signed_out);
|
||||
}
|
||||
(None, None) => {
|
||||
let waiting = app.tr("Connecting to your cloud account…");
|
||||
dim(ui, &style, &waiting);
|
||||
|
||||
@@ -435,6 +435,49 @@ fn signing_out_forgets_everything_this_window_knew() {
|
||||
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too");
|
||||
}
|
||||
|
||||
/// A sharing service that says it can share and answers nothing else.
|
||||
struct Shares;
|
||||
|
||||
impl crate::share::ShareBackend for Shares {
|
||||
fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) {
|
||||
if request == crate::share::Request::Capabilities {
|
||||
reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_out_takes_sharing_with_it() {
|
||||
let (mut app, _jobs, ctx) = wired();
|
||||
app.share.connect(Shares);
|
||||
// Enough frames for an account answer to land, the provider to be asked,
|
||||
// and its answer to be read.
|
||||
let frames = |app: &mut Notebook| {
|
||||
for _ in 0..3 {
|
||||
ctx.begin_pass(Default::default());
|
||||
app.share.show(&ctx);
|
||||
pump(app, &ctx);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
}
|
||||
};
|
||||
frames(&mut app);
|
||||
assert!(app.share.available());
|
||||
app.share.open("/Minutes.note", "Minutes");
|
||||
assert!(app.share.is_open());
|
||||
|
||||
sign_out(&mut app);
|
||||
assert!(!app.share.is_open(), "a sheet open on the old account's document closes");
|
||||
assert!(!app.share.available(), "Share is not offered on the old account's answer");
|
||||
// The provider is not asked again while the sign-out may still be on its
|
||||
// way, so a service that still has the old account cannot offer it back.
|
||||
frames(&mut app);
|
||||
assert!(!app.share.available(), "nobody is signed in");
|
||||
|
||||
sign_in(&mut app);
|
||||
frames(&mut app);
|
||||
assert!(app.share.available(), "the next sign-in asks again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_queued_before_the_session_changed_is_dropped() {
|
||||
let (mut app, _jobs, ctx) = wired();
|
||||
|
||||
@@ -338,6 +338,10 @@ pub struct ShareDialog {
|
||||
provider: Option<Provider>,
|
||||
/// When the capability question was last asked.
|
||||
asked: Option<f64>,
|
||||
/// The last request number issued before the latest [`ShareDialog::refresh`]
|
||||
/// or [`ShareDialog::connect`]. A capabilities answer to that request or an
|
||||
/// earlier one describes the account as it was, and is ignored.
|
||||
capabilities_after: u64,
|
||||
open: Option<Sheet>,
|
||||
/// Keyed by the URL the contact carried, so reopening the dialog does not
|
||||
/// fetch the same faces again.
|
||||
@@ -370,6 +374,7 @@ impl ShareDialog {
|
||||
seq: 0,
|
||||
provider: None,
|
||||
asked: None,
|
||||
capabilities_after: 0,
|
||||
open: None,
|
||||
avatars: HashMap::new(),
|
||||
wants_save: None,
|
||||
@@ -387,6 +392,7 @@ impl ShareDialog {
|
||||
self.backend = Some(Box::new(backend));
|
||||
self.provider = None;
|
||||
self.asked = None;
|
||||
self.capabilities_after = self.seq;
|
||||
}
|
||||
|
||||
pub fn connected(&self) -> bool {
|
||||
@@ -413,10 +419,25 @@ impl ShareDialog {
|
||||
/// The answer is kept once it arrives, so a host that signs somebody
|
||||
/// in after the first answer has to say so. Without this the dialog
|
||||
/// keeps the answer it got while nobody was signed in, and Share
|
||||
/// stays unavailable for the rest of the run.
|
||||
/// stays unavailable for the rest of the run. An answer to a question
|
||||
/// asked before the refresh is ignored when it arrives.
|
||||
pub fn refresh(&mut self) {
|
||||
self.provider = None;
|
||||
self.asked = None;
|
||||
self.capabilities_after = self.seq;
|
||||
}
|
||||
|
||||
/// Forget sharing for an account that signed out.
|
||||
///
|
||||
/// Closes the sheet and offers nothing until [`ShareDialog::refresh`],
|
||||
/// which the next sign-in calls. The provider is not asked again here: a
|
||||
/// question asked before the sign-out reaches the service would describe
|
||||
/// the account that is leaving. Answers to earlier questions are ignored.
|
||||
pub fn signed_out(&mut self) {
|
||||
self.close();
|
||||
self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false });
|
||||
self.asked = None;
|
||||
self.capabilities_after = self.seq;
|
||||
}
|
||||
|
||||
pub fn available(&self) -> bool {
|
||||
@@ -639,6 +660,8 @@ impl ShareDialog {
|
||||
// once the open sheet is no longer borrowed.
|
||||
let mut reload = None;
|
||||
match answer {
|
||||
// Asked before the account changed: it describes the old one.
|
||||
Answer::Capabilities { .. } if seq <= self.capabilities_after => {}
|
||||
Answer::Capabilities { capabilities, linked } => {
|
||||
self.provider = Some(Provider {
|
||||
sharing: linked && capabilities.contains(&Capability::Sharing),
|
||||
@@ -717,13 +740,16 @@ impl ShareDialog {
|
||||
}
|
||||
}
|
||||
Answer::Linked => {
|
||||
// An account arrived, so the list is stale.
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations = None;
|
||||
}
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
// An account arrived, so the list is stale. With no sheet open
|
||||
// there is no list to reload.
|
||||
if self.open.is_some() {
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations = None;
|
||||
}
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
}
|
||||
}
|
||||
}
|
||||
Answer::Withdrawn { share_id } => {
|
||||
|
||||
@@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() {
|
||||
assert!(dialog.is_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capabilities_answer_asked_before_a_refresh_is_ignored() {
|
||||
let ctx = Context::default();
|
||||
let backend = Silent::default();
|
||||
let mut dialog = ShareDialog::new();
|
||||
dialog.connect(backend.clone());
|
||||
dialog.collect(&ctx);
|
||||
dialog.refresh();
|
||||
dialog.collect(&ctx);
|
||||
assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again");
|
||||
|
||||
// The first question was about the account before the refresh.
|
||||
dialog.receive(&ctx, 1, Ok(everything()));
|
||||
assert!(!dialog.available(), "the old account's answer must not offer Share");
|
||||
dialog.receive(&ctx, 2, Ok(everything()));
|
||||
assert!(dialog.available());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unlinked_account_cannot_share_even_where_the_provider_can() {
|
||||
let ctx = Context::default();
|
||||
@@ -580,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() {
|
||||
assert!(shared.is_empty() && failed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() {
|
||||
let (ctx, mut dialog, backend) = ready();
|
||||
dialog.signed_out();
|
||||
let before = backend.seen().len();
|
||||
dialog.receive(&ctx, 99, Ok(Answer::Linked));
|
||||
assert_eq!(backend.seen().len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressing_return_takes_the_first_match_or_an_address() {
|
||||
let (_ctx, mut dialog, _) = ready();
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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.
|
||||
@@ -59,7 +59,7 @@ pub enum ChosenColor {
|
||||
pub struct ColorChoiceOutput {
|
||||
/// The choice's response.
|
||||
pub response: Response,
|
||||
/// The row chosen this pass; the host stores it.
|
||||
/// The row committed this pass; the host stores it. Navigating an open popup reports no choice.
|
||||
pub chosen: Option<ChosenColor>,
|
||||
/// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key
|
||||
/// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses
|
||||
@@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> {
|
||||
entries.push(Entry::separator());
|
||||
entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned()));
|
||||
let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui);
|
||||
let picked = shown.value().cloned();
|
||||
let picked = shown.events.committed().cloned();
|
||||
let mut pick_color = None;
|
||||
let chosen = match picked {
|
||||
Some(Row::Named(id)) => Some(ChosenColor::Named(id)),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -68,7 +68,7 @@ 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,
|
||||
|
||||
@@ -440,8 +440,13 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
|
||||
flags.set(Flags::MIXED, self.wells[i].paint.same().is_none());
|
||||
flags.set(Flags::CHECKED, well == active);
|
||||
let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) };
|
||||
let part =
|
||||
cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable();
|
||||
let part = cx
|
||||
.part(WELL.at(i as u64), shape)
|
||||
.sense(sense)
|
||||
.priority(HitPriority::new(HitLevel::Body, u8::from(front)))
|
||||
.flags(flags)
|
||||
.focusable()
|
||||
.tooltip(self.wells[i].label.clone());
|
||||
// Focus arrives at the active well, so arriving makes no other well active.
|
||||
let part = if well == active { part.selected() } else { part };
|
||||
if self.popover {
|
||||
@@ -449,10 +454,10 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
|
||||
}
|
||||
}
|
||||
let buttons = self.button_rects(cx.style);
|
||||
for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] {
|
||||
if shown {
|
||||
for (key, button, name) in [(DEFAULT, buttons[0], &self.default_button), (SWAP, buttons[1], &self.swap_button)] {
|
||||
if let Some(name) = name {
|
||||
let at = flow.to_physical(button.translate(rect.min.to_vec2()));
|
||||
cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands");
|
||||
cx.part(key, at).sense(Sense::CLICK).tooltip(name.clone()).pointer_only("The host's Default Colours and Swap Colours commands");
|
||||
}
|
||||
}
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
|
||||
use craft_behavior::{EditEvent, IconId, Mixed, Selection};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{SwatchSpacing, SwatchTable};
|
||||
use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _};
|
||||
use craft_ui::choice::{SwatchSpacing, SwatchTable, SwatchTableOutput};
|
||||
use craft_ui::contract::{ActivateOn, Bind, Held, LeadOnOpen, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _, SpaceAction};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::memory::StageAccess;
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::{Response, Ui};
|
||||
use egui::{PointerButton, Response, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
@@ -35,6 +35,21 @@ pub struct SwatchPaletteOutput {
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
|
||||
pub picked: Option<Srgba>,
|
||||
/// 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 {
|
||||
@@ -65,6 +80,7 @@ pub struct SwatchPalette<'a> {
|
||||
label: Label,
|
||||
color: PaletteColor<'a>,
|
||||
swatches: &'a [(Label, Srgba)],
|
||||
selected_swatch: Option<usize>,
|
||||
spacing: SwatchSpacing,
|
||||
drag: Option<TableMap>,
|
||||
/// The Other… cell: the key of its colour request and its name.
|
||||
@@ -108,8 +124,8 @@ impl PaletteColor<'_> {
|
||||
/// What the body picked in its pass.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Pick {
|
||||
/// A swatch or a recent colour.
|
||||
Color(Srgba),
|
||||
/// A swatch or a recent color, and its cell.
|
||||
Color(Srgba, PaletteCell),
|
||||
/// The Other… cell.
|
||||
Other,
|
||||
}
|
||||
@@ -119,6 +135,15 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option<Srgba>) -> Selection<usize
|
||||
color.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba())).map_or_else(Selection::default, Selection::single)
|
||||
}
|
||||
|
||||
/// A completed activation, or the table's existing secondary-button pick.
|
||||
fn picked_cell(table: &SwatchTableOutput, ui: &Ui) -> Option<usize> {
|
||||
table.open.or_else(|| {
|
||||
table.selected.filter(|_| {
|
||||
ui.input(|input| input.pointer.button_pressed(PointerButton::Secondary) || input.pointer.button_released(PointerButton::Secondary))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
impl<'a> SwatchPalette<'a> {
|
||||
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
|
||||
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
@@ -126,6 +151,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
label: label.into(),
|
||||
color: PaletteColor::Color(Held::new(color)),
|
||||
swatches,
|
||||
selected_swatch: None,
|
||||
spacing: SwatchSpacing::Touching,
|
||||
drag: None,
|
||||
other: None,
|
||||
@@ -141,6 +167,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
label: label.into(),
|
||||
color: PaletteColor::Optional(color),
|
||||
swatches,
|
||||
selected_swatch: None,
|
||||
spacing: SwatchSpacing::Touching,
|
||||
drag: None,
|
||||
other: None,
|
||||
@@ -148,6 +175,13 @@ impl<'a> SwatchPalette<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the entry at `index` when the host knows the swatch's identity. The palette uses the
|
||||
/// bound colour to find a selection when the index is absent or out of range.
|
||||
pub fn selected_swatch(mut self, index: Option<usize>) -> Self {
|
||||
self.selected_swatch = index;
|
||||
self
|
||||
}
|
||||
|
||||
/// The gap between the cells, passed on to its `SwatchTable`.
|
||||
pub fn spacing(mut self, spacing: SwatchSpacing) -> Self {
|
||||
self.spacing = spacing;
|
||||
@@ -179,7 +213,7 @@ impl<'a> SwatchPalette<'a> {
|
||||
|
||||
/// Shows the palette.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
|
||||
let SwatchPalette { label, mut color, swatches, spacing, drag, other, recent } = self;
|
||||
let SwatchPalette { label, mut color, swatches, selected_swatch, spacing, drag, other, recent } = self;
|
||||
let recent = recent.filter(|(_, colors)| !colors.is_empty());
|
||||
let recent_cells: Vec<(Label, Srgba)> =
|
||||
recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
@@ -187,7 +221,8 @@ impl<'a> SwatchPalette<'a> {
|
||||
let mut shown = Stack::new().show(ui, |ui, cx| {
|
||||
let before = color.read(cx)?;
|
||||
let bound = before.same().copied().flatten();
|
||||
let mut current = cell_of(swatches, bound);
|
||||
let preferred = selected_swatch.filter(|&index| index < swatches.len());
|
||||
let mut current = preferred.map_or_else(|| cell_of(swatches, bound), Selection::single);
|
||||
// A palette of recent colours alone has no grid: an empty table would be an empty list box in the tree.
|
||||
let mut pick = None;
|
||||
if !swatches.is_empty() || other.is_some() {
|
||||
@@ -197,7 +232,11 @@ impl<'a> SwatchPalette<'a> {
|
||||
.wells(true)
|
||||
.spacing(spacing)
|
||||
.activate(ActivateOn::Click)
|
||||
.space(SpaceAction::ActivateLead)
|
||||
.selection(Bind::bound(&mut current));
|
||||
if let Some(index) = preferred {
|
||||
table = table.rows_stamp(index as u64).lead_on_open(LeadOnOpen::Selected);
|
||||
}
|
||||
if let Some(map) = &drag {
|
||||
table = map(table);
|
||||
}
|
||||
@@ -207,8 +246,8 @@ impl<'a> SwatchPalette<'a> {
|
||||
let table = table.show_all(ui);
|
||||
// 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 = table.selected.or(table.open).and_then(|at| match swatches.get(at) {
|
||||
Some((_, picked)) => Some(Pick::Color(*picked)),
|
||||
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(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),
|
||||
});
|
||||
}
|
||||
@@ -219,10 +258,11 @@ impl<'a> SwatchPalette<'a> {
|
||||
.tips(true)
|
||||
.wells(true)
|
||||
.activate(ActivateOn::Click)
|
||||
.space(SpaceAction::ActivateLead)
|
||||
.selection(Bind::bound(&mut current))
|
||||
.show_all(ui);
|
||||
if let Some((_, picked)) = row.selected.or(row.open).and_then(|at| recent_cells.get(at)) {
|
||||
pick = Some(Pick::Color(*picked));
|
||||
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))
|
||||
@@ -235,21 +275,25 @@ impl<'a> SwatchPalette<'a> {
|
||||
match pick? {
|
||||
Pick::Other => {
|
||||
let key = other.as_ref().map(|(key, _)| key.clone())?;
|
||||
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone()))))
|
||||
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
|
||||
}
|
||||
Pick::Color(after) => {
|
||||
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))
|
||||
Some((Some(after), edit, None, Some(cell)))
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatten();
|
||||
let (picked, edit, pick_color) = settled.unwrap_or((None, None, None));
|
||||
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked }
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -414,6 +414,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,
|
||||
}
|
||||
@@ -446,9 +448,11 @@ pub struct ColorPanel<'a> {
|
||||
dynamic: 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>>,
|
||||
}
|
||||
@@ -469,9 +473,11 @@ fn recent_setup<P: Send + Sync + 'static>(map: impl Fn(usize) -> Option<P> + Sen
|
||||
#[derive(Clone, Copy)]
|
||||
struct Inputs<'a> {
|
||||
wells: Option<&'a [PairWell; 2]>,
|
||||
buttons: Option<&'a [Label; 2]>,
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_models: &'a [Option<ModelValues>],
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -486,9 +492,11 @@ impl<'a> ColorPanel<'a> {
|
||||
dynamic: true,
|
||||
layout: ColorPanelLayout::default(),
|
||||
wells: None,
|
||||
buttons: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: None,
|
||||
recent_models: &[],
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -528,8 +536,18 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The names of the [`ColorPanelLayout::FillStroke`] layout's swap and default buttons, which are also their
|
||||
/// tooltips: a host names the keys of its own commands there ("Swap Fill and Stroke (Shift+X)"). The panel's
|
||||
/// words by default.
|
||||
pub fn buttons(mut self, swap: impl Into<Label>, default: impl Into<Label>) -> Self {
|
||||
self.buttons = Some([swap.into(), default.into()]);
|
||||
self
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -548,6 +566,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));
|
||||
@@ -562,7 +589,8 @@ 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, edited, shown: rows, recent, recent_setup, gamut } = self;
|
||||
let ColorPanel { state, colors, cmyk, rgb, dynamic, 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);
|
||||
@@ -598,9 +626,11 @@ impl<'a> ColorPanel<'a> {
|
||||
dialog: &dialog,
|
||||
inputs: Inputs {
|
||||
wells: wells.as_ref(),
|
||||
buttons: buttons.as_ref(),
|
||||
edited: edited.as_ref(),
|
||||
shown: rows.as_ref().unwrap_or(&default_rows),
|
||||
recent,
|
||||
recent_models,
|
||||
recent_setup: recent_setup.as_ref(),
|
||||
},
|
||||
now: before,
|
||||
@@ -982,7 +1012,8 @@ impl Body<'_> {
|
||||
}
|
||||
|
||||
/// The foreground over the background (the host's wells when it gave them): a click on the other well edits it, a
|
||||
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons.
|
||||
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons, named by the
|
||||
/// host's [`ColorPanel::buttons`] when it gave them.
|
||||
fn wells(&mut self, ui: &mut Ui) {
|
||||
let was = self.active;
|
||||
let mut active = was;
|
||||
@@ -992,7 +1023,11 @@ impl Body<'_> {
|
||||
let pair = SwatchPair::<()>::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true);
|
||||
let pair = match self.layout {
|
||||
ColorPanelLayout::ForegroundBackground => pair,
|
||||
ColorPanelLayout::FillStroke => pair.swap_button(self.words.swap_colors.clone()).default_button(self.words.default_colors.clone()),
|
||||
ColorPanelLayout::FillStroke => {
|
||||
let [swap, default] =
|
||||
self.inputs.buttons.cloned().unwrap_or_else(|| [self.words.swap_colors.clone(), self.words.default_colors.clone()]);
|
||||
pair.swap_button(swap).default_button(default)
|
||||
}
|
||||
};
|
||||
let pair = pair.show(ui);
|
||||
self.active = active;
|
||||
@@ -1035,12 +1070,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)))
|
||||
}
|
||||
|
||||
@@ -1079,11 +1113,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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()];
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -642,7 +642,11 @@ pub(super) fn panel_source<'a>(
|
||||
} else {
|
||||
entries().filter_map(|e| e.color().map(|color| (e.name.as_str(), color.to_srgb(cmyk)))).collect()
|
||||
};
|
||||
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, PresetFns::new(source_rows).thumb(paint_swatch))
|
||||
let fns = PresetFns::new(source_rows).thumb(paint_swatch).accepts(|_, drag, _, _| {
|
||||
let groups = matches!(drag.grabbed, SwatchKey::Group(_));
|
||||
drag.keys.iter().all(|key| matches!(key, SwatchKey::Group(_)) == groups)
|
||||
});
|
||||
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, fns)
|
||||
}
|
||||
|
||||
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `SwatchesPanel`: the panel body, its state and what it reports.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{AsIdSalt, IdSalt, Response, Ui};
|
||||
|
||||
use super::library::{HostThumb, find_swatch, has, panel_source};
|
||||
use super::library::{HostThumb, find_swatch, group_of, has, panel_source};
|
||||
use super::menu::event_edits;
|
||||
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords};
|
||||
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
|
||||
@@ -40,6 +40,7 @@ pub struct SwatchesPanelOutput {
|
||||
pub edits: Vec<SwatchEdit>,
|
||||
/// The browser events the panel does not turn into `used` or `edits`, in the order they happened: `Activate`,
|
||||
/// `Menu`, `DropAt`, `Dropped` and `Reorder`. `Reorder` is also in `edits`; a host runs one of the two.
|
||||
/// When enabled by [`SwatchesPanel::report_invalid_renames`], rejected inline renames appear here as `Rename`.
|
||||
pub events: Vec<PresetEvent<SwatchKey>>,
|
||||
}
|
||||
|
||||
@@ -89,16 +90,19 @@ pub struct SwatchesPanel<'a> {
|
||||
foreground: Srgba,
|
||||
thumb: Option<HostThumb<'a>>,
|
||||
tools: Option<ToolsFn<'a>>,
|
||||
tools_at_start: bool,
|
||||
drop_zone: Option<DropZone>,
|
||||
footer: Option<Option<PresetFooterOptions<'a>>>,
|
||||
reveal: Option<SwatchKey>,
|
||||
search: bool,
|
||||
row_icons: Option<RowIconsFn<'a>>,
|
||||
select: SelectMode,
|
||||
report_invalid_renames: bool,
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
select_groups: bool,
|
||||
}
|
||||
|
||||
/// What the body decided; `show` stores the state and reports the rest after the real run.
|
||||
@@ -120,16 +124,19 @@ impl<'a> SwatchesPanel<'a> {
|
||||
foreground,
|
||||
thumb: None,
|
||||
tools: None,
|
||||
tools_at_start: false,
|
||||
drop_zone: None,
|
||||
footer: None,
|
||||
reveal: None,
|
||||
search: true,
|
||||
row_icons: None,
|
||||
select: SelectMode::Single,
|
||||
report_invalid_renames: false,
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
select_groups: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +161,12 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Places the host's tools before the browser controls in the toolbar. Off by default.
|
||||
pub fn tools_at_start(mut self, at_start: bool) -> Self {
|
||||
self.tools_at_start = at_start;
|
||||
self
|
||||
}
|
||||
|
||||
/// Where a drop onto the panel lands.
|
||||
pub fn drop_zone(mut self, zone: DropZone) -> Self {
|
||||
self.drop_zone = Some(zone);
|
||||
@@ -191,6 +204,13 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Reports committed inline renames rejected by the panel in [`SwatchesPanelOutput::events`], so the host can
|
||||
/// explain the rejection. Accepted renames produce their usual edit. Off by default.
|
||||
pub fn report_invalid_renames(mut self, enabled: bool) -> Self {
|
||||
self.report_invalid_renames = enabled;
|
||||
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`.
|
||||
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
|
||||
@@ -228,6 +248,12 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Lets panel interactions select group rows alongside swatches in both views. Off by default.
|
||||
pub fn select_groups(mut self, enabled: bool) -> Self {
|
||||
self.select_groups = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the panel and returns the user's actions this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
|
||||
let SwatchesPanel {
|
||||
@@ -237,16 +263,19 @@ impl<'a> SwatchesPanel<'a> {
|
||||
foreground,
|
||||
thumb,
|
||||
mut tools,
|
||||
tools_at_start,
|
||||
drop_zone,
|
||||
footer,
|
||||
reveal,
|
||||
search,
|
||||
row_icons,
|
||||
select,
|
||||
report_invalid_renames,
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
select_groups,
|
||||
} = self;
|
||||
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let words = Env::of(ui).words::<SwatchesWords>();
|
||||
@@ -278,8 +307,10 @@ impl<'a> SwatchesPanel<'a> {
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
|
||||
.thumb_range(SWATCH_ZOOM)
|
||||
.toolbar(true)
|
||||
.tools_at_start(tools_at_start)
|
||||
.search(search)
|
||||
.select(select)
|
||||
.select_groups(select_groups)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.selection(Bind::bound(&mut st.selection));
|
||||
if let Some(id) = document_id {
|
||||
@@ -311,7 +342,21 @@ impl<'a> SwatchesPanel<'a> {
|
||||
let mut used = None;
|
||||
let mut edits = Vec::new();
|
||||
let mut events = Vec::new();
|
||||
let deleting_groups: BTreeSet<_> = out
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
PresetEvent::Delete(key @ SwatchKey::Group(_)) => group_of(groups, key),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for event in out.events {
|
||||
if !deleting_groups.is_empty()
|
||||
&& let PresetEvent::Delete(key @ SwatchKey::Swatch(_)) = &event
|
||||
&& group_of(groups, key).is_some_and(|group| deleting_groups.contains(&group))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } = &event
|
||||
&& let Some(at) = find_swatch(groups, name)
|
||||
&& let Some(entry) = groups.get(at.group).and_then(|g| g.entries.get(at.index))
|
||||
@@ -327,7 +372,15 @@ impl<'a> SwatchesPanel<'a> {
|
||||
| PresetEvent::Reorder { .. }
|
||||
)
|
||||
.then(|| event.clone());
|
||||
edits.extend(event_edits(groups, &mut st, event, foreground, &words));
|
||||
// The browser has discarded empty and unchanged names. Keep a live target's attempt for diagnostics
|
||||
// if translating it into an edit fails. Validation and its selection updates still run in one place.
|
||||
let attempted_rename =
|
||||
(report_invalid_renames && matches!(&event, PresetEvent::Rename { key, .. } if live(key))).then(|| event.clone());
|
||||
let resolved = event_edits(groups, &mut st, event, foreground, &words);
|
||||
if resolved.is_empty() {
|
||||
events.extend(attempted_rename);
|
||||
}
|
||||
edits.extend(resolved);
|
||||
events.extend(forwarded);
|
||||
}
|
||||
Some(Settled { before_state, st, used, edits, events })
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! A named/custom color choice reports only a committed row or custom picker request.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, vec2};
|
||||
|
||||
const RED: Srgba = Srgba::rgb(0.8, 0.1, 0.2);
|
||||
const BLUE: Srgba = Srgba::rgb(0.1, 0.2, 0.8);
|
||||
const CUSTOM: Srgba = Srgba::rgb(0.2, 0.6, 0.4);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Reports {
|
||||
chosen: Vec<ChosenColor>,
|
||||
requests: Vec<ColorRequest>,
|
||||
}
|
||||
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
value: Rc<RefCell<ChosenColor>>,
|
||||
reports: Rc<RefCell<Reports>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(start: ChosenColor, custom: Option<Srgba>) -> Self {
|
||||
let value = Rc::new(RefCell::new(start));
|
||||
let reports = Rc::new(RefCell::new(Reports::default()));
|
||||
let (held, reported) = (value.clone(), reports.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let value = held.borrow().clone();
|
||||
let shown = ColorChoice::new("Color", &value)
|
||||
.named([NamedColor::new("red", "Red", Some(RED)), NamedColor::new("blue", "Blue", Some(BLUE))])
|
||||
.custom(custom)
|
||||
.show(ui);
|
||||
if let Some(chosen) = shown.chosen {
|
||||
*held.borrow_mut() = chosen.clone();
|
||||
reported.borrow_mut().chosen.push(chosen);
|
||||
}
|
||||
reported.borrow_mut().requests.extend(shown.pick_color);
|
||||
});
|
||||
fixture.room(vec2(400.0, 240.0)).settle();
|
||||
Rig { fixture, value, reports }
|
||||
}
|
||||
|
||||
fn open(&mut self) {
|
||||
let field = self.fixture.by_label("Color").expect("the color choice");
|
||||
self.fixture.click(&field);
|
||||
}
|
||||
}
|
||||
|
||||
/// A provisional named row never replaces the host's named or custom choice; Enter reports it once.
|
||||
#[trial]
|
||||
fn canceled_color_navigation_keeps_the_hosts_original_choice() {
|
||||
for original in [ChosenColor::Named("red".into()), ChosenColor::Custom] {
|
||||
let key = if original == ChosenColor::Custom { Key::ArrowUp } else { Key::ArrowDown };
|
||||
let mut rig = Rig::new(original.clone(), Some(CUSTOM));
|
||||
rig.open();
|
||||
rig.fixture.key(key, Modifiers::NONE).idle(2);
|
||||
assert_eq!(*rig.value.borrow(), original, "navigation alone does not replace the original color");
|
||||
assert!(rig.reports.borrow().chosen.is_empty());
|
||||
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert_eq!(*rig.value.borrow(), original);
|
||||
assert!(rig.reports.borrow().chosen.is_empty());
|
||||
assert!(rig.reports.borrow().requests.is_empty());
|
||||
|
||||
rig.open();
|
||||
rig.fixture.key(key, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
|
||||
assert_eq!(*rig.value.borrow(), ChosenColor::Named("blue".into()));
|
||||
assert_eq!(rig.reports.borrow().chosen, [ChosenColor::Named("blue".into())]);
|
||||
assert!(rig.reports.borrow().requests.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Proposing Select Custom Color neither requests the picker nor changes the color; Enter requests it once.
|
||||
#[trial]
|
||||
fn custom_color_picker_waits_for_a_committed_row() {
|
||||
for custom in [Some(CUSTOM), None] {
|
||||
let original = ChosenColor::Named("blue".into());
|
||||
let mut rig = Rig::new(original.clone(), custom);
|
||||
rig.open();
|
||||
rig.fixture.key(Key::End, Modifiers::NONE).idle(2);
|
||||
assert!(rig.reports.borrow().requests.is_empty(), "a provisional custom row cannot open a picker");
|
||||
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert_eq!(*rig.value.borrow(), original);
|
||||
assert!(rig.reports.borrow().requests.is_empty());
|
||||
assert!(rig.reports.borrow().chosen.is_empty());
|
||||
|
||||
rig.open();
|
||||
rig.fixture.key(Key::End, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
|
||||
assert_eq!(*rig.value.borrow(), original, "the host changes its color only after the requested picker answers");
|
||||
let reports = rig.reports.borrow();
|
||||
assert!(reports.chosen.is_empty());
|
||||
assert_eq!(reports.requests.len(), 1);
|
||||
assert_eq!(reports.requests[0].key, ColorChoice::CUSTOM_KEY);
|
||||
assert_eq!(reports.requests[0].color, Some(custom.unwrap_or(BLUE)));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The screen tests of craft-color-ui, folded into the lib's test target.
|
||||
|
||||
pub(crate) mod area_gamut;
|
||||
pub(crate) mod choice;
|
||||
pub(crate) mod color_parts;
|
||||
pub(crate) mod gradient_bar;
|
||||
pub(crate) mod paint_chip;
|
||||
|
||||
@@ -8,7 +8,9 @@ use std::rc::Rc;
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color_ui::ui::{PairWell, SwatchPair, SwatchPairOutput, Well};
|
||||
use craft_theme::{Srgba, ThemeId};
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::pointer::moved;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Rect, Ui, Vec2, vec2};
|
||||
|
||||
@@ -118,6 +120,35 @@ fn the_well_corner_follows_the_theme_well_shape() {
|
||||
assert_eq!(clicks("craft.pro"), [Some(Well::Primary), Some(Well::Primary)], "square wells");
|
||||
}
|
||||
|
||||
/// A rest of the pointer on a well shows the well's label, and one on the Swap or Default button shows that button's
|
||||
/// label: a host that names a well "Fill (X)" shows its key there.
|
||||
#[trial]
|
||||
fn a_rest_on_a_well_or_a_button_shows_its_label() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let wells = [PairWell::new("Fill (X)", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Stroke (X)", Srgba::rgb(1.0, 1.0, 1.0))];
|
||||
SwatchPair::<()>::new("Fill and Stroke", wells, Bind::given(Well::Primary))
|
||||
.swap_button("Swap (Shift+X)")
|
||||
.default_button("Default (D)")
|
||||
.popover(false)
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(vec2(200.0, 200.0)).settle();
|
||||
let wells = fixture.by_role(Role::RADIO_BUTTON);
|
||||
let swap = fixture.by_label("Swap (Shift+X)").expect("the Swap button").rect.center();
|
||||
let default = fixture.by_label("Default (D)").expect("the Default button").rect.center();
|
||||
let spots =
|
||||
[(in_primary(wells[0].rect), "Fill (X)"), (in_secondary(wells[1].rect), "Stroke (X)"), (swap, "Swap (Shift+X)"), (default, "Default (D)")];
|
||||
for (at, tip) in spots {
|
||||
fixture.frame(vec![moved(egui::pos2(199.0, 199.0))]);
|
||||
fixture.settle();
|
||||
assert!(!fixture.texts().iter().any(|run| run.text == tip), "no {tip:?} before the rest");
|
||||
fixture.frame(vec![moved(at)]);
|
||||
fixture.advance(DELAY);
|
||||
fixture.settle();
|
||||
assert!(fixture.texts().iter().any(|run| run.text == tip), "a rest there shows {tip:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A popover that opens with the pair as its first stop puts the focus on the active well, as Tab into the pair does:
|
||||
/// the arrival makes no other well active (a Color panel opened over the Stroke chip leaves Stroke active).
|
||||
#[trial]
|
||||
|
||||
@@ -8,11 +8,12 @@ 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;
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
@@ -196,6 +197,98 @@ fn a_channel_step_keeps_the_other_channels_unrounded() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
@@ -217,6 +310,24 @@ fn a_fill_stroke_panels_warnings_keep_their_room_so_the_spectrum_holds_still() {
|
||||
assert_eq!(clean, warned, "the spectrum with no warning and with both");
|
||||
}
|
||||
|
||||
/// A host's names for the FillStroke layout's swap and default buttons replace the panel's words, so a host can name
|
||||
/// its keys there; without them the buttons keep the words.
|
||||
#[trial]
|
||||
fn a_fill_stroke_panel_names_its_buttons_as_the_host_asks() {
|
||||
let names = |given: bool| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
|
||||
let panel = if given { panel.buttons("Swap (Shift+X)", "Default (D)") } else { panel };
|
||||
let _ = panel.show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
["Swap (Shift+X)", "Default (D)", "Swap fill and stroke", "Default fill and stroke"].map(|name| fixture.by_label(name).is_some())
|
||||
};
|
||||
assert_eq!(names(true), [true, true, false, false], "the host's names");
|
||||
assert_eq!(names(false), [false, false, true, true], "the panel's words");
|
||||
}
|
||||
|
||||
/// The spectrum's tooltip is the shown mode's name, and a Shift click on it moves the state to the next mode without
|
||||
/// editing a paint.
|
||||
#[trial]
|
||||
@@ -256,6 +367,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]
|
||||
@@ -360,6 +553,8 @@ struct PaletteReports {
|
||||
edits: Vec<EditEvent<Srgba>>,
|
||||
requests: Vec<ColorRequest>,
|
||||
picked: Vec<Srgba>,
|
||||
cells: Vec<PaletteCell>,
|
||||
swatches: Vec<usize>,
|
||||
}
|
||||
|
||||
type Reports = Rc<RefCell<PaletteReports>>;
|
||||
@@ -370,6 +565,8 @@ 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);
|
||||
}
|
||||
|
||||
fn palette_swatches() -> Vec<(Label, Srgba)> {
|
||||
@@ -417,7 +614,7 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
let recent = fixture.by_label(&RECENT[0].to_hex()).expect("a recent colour is named by its hex");
|
||||
fixture.click(&recent).settle();
|
||||
let taken = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert!(taken.requests.is_empty(), "a recent pick files no request");
|
||||
assert!(taken.requests.is_empty() && taken.swatches.is_empty(), "a recent pick is not a palette entry");
|
||||
assert_eq!(taken.edits.len(), 1, "one edit for one recent pick");
|
||||
assert!(
|
||||
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Same(before), after, .. }
|
||||
@@ -426,11 +623,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");
|
||||
@@ -440,6 +639,47 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_palette_reports_the_actual_swatch_when_its_color_matches_the_bound_color() {
|
||||
let color = swatch("Green");
|
||||
let swatches = [(Label::from("First green"), color), (Label::from("Second green"), color), (Label::from("Third green"), color)];
|
||||
let selected = Rc::new(Cell::new(2));
|
||||
let preferred = Rc::clone(&selected);
|
||||
let reports = Reports::default();
|
||||
let out = reports.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
collect(&out, SwatchPalette::new("Swatches", Bind::given(color), &swatches).selected_swatch(Some(preferred.get())).show(ui));
|
||||
let _ = Button::new("Next control").show(ui);
|
||||
});
|
||||
fixture.room(PALETTE_WIDE).settle();
|
||||
let third = fixture.by_label("Third green").expect("the linked entry");
|
||||
assert_eq!(fixture.tree().selected_of(third.node), Some(true), "the linked entry stays selected");
|
||||
let second = fixture.by_label("Second green").expect("the second entry");
|
||||
fixture.hold(Modifiers::SHIFT).click(&second).hold(Modifiers::NONE).settle();
|
||||
let click = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert_eq!(click.swatches, [1]);
|
||||
assert_eq!(click.picked.iter().map(|picked| picked.to_rgba()).collect::<Vec<_>>(), [color.to_rgba()]);
|
||||
assert!(click.edits.is_empty(), "the color binding has not changed");
|
||||
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).key(Key::Space, Modifiers::NONE).settle();
|
||||
let keys = std::mem::take(&mut *reports.borrow_mut());
|
||||
assert_eq!(keys.swatches, [2], "Space picks the already selected swatch");
|
||||
assert!(keys.edits.is_empty());
|
||||
|
||||
let focused = |fixture: &Fixture| {
|
||||
let tree = fixture.tree();
|
||||
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
|
||||
};
|
||||
fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Next control"));
|
||||
selected.set(0);
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::SHIFT).settle();
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("First green"));
|
||||
fixture.key(Key::Space, Modifiers::NONE).settle();
|
||||
assert_eq!(reports.borrow().swatches, [0], "Tab returns to the host's current swatch");
|
||||
}
|
||||
|
||||
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
|
||||
/// it; a host that gives no recent colors gets no row.
|
||||
#[trial]
|
||||
@@ -595,6 +835,54 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_mixed_swatches_selection_rejects_reorder_and_deletes_each_entry_once() {
|
||||
use craft_ui::contract::SelectMode;
|
||||
|
||||
let entry = |name: &str, color| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(color));
|
||||
let groups = vec![
|
||||
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", [1.0, 0.0, 0.0])] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", [0.0, 0.0, 1.0])] },
|
||||
];
|
||||
let state = Rc::new(RefCell::new(SwatchesState::default()));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let reorders = Rc::new(Cell::new(0));
|
||||
let (seen, moves, held) = (edits.clone(), reorders.clone(), state.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut *held.borrow_mut()), RED).select(SelectMode::Multi).select_groups(true).show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
for event in out.events {
|
||||
if matches!(event, craft_ui::patterns::presets::PresetEvent::Reorder(_)) {
|
||||
moves.set(moves.get() + 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(320.0, 400.0)).settle();
|
||||
let group = |name: &str| {
|
||||
let tree = fixture.tree();
|
||||
tree.with_role(Role::LIST_BOX_OPTION)
|
||||
.into_iter()
|
||||
.find(|&key| tree.name_of(key).is_some_and(|label| label == name || label.starts_with(&format!("{name},"))))
|
||||
.and_then(|key| fixture.target(key))
|
||||
.unwrap_or_else(|| panic!("the {name} group"))
|
||||
};
|
||||
let basics = group("Basics");
|
||||
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
|
||||
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch");
|
||||
let other = group("Other");
|
||||
fixture.click(&basics).hold(Modifiers::COMMAND).click(&red).click(&blue).hold(Modifiers::NONE).settle();
|
||||
let keys = [SwatchKey::Group("Basics".to_owned()), SwatchKey::Swatch("Red".to_owned()), SwatchKey::Swatch("Blue".to_owned())];
|
||||
assert_eq!(state.borrow().selection.items, keys, "the group and swatch keys are selected together");
|
||||
fixture.drag(&red, other.center() - red.center()).settle();
|
||||
assert!(edits.borrow().is_empty());
|
||||
assert_eq!(reorders.get(), 0, "the swatch source refuses a mixed reorder");
|
||||
fixture.key(Key::Delete, Modifiers::NONE).settle();
|
||||
let reported = edits.borrow();
|
||||
assert_eq!(reported.len(), 2, "the group delete already includes Red: {reported:?}");
|
||||
assert!(reported.contains(&SwatchEdit::DeleteGroup { group: "Basics".to_owned() }));
|
||||
assert!(reported.contains(&SwatchEdit::delete("Blue".to_owned())));
|
||||
}
|
||||
|
||||
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
|
||||
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
|
||||
#[trial]
|
||||
@@ -734,6 +1022,85 @@ fn a_rename_left_open_stays_with_its_document() {
|
||||
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn opt_in_reports_only_rejected_swatch_and_group_renames() {
|
||||
use craft_ui::patterns::presets::{PresetEvent, PresetView};
|
||||
|
||||
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
|
||||
let groups = vec![
|
||||
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: Vec::new() },
|
||||
];
|
||||
let red = SwatchKey::Swatch("Red".to_owned());
|
||||
let basics = SwatchKey::Group("Basics".to_owned());
|
||||
for (opt_in, key, name, accepted) in [
|
||||
(false, &red, "Rose", false),
|
||||
(false, &basics, "Other", false),
|
||||
(true, &red, "Rose", false),
|
||||
(true, &basics, "Other", false),
|
||||
(true, &red, " Red ", false),
|
||||
(true, &red, "Coral", true),
|
||||
(true, &basics, "Favorites", true),
|
||||
] {
|
||||
let mut start = SwatchesState::default();
|
||||
start.browser.view = PresetView::List;
|
||||
let state = Rc::new(RefCell::new(start));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let renames = Rc::new(RefCell::new(Vec::new()));
|
||||
let (held, seen_edits, seen_renames) = (Rc::clone(&state), Rc::clone(&edits), Rc::clone(&renames));
|
||||
let groups = groups.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = held.borrow_mut();
|
||||
let mut panel = SwatchesPanel::new(&groups, Bind::bound(&mut *current), RED);
|
||||
if opt_in {
|
||||
panel = panel.report_invalid_renames(true);
|
||||
}
|
||||
let out = panel.show(ui);
|
||||
seen_edits.borrow_mut().extend(out.edits);
|
||||
seen_renames.borrow_mut().extend(out.events.into_iter().filter_map(|event| match event {
|
||||
PresetEvent::Rename { key, text, .. } => Some((key, text)),
|
||||
_ => None,
|
||||
}));
|
||||
});
|
||||
fixture.room(Vec2::new(320.0, 400.0)).settle();
|
||||
let label = if key == &red { "Red" } else { "Basics" };
|
||||
let tree = fixture.tree();
|
||||
let row = tree
|
||||
.with_role(Role::TREE_ITEM)
|
||||
.into_iter()
|
||||
.find(|&node| tree.name_of(node).is_some_and(|actual| actual == label || actual.starts_with(&format!("{label},"))))
|
||||
.and_then(|node| fixture.target(node))
|
||||
.unwrap_or_else(|| {
|
||||
panic!("the {label} row is shown, names: {:?}", tree.keys().into_iter().filter_map(|key| tree.name_of(key)).collect::<Vec<_>>())
|
||||
});
|
||||
fixture.click(&row).key(Key::F2, Modifiers::NONE).type_text(name).settle();
|
||||
let tree = fixture.tree();
|
||||
assert!(tree.keys().into_iter().any(|key| tree.value_of(key) == Some(name)), "the rename field shows {name}");
|
||||
let selection = state.borrow().selection.clone();
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
let rejected = opt_in && matches!(name, "Rose" | "Other");
|
||||
if rejected {
|
||||
assert_eq!(*renames.borrow(), [(key.clone(), name.to_owned())]);
|
||||
} else {
|
||||
assert!(renames.borrow().is_empty(), "{name}");
|
||||
}
|
||||
if accepted {
|
||||
let reported = edits.borrow();
|
||||
assert!(
|
||||
match &reported[..] {
|
||||
[SwatchEdit::Rename { swatch, name: new }] => key == &SwatchKey::Swatch(swatch.clone()) && new == name,
|
||||
[SwatchEdit::RenameGroup { group, name: new }] => key == &SwatchKey::Group(group.clone()) && new == name,
|
||||
_ => false,
|
||||
},
|
||||
"{name}: {reported:?}",
|
||||
);
|
||||
} else {
|
||||
assert!(edits.borrow().is_empty(), "{name}");
|
||||
assert_eq!(state.borrow().selection, selection, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
|
||||
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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 916 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user