Merge craft-libs main and keep both sets of text trials

This commit is contained in:
skylartaylor committed 2026-11-28 18:31:24 +01:00
commit a9fca8edb1
655 files changed
+86940 -4903

No files matched your search

+1
View File
@@ -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'
+29
View File
@@ -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 }}
+5
View File
@@ -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
+94 -3
View File
@@ -1819,9 +1819,11 @@ dependencies = [
"craft-geom",
"craft-gif",
"craft-gpu",
"craft-gpu-device",
"craft-gpu-null",
"craft-gpu-providers",
"craft-gpu-wgpu",
"craft-gpu-yuv",
"craft-gridcraft-format",
"craft-gzip",
"craft-har",
@@ -1863,6 +1865,7 @@ dependencies = [
"craft-media-source",
"craft-menu",
"craft-mesh",
"craft-mesh-ops",
"craft-metadata",
"craft-metafile",
"craft-midi",
@@ -1905,6 +1908,7 @@ dependencies = [
"craft-review",
"craft-rtf",
"craft-sbs",
"craft-scopes",
"craft-score",
"craft-scraft-format",
"craft-settings",
@@ -2284,7 +2288,6 @@ dependencies = [
"craft-flags",
"craft-platform",
"dirs",
"getrandom 0.3.4",
"log",
"proptest",
"serde",
@@ -2297,6 +2300,7 @@ dependencies = [
name = "craft-control-protocol"
version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"serde_json",
"subtle",
]
@@ -2502,6 +2506,7 @@ dependencies = [
"chrono",
"craft-cfb",
"craft-drawingml",
"craft-flow",
"craft-math",
"craft-offcrypto",
"craft-opc",
@@ -2920,6 +2925,18 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-gpu-device"
version = "0.1.0"
dependencies = [
"craft-gpu",
"log",
"pollster 0.4.0",
"serde",
"serde_json",
"wgpu",
]
[[package]]
name = "craft-gpu-null"
version = "0.1.0"
@@ -2945,6 +2962,17 @@ dependencies = [
"wgpu",
]
[[package]]
name = "craft-gpu-yuv"
version = "0.1.0"
dependencies = [
"craft-gpu",
"craft-gpu-null",
"pollster 0.4.0",
"wgpu",
"yuv",
]
[[package]]
name = "craft-gridcraft-format"
version = "0.1.0"
@@ -3418,6 +3446,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-mesh-ops"
version = "0.1.0"
dependencies = [
"glam 0.30.10",
"mikktspace",
"rayon",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
@@ -3580,6 +3619,8 @@ version = "0.1.0"
name = "craft-pbr"
version = "0.1.0"
dependencies = [
"craft-materialx",
"craft-mesh",
"craft-pbr",
"craft-texture",
"glam 0.30.10",
@@ -4041,6 +4082,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-scopes"
version = "0.1.0"
dependencies = [
"craft-color",
"serde",
"serde_json",
]
[[package]]
name = "craft-score"
version = "0.1.0"
@@ -4294,7 +4344,14 @@ dependencies = [
name = "craft-testkit"
version = "0.1.0"
dependencies = [
"libc",
"png 0.18.1",
"rustix 1.1.6",
"serde_json",
"sha2 0.10.9",
"skrifa 0.47.0",
"tempfile",
"toml",
]
[[package]]
@@ -4328,8 +4385,12 @@ name = "craft-texture"
version = "0.1.0"
dependencies = [
"bytemuck",
"craft-exr",
"craft-hdr",
"craft-image-codecs",
"dds",
"half",
"png 0.18.1",
"rayon",
"thiserror 2.0.21",
]
@@ -4931,9 +4992,14 @@ name = "craft-xtask"
version = "0.1.0"
dependencies = [
"craft-atomic",
"flate2",
"libc",
"serde_json",
"sha2 0.10.9",
"tar",
"tempfile",
"toml_edit",
"unicode-normalization",
]
[[package]]
@@ -6807,6 +6873,12 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glam"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
[[package]]
name = "glam"
version = "0.25.0"
@@ -6818,6 +6890,9 @@ name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
dependencies = [
"serde_core",
]
[[package]]
name = "glifo"
@@ -8346,8 +8421,6 @@ dependencies = [
[[package]]
name = "kurbo"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
dependencies = [
"arrayvec",
"euclid",
@@ -8663,6 +8736,15 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
[[package]]
name = "mikktspace"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0"
dependencies = [
"glam 0.15.2",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -15036,6 +15118,15 @@ dependencies = [
"synstructure 0.14.0",
]
[[package]]
name = "yuv"
version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607"
dependencies = [
"num-traits",
]
[[package]]
name = "zbus"
version = "5.19.0"
+6 -1
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/*"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
[workspace.package]
version = "0.1.0"
@@ -37,7 +37,9 @@ acadrust = "=0.6.6"
log = "0.4"
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
craft-plist = { path = "crates/plist" }
craft-gpu-device = { path = "crates/gpu-device" }
craft-wasm = { path = "crates/wasm" }
craft-gpu-yuv = { path = "crates/gpu-yuv" }
craft-platform = { path = "crates/platform" }
craft-png = { path = "crates/png" }
craft-aep = { path = "crates/aep" }
@@ -82,6 +84,7 @@ craft-cloud = { path = "crates/cloud" }
craft-cloud-local = { path = "crates/cloud-local" }
craft-cloud-ui = { path = "crates/cloud-ui" }
craft-color = { path = "crates/color" }
craft-scopes = { path = "crates/scopes" }
craft-color-ui = { path = "crates/color-ui" }
craft-color-transform = { path = "crates/color-transform" }
craft-frame = { path = "crates/frame" }
@@ -133,6 +136,7 @@ craft-gcode = { path = "crates/gcode" }
craft-gif = { path = "crates/gif" }
craft-hdr = { path = "crates/hdr" }
craft-mesh = { path = "crates/mesh" }
craft-mesh-ops = { path = "crates/mesh-ops" }
craft-html = { path = "crates/html" }
craft-ipp = { path = "crates/ipp" }
craft-heif = { path = "crates/heif" }
@@ -321,6 +325,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
kurbo = { path = "vendor/kurbo" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
+26 -4
View File
@@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
@@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from:
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
(CC0-1.0); see ATTRIBUTION.md.
The mesh operations in crates/mesh-ops are moved from:
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
https://github.com/storytold/texturecraft
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
3133062968b8a1566eda12a357cb06062db16687.
https://github.com/storytold/materialcraft
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
All licensed MIT OR Apache-2.0.
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
@@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy.
linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
patches and the files left out.
changes and the files left out.
kurbo
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
vendor/kurbo/SOURCE.json for provenance and the local patches.
Platform lifecycle source provenance
+29 -8
View File
@@ -72,7 +72,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target).
- [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite.
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft.
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft.
- [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral
model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and
TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from
@@ -211,6 +211,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
every frame's position, delay, disposal and transparent colour, the loop count and the first
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
a file can hold the picture it declares before a decoder runs.
- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to
NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full
range, through the `craft-gpu` job registry on the null context or on a device. Each output texel
averages the part of the source it covers. The crate also has the render passes for a caller's
own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the
CPU. Encoders and scopes stay in each app.
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
low power, a named adapter that survives a reordered list and a driver update, or software;
corrections for drivers that crash; the next adapter and then a software one when a device fails
to open; a capability report; device-loss and error recording without panics; and what to reopen
after a loss. Settings pages and the window stay in each app.
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
@@ -318,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file
themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft.
- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft.
- [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and
2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per
quarter note. From SoundCraft.
@@ -412,11 +426,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
reference picking, selection statistics, error tags and filter buttons (`ui` feature).
- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module
reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals
out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test
whose body runs past a limit, or whose condition does not hold in time; a variable the caller names
replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged
copies of a valid input, and fails the test with the case that panicked or did not finish. Its `rng`
module holds two seeded generators for repeatable test input. Not published.
out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts
from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its
`deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time;
a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation
and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did
not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
test when the variable the caller names is `1`. Any other value of that variable except empty fails
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
under `target/fixtures` and publishes each one under a lock. Not published.
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
@@ -424,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
(regex) are features.
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
bounded by `Limits`. From MaterialCraft.
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
samples. Sizes are bounded by `Limits`. From MaterialCraft.
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
+23 -3
View File
@@ -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.
+11 -1
View File
@@ -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),
+19 -2
View File
@@ -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
+7 -4
View File
@@ -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
+8 -1
View File
@@ -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]
+771 -27
View File
@@ -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(&amp(*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());
}
+47 -4
View File
@@ -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()
}
+1 -32
View File
@@ -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
+5 -3
View File
@@ -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
+5 -5
View 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 -5
View File
@@ -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),
_ => {}
}
}
+14
View File
@@ -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 };
+2
View File
@@ -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];
+92 -1
View File
@@ -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 })
}
+174 -2
View File
@@ -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))
}
+336 -1
View File
@@ -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());
}
+2 -4
View File
@@ -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");
+24 -4
View File
@@ -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"));
}
+31
View File
@@ -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.
+41 -5
View File
@@ -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();
+53 -23
View File
@@ -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.
+113 -71
View File
@@ -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));
}
+2 -2
View File
@@ -544,7 +544,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9;
const PHI: f64 = 1.0 + INV_PHI;
/// The composition guide drawn inside a crop frame, in Photoshop's menu order.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CropGuide {
@@ -727,7 +727,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 {
+3 -1
View File
@@ -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()) {
+33 -1
View File
@@ -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();
+22 -11
View File
@@ -2,7 +2,7 @@
The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15
files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer
(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each
(`src/cmx_write.rs`) writes in them, with R74 and R77 for what only it needs ("Written fields" lists each
field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a
cited id has no row here.
@@ -56,9 +56,16 @@ Sources:
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs,
was read for the order of fields that the notes do not spell out (the table entries, the rendering
attributes and the curve body); no code was copied from it
- **LC**: the `.cmx` reader of libcdr (MPL-2.0), `src/lib/CMXParser.cpp`, `src/lib/CMXParser.h`
and `src/lib/CMXDocumentStructure.h` at commit `b5211a57af37dac59a04f6041822a07f4a7cf7d6`,
https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.cpp,
https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXParser.h
and https://github.com/LibreOffice/libcdr/blob/b5211a57af37dac59a04f6041822a07f4a7cf7d6/src/lib/CMXDocumentStructure.h,
read for the header's offsets, the index chunks and the fields of a color entry; no code was
copied from it
Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
confirmed that no CX file shows), `public-reader` (a layout LC reads), `unconfirmed` (a point no source states and no sample file shows;
listed so it can be checked against a file, with what the reader does when it is wrong). The
"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test
files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and
@@ -129,7 +136,7 @@ file is committed.
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list. When that chunk is one the reader passes over or a `page`, the reader may resume instead at a `page` chunk that starts 8 to 64 bytes after it, inside its body, is not empty, ends inside the list and, when the chunk found ends inside the list, reaches its end. It does so only when that page reads with objects and without damage in its instructions, and when walking on from the chunk found and from the page, each without this recovery and entering lists as the reader does, reaches the same position inside the same lists, or leaves the list (at its end, or at stray bytes with no chunk id after them), within 16 steps, with every chunk the reader uses that the first walk reads before then also read by the second, with its body cut at the same place (pages that read without objects aside). Of the chunks that only the second walk reads, or that it reads with its body cut at another place than the first walk does, the header or a table is used only when no other chunk of its id is read, and a page is kept only when it reads with objects and without damage in its instructions. Letters spelling `page` whose length runs past the list are checked the same way. In one read, the search for pages to resume at spends at most four times the length of the RIFF form (cut at the file's length), or 1,048,576 when that is more, counting 64 for each step of a walk and the length of each page body judged; past that, the reader resumes at the first chunk id found. It does the same when a limit stops the read of a page it judges. Pages kept this way are read after the other pages, so they spend only what the limits leave, and keep their place in the file; each is judged once more before it is read. One that a limit stops, or leaves without objects, is left out with the warning for limits; one the limits cut short is read as far as they allow, as other pages are. When the chunks that only these recoveries read make the read stop at a limit, the file is read again without the recoveries, with the warning for limits. Resuming at an inner page, at a chunk the reader passes over that is not followed by another chunk id or by the list's end, or after letters whose length runs past the list is reported as damage (this reader's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); LC `CMXParser.cpp` L1698-L1749 (a file with 32-bit coordinates: the model byte and a byte in tag 1, the values in tag 2, other tags passed over), L2254-L2371 (the values of each model: 2 and 3 four bytes, 5 red, green and blue, 9 one byte), `CMXDocumentStructure.h` L138-L139 (the tags); S: every color of the nine CX files is model 2 in the older fields, with the second byte of field 1 5 | sample (model 2), public-reader (the tags and the values of models 2, 5 and 9), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample |
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
@@ -148,24 +155,26 @@ file is committed.
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) |
## Written fields
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the
index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in
their page, layer and group records, and the bounds they keep in layer and group records are not
written: no public source describes
them, and the reader finds every chunk by its id and walks the instructions in order.
the synthetic test files of `src/synth_cmx.rs` set it.
| Field written | Rows | Status |
|---|---|---|
| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample |
| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) |
| Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) |
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
| `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) |
| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) |
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
| `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) |
| `rlst` for each page: its layers' numbers | R77 | sample |
| Table counts and field lists | R55 | sample |
| `rclr` fields 1 and 2, before field 10: the model and 5, then four value bytes; model 2 (CMYK in percent), 5 (red, green, blue, then 0) and 9 (gray, then three zero bytes); a spot color as model 5 with its look at its tint, and the registration color as model 2 with four values of 100 | R56 | sample (the fields, model 2 and the 5), public-reader (models 5 and 9), the writer's choice (the models of spot and registration colors, the zero bytes and the order of the fields) |
| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) |
| `rpen` field 1: the width | R57 | public-notes |
| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own |
@@ -177,9 +186,11 @@ them, and the reader finds every chunk by its id and walks the instructions in o
| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample |
| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) |
| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) |
| Begin page, field 1 after the edges: the offset of the end-page instruction, the layer count and the instruction count | R77 | sample |
| Begin page, field 4: the page's width and height | R61 | public-notes |
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) |
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 4 zero bytes, the layer's instruction count, then the name as a u16 byte count and 8-bit characters | R62, R77 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the count; the name), own (the 4 bytes) |
| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes |
| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) |
| Begin group, field 1: the edges of the group's curves as the page's are measured (all 0 for a group with none), the groups directly inside it, its instruction count and the offset of the instruction after its end | R77 | sample (the counts and the offset), public-reader (the order), the writer's choice (the edges where they differ from the points' edges, as for a page) |
| End layer, group and page with no fields | R60 | own (the bodies are not read) |
| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) |
| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) |
+15 -8
View File
@@ -107,12 +107,17 @@ corners, not stretched ones. Hidden layers, groups and shapes, guide and grid la
and master layers are left out; opacity, blend modes, fill rules and locked states are not
written, desktop layers are written as drawing layers, and a spot color with no name opens as a
process color; every use of a named spot color takes the look of its use at the strongest tint
among the uses whose look is known.
among the uses whose look is known. Each color entry holds the color twice: as the property list
`read_cmx` reads, and as the model and value fields that other readers, such as libcdr, read. In
those fields a spot color is written as its look at its tint, and the registration color as 100
percent cyan, magenta, yellow and black.
`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width
past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than
65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks,
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, a depth limit
of 0 (at which `read_cmx` leaves out the index list), more than 65,535 groups directly inside one
group, more chunks,
objects, coordinates or dashes than a read within the limits takes, a file longer than their input
size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes
rounded to whole outline widths, nonzero fills that may fill differently, names that open
@@ -120,12 +125,14 @@ shortened, spot colors at a tint too low to keep their look, with no name or wit
(written black), uses of one ink with different looks, and what was left out or written opaque,
unclipped or unlocked.
The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
inside page, layer and group records, and the bounds inside layer and group records are not
written, so a reader must find the chunks by their ids and walk the instructions in order, as
`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page
when it has none. `PROVENANCE.md`'s "Written
fields" table lists every field the `.cmx` writer sets.
The file holds an index, so that a reader that finds the tables and pages through it, rather than
by their chunk ids, opens it: the header gives where the master index starts, the index list
(`LIST indx`) gives where each table, page, page reference list and layer starts, and the page,
layer and group records give their instruction counts. A page's record also gives where its
end-page instruction starts, and a group's record gives where the instruction after its end-group
instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or
of the page when it has none. The header repeats the first page's edges and instruction count.
`PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets.
## Writing
+347 -67
View File
@@ -2,8 +2,8 @@
//! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and
//! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for
//! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines
//! (R63). `PROVENANCE.md`'s "Written fields" lists every field the writer sets and where its layout
//! comes from.
//! (R63), and the index that gives where each of them starts (R77). `PROVENANCE.md`'s "Written
//! fields" lists every field the writer sets and where its layout comes from.
//!
//! Rectangles and ellipses are written as curves. A clipping container is written as a group of
//! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes,
@@ -130,28 +130,58 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result<Written, Error>
children.push(c);
Ok(())
};
add(chunk(b"cont", &cont())?)?;
for (n, page) in drawing.pages.iter().enumerate() {
add(w.page(n, page.size.or(drawing.page_size), &page.layers)?)?;
// The header's index offset is set once the index is placed.
add(chunk(b"cont", &cont(0, PageHead::default()))?)?;
// Each page chunk and its reference list, with where they start in the file and the start and
// name of each of the page's layers.
let mut pages = Vec::new();
let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> {
let at = w.file_bytes;
let (c, written, head) = w.page(n, size, layers)?;
add(c)?;
let refs = w.file_bytes;
let r = chunk(b"rlst", &reference_list(written.len()))?;
w.check_bytes(r.len())?;
w.file_bytes += r.len();
add(r)?;
pages.push(PageAt { at, refs, layers: written, head });
Ok(())
};
for (n, p) in drawing.pages.iter().enumerate() {
page(&mut w, n, p.size.or(drawing.page_size), &p.layers)?;
}
// A drawing with no pages but a page size is written as one empty page of that size.
if drawing.pages.is_empty() && drawing.page_size.is_some() {
add(w.page(0, drawing.page_size, &[])?)?;
page(&mut w, 0, drawing.page_size, &[])?;
}
// The reader also counts every chunk (`cont`, the pages and the seven tables), every table entry
// and the one arrowhead pair.
let pages = if drawing.pages.is_empty() { usize::from(drawing.page_size.is_some()) } else { drawing.pages.len() };
// The reader leaves out a list as deep as its depth limit, and the index is a list.
if w.limits.depth == 0 {
return Err(Error::Limit("nesting depth"));
}
// The reader also counts every chunk (`cont`, each page and its reference list, the seven
// tables, and the index list with its three chunks and a layer table for each page), every
// table entry and the one arrowhead pair.
let t = &w.tables;
let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1;
w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + pages + 7 + entries);
let index_chunks = pages.len().saturating_add(4);
w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + 2 * pages.len() + 7 + entries + index_chunks);
w.read_cost.check(&w.limits)?;
// Where each table chunk starts, by its id.
let mut tables = Vec::new();
let mut at = w.file_bytes;
for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? {
let id: [u8; 4] = c[0..4].try_into().map_err(|_| Error::Limit("chunk size"))?;
tables.push((id, at));
at = at.saturating_add(c.len());
add(c)?;
}
let (list, ixmr) = index(at, &pages, &tables)?;
add(list)?;
let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?;
if total > w.limits.input {
return Err(Error::Limit("input size"));
}
children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?;
let mut bytes = Vec::new();
bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?;
bytes.extend(b"RIFF");
@@ -190,16 +220,124 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result<Vec<u8>, Error> {
}
/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files; the rest are zeros.
fn cont() -> Vec<u8> {
/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file
/// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the
/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and
/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros.
fn cont(ixmr: u32, first: PageHead) -> Vec<u8> {
let mut c = vec![0u8; 180];
c[48] = b'2';
c[52] = b'4';
c[54] = b'2';
c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes());
c[84..88].copy_from_slice(&ixmr.to_le_bytes());
c[88..96].fill(0xFF);
for (i, v) in first.edges.iter().enumerate() {
c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes());
}
c[112..116].copy_from_slice(&first.instructions.to_le_bytes());
c
}
/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom
/// edges and its instruction count, begin and end page included.
#[derive(Clone, Copy, Default)]
struct PageHead {
edges: [i32; 4],
instructions: u32,
}
/// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name.
type LayerAt = (usize, Vec<u8>);
/// Where a page's chunks start in the file, and its layers.
struct PageAt {
at: usize,
/// The page's reference list `rlst`.
refs: usize,
layers: Vec<LayerAt>,
/// What the header repeats of its begin-page record.
head: PageHead,
}
/// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16
/// values 2 and 9 and its number.
fn reference_list(layers: usize) -> Vec<u8> {
let mut r = (layers as u16).to_le_bytes().to_vec();
for n in 1..=layers {
r.extend([2u16, 9, n as u16].map(u16::to_le_bytes).concat());
}
r
}
/// A file offset as the u32 the index stores.
fn offset(at: usize) -> Result<u32, Error> {
u32::try_from(at).map_err(|_| Error::Limit("chunk size"))
}
/// The index list `LIST indx` starting at file offset `at` (R77): a layer table `ixlr` for each
/// page, the table of layer tables `ixtl`, the page index `ixpg` and the master index `ixmr`, with
/// the file offset of `ixmr`. `tables` gives where each table chunk starts, by its id.
fn index(at: usize, pages: &[PageAt], tables: &[([u8; 4], usize)]) -> Result<(Vec<u8>, u32), Error> {
let mut body = b"indx".to_vec();
// Where the next chunk of the list starts.
let next = |body: &Vec<u8>| at.saturating_add(8).saturating_add(body.len());
let mut layer_tables = Vec::with_capacity(pages.len());
for (n, p) in pages.iter().enumerate() {
layer_tables.push(next(&body));
// The layer count and the page number, then for each layer the size of its record before
// the 0xFFFFFFFF that ends it, its begin-layer instruction and its name.
let mut t = (p.layers.len() as u16).to_le_bytes().to_vec();
t.extend(u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?.to_le_bytes());
for (start, name) in &p.layers {
t.extend(((8 + name.len()) as u16).to_le_bytes());
t.extend(offset(*start)?.to_le_bytes());
t.extend((name.len() as u16).to_le_bytes());
t.extend(name);
t.extend(u32::MAX.to_le_bytes());
}
body.extend(chunk(b"ixlr", &t)?);
}
// The table of layer tables: their count, the size of each record, the type 3 and the offsets.
let ixtl = next(&body);
let mut t = (pages.len() as u16).to_le_bytes().to_vec();
t.extend(4u16.to_le_bytes());
t.extend(3u16.to_le_bytes());
for l in &layer_tables {
t.extend(offset(*l)?.to_le_bytes());
}
body.extend(chunk(b"ixtl", &t)?);
// The page index: the page count, then for each page the size of its record, its page chunk,
// its layer table, 0xFFFFFFFF for a picture of the page it does not have and its reference
// list.
let ixpg = next(&body);
let mut t = (pages.len() as u16).to_le_bytes().to_vec();
for (p, l) in pages.iter().zip(&layer_tables) {
t.extend(16u16.to_le_bytes());
for v in [offset(p.at)?, offset(*l)?, u32::MAX, offset(p.refs)?] {
t.extend(v.to_le_bytes());
}
}
body.extend(chunk(b"ixpg", &t)?);
// The master index: the values 1 and 24, the entry count, then an id and an offset for itself,
// the page index, the table of layer tables and each table.
let ixmr = next(&body);
let ids: [(&[u8; 4], u16); 7] = [(b"rotl", 15), (b"rott", 16), (b"rota", 17), (b"rscr", 18), (b"rpen", 19), (b"rdot", 20), (b"rclr", 21)];
let mut entries = vec![(1u16, ixmr), (2, ixpg), (3, ixtl)];
for (id, n) in ids {
if let Some((_, start)) = tables.iter().find(|(t, _)| t == id) {
entries.push((n, *start));
}
}
let mut t = [1u16, 24, entries.len() as u16].map(u16::to_le_bytes).concat();
for (n, start) in entries {
t.extend(n.to_le_bytes());
t.extend(offset(start)?.to_le_bytes());
}
body.extend(chunk(b"ixmr", &t)?);
Ok((chunk(b"LIST", &body)?, offset(ixmr)?))
}
/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the
/// data does not fit the length.
fn field(tag: u8, data: &[u8]) -> Option<Vec<u8>> {
@@ -397,9 +535,25 @@ fn color_key(c: &Color) -> ColorKey {
}
}
/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32
/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the
/// values; R14), and for a named color part 3, a u32 count and UTF-16 units.
/// The color of `k` in the fields 1 and 2 of a color entry (R56): the model and the palette 5,
/// then four value bytes. A spot color is written as its look at its tint in red, green and blue,
/// and the registration color as cyan, magenta, yellow and black at 100 percent, since the
/// models of these fields hold neither.
fn older_fields(k: &ColorKey) -> (u8, [u8; 4]) {
let [v0, v1, v2, v3] = k.values;
match k.model {
2 => (2, [v0, v1, v2, v3]),
// Red, green and blue, where the color record holds blue, green and red.
5 | 21 => (5, [v2, v1, v0, 0]),
9 => (9, [v0, 0, 0, 0]),
_ => (2, [100; 4]),
}
}
/// A color entry (R56): field 1 the model and the palette, field 2 the values, as
/// [`older_fields`] gives them, then field 10, a property list: a u32 length then parts of a u8
/// kind, a u32 length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes,
/// the values; R14), and for a named color part 3, a u32 count and UTF-16 units.
fn color_entry(k: &ColorKey) -> Result<Vec<u8>, Error> {
let mut list = vec![1u8];
list.extend(12u32.to_le_bytes());
@@ -416,7 +570,9 @@ fn color_entry(k: &ColorKey) -> Result<Vec<u8>, Error> {
}
let mut rec = (list.len() as u32).to_le_bytes().to_vec();
rec.extend(list);
Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?]))
let (model, values) = older_fields(k);
let size = || Error::Limit("table entry size");
Ok(fields(&[field(1, &[model, 5]).ok_or_else(size)?, field(2, &values).ok_or_else(size)?, field(10, &rec).ok_or_else(size)?]))
}
/// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file.
@@ -462,8 +618,14 @@ struct Writer {
looks: HashMap<String, [f32; 3]>,
/// The comparisons [`may_fill_differently`] may still make.
crossing_budget: u64,
/// The groups open where the next instruction is written.
open_groups: usize,
/// The groups open where the next instruction is written, outermost first.
open_groups: Vec<OpenGroup>,
/// The instructions written on the current page, its begin-page instruction included.
instructions: usize,
/// For each group closed on the current page, where its end offset goes in the page's
/// instructions after the begin-page instruction, and the offset there, both counted from the
/// end of the begin-page instruction.
group_ends: Vec<(usize, usize)>,
/// The smallest and largest x and y the curves written on the current page reach, in
/// coordinate units.
bounds: Option<[i32; 4]>,
@@ -585,10 +747,17 @@ impl Writer {
self.tables.colors.index(key)
}
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60).
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<Vec<u8>, Error> {
/// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60),
/// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and
/// what the header repeats of the begin-page record. The chunk starts at the file offset
/// [`Writer::file_bytes`] gives.
fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec<u8>, Vec<LayerAt>, PageHead), Error> {
let mut out = Vec::new();
self.bounds = None;
self.instructions = 1;
self.group_ends.clear();
// Where each layer's begin-layer instruction starts in `out`, and its 8-bit name.
let mut starts = Vec::new();
// The model holds layers and objects front to back; the file lists them back to front.
let mut written = 0;
for layer in layers.iter().rev() {
@@ -604,19 +773,43 @@ impl Writer {
// The reader also stops a layer's name at its first NUL and takes a blank name as none.
let name = &layer.name;
self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty());
out.extend(instr(BEGIN_LAYER, &layer_fields(n, written, &layer.name)?));
let body = layer_fields(n, written, &layer.name)?;
let begin = instr(BEGIN_LAYER, &body);
// The layer's instruction count goes at bytes 8 to 12 of field 1, after the
// instruction's header and the field's tag and length.
let count_at = out.len() + begin.len() - body.len() + 3 + 8;
let first = self.instructions;
starts.push((out.len(), narrow_name(&layer.name)));
out.extend(begin);
self.instructions += 1;
written += 1;
self.objects(&layer.objects, &mut out)?;
out.extend(instr(END_LAYER, &[]));
self.instructions += 1;
put_u32(&mut out, count_at, self.instructions - first)?;
self.read_cost.chunks += 2;
self.read_cost.check(&self.limits)?;
self.check_bytes(out.len())?;
}
let end = out.len();
out.extend(instr(END_PAGE, &[]));
self.instructions += 1;
// The begin and end page instructions.
self.read_cost.chunks += 2;
self.read_cost.check(&self.limits)?;
let begin = begin_page(n, size, self.bounds.take())?;
let bounds = self.bounds.take();
let begin_len = begin_page(n, size, bounds, PageTail::default())?.len();
// The page's instructions after the begin-page instruction start here in the file.
let base = self.file_bytes.saturating_add(8).saturating_add(begin_len);
let tail = PageTail {
end: offset(base.saturating_add(end))?,
layers: u16::try_from(written).map_err(|_| Error::Limit("layers"))?,
instructions: u32::try_from(self.instructions).map_err(|_| Error::Limit("chunk count"))?,
};
for (at, end) in std::mem::take(&mut self.group_ends) {
put_u32(&mut out, at, base.saturating_add(end))?;
}
let begin = begin_page(n, size, bounds, tail)?;
if u32::try_from(begin.len() + out.len()).is_err() {
return Err(Error::Limit("chunk size"));
}
@@ -624,8 +817,9 @@ impl Writer {
page.extend(out);
let c = chunk(b"page", &page)?;
self.check_bytes(c.len())?;
let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect();
self.file_bytes += c.len();
Ok(c)
Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions }))
}
/// An [`Error::Limit`] when the file would be longer than the input size of the limits with
@@ -657,7 +851,7 @@ impl Writer {
self.shape(&s, out)?;
}
if ends {
self.end_group(out);
self.end_group(out)?;
}
}
continue;
@@ -699,20 +893,55 @@ impl Writer {
/// Begin a group. A group inside as many groups as the reader opens (the depth of the
/// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds.
fn begin_group(&mut self, out: &mut Vec<u8>) -> Result<(), Error> {
if self.open_groups >= self.limits.depth {
if self.open_groups.len() >= self.limits.depth {
return Err(Error::Limit("nesting depth"));
}
self.open_groups += 1;
if let Some(parent) = self.open_groups.last_mut() {
parent.groups = parent.groups.checked_add(1).ok_or(Error::Limit("groups"))?;
}
self.open_groups.push(OpenGroup { at: out.len(), first: self.instructions, groups: 0, bounds: None });
out.extend(group());
self.instructions += 1;
self.read_cost.chunks += 1;
self.read_cost.objects += 1;
self.read_cost.check(&self.limits)
}
fn end_group(&mut self, out: &mut Vec<u8>) {
self.open_groups = self.open_groups.saturating_sub(1);
/// End the innermost open group, and fill in its begin-group record (R77): the edges of its
/// curves (all 0 when it has none), the groups directly inside it, its instructions from begin
/// to end, and where the instruction after its end starts, which [`Writer::page`] places in
/// the file.
fn end_group(&mut self, out: &mut Vec<u8>) -> Result<(), Error> {
out.extend(instr(END_GROUP, &[]));
self.instructions += 1;
self.read_cost.chunks += 1;
let Some(g) = self.open_groups.pop() else { return Ok(()) };
if let (Some(parent), Some(b)) = (self.open_groups.last_mut(), g.bounds) {
parent.bounds = Some(match parent.bounds {
Some(p) => [p[0].min(b[0]), p[1].min(b[1]), p[2].max(b[2]), p[3].max(b[3])],
None => b,
});
}
// Field 1's data starts after the instruction's 4-byte header and the field's tag and
// length.
let data = g.at + 4 + 3;
let [x0, y0, x1, y1] = g.bounds.unwrap_or_default();
for (i, v) in [x0, y1, x1, y0].into_iter().enumerate() {
out[data + 4 * i..data + 4 * i + 4].copy_from_slice(&v.to_le_bytes());
}
out[data + 16..data + 18].copy_from_slice(&g.groups.to_le_bytes());
put_u32(out, data + 18, self.instructions - g.first)?;
self.group_ends.push((data + 22, out.len()));
Ok(())
}
/// Take in `[x0, y0, x1, y1]`, the edges of a written curve, in the page's and the innermost
/// open group's edges.
fn reach(&mut self, e: [i32; 4]) {
for b in [Some(&mut self.bounds), self.open_groups.last_mut().map(|g| &mut g.bounds)].into_iter().flatten() {
let b = b.get_or_insert(e);
*b = [b[0].min(e[0]), b[1].min(e[1]), b[2].max(e[2]), b[3].max(e[3])];
}
}
/// A shape as one curve, or as a group of curves when its path holds more than
@@ -802,9 +1031,7 @@ impl Writer {
_ => [p.x, p.y, p.x, p.y],
};
// Within the anchors and control points, which are i32, so the casts keep them.
let (x0, y0, x1, y1) = (x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32);
let b = self.bounds.get_or_insert([x0, y0, x1, y1]);
*b = [b[0].min(x0), b[1].min(y0), b[2].max(x1), b[3].max(y1)];
self.reach([x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32]);
}
g.extend(c.iter().map(|(_, t)| *t));
bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?);
@@ -815,10 +1042,11 @@ impl Writer {
let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()]));
self.check_bytes(out.len().saturating_add(i.len()))?;
out.extend(i);
self.instructions += 1;
}
}
if curves.len() > 1 {
self.end_group(out);
self.end_group(out)?;
}
Ok(())
}
@@ -912,41 +1140,61 @@ impl Writer {
}
}
/// A group open where the next instruction is written.
struct OpenGroup {
/// Where its begin-group instruction starts in the page's instructions after the begin-page
/// instruction.
at: usize,
/// The page's instructions written before it.
first: usize,
/// The groups directly inside it so far.
groups: u16,
/// The smallest and largest x and y its curves reach so far, in coordinate units.
bounds: Option<[i32; 4]>,
}
/// What begin page keeps of the rest of the page (R77).
#[derive(Clone, Copy, Default)]
struct PageTail {
/// The file offset of the end-page instruction.
end: u32,
/// The layers on the page.
layers: u16,
/// The page's instructions, begin and end page included.
instructions: u32,
}
/// Write `v` as a u32 at `at` of `out`.
fn put_u32(out: &mut [u8], at: usize, v: usize) -> Result<(), Error> {
let v = u32::try_from(v).map_err(|_| Error::Limit("chunk size"))?;
out.get_mut(at..at + 4).ok_or(Error::Limit("chunk size"))?.copy_from_slice(&v.to_le_bytes());
Ok(())
}
/// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left,
/// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y),
/// or of the page around its center when it has no art; field 4 its width and height. Without a
/// size the edges are all 0, which the reader takes as no size.
fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<Vec<u8>, Error> {
/// or of the page around its center when it has no art, then `tail` (R77); field 4 its width and
/// height. Without a size the edges are all 0, which the reader takes as no size.
fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail: PageTail) -> Result<Vec<u8>, Error> {
let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?;
let mut d = number.to_le_bytes().to_vec();
d.extend(0u32.to_le_bytes());
let mut list = Vec::new();
let mut size_field = None;
let mut edges = [0i32; 4];
if let Some((w, h)) = size {
// A negative or NaN side counts as 0.
let (wu, hu) = (width_units(w)?, width_units(h)?);
// A side that rounds to nothing would make the reader drop the page's whole size.
if wu == 0 || hu == 0 {
return Err(Error::Limit("page size"));
let edges = page_edges(size, bounds)?;
let size_field = match size {
Some((w, h)) => {
let mut s = width_units(w)?.to_le_bytes().to_vec();
s.extend(width_units(h)?.to_le_bytes());
Some(s)
}
edges = match bounds {
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
None => {
// The page around its center; an odd size keeps its extra unit on the left and
// bottom, where the edge reaches -2^31.
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
let (w, h) = (i64::from(wu), i64::from(hu));
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
}
};
let mut s = wu.to_le_bytes().to_vec();
s.extend(hu.to_le_bytes());
size_field = Some(s);
}
None => None,
};
for v in edges {
d.extend(v.to_le_bytes());
}
d.extend(tail.end.to_le_bytes());
d.extend(tail.layers.to_le_bytes());
d.extend(tail.instructions.to_le_bytes());
list.push(field(1, &d).ok_or(Error::Limit("page size"))?);
if let Some(s) = size_field {
list.push(field(4, &s).ok_or(Error::Limit("page size"))?);
@@ -954,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> R
Ok(instr(BEGIN_PAGE, &fields(&list)))
}
/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches
/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`].
fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> {
let Some((w, h)) = size else { return Ok([0; 4]) };
// A negative or NaN side counts as 0.
let (wu, hu) = (width_units(w)?, width_units(h)?);
// A side that rounds to nothing would make the reader drop the page's whole size.
if wu == 0 || hu == 0 {
return Err(Error::Limit("page size"));
}
Ok(match bounds {
Some([x0, y0, x1, y1]) => [x0, y1, x1, y0],
None => {
// The page around its center; an odd size keeps its extra unit on the left and
// bottom, where the edge reaches -2^31.
let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size"));
let (w, h) = (i64::from(wu), i64::from(hu));
[edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?]
}
})
}
/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it.
fn windows_1252_byte(c: char) -> u8 {
match u8::try_from(u32::from(c)) {
@@ -962,16 +1232,26 @@ fn windows_1252_byte(c: char) -> u8 {
}
}
/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 8 zero
/// bytes, then the name as a u16 count and 8-bit characters (Windows-1252: characters the code
/// page has no byte for are written as `?`); field 4 the name as a u32 count and UTF-16 units.
/// `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers is an
/// [`Error::Limit`].
/// Whether a layer's `name`, up to the first NUL where the reader stops, is blank: it is written
/// empty, so it opens with no name.
fn blank_name(name: &str) -> bool {
name.split('\0').next().unwrap_or_default().trim().is_empty()
}
/// A layer's name as written in 8-bit characters (Windows-1252: characters the code page has no
/// byte for are written as `?`).
fn narrow_name(name: &str) -> Vec<u8> {
if blank_name(name) { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() }
}
/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 4 zero
/// bytes, the layer's instruction count, which [`Writer::page`] fills in (R77), then the name as a
/// u16 count and 8-bit characters ([`narrow_name`]); field 4 the name as a u32 count and UTF-16
/// units. `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers
/// is an [`Error::Limit`].
fn layer_fields(page: usize, n: usize, name: &str) -> Result<Vec<u8>, Error> {
// A blank name, up to the first NUL where the reader stops, is written empty in both fields,
// so it opens with no name.
let blank = name.split('\0').next().unwrap_or_default().trim().is_empty();
let narrow: Vec<u8> = if blank { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() };
let blank = blank_name(name);
let narrow = narrow_name(name);
let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?;
let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?;
let mut d = page.to_le_bytes().to_vec();
@@ -987,7 +1267,7 @@ fn layer_fields(page: usize, n: usize, name: &str) -> Result<Vec<u8>, Error> {
Ok(fields(&[f1, f4]))
}
/// Begin a group: field 1 of 26 zero bytes, as the test files of `synth_cmx` hold.
/// Begin a group: field 1 of 26 bytes, which [`Writer::end_group`] fills in (R77).
fn group() -> Vec<u8> {
instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()]))
}
+15 -7
View File
@@ -133,8 +133,9 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
/// width, or a page side that rounds to 0;
/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash
/// patterns or outlines, or a dash pattern of more than 32,765 lengths;
/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or
/// dashes than a read within `limits` takes;
/// - groups nested deeper than the depth of `limits`, a depth of 0, at which the reader leaves out
/// the index list, more than 65,535 groups directly inside one group, or more chunks, objects,
/// coordinates or dashes than a read within `limits` takes;
/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds.
///
/// [`Written`] reports what the file holds differently from the drawing; its fields name each
@@ -142,11 +143,18 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
/// written with round corners of its radii times the square root of the scales' product, not with
/// stretched corners, and is not reported.
///
/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
/// inside page, layer and group records, and the bounds inside layer and group records are not
/// written, so a reader must find the chunks by their ids and walk the instructions in order, as
/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the
/// page when it has none.
/// Each color entry holds the color twice: as the property list [`read_cmx`] reads, and as the
/// model and value fields that other readers read. In those fields a spot color is written as its
/// look at its tint, and the registration color as 100 percent cyan, magenta, yellow and black.
///
/// The file holds an index, so that a reader that finds the tables and pages through it, rather
/// than by their chunk ids, opens it: the header gives where the master index starts, the index
/// list (`LIST indx`) gives where each table, page, page reference list and layer starts, and the
/// page, layer and group records give their instruction counts. A page's record also gives where
/// its end-page instruction starts, and a group's record gives where the instruction after its
/// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of
/// its curves, or of the page when it has none. The header repeats the first page's edges and
/// instruction count.
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
cmx_write::write(drawing, limits)
}
+338 -8
View File
@@ -283,9 +283,15 @@ fn pages_are_numbered_in_their_order() {
assert_eq!(numbers, [1, 2]);
}
/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag,
/// a u16 length counting the 3 header bytes, the data; 0xff after the last field).
/// Field 1 of each entry of the table chunk `id`.
fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
table_fields(bytes, id).into_iter().map(|e| e.into_iter().find(|(tag, ..)| *tag == 1).map(|(.., data)| data).expect("field 1")).collect()
}
/// The fields of each entry of the table chunk `id`, each its tag, where it starts in the file and
/// its data: a u16 count, then a field list per entry (a tag, a u16 length counting the 3 header
/// bytes, the data; 0xff after the last field).
fn table_fields(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<(u8, usize, Vec<u8>)>> {
let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8;
// The chunk's body runs for the size after its id.
let end = at + u32::from_le_bytes(bytes[at - 4..at].try_into().unwrap()) as usize;
@@ -294,7 +300,7 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
let mut p = at + 2;
let mut out = Vec::new();
for _ in 0..count {
let mut first = None;
let mut entry = Vec::new();
loop {
assert!(p < end, "entry runs past the {id:?} chunk at {p}");
if bytes[p] == 0xff {
@@ -304,13 +310,11 @@ fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec<Vec<u8>> {
let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]]));
// A length shorter than its header, or past the chunk, would stop the walk.
assert!(len >= 3 && p + len <= end, "field at {p} has length {len}");
if bytes[p] == 1 {
first = Some(bytes[p + 3..p + len].to_vec());
}
entry.push((bytes[p], p, bytes[p + 3..p + len].to_vec()));
p += len;
}
p += 1;
out.push(first.expect("field 1"));
out.push(entry);
}
// The size counts the u16 count and the entries; the pad byte comes after it.
assert_eq!(p, end, "{id:?} chunk has bytes left after its entries");
@@ -348,6 +352,61 @@ fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() {
assert_eq!(patterns, vec![(false, vec![]), (true, vec![3, 1])]);
}
#[test]
fn colors_are_also_written_in_the_model_and_value_fields() {
let colors = [
Color::Rgb([1.0, 0.2, 0.0]),
Color::Cmyk([0.6, 0.0, 0.13, 0.05]),
Color::Gray(0.75),
Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) },
Color::Registration,
];
let objects = colors
.iter()
.enumerate()
.map(|(i, c)| Object::Shape(Box::new(Shape::new(square(20.0 * i as f64, 0.0, 10.0), Matrix::IDENTITY, Some(c.clone()), None))))
.collect();
let d = drawing(vec![Page { size: Some((200.0, 100.0)), layers: vec![layer("Art", objects)] }]);
let mut bytes = write_cmx(&d).unwrap().bytes;
let entries = table_fields(&bytes, b"rclr");
// Each entry holds the model and the palette 5 in field 1 and four values in field 2, before
// the property list of field 10.
let mut older: Vec<(Vec<u8>, Vec<u8>)> = entries
.iter()
.map(|e| {
assert_eq!(e.iter().map(|(tag, ..)| *tag).collect::<Vec<_>>(), [1, 2, 10]);
(e[0].2.clone(), e[1].2.clone())
})
.collect();
older.sort();
let mut want = vec![
// Red, green and blue.
(vec![5, 5], vec![255, 51, 0, 0]),
// Cyan, magenta, yellow and black in percent.
(vec![2, 5], vec![60, 0, 13, 5]),
// Gray, 255 white.
(vec![9, 5], vec![64, 0, 0, 0]),
// The spot color's look at its tint of 40 percent.
(vec![5, 5], vec![153, 194, 235, 0]),
// The registration color as every ink at 100 percent.
(vec![2, 5], vec![100, 100, 100, 100]),
];
want.sort();
assert_eq!(older, want);
// With field 10 retagged, the reader takes each color from fields 1 and 2.
for e in &entries {
bytes[e[2].1] = 11;
}
let back = read_cmx(&bytes, Limits::default()).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
let fills: Vec<Color> = back.pages[0].layers[0].objects.iter().map(|o| shape(o).fill.clone().unwrap()).collect();
let opened = [colors[0].clone(), colors[1].clone(), colors[2].clone(), Color::Rgb([0.6, 0.76, 0.92]), Color::Cmyk([1.0; 4])];
assert_eq!(fills.len(), opened.len());
for (got, want) in fills.iter().zip(&opened) {
assert!(near_color(got, want), "{got:?} for {want:?}");
}
}
#[test]
fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() {
let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]);
@@ -657,7 +716,7 @@ fn a_page_without_a_size_still_writes_its_four_edges() {
// The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length.
assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9);
let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]]));
assert_eq!(len - 3, 2 + 4 + 16, "the page number, the flags and four edges");
assert_eq!(len - 3, 2 + 4 + 16 + 4 + 2 + 4, "the page number, the flags, four edges, the end, the layers and the instructions");
}
#[test]
@@ -950,6 +1009,277 @@ fn layers_give_their_page_and_their_number() {
assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]);
}
fn u16_at(b: &[u8], at: usize) -> usize {
usize::from(u16::from_le_bytes([b[at], b[at + 1]]))
}
fn u32_at(b: &[u8], at: usize) -> usize {
u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize
}
/// The id of each chunk of a written file by where it starts, those inside lists included.
fn chunk_ids(b: &[u8]) -> std::collections::HashMap<usize, [u8; 4]> {
let mut ids = std::collections::HashMap::new();
let mut stack = vec![(12, b.len())];
while let Some((mut at, end)) = stack.pop() {
while at + 8 <= end {
let id: [u8; 4] = b[at..at + 4].try_into().unwrap();
let size = u32_at(b, at + 4);
ids.insert(at, id);
if id == *b"LIST" {
stack.push((at + 12, at + 8 + size));
}
at += 8 + size + size % 2;
}
}
ids
}
/// The field list at `at` of `b`, in an instruction that ends at `end`: each field's tag and where
/// its data starts. A field shorter than its 3 header bytes, or past `end`, fails the test.
fn field_starts(b: &[u8], mut at: usize, end: usize) -> Vec<(u8, usize)> {
let mut out = Vec::new();
while b[at] != 0xff {
let len = u16_at(b, at + 1);
assert!(len >= 3 && at + len <= end, "a field of length {len} at {at}, in an instruction that ends at {end}");
out.push((b[at], at + 3));
at += len;
}
out
}
#[test]
#[should_panic(expected = "a field of length 0")]
fn a_field_of_length_0_fails_the_check() {
field_starts(&[1, 0, 0, 0xff], 0, 4);
}
#[test]
#[should_panic(expected = "a field of length 9")]
fn a_field_past_its_instruction_fails_the_check() {
field_starts(&[1, 9, 0, 0, 0xff], 0, 5);
}
#[test]
fn the_index_and_the_records_give_where_everything_is() {
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
let inner = Object::Group { objects: vec![plain(20.0)], flags: Flags::default() };
let outer = Object::Group { objects: vec![plain(0.0), inner, plain(50.0)], flags: Flags::default() };
let pages = vec![
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![outer]), layer("Back", vec![plain(5.0)])] },
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0), plain(2.0)])] },
];
let b = write_cmx(&drawing(pages)).unwrap().bytes;
let page_entries = page_index(&b);
let layer_starts = layer_tables(&b, &page_entries, &[&["Back", "Front"], &["Only"]]);
let (seen_layers, groups) = page_records(&b, &page_entries);
assert_eq!(seen_layers, layer_starts);
// The inner group: itself and a curve; the outer: two curves and the inner group.
assert_eq!(groups, [(0, 3), (1, 7)]);
}
#[test]
fn the_header_repeats_the_first_pages_edges_and_instruction_count() {
let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)));
let pages = vec![
Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] },
Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] },
];
let b = write_cmx(&drawing(pages)).unwrap().bytes;
let cont = 12 + 8;
let chunk = page_index(&b)[0][0];
let page = chunk + 8;
// Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count
// and the instruction count.
let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4)));
assert_eq!(fields[0].0, 1);
let f1 = fields[0].1;
assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]);
// The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down.
let edges: Vec<i32> = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect();
let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32;
assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]);
// Begin and end page, two begin and end layers and three curves.
assert_eq!(u32_at(&b, cont + 112), 9);
assert_eq!(u32_at(&b, f1 + 28), 9);
// A drawing without pages leaves them 0.
let b = write_cmx(&drawing(Vec::new())).unwrap().bytes;
assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0));
}
/// The page index of a written file of two pages, each entry's page chunk, layer table, picture
/// and reference list, checked through the header and the master index.
fn page_index(b: &[u8]) -> Vec<[usize; 4]> {
let ids = chunk_ids(b);
let id = |at: usize| ids.get(&at).map(|i| String::from_utf8_lossy(i).into_owned()).unwrap_or_default();
// The header names the master index, and no information list or picture.
let cont = 12 + 8;
let ixmr = u32_at(b, cont + 84);
assert_eq!(id(ixmr), "ixmr");
assert_eq!((u32_at(b, cont + 88), u32_at(b, cont + 92)), (u32::MAX as usize, u32::MAX as usize));
// The master index names itself, the page index, the table of layer tables and each table.
let m = ixmr + 8;
assert_eq!((u16_at(b, m), u16_at(b, m + 2)), (1, 24));
let entries: Vec<(usize, String)> = (0..u16_at(b, m + 4)).map(|i| (u16_at(b, m + 6 + 6 * i), id(u32_at(b, m + 8 + 6 * i)))).collect();
let want =
[(1, "ixmr"), (2, "ixpg"), (3, "ixtl"), (15, "rotl"), (16, "rott"), (17, "rota"), (18, "rscr"), (19, "rpen"), (20, "rdot"), (21, "rclr")];
assert_eq!(entries, want.map(|(n, s)| (n, s.to_string())));
let at_of = |n: usize| u32_at(b, m + 8 + 6 * entries.iter().position(|(k, _)| *k == n).unwrap());
// The page index: each page chunk, its layer table, no picture and its reference list.
let pg = at_of(2) + 8;
assert_eq!(u16_at(b, pg), 2);
let page_entries: Vec<[usize; 4]> = (0..2)
.map(|i| {
let e = pg + 2 + 18 * i;
assert_eq!(u16_at(b, e), 16);
[0, 1, 2, 3].map(|k| u32_at(b, e + 2 + 4 * k))
})
.collect();
for [page, layers, picture, refs] in &page_entries {
assert_eq!((id(*page), id(*layers), *picture, id(*refs)), ("page".into(), "ixlr".into(), u32::MAX as usize, "rlst".into()));
}
// The table of layer tables lists each page's.
let tl = at_of(3) + 8;
assert_eq!([u16_at(b, tl), u16_at(b, tl + 2), u16_at(b, tl + 4)], [2, 4, 3]);
assert_eq!([u32_at(b, tl + 6), u32_at(b, tl + 10)], [page_entries[0][1], page_entries[1][1]]);
page_entries
}
/// Where each layer table of `page_entries` says the layers named `names` start, checking each
/// table and each reference list: a layer table holds its count, the page number, then each
/// layer's begin-layer instruction and name, back to front; a reference list a count, and 2, 9 and
/// the number of each layer.
fn layer_tables(b: &[u8], page_entries: &[[usize; 4]], names: &[&[&str]]) -> Vec<usize> {
let mut layer_starts = Vec::new();
for (n, (entry, names)) in page_entries.iter().zip(names).enumerate() {
let t = entry[1] + 8;
assert_eq!((u16_at(b, t), u16_at(b, t + 2)), (names.len(), n + 1));
let mut at = t + 4;
for name in *names {
let size = u16_at(b, at);
let start = u32_at(b, at + 2);
let len = u16_at(b, at + 6);
assert_eq!((size, &b[at + 8..at + 8 + len]), (8 + name.len(), name.as_bytes()));
assert_eq!(u32_at(b, at + 8 + len), u32::MAX as usize);
assert_eq!(u16_at(b, start + 2), 11, "a begin-layer instruction");
layer_starts.push(start);
at += size + 4;
}
let r = entry[3] + 8;
let refs: Vec<usize> = (0..1 + 3 * names.len()).map(|i| u16_at(b, r + 2 * i)).collect();
let want: Vec<usize> = std::iter::once(names.len()).chain((1..=names.len()).flat_map(|k| [2, 9, k])).collect();
assert_eq!(refs, want);
}
layer_starts
}
/// An open begin-page, begin-layer or begin-group record: its code, where its field 1 starts, the
/// instructions before it, the records found directly inside it and the edges of its curves.
type Open = (usize, usize, usize, usize, Option<[i32; 4]>);
/// Check what the record `open` gives, now closed by the instruction of `code` and `size` at `at`
/// after `count` instructions of its page: begin page where the page ends, its layers and its
/// instructions; begin layer its instructions; begin group the edges of its curves, then its
/// groups and instructions, which are returned, and where the instruction after it starts.
fn closed_record(b: &[u8], open: Open, code: usize, at: usize, size: usize, count: usize) -> Option<(usize, usize)> {
let (opened, f1, before, inside, edges) = open;
assert_eq!(opened + 1, code);
let instructions = count - before;
match code {
10 => {
assert_eq!(u32_at(b, f1 + 22), at, "where the page ends");
assert_eq!(u16_at(b, f1 + 26), inside, "the page's layers");
assert_eq!(u32_at(b, f1 + 28), instructions);
None
}
12 => {
assert_eq!(u32_at(b, f1 + 8), instructions);
None
}
_ => {
let [x0, y0, x1, y1] = edges.unwrap();
let stored: Vec<i32> = (0..4).map(|k| u32_at(b, f1 + 4 * k) as i32).collect();
assert_eq!(stored, [x0, y1, x1, y0], "left, top, right and bottom");
assert_eq!(u32_at(b, f1 + 22), at + size, "where the group ends");
Some((u16_at(b, f1 + 16), u32_at(b, f1 + 18)))
}
}
}
/// Walk the instructions of each page of `page_entries`, checking the begin-page, begin-layer and
/// begin-group records, and give where each begin-layer instruction starts and each group's
/// groups and instructions, in the order the groups end.
fn page_records(b: &[u8], page_entries: &[[usize; 4]]) -> (Vec<usize>, Vec<(usize, usize)>) {
let mut seen_layers = Vec::new();
let mut groups = Vec::new();
for entry in page_entries {
let end = entry[0] + 8 + u32_at(b, entry[0] + 4);
let mut at = entry[0] + 8;
let mut open: Vec<Open> = Vec::new();
let mut count = 0;
while at < end {
let size = instruction_size(b, at, end);
let code = u16_at(b, at + 2);
count += 1;
match code {
9 | 11 | 13 => {
let f1 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 1).unwrap().1;
if code == 11 {
seen_layers.push(at);
}
// A page counts its layers and a group the groups directly inside it.
if code != 9 {
open.last_mut().unwrap().3 += 1;
}
open.push((code, f1, count - 1, 0, None));
}
67 => {
let f2 = field_starts(b, at + 4, at + size).iter().find(|(t, _)| *t == 2).unwrap().1;
for i in 0..u16_at(b, f2) {
let p = f2 + 2 + 8 * i;
let (x, y) = (u32_at(b, p) as i32, u32_at(b, p + 4) as i32);
for o in open.iter_mut().filter(|o| o.0 == 13) {
let e = o.4.get_or_insert([x, y, x, y]);
*e = [e[0].min(x), e[1].min(y), e[2].max(x), e[3].max(y)];
}
}
}
10 | 12 | 14 => groups.extend(closed_record(b, open.pop().unwrap(), code, at, size, count)),
_ => {}
}
at += size;
}
}
(seen_layers, groups)
}
/// The size of the instruction at `at` of `b`, in a page that ends at `end`. These files hold
/// only short instructions, so the long form (0xFFFF), a size shorter than the 4-byte header or
/// one past `end` fails the test.
fn instruction_size(b: &[u8], at: usize, end: usize) -> usize {
let size = u16_at(b, at);
assert!(size != 0xFFFF && size >= 4 && at + size <= end, "an instruction of size {size} at {at}, in a page that ends at {end}");
size
}
#[test]
#[should_panic(expected = "an instruction of size 0")]
fn an_instruction_of_size_0_fails_the_check() {
instruction_size(&[0, 0, 67, 0], 0, 4);
}
#[test]
#[should_panic(expected = "an instruction of size 65535")]
fn a_long_instruction_fails_the_check() {
instruction_size(&[0xff, 0xff, 67, 0, 8, 0, 0, 0], 0, 8);
}
#[test]
#[should_panic(expected = "an instruction of size 8")]
fn an_instruction_past_its_page_fails_the_check() {
instruction_size(&[8, 0, 67, 0], 0, 4);
}
#[test]
fn a_uniform_fill_names_the_screen_the_file_holds() {
let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes;
+10 -7
View File
@@ -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");
+1 -1
View File
@@ -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");
+5
View File
@@ -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.
+3 -3
View File
@@ -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)
+1 -1
View File
@@ -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,
+25 -9
View File
@@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput {
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
/// The recent row and the Other… cell do not report a swatch index.
pub picked_swatch: Option<usize>,
/// The cell `picked` came from, so a host can tell apart cells that show the same color.
pub cell: Option<PaletteCell>,
}
/// A cell of a [`SwatchPalette`] by its place in the host's lists.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaletteCell {
/// The swatch at this index of the palette's swatches.
Swatch(usize),
/// The color at this index of the recent row's colors.
Recent(usize),
}
impl Outcome for SwatchPaletteOutput {
@@ -112,8 +124,8 @@ impl PaletteColor<'_> {
/// What the body picked in its pass.
#[derive(Clone, Copy)]
enum Pick {
/// A swatch or a recent colour.
Color { color: Srgba, swatch: Option<usize> },
/// A swatch or a recent color, and its cell.
Color(Srgba, PaletteCell),
/// The Other… cell.
Other,
}
@@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> {
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
// on its release, so only the activation files the request: one request for one click.
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))),
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
});
}
@@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> {
.space(SpaceAction::ActivateLead)
.selection(Bind::bound(&mut current))
.show_all(ui);
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color { color: *picked, swatch: None });
if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) {
pick = Some(Pick::Color(*picked, PaletteCell::Recent(at)));
}
}
Some((before, pick))
@@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> {
let key = other.as_ref().map(|(key, _)| key.clone())?;
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
}
Pick::Color { color: after, swatch } => {
Pick::Color(after, cell) => {
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
let edit = (!unchanged).then(|| {
color.write(cx, before, after, name.as_str());
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
});
Some((Some(after), edit, None, swatch))
Some((Some(after), edit, None, Some(cell)))
}
}
})
.flatten();
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None));
let picked_swatch = match cell {
Some(PaletteCell::Swatch(at)) => Some(at),
_ => None,
};
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell }
}
}
+54 -9
View File
@@ -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,
}
@@ -450,6 +452,7 @@ pub struct ColorPanel<'a> {
edited: Option<Option<PickedColor>>,
shown: Option<ColorPanelShown>,
recent: Option<&'a [Srgba]>,
recent_models: &'a [Option<ModelValues>],
recent_setup: Option<RecentSetup>,
gamut: Option<Gamut<'a>>,
}
@@ -474,6 +477,7 @@ struct Inputs<'a> {
edited: Option<&'a Option<PickedColor>>,
shown: &'a ColorPanelShown,
recent: Option<&'a [Srgba]>,
recent_models: &'a [Option<ModelValues>],
recent_setup: Option<&'a RecentSetup>,
}
@@ -492,6 +496,7 @@ impl<'a> ColorPanel<'a> {
edited: None,
shown: None,
recent: None,
recent_models: &[],
recent_setup: None,
gamut: None,
}
@@ -541,6 +546,8 @@ impl<'a> ColorPanel<'a> {
/// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited
/// well's colour by default.
/// Explicit components take precedence over remembered values for their model, including when the host uses a
/// different working-space transform to render the colour.
pub fn edited(mut self, color: Option<PickedColor>) -> Self {
self.edited = Some(color);
self
@@ -559,6 +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));
@@ -573,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, buttons, 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);
@@ -613,6 +630,7 @@ impl<'a> ColorPanel<'a> {
edited: edited.as_ref(),
shown: rows.as_ref().unwrap_or(&default_rows),
recent,
recent_models,
recent_setup: recent_setup.as_ref(),
},
now: before,
@@ -1052,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)))
}
@@ -1096,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);
}
+26 -5
View File
@@ -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));
}
+1 -1
View File
@@ -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);
+182 -4
View File
@@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection};
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
use craft_color_ui::ui::{
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
SwatchesWords, swatch_rows,
PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel,
SwatchesState, SwatchesWords, swatch_rows,
};
use craft_host::target::Os;
use craft_theme::{ColorModel as _, HsbModel, Srgba};
use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba};
use craft_ui::buttons::Button;
use craft_ui::choice::SwatchTable;
use craft_ui::contract::Role;
@@ -197,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| {
@@ -275,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]
@@ -379,6 +553,7 @@ struct PaletteReports {
edits: Vec<EditEvent<Srgba>>,
requests: Vec<ColorRequest>,
picked: Vec<Srgba>,
cells: Vec<PaletteCell>,
swatches: Vec<usize>,
}
@@ -390,6 +565,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
reports.edits.extend(shown.edit);
reports.requests.extend(shown.pick_color);
reports.picked.extend(shown.picked);
reports.cells.extend(shown.cell);
reports.swatches.extend(shown.picked_swatch);
}
@@ -447,11 +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");
+4
View File
@@ -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"
+248 -2
View File
@@ -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();
+2 -3
View File
@@ -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 }
+19 -3
View File
@@ -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()
+15 -5
View File
@@ -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 {
+93 -22
View File
@@ -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
View File
@@ -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
View File
@@ -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))));
}
+24
View File
@@ -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"]
+1
View File
@@ -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`).
+8
View File
@@ -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")]
+8 -1
View File
@@ -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();
}
+14 -12
View File
@@ -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"));
+1 -1
View File
@@ -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 });
}
}
}
+1 -1
View File
@@ -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,
+13
View File
@@ -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]);
+1
View File
@@ -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
View File
@@ -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));
+3
View File
@@ -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,
+109 -38
View File
@@ -115,37 +115,62 @@ impl Reader<'_> {
/// Part 1 §20.4.2.5, §21.1.2.3.5) naming an external hyperlink relationship. Word stores a
/// picture's link there rather than in a `w:hyperlink` around its run (#5267). Its `#name`
/// part, when the address has one, stays part of the address.
pub(super) fn drawing_link(d: &El, rels: &Rels) -> Option<String> {
pub(super) fn drawing_link(&mut self, d: &El, rels: &Rels) -> Option<String> {
let frame = d.child("wp:inline").or_else(|| d.child("wp:anchor"))?;
let id = frame.child("wp:docPr")?.child("a:hlinkClick")?.attr("r:id")?;
self.drawing_property_link(frame.child("wp:docPr"), rels)
}
fn drawing_property_link(&mut self, nv: Option<&El>, rels: &Rels) -> Option<String> {
let id = nv?.child("a:hlinkClick")?.attr("r:id")?;
let rel = rels.by_id(id).filter(|r| r.external && crate::package::rel_is(&r.kind, rt::HYPERLINK))?;
Some(rel.target.trim().to_string()).filter(|u| !u.is_empty())
self.keep_drawing_link(&rel.target)
}
/// A template or relationship can be referenced many times. Charge each retained copy
/// before allocating, using the same target and string ceilings as Flow.
pub(super) fn keep_drawing_link(&mut self, target: &str) -> Option<String> {
let target = target.trim();
if target.is_empty() || target.len() > 8 << 10 || target.len() > (64 << 20) - self.drawing_link_bytes {
return None;
}
self.drawing_link_bytes += target.len();
Some(target.to_string())
}
/// Native ink or an Office 2016 chart kept with its fallback (`mc:AlternateContent`), and the
/// [`Self::drawing_link`] of the choice it was read from, else of its fallback: another
/// choice's link is not this object's.
pub(super) fn read_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option<String>)> {
let (object, choice) = match self.read_ink_alternate(sc, ac, rels) {
Some(o) => (o, children_of_choice(ac).filter(|e| e.name == "mc:Choice")),
None => (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac)),
};
if let Some(linked) = self.read_ink_alternate(sc, ac, rels) {
return Some(linked);
}
let (object, choice) = (self.read_chartex_alternate(sc, ac, rels)?, chartex_choice(ac));
let link =
[choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| Self::drawing_link(d, rels));
[choice, ac.child("mc:Fallback")].into_iter().flatten().filter_map(|e| e.child("w:drawing")).find_map(|d| self.drawing_link(d, rels));
Some((object, link))
}
/// Keep the selected native-ink branch and its picture fallback as one object. Reading only
/// the fallback flattens the ink; reading only the choice loses its preview on the next save.
fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<InlineObject> {
fn read_ink_alternate(&mut self, sc: &mut StoryCtx, ac: &El, rels: &Rels) -> Option<(InlineObject, Option<String>)> {
let choice = children_of_choice(ac).filter(|e| e.name == "mc:Choice")?;
let drawing = choice.child("w:drawing")?;
if drawing.find("a:graphicData")?.attr("uri") != Some(INK_URI) {
return None;
}
let fallback = ac.child("mc:Fallback");
let preview = fallback.and_then(|f| f.child("w:pict")).and_then(|p| self.read_vml(sc, p, rels));
let Some(mut object) = self.read_drawing(sc, drawing, rels) else { return preview };
let native = self.read_drawing(sc, drawing, rels);
// A lower-priority preview must not spend the native target's budget.
let native_link = native.as_ref().and_then(|_| {
self.drawing_link(drawing, rels).or_else(|| fallback.and_then(|f| f.child("w:drawing")).and_then(|d| self.drawing_link(d, rels)))
});
let preview = fallback
.and_then(|f| f.child("w:pict"))
.and_then(|p| if native.is_some() { self.read_vml_preview(sc, p, rels) } else { self.read_vml(sc, p, rels) });
let Some(mut object) = native else {
return preview.map(|(object, target)| (object, target.and_then(|target| self.keep_drawing_link(target))));
};
let (preview, preview_link) = preview.map(|(object, link)| (Some(object), link)).unwrap_or_default();
if let InlineObject::Graphic { w, h, graphic, .. } = &mut object {
let graphic = Arc::make_mut(graphic);
if let Some(InlineObject::Image { media, .. }) = preview {
@@ -160,7 +185,8 @@ impl Reader<'_> {
// A malformed or over-budget fallback must not discard a valid native part.
}
}
Some(object)
let link = native_link.or_else(|| preview_link.and_then(|target| self.keep_drawing_link(target)));
Some((object, link))
}
/// An Office 2016 chart (`cx:chart`: waterfall, sunburst, box & whisker…) drawn from its
@@ -323,7 +349,7 @@ impl Reader<'_> {
}
/// A `wpg:wgp` group (`w` × `h`): its pictures, shapes and text boxes, nested groups
/// flattened into it. `None` when it has no member we can show.
/// flattened into it unless they carry their own hyperlink. `None` when it has no member we can show.
fn read_group(&mut self, sc: &mut StoryCtx, g: &El, rels: &Rels, w: f32, h: f32, mut float: Float) -> Option<InlineObject> {
let x = group_xfrm(g.child("wpg:grpSpPr"));
float.set_spin(xfrm_spin(g.child("wpg:grpSpPr")));
@@ -336,7 +362,8 @@ impl Reader<'_> {
let mut children = Vec::new();
let outer = self.group_fill.take();
self.group_fill = own_fill(g.child("wpg:grpSpPr"), &self.doc.settings.theme_colors, None).flatten();
self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, &mut children);
let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN;
self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, (&mut children, &mut remaining));
self.group_fill = outer;
if children.is_empty() {
return None;
@@ -362,7 +389,8 @@ impl Reader<'_> {
stroke_width: ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, 100.0),
};
let mut children = Vec::new();
self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, &mut children);
let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN;
self.group_members(sc, c, rels, (0.0, 0.0, 1.0, 1.0), 0, (&mut children, &mut remaining));
InlineObject::Group { w, h, float, ch_w: w.max(1.0), ch_h: h.max(1.0), children, canvas: Some(style) }
}
@@ -375,11 +403,12 @@ impl Reader<'_> {
rels: &Rels,
t: (f32, f32, f32, f32),
depth: usize,
out: &mut Vec<craft_wordmodel::para::GroupChild>,
output: (&mut Vec<craft_wordmodel::para::GroupChild>, &mut usize),
) {
let (out, remaining) = output;
let (x0, y0, sx, sy) = t;
for e in g.els() {
if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN {
if *remaining == 0 {
return;
}
// Native ink (`w14:contentPart`), alone or with a picture fallback: kept whole, in its
@@ -412,33 +441,21 @@ impl Reader<'_> {
"wpg:grpSp" | "wpg:wgp" => e.child("wpg:grpSpPr"),
_ => continue,
};
let x = group_xfrm(sppr);
let ((ox, oy), (ew, eh)) = (x.off, x.ext);
if e.name == "wpg:grpSp" || e.name == "wpg:wgp" {
if depth >= 8 {
continue;
}
// Its members' space maps onto its own box.
let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0));
let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0)));
let (kx, ky) = (ew / cw, eh / ch);
let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky);
// Its own fill, for its members' `a:grpFill` (#1500).
// One without a fill of its own passes its group's on.
let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone());
let outer = std::mem::replace(&mut self.group_fill, own);
self.group_members(sc, e, rels, nt, depth + 1, out);
self.group_fill = outer;
self.group_member_group(sc, e, rels, t, depth, (&mut *out, &mut *remaining));
continue;
}
let max = crate::units::MAX_LEN_PT;
let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max);
let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0));
let x = group_xfrm(sppr);
let ((ox, oy), (ew, eh)) = (x.off, x.ext);
let nv = match e.name.as_str() {
"pic:pic" => e.find("pic:cNvPr"),
"pic:pic" => e.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")),
"w14:contentPart" => e.child("w14:nvContentPartPr").and_then(|p| p.child("w14:cNvPr")),
_ => e.child("wps:cNvPr"),
};
let link = self.drawing_property_link(nv, rels);
let max = crate::units::MAX_LEN_PT;
let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max);
let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0));
let (alt, meta) = nv_alt(nv);
let float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() };
let obj = if let Some((source, preview)) = ink {
@@ -460,11 +477,65 @@ impl Reader<'_> {
o
});
if let Some(obj) = obj {
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj });
*remaining -= 1;
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link });
}
}
}
/// Retain a linked nested group without turning the per-root limit into a per-level limit.
fn group_member_group(
&mut self,
sc: &mut StoryCtx,
e: &El,
rels: &Rels,
t: (f32, f32, f32, f32),
depth: usize,
output: (&mut Vec<craft_wordmodel::para::GroupChild>, &mut usize),
) {
if depth >= 8 {
return;
}
let (out, remaining) = output;
let (x0, y0, sx, sy) = t;
let sppr = e.child("wpg:grpSpPr");
let x = group_xfrm(sppr);
let ((ox, oy), (ew, eh)) = (x.off, x.ext);
let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0));
let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0)));
let nv = e.child("wpg:cNvPr");
let link = self.drawing_property_link(nv, rels);
// A group's own fill supplies its members' grpFill, otherwise its parent's does.
let own = own_fill(sppr, &self.doc.settings.theme_colors, self.group_fill.as_ref()).unwrap_or_else(|| self.group_fill.clone());
let outer = std::mem::replace(&mut self.group_fill, own);
if link.is_none() {
let (kx, ky) = (ew / cw, eh / ch);
let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky);
self.group_members(sc, e, rels, nt, depth + 1, (out, remaining));
} else {
*remaining -= 1;
let mut children = Vec::new();
let max = crate::units::MAX_LEN_PT;
let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max);
let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0));
// Store members in the group's displayed space. Clipping raw child coordinates
// before scaling would move a valid member with a large rebased offset.
let (kx, ky) = (w / cw, h / ch);
self.group_members(sc, e, rels, (-cox * kx, -coy * ky, kx, ky), depth + 1, (&mut children, &mut *remaining));
if children.is_empty() {
*remaining += 1;
} else {
let (alt, meta) = nv_alt(nv);
let mut float = Float { alt: meta, hidden: nv.is_some_and(|p| on_off_attr(p, "hidden")), ..Float::default() };
float.set_spin(xfrm_spin(sppr));
let mut obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None };
obj.set_alt_text(&alt);
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link });
}
}
self.group_fill = outer;
}
/// Build a shape from `wps:wsp`, using frame dimensions `w` and `h` in points and the caller's
/// placement. Reads geometry, paint, effects and connector ends, and creates a text-box story
/// when present within the nesting limit. Explicit outline caps are preserved; missing or
+9 -7
View File
@@ -272,21 +272,23 @@ impl Reader<'_> {
},
"w:drawing" => {
if let Some(o) = self.read_drawing(sc, k, rels) {
self.emit_linked_obj(sc, pb, o, props, Self::drawing_link(k, rels));
let link = self.drawing_link(k, rels);
self.emit_linked_obj(sc, pb, o, props, link);
}
}
"w:pict" => {
if let Some(o) = self.read_signature_line(sc, k, rels) {
self.emit_obj(sc, pb, o, props);
if let Some((o, link)) = self.read_signature_line(sc, k, rels) {
self.emit_linked_obj(sc, pb, o, props, link);
} else {
for o in self.read_vml_all(sc, k, rels) {
self.emit_obj(sc, pb, o, props);
for (o, target) in self.read_vml_all(sc, k, rels) {
let link = target.and_then(|target| self.keep_drawing_link(target));
self.emit_linked_obj(sc, pb, o, props, link);
}
}
}
"w:object" => {
if let Some(o) = self.read_object(sc, k, rels) {
self.emit_obj(sc, pb, o, props);
if let Some((o, link)) = self.read_object(sc, k, rels) {
self.emit_linked_obj(sc, pb, o, props, link);
}
}
"w:contentPart" => {
+173 -38
View File
@@ -10,14 +10,80 @@ struct VmlGroupSpace {
depth: usize,
}
/// Borrowed templates for one picture. Build once so repeated missing IDs do not
/// rescan the picture's groups. Direct definitions keep their existing priority.
struct VmlLinks<'a> {
pict: &'a El,
templates: std::collections::HashMap<&'a str, Option<&'a str>>,
member_links: bool,
}
impl<'a> VmlLinks<'a> {
fn new(pict: &'a El, member_links: bool) -> Self {
let mut links = Self { pict, templates: Default::default(), member_links };
links.definitions(pict);
for group in pict.els().filter(|e| e.name == "v:group") {
links.group(group, 0);
}
links
}
fn definitions(&mut self, parent: &'a El) {
for template in parent.els().filter(|e| e.name == "v:shapetype") {
if let Some(id) = template.attr("id") {
self.templates.entry(id).or_insert_with(|| template.attr("href"));
}
}
}
fn group(&mut self, group: &'a El, depth: usize) {
self.definitions(group);
if depth < MAX_VML_GROUP_DEPTH {
for nested in group.els().filter(|e| e.name == "v:group") {
self.group(nested, depth + 1);
}
}
}
fn target(&self, shape: &'a El) -> Option<&'a str> {
shape
.attr("href")
.or_else(|| {
let id = shape.attr("type")?.trim().trim_start_matches('#');
self.templates.get(id).copied().flatten()
})
.map(str::trim)
.filter(|target| !target.is_empty())
}
fn keep(&self, reader: &mut Reader<'_>, shape: &'a El) -> Option<String> {
if !self.member_links {
return None;
}
self.target(shape).and_then(|target| reader.keep_drawing_link(target))
}
}
impl Reader<'_> {
/// Every legacy VML drawing in one `w:pict`, in document order: a `w:pict` may hold any
/// number of shapes (ECMA-376 Part 4, VML), and each one is its own object. A `v:group`
/// becomes an [`InlineObject::Group`].
pub(super) fn read_vml_all(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Vec<InlineObject> {
pub(super) fn read_vml_all<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Vec<(InlineObject, Option<&'a str>)> {
self.vml_objects(sc, pict, rels, craft_wordmodel::para::MAX_GROUP_CHILDREN, true)
}
fn vml_objects<'a>(
&mut self,
sc: &mut StoryCtx,
pict: &'a El,
rels: &Rels,
limit: usize,
member_links: bool,
) -> Vec<(InlineObject, Option<&'a str>)> {
let links = VmlLinks::new(pict, member_links);
let mut out = Vec::new();
for e in pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype") {
if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN {
if out.len() >= limit {
break;
}
if sc.in_hf
@@ -28,23 +94,29 @@ impl Reader<'_> {
self.doc.settings.watermark.get_or_insert(wm);
continue;
}
let o = if e.local() == "group" { self.read_vml_group(sc, pict, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) };
out.extend(o);
let o = if e.local() == "group" { self.read_vml_group(sc, &links, e, rels) } else { self.read_vml_shape(sc, pict, e, rels, None) };
out.extend(o.map(|o| (o, links.target(e))));
}
out
}
/// The first VML drawing in `pict`, for the places that show a single one: an OLE object's
/// picture and a `mc:Fallback` preview.
pub(super) fn read_vml(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<InlineObject> {
self.read_vml_all(sc, pict, rels).into_iter().next()
/// The first VML drawing and its own target in `pict`, for an OLE object's
/// picture and a selected `mc:Fallback` preview.
pub(super) fn read_vml<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> {
self.vml_objects(sc, pict, rels, 1, true).into_iter().next()
}
/// A native ink preview needs its media and root target, not member targets
/// belonging to a group the ink renderer will not retain.
pub(super) fn read_vml_preview<'a>(&mut self, sc: &mut StoryCtx, pict: &'a El, rels: &Rels) -> Option<(InlineObject, Option<&'a str>)> {
self.vml_objects(sc, pict, rels, 1, false).into_iter().next()
}
/// A `v:group`: its own box from its `style`, its members in the space `coordsize` and
/// `coordorigin` give it, nested groups flattened into it as [`Self::group_members`] does for
/// DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits
/// `coordorigin` give it. Unlinked nested groups are flattened; a linked group keeps its
/// own node and target, as in DrawingML. `None` when it has no member we can show. `pict` is the picture the group sits
/// in, where a member's `v:shapetype` is written.
fn read_vml_group(&mut self, sc: &mut StoryCtx, pict: &El, grp: &El, rels: &Rels) -> Option<InlineObject> {
fn read_vml_group<'a>(&mut self, sc: &mut StoryCtx, links: &VmlLinks<'a>, grp: &'a El, rels: &Rels) -> Option<InlineObject> {
let style = grp.attr("style").unwrap_or("");
let len = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
let (w, h) = (len("width"), len("height"));
@@ -53,7 +125,15 @@ impl Reader<'_> {
let (ch_w, ch_h) = vml_coordpair(grp, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((w.max(1.0), h.max(1.0)));
let (cx, cy) = vml_coordpair(grp, "coordorigin").unwrap_or((0.0, 0.0));
let mut children = Vec::new();
self.vml_group_members(sc, pict, grp, rels, VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 }, &mut children);
let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN;
self.vml_group_members(
sc,
links,
grp,
rels,
VmlGroupSpace { origin: (-cx, -cy), scale: (1.0, 1.0), depth: 0 },
(&mut children, &mut remaining),
);
if children.is_empty() {
return None;
}
@@ -63,42 +143,36 @@ impl Reader<'_> {
/// The members of VML group `g` into `out`, mapped into the outermost group's space by `t`
/// (x0, y0, sx, sy: outer = x0 + inner × sx). A member is placed by `left`/`top` in that
/// space, except a `v:line`, which carries its own offset in `from`.
fn vml_group_members(
fn vml_group_members<'a>(
&mut self,
sc: &mut StoryCtx,
pict: &El,
g: &El,
links: &VmlLinks<'a>,
g: &'a El,
rels: &Rels,
space: VmlGroupSpace,
out: &mut Vec<craft_wordmodel::para::GroupChild>,
output: (&mut Vec<craft_wordmodel::para::GroupChild>, &mut usize),
) {
let (out, remaining) = output;
let (x0, y0) = space.origin;
let (sx, sy) = space.scale;
let max = crate::units::MAX_LEN_PT;
let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max);
for e in g.els() {
if out.len() >= craft_wordmodel::para::MAX_GROUP_CHILDREN {
if *remaining == 0 {
return;
}
if !e.name.starts_with("v:") || e.local() == "shapetype" {
continue;
}
let style = e.attr("style").unwrap_or("");
let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite);
let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height")));
if e.local() == "group" {
if space.depth >= MAX_VML_GROUP_DEPTH {
continue;
}
// Its members' space maps onto its own box.
let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0)));
let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0));
let (kx, ky) = (ew / cw, eh / ch);
let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky);
self.vml_group_members(sc, pict, e, rels, VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 }, out);
self.vml_group_member(sc, links, e, rels, space, (&mut *out, &mut *remaining));
continue;
}
let Some(mut obj) = self.read_vml_shape(sc, pict, e, rels, Some((sx, sy))) else { continue };
let style = e.attr("style").unwrap_or("");
let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite);
let (ox, oy) = (num("left"), num("top"));
let link = links.keep(self, e);
let Some(mut obj) = self.read_vml_shape(sc, links.pict, e, rels, Some((sx, sy))) else { continue };
// A member is placed by `x`/`y`, so a line's own offset comes off the member itself.
let (dx, dy) = match obj.float_mut() {
Some(f) => {
@@ -108,10 +182,71 @@ impl Reader<'_> {
}
None => (0.0, 0.0),
};
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj });
*remaining -= 1;
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + (ox + dx) * sx, -max), y: fit(y0 + (oy + dy) * sy, -max), obj, link });
}
}
/// An inner group shares its root's retained-member budget. Only a group with its
/// own target needs a node; unlinked groups keep the established flattening path.
fn vml_group_member<'a>(
&mut self,
sc: &mut StoryCtx,
links: &VmlLinks<'a>,
e: &'a El,
rels: &Rels,
space: VmlGroupSpace,
output: (&mut Vec<craft_wordmodel::para::GroupChild>, &mut usize),
) {
if space.depth >= MAX_VML_GROUP_DEPTH {
return;
}
let (out, remaining) = output;
let (x0, y0) = space.origin;
let (sx, sy) = space.scale;
let style = e.attr("style").unwrap_or("");
let num = |k: &str| vml_style(style, k).and_then(|v| measure(v, 1.0)).map_or(0.0, craft_wordmodel::geom::finite);
let ((ox, oy), (ew, eh)) = ((num("left"), num("top")), (num("width"), num("height")));
let (cw, ch) = vml_coordpair(e, "coordsize").filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0)));
let (cox, coy) = vml_coordpair(e, "coordorigin").unwrap_or((0.0, 0.0));
let link = links.keep(self, e);
if link.is_none() {
let (kx, ky) = (ew / cw, eh / ch);
let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky);
self.vml_group_members(
sc,
links,
e,
rels,
VmlGroupSpace { origin: (nt.0, nt.1), scale: (nt.2, nt.3), depth: space.depth + 1 },
(out, remaining),
);
return;
}
*remaining -= 1;
let mut children = Vec::new();
let max = crate::units::MAX_LEN_PT;
let fit = |v: f32, lo: f32| craft_wordmodel::geom::finite(v).clamp(lo, max);
let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0));
let (kx, ky) = (w / cw, h / ch);
self.vml_group_members(
sc,
links,
e,
rels,
VmlGroupSpace { origin: (-cox * kx, -coy * ky), scale: (kx, ky), depth: space.depth + 1 },
(&mut children, &mut *remaining),
);
if children.is_empty() {
*remaining += 1;
return;
}
let mut float = vml_float(e, style, sc.in_hf);
(float.x, float.y) = (0.0, 0.0);
let obj = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children, canvas: None };
out.push(craft_wordmodel::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj, link });
}
/// One legacy VML picture, text box, line, rectangle, oval or preset shape (best effort).
/// `pict` is the picture it sits in, where its `v:shapetype` is written -- for a group's
/// member too, since Word writes each shapetype once, beside the group rather than inside
@@ -395,25 +530,25 @@ impl Reader<'_> {
/// An OLE object (`w:object`, ECMA-376 §17.3.3.19): shown as its picture (VML, or a DrawingML
/// picture in `w:drawing`), and kept whole so saving writes the object back.
pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option<InlineObject> {
let mut o = match self.read_vml(sc, obj, rels) {
Some(o) => o,
pub(super) fn read_object(&mut self, sc: &mut StoryCtx, obj: &El, rels: &Rels) -> Option<(InlineObject, Option<String>)> {
let (mut o, link) = match self.read_vml(sc, obj, rels) {
Some((object, target)) => (object, target.and_then(|target| self.keep_drawing_link(target))),
None => {
let d = obj.child("w:drawing")?;
self.read_drawing(sc, d, rels)?
(self.read_drawing(sc, d, rels)?, self.drawing_link(d, rels))
}
};
if let InlineObject::Image { ole, .. } = &mut o {
*ole = self.keep_embedded(obj, rels, &[]);
}
Some(o)
Some((o, link))
}
/// A Word signature line (Insert › Signature Line): a `w:pict` whose one VML picture carries
/// an `o:signatureline` (the suggested signer, title, e-mail and instructions). Shown as its
/// picture, and kept whole like an OLE object so saving writes the signature line back,
/// still signable in Word, not a plain picture. `None` for any other `w:pict`.
pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<InlineObject> {
pub(super) fn read_signature_line(&mut self, sc: &mut StoryCtx, pict: &El, rels: &Rels) -> Option<(InlineObject, Option<String>)> {
let mut drawings = pict.els().filter(|e| e.name.starts_with("v:") && e.local() != "shapetype");
let shape = drawings.next().filter(|s| s.name == "v:shape")?;
if drawings.next().is_some() || shape.child("o:signatureline").is_none() {
@@ -423,7 +558,7 @@ impl Reader<'_> {
if let InlineObject::Image { ole, .. } = &mut o {
*ole = self.keep_embedded(pict, rels, &[]);
}
Some(o)
Some((o, VmlLinks::new(pict, true).target(shape).and_then(|target| self.keep_drawing_link(target))))
}
}
+15 -8
View File
@@ -14,6 +14,14 @@ pub(super) struct DrawingInfo<'a> {
pub link: Option<&'a str>,
}
/// The non-visual identity, placement and hyperlink relationship of one group member.
/// Top-level objects keep their link on `wp:docPr` instead.
pub(super) struct MemberInfo<'a> {
pub id: Option<&'a str>,
pub off: (f32, f32),
pub link: Option<&'a str>,
}
impl Writer<'_> {
/// The relationship of the hyperlink a drawing in a run with `props` carries on itself, as
/// Word writes a picture's link (`wp:docPr/a:hlinkClick`, #5267): a web or file address. A
@@ -24,13 +32,13 @@ impl Writer<'_> {
}
/// A picture's `pic:pic` (the image in `media/{file}`), at `off` in its group (or 0, 0).
pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, off: (f32, f32), rels: &mut PartRels) {
pub(super) fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, member: MemberInfo<'_>, rels: &mut PartRels) {
let InlineObject::Image { media, w: iw, h: ih, alt, crop, float, fx, .. } = o else { return };
let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false);
self.used_media.insert(media.clone());
w.open("pic:pic", &[]);
w.open("pic:nvPicPr", &[]);
nv_props(w, "pic:cNvPr", ("0", file), alt, &float.alt, float.hidden, None);
nv_props(w, "pic:cNvPr", (member.id.unwrap_or("0"), file), alt, &float.alt, float.hidden, member.link);
w.open("pic:cNvPicPr", &[]);
w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]);
w.close("pic:cNvPicPr");
@@ -60,7 +68,7 @@ impl Writer<'_> {
w.close("a:stretch");
w.close("pic:blipFill");
w.open("pic:spPr", &[("bwMode", "auto")]);
xfrm(w, off, *iw, *ih, float.spin());
xfrm(w, member.off, *iw, *ih, float.spin());
w.open("a:prstGeom", &[("prst", "rect")]);
w.empty("a:avLst", &[]);
w.close("a:prstGeom");
@@ -80,17 +88,16 @@ impl Writer<'_> {
&mut self,
w: &mut W,
o: &InlineObject,
id: Option<&str>,
off: (f32, f32),
member: MemberInfo<'_>,
rels: &mut PartRels,
depth: usize,
) -> Option<std::ops::Range<usize>> {
let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return None };
let geom = freeform.as_deref().filter(|_| *kind == ShapeKind::Freeform);
w.open("wps:wsp", &[]);
if let Some(id) = id {
if let Some(id) = member.id {
let name = shape_name(*kind, freeform.as_deref(), id);
nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, None);
nv_props(w, "wps:cNvPr", (id, &name), &float.alt.text, &float.alt, float.hidden, member.link);
}
if kind.is_connector() {
// A connector's glued ends (ECMA-376 §20.1.2.2.8 `cNvCxnSpPr`).
@@ -112,7 +119,7 @@ impl Writer<'_> {
w.empty("wps:cNvSpPr", &[]);
}
w.open("wps:spPr", &[]);
xfrm(w, off, *sw, *sh, float.spin());
xfrm(w, member.off, *sw, *sh, float.spin());
let prst = match kind {
ShapeKind::Rectangle | ShapeKind::TextBox | ShapeKind::Freeform => "rect",
ShapeKind::RoundedRectangle => "roundRect",
+84 -28
View File
@@ -1,7 +1,7 @@
use super::drawing::{DrawingInfo, shape_name, spin_attrs, write_fill, xfrm_spin_only};
use super::drawing::{DrawingInfo, MemberInfo, nv_props, shape_name, spin_attrs, write_fill, xfrm_spin_only};
use super::field::{FieldData, field_run};
use super::section::comment_reference_style;
use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr};
use super::{Anchor, CharProps, Fill, Float, InlineObject, MAX_DEPTH, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr, rt};
impl Writer<'_> {
/// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.).
@@ -284,7 +284,7 @@ impl Writer<'_> {
w.empty("wp:cNvGraphicFramePr", &[]);
w.open("a:graphic", &[]);
w.open("a:graphicData", &[("uri", "http://schemas.openxmlformats.org/drawingml/2006/picture")]);
self.pic(w, o, &file, (0.0, 0.0), rels);
self.pic(w, o, &file, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels);
w.close("a:graphicData");
w.close("a:graphic");
w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" });
@@ -404,7 +404,7 @@ impl Writer<'_> {
w.empty("wp:cNvGraphicFramePr", &[]);
w.open("a:graphic", &[]);
w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]);
let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth);
let content = self.wsp(w, o, MemberInfo { id: None, off: (0.0, 0.0), link: None }, rels, depth);
w.close("a:graphicData");
w.close("a:graphic");
w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" });
@@ -605,30 +605,8 @@ impl Writer<'_> {
"wpg:wgp"
}
};
for c in children.iter().take(craft_wordmodel::para::MAX_GROUP_CHILDREN) {
let at = (c.x, c.y);
match &c.obj {
InlineObject::Image { media, .. } => {
if let Some(file) = self.media_files.get(media).cloned() {
self.pic(w, &c.obj, &file, at, rels);
}
}
InlineObject::Shape { extra, .. } => {
let id = self.shape_docpr(extra.id);
self.wsp(w, &c.obj, Some(&id), at, rels, depth);
}
// Native ink kept from the file, with its fallback, at the member's place.
InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => {
if let Some(src) = graphic.source.as_deref()
&& let Some(mut root) = self.embedded_tree(src, rels, None)
{
Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0);
w.raw(&root.to_xml());
}
}
_ => {}
}
}
let mut remaining = craft_wordmodel::para::MAX_GROUP_CHILDREN;
self.write_group_members(w, children, rels, depth, &mut remaining);
if canvas.is_some() && float.spin() != craft_wordmodel::geom::Spin::default() {
// The canvas schema has no transform of its own: keep its turn in our
// extension (Word draws it unturned, as it can't turn a canvas).
@@ -646,6 +624,84 @@ impl Writer<'_> {
w.close("w:r");
self.rev_close(w, props);
}
/// Members share one finite budget across the whole recursive group, not one per level.
fn write_group_members(
&mut self,
w: &mut W,
children: &[craft_wordmodel::para::GroupChild],
rels: &mut PartRels,
depth: usize,
remaining: &mut usize,
) {
if depth > MAX_DEPTH {
return;
}
for c in children {
if *remaining == 0 {
break;
}
*remaining -= 1;
let at = (c.x, c.y);
match &c.obj {
InlineObject::Image { media, .. } => {
if let Some(file) = self.media_files.get(media).cloned() {
let id = self.next_docpr();
let link = member_link(c.link.as_deref(), rels);
self.pic(w, &c.obj, &file, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels);
}
}
InlineObject::Shape { extra, .. } => {
let id = self.shape_docpr(extra.id);
let link = member_link(c.link.as_deref(), rels);
self.wsp(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth);
}
InlineObject::Group { .. } if depth < MAX_DEPTH => {
let id = self.next_docpr();
let link = member_link(c.link.as_deref(), rels);
self.write_inner_group(w, &c.obj, MemberInfo { id: Some(&id), off: at, link: link.as_deref() }, rels, depth + 1, remaining);
}
// Native ink kept from the file, with its fallback, at the member's place.
InlineObject::Graphic { w: iw, h: ih, float, graphic, .. } if graphic.kind == craft_wordmodel::graphic::GraphicKind::Ink => {
if let Some(src) = graphic.source.as_deref()
&& let Some(mut root) = self.embedded_tree(src, rels, None)
{
Self::place_member(&mut root, [c.x, c.y, *iw, *ih], float, 0);
w.raw(&root.to_xml());
}
}
_ => {}
}
}
}
/// A nested group is an inner `wpg:grpSp`, never another run or drawing anchor.
fn write_inner_group(&mut self, w: &mut W, o: &InlineObject, member: MemberInfo<'_>, rels: &mut PartRels, depth: usize, remaining: &mut usize) {
if depth > MAX_DEPTH {
return;
}
let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, .. } = o else { return };
let id = member.id.unwrap_or("0");
let name = format!("Group {id}");
w.open("wpg:grpSp", &[]);
nv_props(w, "wpg:cNvPr", (id, &name), o.alt_text(), &float.alt, float.hidden, member.link);
w.empty("wpg:cNvGrpSpPr", &[]);
w.open("wpg:grpSpPr", &[]);
w.open("a:xfrm", &spin_attrs(float.spin()).iter().map(|(k, v)| (*k, v.as_str())).collect::<Vec<_>>());
w.empty("a:off", &[("x", &emu(member.off.0)), ("y", &emu(member.off.1))]);
w.empty("a:ext", &[("cx", &emu(gw.max(0.0))), ("cy", &emu(gh.max(0.0)))]);
w.empty("a:chOff", &[("x", "0"), ("y", "0")]);
w.empty("a:chExt", &[("cx", &emu(ch_w.max(0.0))), ("cy", &emu(ch_h.max(0.0)))]);
w.close("a:xfrm");
w.close("wpg:grpSpPr");
self.write_group_members(w, children, rels, depth, remaining);
w.close("wpg:grpSp");
}
}
/// Group members have no enclosing run, so even a literal `#name` needs its own
/// external hyperlink relationship. Top-level drawings retain `drawing_link`'s policy.
fn member_link(target: Option<&str>, rels: &mut PartRels) -> Option<String> {
target.filter(|url| !url.is_empty()).map(|url| rels.add(rt::HYPERLINK, url, true))
}
/// The VML element that draws a shape kind, for the kinds VML has one for.
+1 -1
View File
@@ -108,7 +108,7 @@ fn picture_group_canvas_keep_kind() {
float: Default::default(),
ch_w: 100.0,
ch_h: 50.0,
children: vec![GroupChild { x: 3.0, y: 4.0, obj: picture() }],
children: vec![GroupChild { link: None, x: 3.0, y: 4.0, obj: picture() }],
canvas,
};
for original in [picture(), group(None), group(Some(CanvasStyle::default()))] {
+1 -1
View File
@@ -3668,7 +3668,7 @@ const INK_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessi
const INK_XML: &str = r##"<ink xmlns="http://www.w3.org/2003/InkML"><definitions><context xml:id="ctx"><inkSource xml:id="src"><traceFormat><channel name="X" type="integer" units="cm"/><channel name="Y" type="integer" units="cm"/></traceFormat></inkSource></context><brush xml:id="blue"><brushProperty name="color" value="#2563EB"/><brushProperty name="width" value="0.08" units="cm"/></brush></definitions><trace contextRef="#ctx" brushRef="#blue">0 0, 1 1, 2 0</trace></ink>"##;
const INK_TYPES: &str = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/word/ink/ink1.xml" ContentType="application/inkml+xml"/><Default Extension="png" ContentType="image/png"/></Types>"#;
fn ink_docx(fallback: bool, alias: bool) -> Vec<u8> {
pub(super) fn ink_docx(fallback: bool, alias: bool) -> Vec<u8> {
let content = r#"<q:contentPart xmlns:q="http://schemas.microsoft.com/office/word/2010/wordml" r:id="rInk"><q:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/></q:xfrm></q:contentPart>"#;
let drawing = format!(
r#"<w:drawing><wp:inline><wp:extent cx="1828800" cy="914400"/><wp:docPr id="1" name="Study ink"/><a:graphic><a:graphicData uri="{INK_NS}">{content}</a:graphicData></a:graphic></wp:inline></w:drawing>"#
+7 -2
View File
@@ -179,9 +179,14 @@ fn many_fields_and_huge_attribute_values() {
/// limit error, or the extras are dropped and the text survives (#3702, WC-06).
#[test]
fn millions_of_attributes_on_one_paragraph_are_capped() {
use std::fmt::Write as _;
// The gate reads a fraction of the attributes; nightly all of them.
let attrs: String = (0..2_000_000 / craft_testkit::hostile::divisor()).map(|i| format!(" a{i}=\"\"")).collect();
let x = format!("<w:document {W_NS}><w:body><w:p{attrs}><w:r><w:t>kept</w:t></w:r></w:p></w:body></w:document>");
let mut x = format!("<w:document {W_NS}><w:body><w:p");
for i in 0..2_000_000 / craft_testkit::hostile::divisor() {
write!(&mut x, " a{i}=\"\"").unwrap();
}
x.push_str("><w:r><w:t>kept</w:t></w:r></w:p></w:body></w:document>");
// Only the read is timed: deflating the test input in a debug build is not what is bounded.
let z = doc_zip(x.as_bytes());
let start = std::time::Instant::now();
+691
View File
@@ -213,3 +213,694 @@ fn a_vml_picture_keeps_its_crop_when_saved() {
}
assert!(lost.is_empty(), "VML picture crops were lost: {lost:?}");
}
// Original Transitional DOCX/VML: ISO 29500 VML shape/group href attributes, with
// independent literal targets at each level. No reference-app file or click oracle.
#[test]
fn vml_objects_keep_their_own_hyperlinks() {
fn check_images(doc: &Document, object: &InlineObject, original_png: &[u8], out: &mut Vec<(String, f32, f32)>) {
match object {
InlineObject::Image { media, w, h, alt, crop, .. } => {
assert_eq!(doc.media.get(media).expect("the original embedded picture").as_slice(), original_png);
assert_eq!(*crop, [0.0; 4], "a hyperlink must not invent a crop");
out.push((alt.clone(), *w, *h));
}
InlineObject::Group { children, .. } => {
for child in children {
check_images(doc, &child.obj, original_png, out);
}
}
InlineObject::Shape { kind, w, h, .. } => {
assert_eq!(*kind, craft_wordmodel::para::ShapeKind::Rectangle);
assert!((*w - 5.0).abs() < 0.001 && (*h - 7.0).abs() < 0.001);
}
other => panic!("the original picture fixture produced another object: {other:?}"),
}
}
fn top_links(doc: &Document) -> Vec<Option<String>> {
let paragraph = doc.body[1].as_para().expect("the VML paragraph");
paragraph.object_offsets().into_iter().map(|off| paragraph.props_of_char(off).link.clone()).collect()
}
fn model_links(doc: &Document) -> Vec<(Vec<usize>, Option<String>)> {
fn member_links(object: &InlineObject, path: &[usize], out: &mut Vec<(Vec<usize>, Option<String>)>) {
if let InlineObject::Group { children, .. } = object {
for (i, child) in children.iter().enumerate() {
let mut path = path.to_vec();
path.push(i);
out.push((path.clone(), child.link.clone()));
member_links(&child.obj, &path, out);
}
}
}
let paragraph = doc.body[1].as_para().unwrap();
let mut out = Vec::new();
for (i, off) in paragraph.object_offsets().into_iter().enumerate() {
out.push((vec![i], paragraph.props_of_char(off).link.clone()));
member_links(paragraph.object_at(off).unwrap(), &[i], &mut out);
}
out
}
fn xml_link(nv: Option<&craft_xml::El>, rels: &craft_xml::El) -> Option<String> {
let id = nv?.child("a:hlinkClick")?.attr("r:id")?;
let rel = rels.children("Relationship").find(|r| r.attr("Id") == Some(id)).expect("every click must name a saved relationship");
assert_eq!(rel.attr("Type"), Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"));
assert_eq!(rel.attr("TargetMode"), Some("External"));
Some(rel.attr("Target").expect("the click target").to_string())
}
fn saved_member_links(group: &craft_xml::El, path: &[usize], rels: &craft_xml::El, out: &mut Vec<(Vec<usize>, Option<String>)>) {
for (i, child) in group.elements().filter(|e| matches!(e.name.as_str(), "pic:pic" | "wps:wsp" | "wpg:grpSp")).enumerate() {
let mut path = path.to_vec();
path.push(i);
let nv = match child.name.as_str() {
"pic:pic" => child.child("pic:nvPicPr").and_then(|p| p.child("pic:cNvPr")),
"wps:wsp" => child.child("wps:cNvPr"),
_ => child.child("wpg:cNvPr"),
};
out.push((path.clone(), xml_link(nv, rels)));
if child.name == "wpg:grpSp" {
saved_member_links(child, &path, rels, out);
}
}
}
fn check_group_geometry(current: &Document) {
let InlineObject::Group { children, .. } = &current.body[1].as_para().unwrap().objects[3] else { panic!() };
assert_eq!(children.len(), 3);
assert!((children[0].x - 3.0).abs() < 0.001 && (children[0].y - 4.0).abs() < 0.001);
assert!((children[2].x - 20.0).abs() < 0.001 && (children[2].y - 5.0).abs() < 0.001);
let InlineObject::Group { children, float, ch_w, ch_h, .. } = &children[2].obj else { panic!("the linked nested group must remain a group") };
assert_eq!((*ch_w, *ch_h), (10.0, 10.0));
assert_eq!(float.spin(), craft_wordmodel::geom::Spin::new(30.0, true, false));
assert_eq!(children.len(), 1);
assert!((children[0].x - 1.0).abs() < 0.001 && (children[0].y - 2.0).abs() < 0.001);
}
let vml = r##"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml">
<v:shape id="TopFirst" style="width:24pt;height:12pt" alt="first" href="https://example.com/TopFirst"><v:imagedata r:id="rIdPic"/></v:shape>
<v:shape id="Unlinked" style="width:16pt;height:8pt" alt="unlinked"><v:imagedata r:id="rIdPic"/></v:shape>
<v:shape id="TopLast" style="width:12pt;height:6pt" alt="last" href="https://example.com/TopLast"><v:imagedata r:id="rIdPic"/></v:shape>
<v:group id="Outer" style="width:40pt;height:20pt" coordsize="40,20" href="https://example.com/Outer">
<v:shape id="Child" style="left:3pt;top:4pt;width:6pt;height:4pt" alt="child" href="https://example.com/Child"><v:imagedata r:id="rIdPic"/></v:shape>
<v:rect id="ChildShape" style="left:12pt;top:2pt;width:5pt;height:7pt" fillcolor="#123456" href="https://example.com/Shape"/>
<v:group id="Nested" style="left:20pt;top:5pt;width:10pt;height:10pt;rotation:30;flip:x" coordsize="10,10" href="https://example.com/Nested">
<v:shape id="Fragment" style="left:1pt;top:2pt;width:2pt;height:3pt" alt="fragment" href="#Spot"><v:imagedata r:id="rIdPic"/></v:shape>
</v:group></v:group></w:pict></w:r></w:p>"##;
// A known DrawingML link is a positive control in the same package, with the
// same generated media and relationship table as the independently linked VML.
let body = format!("<w:p>{}</w:p>{vml}", picture_run(10, r#"<a:hlinkClick r:id="rIdWeb"/>"#));
let original_png = png();
let doc = craft_docx::read(&package(&body)).expect("the original Transitional package must read");
let saved = craft_docx::write(&doc).expect("the supported picture/group content must save");
let reopened = craft_docx::read(&saved).expect("the normalized DOCX must reopen");
let expected_images = [("first", 24.0, 12.0), ("unlinked", 16.0, 8.0), ("last", 12.0, 6.0), ("child", 6.0, 4.0), ("fragment", 2.0, 3.0)];
// All payload, ordering, geometry and positive/unlinked controls run before
// the missing-target assertion; neither a dropped object nor bad media is red proof.
for current in [&doc, &reopened] {
assert_eq!(current.body.len(), 2);
assert_eq!(picture_links(current), [Some("https://example.com/picture".to_string())]);
let paragraph = current.body[1].as_para().expect("the VML paragraph remains a paragraph");
assert_eq!(paragraph.objects.len(), 4, "three top-level pictures and their following group");
let InlineObject::Group { w, h, .. } = &paragraph.objects[3] else {
panic!("the last VML object must remain a group");
};
assert!((*w - 40.0).abs() < 0.001 && (*h - 20.0).abs() < 0.001);
let mut images = Vec::new();
for object in &paragraph.objects {
check_images(current, object, &original_png, &mut images);
}
assert_eq!(images.len(), expected_images.len(), "every original picture must remain");
for ((alt, w, h), (expected_alt, expected_w, expected_h)) in images.iter().zip(expected_images) {
assert_eq!(alt, expected_alt, "picture order/identity changed");
assert!((w - expected_w).abs() < 0.001 && (h - expected_h).abs() < 0.001, "{alt}: {w} x {h}");
}
assert_eq!(top_links(current)[1], None, "the unlinked neighbor must stay unlinked");
}
let rels = part(&saved, "word/_rels/document.xml.rels");
assert!(rels.contains(r#"Target="https://example.com/picture""#), "the DrawingML control's relationship must survive");
let expected_top = [Some("https://example.com/TopFirst"), None, Some("https://example.com/TopLast"), Some("https://example.com/Outer")];
let mut lost = Vec::new();
for (phase, current) in [("read", &doc), ("reopened", &reopened)] {
for (index, (actual, expected)) in top_links(current).iter().zip(expected_top).enumerate() {
if actual.as_deref() != expected {
lost.push(format!("{phase} top-level object {index}: {actual:?} instead of {expected:?}"));
}
}
}
// These are necessary persistence checks using today's APIs, not a claim that
// relationship presence proves nested path-to-target association or activation.
for (label, target) in [
("first", "https://example.com/TopFirst"),
("last", "https://example.com/TopLast"),
("outer group", "https://example.com/Outer"),
("group child", "https://example.com/Child"),
("group shape", "https://example.com/Shape"),
("nested group", "https://example.com/Nested"),
("fragment data", "#Spot"),
] {
if !rels.contains(&format!(r#"Target="{target}""#)) {
lost.push(format!("saved {label} target: {target}"));
}
}
let expected: Vec<_> = [
(vec![0], Some("https://example.com/TopFirst")),
(vec![1], None),
(vec![2], Some("https://example.com/TopLast")),
(vec![3], Some("https://example.com/Outer")),
(vec![3, 0], Some("https://example.com/Child")),
(vec![3, 1], Some("https://example.com/Shape")),
(vec![3, 2], Some("https://example.com/Nested")),
(vec![3, 2, 0], Some("#Spot")),
]
.into_iter()
.map(|(path, link)| (path, link.map(str::to_string)))
.collect();
for current in [&doc, &reopened] {
assert_eq!(model_links(current), expected, "each target must remain on its own object path");
check_group_geometry(current);
}
let xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap();
let relationships = craft_xml::parse(rels.as_bytes()).unwrap();
let paragraph = xml.child("w:body").unwrap().children("w:p").nth(1).unwrap();
let mut xml_links = Vec::new();
for (i, drawing) in paragraph.find_all("w:drawing").enumerate() {
let frame = drawing.child("wp:inline").or_else(|| drawing.child("wp:anchor")).unwrap();
xml_links.push((vec![i], xml_link(frame.child("wp:docPr"), &relationships)));
if let Some(group) = frame.child("a:graphic").and_then(|g| g.child("a:graphicData")).and_then(|d| d.child("wpg:wgp")) {
saved_member_links(group, &[i], &relationships, &mut xml_links);
}
}
assert_eq!(xml_links, expected, "saved cNvPr/docPr clicks must name the target at the same path");
assert!(lost.is_empty(), "VML object hyperlinks were lost: {lost:?}");
}
#[test]
fn vml_hyperlink_templates_and_outer_runs_keep_their_scope() {
let cases = [
(r##"type="#Linked""##, "", Some("https://example.com/Template")),
(r##"type="#Linked" href="https://example.com/Direct""##, "", Some("https://example.com/Direct")),
(r##"type="#Linked" href=" ""##, "", None),
(r#"href=" https://example.com/Trimmed ""#, "", Some("https://example.com/Trimmed")),
("", r#"o:href="https://example.com/ImageSource" r:href="rIdWeb""#, None),
];
let mut shapes = String::new();
for (attributes, image_attributes, _) in cases {
shapes
.push_str(&format!(r#"<v:shape style="width:24pt;height:12pt" {attributes}><v:imagedata r:id="rIdPic" {image_attributes}/></v:shape>"#,));
}
let body = format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><v:shapetype id="Linked" href=" https://example.com/Template "/>{shapes}</w:pict></w:r></w:p><w:p><w:hyperlink r:id="rIdRun"><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:24pt;height:12pt" coordsize="24,12" href="https://example.com/Group"><v:shape style="width:24pt;height:12pt" href="https://example.com/Child"><v:imagedata r:id="rIdPic"/></v:shape></v:group></w:pict></w:r></w:hyperlink></w:p>"#,
);
let doc = craft_docx::read(&package(&body)).unwrap();
let saved = craft_docx::write(&doc).unwrap();
let reopened = craft_docx::read(&saved).unwrap();
let expected: Vec<_> = cases.into_iter().map(|(_, _, link)| link.map(str::to_string)).collect();
for current in [&doc, &reopened] {
assert_eq!(picture_links(current), expected, "presence-aware template/direct href precedence");
let paragraph = current.body[1].as_para().unwrap();
assert_eq!(paragraph.objects.len(), 1);
assert_eq!(paragraph.props_of_char(paragraph.object_offsets()[0]).link.as_deref(), Some("https://example.com/run"));
let InlineObject::Group { children, .. } = &paragraph.objects[0] else { panic!() };
assert_eq!(children.len(), 1);
assert_eq!(children[0].link.as_deref(), Some("https://example.com/Child"), "the run overrides the group, not its child");
}
// A shape type may be declared inside the group rather than beside it. These
// original inputs use unique IDs and keep image-source URLs out of click lookup.
let local_cases = [(r##"type="#GroupLocal""##, Some("https://example.com/GroupTemplate")), (r##"type="#NotSelected""##, None)];
let mut local_shapes = String::new();
for (attributes, _) in local_cases {
local_shapes.push_str(&format!(
r#"<v:shape style="width:6pt;height:5pt" {attributes}><v:imagedata r:id="rIdPic" o:href="https://example.com/ImageSource" r:href="rIdWeb"/></v:shape>"#,
));
}
let local_body = format!(
r##"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:other="urn:original-test:unselected"><mc:AlternateContent><mc:Choice Requires="other"><v:shapetype id="NotSelected" href="https://example.com/Unselected"/></mc:Choice><mc:Fallback/></mc:AlternateContent><v:group style="width:36pt;height:10pt" coordsize="36,10"><v:shapetype id="GroupLocal" href=" https://example.com/GroupTemplate "/>{local_shapes}<v:group style="left:12pt;top:5pt;width:6pt;height:5pt" coordsize="6,5" href="https://example.com/NestedTemplateGroup"><v:shapetype id="DeepLocal" href="https://example.com/DeepTemplate"/><v:shape type="#DeepLocal" style="width:6pt;height:5pt"><v:imagedata r:id="rIdPic"/></v:shape></v:group></v:group></w:pict></w:r></w:p>"##,
);
let local_doc = craft_docx::read(&package(&local_body)).unwrap();
let local_saved = craft_docx::write(&local_doc).unwrap();
let local_reopened = craft_docx::read(&local_saved).unwrap();
let original_png = png();
for current in [&local_doc, &local_reopened] {
assert_eq!(current.body.len(), 1);
let paragraph = current.body[0].as_para().unwrap();
assert_eq!(paragraph.objects.len(), 1);
assert_eq!(paragraph.props_of_char(0).link, None, "a template must not become its containing group's link");
let InlineObject::Group { children, .. } = &paragraph.objects[0] else { panic!() };
assert_eq!(children.len(), local_cases.len() + 1);
for (child, (_, expected)) in children.iter().zip(local_cases) {
let InlineObject::Image { media, w, h, .. } = &child.obj else { panic!() };
assert_eq!(current.media.get(media).unwrap().as_slice(), original_png.as_slice());
assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001);
assert_eq!(child.link.as_deref(), expected, "group-local template href");
}
let nested = &children[local_cases.len()];
assert_eq!(nested.link.as_deref(), Some("https://example.com/NestedTemplateGroup"));
let InlineObject::Group { children: nested_children, .. } = &nested.obj else { panic!() };
assert_eq!(nested_children.len(), 1);
assert_eq!(nested_children[0].link.as_deref(), Some("https://example.com/DeepTemplate"), "nested group-local template href");
}
}
fn replacing_picture_part(bytes: &[u8], name: &str, replacement: &str) -> Vec<u8> {
let mut input = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut output = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for i in 0..input.len() {
let mut file = input.by_index(i).unwrap();
let entry = file.name().unwrap().to_string();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
if entry == name {
data = replacement.as_bytes().to_vec();
}
output.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap();
output.write_all(&data).unwrap();
}
output.finish().unwrap().into_inner()
}
#[test]
fn group_picture_links_require_their_own_external_hyperlink_relationship() {
let body = r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:24pt;height:12pt" coordsize="24,12"><v:shape style="width:24pt;height:12pt" href="https://example.com/Child"><v:imagedata r:id="rIdPic"/></v:shape></v:group></w:pict></w:r></w:p>"#;
let doc = craft_docx::read(&package(body)).unwrap();
let saved = craft_docx::write(&doc).unwrap();
let xml = part(&saved, "word/document.xml");
let rels = part(&saved, "word/_rels/document.xml.rels");
let tree = craft_xml::parse(xml.as_bytes()).unwrap();
let nv = tree.find("pic:pic").unwrap().child("pic:nvPicPr").unwrap().child("pic:cNvPr").unwrap();
let click = nv.child("a:hlinkClick").expect("the valid child's click must be on its cNvPr");
let id = click.attr("r:id").unwrap();
let original_png = png();
let check = |bytes: &[u8], expected: Option<&str>| {
let doc = craft_docx::read(bytes).unwrap();
let paragraph = doc.body[0].as_para().unwrap();
assert_eq!(paragraph.objects.len(), 1);
assert_eq!(paragraph.props_of_char(0).link, None, "an unlinked group must not borrow its child's link");
let InlineObject::Group { children, .. } = &paragraph.objects[0] else { panic!() };
assert_eq!(children.len(), 1);
let InlineObject::Image { media, w, h, .. } = &children[0].obj else { panic!() };
assert_eq!(doc.media.get(media).unwrap().as_slice(), original_png.as_slice());
assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001);
assert_eq!(children[0].link.as_deref(), expected);
};
check(&saved, Some("https://example.com/Child"));
let type_name = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
for modified in [
rels.replace(type_name, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"),
rels.replace(" TargetMode=\"External\"", ""),
rels.replace("Target=\"https://example.com/Child\"", "Target=\" \""),
rels.replace("https://example.com/Child", &format!("https://example.com/{}", "x".repeat(8 << 10))),
] {
assert_ne!(modified, rels);
check(&replacing_picture_part(&saved, "word/_rels/document.xml.rels", &modified), None);
}
let missing = xml.replace(&format!(r#"r:id="{id}""#), r#"r:id="rIdAbsent""#);
assert_ne!(missing, xml);
check(&replacing_picture_part(&saved, "word/document.xml", &missing), None);
// A click in an unrelated extension is not the picture's nonvisual properties.
let mut unrelated = tree.clone();
let picture = unrelated
.child_mut("w:body")
.unwrap()
.child_mut("w:p")
.unwrap()
.child_mut("w:r")
.unwrap()
.child_mut("w:drawing")
.unwrap()
.child_mut("wp:inline")
.unwrap()
.child_mut("a:graphic")
.unwrap()
.child_mut("a:graphicData")
.unwrap()
.child_mut("wpg:wgp")
.unwrap()
.child_mut("pic:pic")
.unwrap();
picture.child_mut("pic:nvPicPr").unwrap().child_mut("pic:cNvPr").unwrap().children.clear();
let extension = craft_xml::parse(format!(r#"<a:extLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><a:ext uri="urn:original-test:unrelated"><a:hlinkClick r:id="{id}"/></a:ext></a:extLst>"#).as_bytes()).unwrap();
picture.child_mut("pic:spPr").unwrap().push(extension);
check(&replacing_picture_part(&saved, "word/document.xml", &unrelated.to_xml()), None);
}
#[test]
fn linked_groups_share_one_retained_member_budget() {
fn count(object: &InlineObject) -> usize {
match object {
InlineObject::Group { children, .. } => children.iter().map(|c| 1 + count(&c.obj)).sum(),
_ => 0,
}
}
fn input(per_group: usize) -> Vec<u8> {
let leaf = r#"<v:shape style="width:1pt;height:1pt"><v:imagedata r:id="rIdPic"/></v:shape>"#.repeat(per_group);
package(&format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:24pt;height:12pt" coordsize="24,12"><v:group style="width:12pt;height:12pt" coordsize="12,12" href="https://example.com/Left">{leaf}</v:group><v:group style="left:12pt;width:12pt;height:12pt" coordsize="12,12" href="https://example.com/Right">{leaf}</v:group></v:group></w:pict></w:r></w:p>"#,
))
}
let small = craft_docx::read(&input(1)).unwrap();
assert_eq!(count(&small.body[0].as_para().unwrap().objects[0]), 4, "two linked groups and two picture leaves");
let saved_small = craft_docx::write(&small).unwrap();
let reopened_small = craft_docx::read(&saved_small).unwrap();
assert_eq!(count(&reopened_small.body[0].as_para().unwrap().objects[0]), 4);
let max = craft_wordmodel::para::MAX_GROUP_CHILDREN;
assert_eq!(max, 1000, "this original fixture is bounded to the existing limit plus two nodes");
let large = craft_docx::read(&input(500)).unwrap();
assert_eq!(count(&large.body[0].as_para().unwrap().objects[0]), max, "VML must count linked nodes and leaves together");
// Independently construct the same 1002-node DrawingML input from our small
// original save, so the VML reader's own bound cannot hide a DML budget regression.
let mut xml = craft_xml::parse(part(&saved_small, "word/document.xml").as_bytes()).unwrap();
let group = xml
.child_mut("w:body")
.unwrap()
.child_mut("w:p")
.unwrap()
.child_mut("w:r")
.unwrap()
.child_mut("w:drawing")
.unwrap()
.child_mut("wp:inline")
.unwrap()
.child_mut("a:graphic")
.unwrap()
.child_mut("a:graphicData")
.unwrap()
.child_mut("wpg:wgp")
.unwrap();
for child in group.elements_mut().filter(|e| e.name == "wpg:grpSp") {
let picture = child.child("pic:pic").unwrap().clone();
child.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic"));
for _ in 0..500 {
child.push(picture.clone());
}
}
let dml = replacing_picture_part(&saved_small, "word/document.xml", &xml.to_xml());
let doc = craft_docx::read(&dml).unwrap();
assert_eq!(count(&doc.body[0].as_para().unwrap().objects[0]), max, "DrawingML must share the same root-wide bound");
}
/// An omitted linked group returns its reserved slot before the following drawable is read.
#[test]
fn empty_linked_groups_release_the_last_member_slot() {
let max = craft_wordmodel::para::MAX_GROUP_CHILDREN;
let before = r#"<v:shape style="width:1pt;height:1pt" alt="before-empty"><v:imagedata r:id="rIdPic"/></v:shape>"#;
let after = r#"<v:shape style="width:1pt;height:1pt" alt="after-empty"><v:imagedata r:id="rIdPic"/></v:shape>"#;
let empty = r#"<v:group style="width:1pt;height:1pt" coordsize="1,1" href="https://example.com/Empty"/>"#;
let input = |members: &str| {
package(&format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:24pt;height:12pt" coordsize="24,12">{members}</v:group></w:pict></w:r></w:p>"#,
))
};
let check = |doc: &Document| {
let InlineObject::Group { children, .. } = &doc.body[0].as_para().unwrap().objects[0] else {
panic!("the original root group must remain");
};
assert_eq!(children.len(), max, "the empty linked group must return the last member slot");
assert!(children.iter().all(|child| matches!(&child.obj, InlineObject::Image { .. }) && child.link.is_none()));
assert!(
matches!(&children.last().unwrap().obj, InlineObject::Image { alt, .. } if alt == "after-empty"),
"the drawable after the omitted group must survive"
);
};
let vml = input(&format!("{}{empty}{after}", before.repeat(max - 1)));
check(&craft_docx::read(&vml).unwrap());
// Save a small, nonempty linked group to obtain normalized DrawingML with its relationship.
// Then remove its drawable and fill the root independently of the VML boundary input.
let seed =
input(&format!(r#"<v:group style="width:1pt;height:1pt" coordsize="1,1" href="https://example.com/Empty">{before}</v:group>{after}"#,));
let saved = craft_docx::write(&craft_docx::read(&seed).unwrap()).unwrap();
let mut xml = craft_xml::parse(part(&saved, "word/document.xml").as_bytes()).unwrap();
let group = xml
.child_mut("w:body")
.unwrap()
.child_mut("w:p")
.unwrap()
.child_mut("w:r")
.unwrap()
.child_mut("w:drawing")
.unwrap()
.child_mut("wp:inline")
.unwrap()
.child_mut("a:graphic")
.unwrap()
.child_mut("a:graphicData")
.unwrap()
.child_mut("wpg:wgp")
.unwrap();
let mut empty = group.child("wpg:grpSp").unwrap().clone();
let filler = empty.child("pic:pic").unwrap().clone();
let last = group.child("pic:pic").unwrap().clone();
assert!(empty.child("wpg:cNvPr").unwrap().child("a:hlinkClick").is_some(), "exercise the linked-group reservation path");
empty.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if e.name == "pic:pic"));
group.children.retain(|n| !matches!(n, craft_xml::Node::El(e) if matches!(e.name.as_str(), "wpg:grpSp" | "pic:pic")));
for _ in 0..max - 1 {
group.push(filler.clone());
}
group.push(empty);
group.push(last);
let dml = replacing_picture_part(&saved, "word/document.xml", &xml.to_xml());
check(&craft_docx::read(&dml).unwrap());
}
#[test]
fn linked_group_coordinates_keep_their_scale() {
fn image_rect(object: &InlineObject, x: f32, scale: f32) -> (f32, f32) {
match object {
InlineObject::Image { w, .. } => (x, w * scale),
InlineObject::Group { w, ch_w, children, .. } => {
assert_eq!(children.len(), 1);
let inner = scale * w / ch_w;
image_rect(&children[0].obj, x + children[0].x * inner, inner)
}
_ => panic!("expected a picture or its group"),
}
}
let picture = picture_run(1, "");
let picture = &picture[picture.find("<pic:pic>").unwrap()..picture.find("</pic:pic>").unwrap() + "</pic:pic>".len()];
let picture = picture
.replace(r#"<a:off x="0" y="0"/><a:ext cx="254000" cy="254000"/>"#, r#"<a:off x="114300000" y="0"/><a:ext cx="12700000" cy="12700000"/>"#);
for linked in [false, true] {
let vml_link = if linked { r#"href="https://example.com/subgroup""# } else { "" };
let dml_link = if linked { r#"<a:hlinkClick r:id="rIdWeb"/>"# } else { "" };
let vml = format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:200pt;height:200pt" coordsize="200,200"><v:group style="width:100pt;height:100pt" coordsize="10000,10000" coordorigin="-7000,0" {vml_link}><v:shape style="left:9000;width:1000;height:1000"><v:imagedata r:id="rIdPic"/></v:shape></v:group></v:group></w:pict></w:r></w:p>"#,
);
let dml = format!(
r#"<w:p><w:r><w:drawing><wp:inline><wp:extent cx="2540000" cy="2540000"/><wp:docPr id="1" name="Group"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2540000" cy="2540000"/><a:chOff x="0" y="0"/><a:chExt cx="2540000" cy="2540000"/></a:xfrm></wpg:grpSpPr><wpg:grpSp><wpg:cNvPr id="2" name="Subgroup">{dml_link}</wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="1270000"/><a:chOff x="-88900000" y="0"/><a:chExt cx="127000000" cy="127000000"/></a:xfrm></wpg:grpSpPr>{picture}</wpg:grpSp></wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#,
);
for body in [vml, dml] {
let doc = craft_docx::read(&package(&body)).unwrap();
let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
for current in [&doc, &reopened] {
let (x, w) = image_rect(&current.body[0].as_para().unwrap().objects[0], 0.0, 1.0);
assert!((x - 160.0).abs() < 0.01, "the rebased offset must be scaled before clipping: {x}");
assert!((w - 10.0).abs() < 0.01, "the picture keeps its size in the same coordinate system: {w}");
}
}
}
}
#[test]
fn inherited_drawing_targets_share_a_document_byte_budget() {
let target = format!("https://example.com/{}", "x".repeat((8 << 10) - "https://example.com/".len()));
let leaf = r##"<v:shape type="#Target" style="width:1pt;height:1pt"><v:imagedata r:id="rIdPic"/></v:shape>"##.repeat(1000);
let paragraph = format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:shapetype id="Target" href="{target}"/><v:group style="width:100pt;height:100pt" coordsize="100,100">{leaf}</v:group></w:pict></w:r></w:p>"#,
);
let doc = craft_docx::read(&package(&paragraph.repeat(9))).unwrap();
let mut bytes = 0;
let mut retained = 0;
let mut dropped = 0;
for block in &doc.body {
let InlineObject::Group { children, .. } = &block.as_para().unwrap().objects[0] else { panic!() };
assert_eq!(children.len(), 1000, "a target budget must not discard the drawing");
for child in children {
assert!(matches!(child.obj, InlineObject::Image { .. }));
if let Some(link) = &child.link {
assert_eq!(link, &target);
bytes += link.len();
retained += 1;
} else {
dropped += 1;
}
}
}
assert!(retained > 0 && dropped > 0, "the same budget must span every group in the document");
assert!(bytes <= 64 << 20);
}
#[test]
fn native_ink_keeps_its_vml_preview_target_without_overriding_its_own() {
for own_target in [false, true] {
let input = super::fixtures::ink_docx(true, false);
let mut xml = part(&input, "word/document.xml");
xml = xml.replace(r#"<v:shape id="preview""#, r#"<v:shape id="preview" href="https://example.com/preview""#);
let target = format!("https://example.com/{}", "x".repeat((8 << 10) - "https://example.com/".len()));
let leaf = r##"<v:shape type="#Later" style="width:1pt;height:1pt"><v:imagedata r:id="rPreview"/></v:shape>"##.repeat(1000);
let later = format!(r#"<v:group style="width:1pt;height:1pt" coordsize="1,1">{leaf}</v:group>"#).repeat(9);
xml = xml.replace("</w:pict>", &format!(r#"<v:shapetype id="Later" href="{target}"/>{later}</w:pict>"#));
let mut input = replacing_picture_part(&input, "word/document.xml", &xml);
if own_target {
let xml = xml.replace(
r#"<wp:docPr id="1" name="Study ink"/>"#,
r#"<wp:docPr id="1" name="Study ink"><a:hlinkClick r:id="rNativeLink"/></wp:docPr>"#,
);
let rels = part(&input, "word/_rels/document.xml.rels").replace(
"</Relationships>",
r#"<Relationship Id="rNativeLink" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/native" TargetMode="External"/></Relationships>"#,
);
input = replacing_picture_part(&input, "word/document.xml", &xml);
input = replacing_picture_part(&input, "word/_rels/document.xml.rels", &rels);
}
let mut doc = craft_docx::read(&input).unwrap();
for _ in 0..2 {
let paragraph = doc.body[1].as_para().unwrap();
let InlineObject::Graphic { graphic, .. } = &paragraph.objects[0] else { panic!() };
assert_eq!(graphic.kind.noun(), "ink");
assert!(graphic.source.is_some() && !graphic.items.is_empty());
let expected = if own_target { "https://example.com/native" } else { "https://example.com/preview" };
assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some(expected));
doc = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
}
}
}
#[test]
fn deepest_linked_vml_tree_survives_flow_and_docx() {
fn check(doc: &Document) {
let paragraph = doc.body[0].as_para().unwrap();
assert_eq!(paragraph.objects.len(), 1);
assert_eq!(paragraph.props_of_char(0).link.as_deref(), Some("https://example.com/root"));
let mut object = &paragraph.objects[0];
for level in 0..=8 {
let InlineObject::Group { children, .. } = object else { panic!("group at level {level}") };
assert_eq!(children.len(), 1);
let expected = if level == 8 { "#last-picture".to_string() } else { format!("https://example.com/level{}", level + 1) };
assert_eq!(children[0].link.as_deref(), Some(expected.as_str()));
object = &children[0].obj;
}
let InlineObject::Image { media, w, h, .. } = object else { panic!("deepest picture") };
assert_eq!(doc.media.get(media).unwrap().as_slice(), png().as_slice());
assert!((*w - 6.0).abs() < 0.001 && (*h - 5.0).abs() < 0.001);
}
let mut members = r##"<v:shape style="width:6pt;height:5pt" href="#last-picture"><v:imagedata r:id="rIdPic"/></v:shape>"##.to_string();
for level in (1..=8).rev() {
members = format!(r#"<v:group style="width:12pt;height:8pt" coordsize="12,8" href="https://example.com/level{level}">{members}</v:group>"#,);
}
let body = format!(
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:group style="width:12pt;height:8pt" coordsize="12,8" href="https://example.com/root">{members}</v:group></w:pict></w:r></w:p>"#,
);
let imported = craft_docx::read(&package(&body)).unwrap();
check(&imported);
let flow = craft_flow::from_doc_with(&imported, craft_flow::FlowOpts { boxes: true, paras: true, ..Default::default() });
let rebuilt = craft_flow::to_doc(&flow);
check(&rebuilt);
let reopened = craft_docx::read(&craft_docx::write(&rebuilt).unwrap()).unwrap();
check(&reopened);
}
/// Original Flow callers used the mark for a textless paragraph's single drawing.
#[test]
fn a_single_flow_picture_keeps_its_paragraph_mark_link() {
const MARK: &str = "https://example.com/paragraph";
const OWN: &str = "https://example.com/object";
let bytes = Arc::new(png());
for (links, text, expected) in [
(vec![None], false, vec![Some(MARK)]),
(vec![Some(OWN)], false, vec![Some(OWN)]),
(vec![Some("")], false, vec![None]),
(vec![None, None], false, vec![None, None]),
(vec![Some(OWN), None], false, vec![Some(OWN), None]),
(vec![None, Some(OWN)], false, vec![None, Some(OWN)]),
(vec![None], true, vec![None]),
] {
let inlines = links
.into_iter()
.map(|link| {
let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap();
picture.link = link.map(str::to_string);
craft_flow::Inline::Image(picture)
})
.collect();
let mut paragraph =
craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(MARK.into()), ..Default::default() })), ..Default::default() };
if text {
paragraph.push_text("beside the picture", &Default::default());
}
let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() };
let model = craft_flow::to_doc(&flow);
let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap();
let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect();
for current in [&model, &reopened] {
assert_eq!(
picture_links(current),
expected,
"only the legacy single drawing inherits the mark; explicit targets and neighbors keep their own scope"
);
let paragraph = current.body[0].as_para().unwrap();
assert_eq!(paragraph.objects.len(), expected.len());
for object in &paragraph.objects {
let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") };
assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice());
assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained");
}
}
}
}
/// The legacy paragraph target has the same byte limit as an object's own target.
#[test]
fn a_single_flow_picture_bounds_its_inherited_mark_target() {
const OWN: &str = "https://example.com/object";
let prefix = "https://example.com/";
let remaining = craft_flow::MAX_LINK - prefix.len();
let ascii = format!("{prefix}{}", "a".repeat(remaining));
let utf8 = format!("{prefix}{}{}", "é".repeat(remaining / 2), "a".repeat(remaining % 2));
let ascii_over = format!("{ascii}a");
let utf8_over = format!("{utf8}a");
let bytes = Arc::new(png());
for (mark, links, expected) in [
(ascii.as_str(), vec![None], vec![Some(ascii.as_str())]),
(ascii_over.as_str(), vec![None], vec![None]),
(utf8.as_str(), vec![None], vec![Some(utf8.as_str())]),
(utf8_over.as_str(), vec![None], vec![None]),
(ascii_over.as_str(), vec![Some(OWN)], vec![Some(OWN)]),
(ascii_over.as_str(), vec![Some("")], vec![None]),
(ascii_over.as_str(), vec![Some(" \t ")], vec![None]),
(ascii_over.as_str(), vec![Some(ascii_over.as_str())], vec![None]),
(OWN, vec![Some(utf8_over.as_str())], vec![None]),
(ascii_over.as_str(), vec![None, None], vec![None, None]),
(ascii_over.as_str(), vec![Some(OWN), None], vec![Some(OWN), None]),
(ascii_over.as_str(), vec![None, Some(OWN)], vec![None, Some(OWN)]),
] {
let inlines = links
.into_iter()
.map(|link| {
let mut picture = craft_flow::make_img(bytes.clone(), Some(12.0), Some(6.0), "original picture").unwrap();
picture.link = link.map(str::to_string);
craft_flow::Inline::Image(picture)
})
.collect();
let paragraph =
craft_flow::Para { inlines, mark: Some(Box::new(CharProps { link: Some(mark.into()), ..Default::default() })), ..Default::default() };
let flow = craft_flow::Flow { blocks: vec![craft_flow::FBlock::Para(paragraph)], ..Default::default() };
let expected: Vec<_> = expected.into_iter().map(|target| target.map(str::to_string)).collect();
let check = |current: &Document| {
assert_eq!(picture_links(current), expected, "each drawing keeps only its own or eligible inherited target");
let paragraph = current.body[0].as_para().unwrap();
assert_eq!(paragraph.objects.len(), expected.len());
for object in &paragraph.objects {
let InlineObject::Image { media, w, h, .. } = object else { panic!("the picture remains a picture") };
assert_eq!(current.media.get(media).unwrap().as_slice(), bytes.as_slice());
assert!((*w - 12.0).abs() < 0.001 && (*h - 6.0).abs() < 0.001, "the original picture size is retained");
}
};
let model = craft_flow::to_doc(&flow);
check(&model);
let reopened = craft_docx::read(&craft_docx::write(&model).unwrap()).unwrap();
check(&reopened);
}
}
+9 -7
View File
@@ -1412,9 +1412,9 @@ fn groups_round_trip() {
ch_w: 200.0,
ch_h: 100.0,
children: vec![
GroupChild { x: 0.0, y: 0.0, obj: pic },
GroupChild { x: 150.0, y: 10.0, obj: oval.clone() },
GroupChild { x: 50.0, y: 60.0, obj: tb },
GroupChild { link: None, x: 0.0, y: 0.0, obj: pic },
GroupChild { link: None, x: 150.0, y: 10.0, obj: oval.clone() },
GroupChild { link: None, x: 50.0, y: 60.0, obj: tb },
],
canvas: None,
};
@@ -1486,7 +1486,7 @@ fn drawing_canvas_round_trips() {
float: Float::default(),
ch_w: 432.0,
ch_h: 216.0,
children: vec![GroupChild { x: 12.0, y: 18.0, obj: pic }, GroupChild { x: 300.0, y: 100.0, obj: star.clone() }],
children: vec![GroupChild { link: None, x: 12.0, y: 18.0, obj: pic }, GroupChild { link: None, x: 300.0, y: 100.0, obj: star.clone() }],
canvas: Some(style.clone()),
};
let mut p = Paragraph::with_text("drawn ", CharProps::default());
@@ -1533,7 +1533,7 @@ fn rotated_drawing_canvas_round_trips() {
float,
ch_w: 200.0,
ch_h: 100.0,
children: vec![GroupChild { x: 10.0, y: 20.0, obj: member.clone() }],
children: vec![GroupChild { link: None, x: 10.0, y: 20.0, obj: member.clone() }],
canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }),
};
let square = Float { wrap: Wrap::Square, ..Default::default() };
@@ -2484,6 +2484,7 @@ fn rotation_and_flips_round_trip() {
ch_w: 120.0,
ch_h: 60.0,
children: vec![craft_wordmodel::para::GroupChild {
link: None,
x: 0.0,
y: 0.0,
obj: shape(ShapeKind::Ellipse, Float { rot: 10.0, ..Default::default() }),
@@ -2542,8 +2543,8 @@ fn rotated_group_and_shadow_rotation_round_trip() {
ch_w: 120.0,
ch_h: 40.0,
children: vec![
craft_wordmodel::para::GroupChild { x: 0.0, y: 0.0, obj: member(true) },
craft_wordmodel::para::GroupChild { x: 60.0, y: 0.0, obj: member(false) },
craft_wordmodel::para::GroupChild { link: None, x: 0.0, y: 0.0, obj: member(true) },
craft_wordmodel::para::GroupChild { link: None, x: 60.0, y: 0.0, obj: member(false) },
],
canvas: None,
};
@@ -2996,6 +2997,7 @@ fn alt_text_title_and_decorative_round_trip_for_every_object() {
ch_w: 120.0,
ch_h: 60.0,
children: vec![craft_wordmodel::para::GroupChild {
link: None,
x: 0.0,
y: 0.0,
obj: shape(AltText { text: "Left circle".into(), ..Default::default() }),
+59 -8
View File
@@ -41,10 +41,13 @@ pub enum ShapeGeometry {
rect: Rect,
},
/// A triangle filling `rect`: the apex at the top centre, the base on the bottom edge (PhotoCraft's Triangle
/// tool and Create Triangle).
/// tool and Create Triangle), each corner rounded by `corner_radius`.
Triangle {
/// The triangle's bounds.
rect: Rect,
/// One radius for every corner, in document units; 0 for sharp corners. A radius larger than the
/// triangle allows is capped by the shape ([`ShapeGeometry::to_path`]).
corner_radius: f64,
},
/// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Polygon).
/// `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon.
@@ -98,7 +101,9 @@ impl ShapeGeometry {
/// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain
/// rectangle.
/// - `Ellipse`: kurbo's `Ellipse::from_rect`.
/// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`.
/// - `Triangle`: the top centre, the bottom right and the bottom left of `rect`. A `corner_radius` over 0
/// rounds each corner with a circular arc tangent to both its edges; the arc's ends lie no farther from
/// the corner than half its shorter edge, which caps a radius the triangle cannot hold.
/// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point
/// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine:
/// a 3-sided polygon's base lies a quarter of the height below the centre, not on the bottom
@@ -125,10 +130,10 @@ impl ShapeGeometry {
}
}
Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance),
Self::Triangle { rect } => {
// pc: #13350 (the triangle fills its box, apex on top).
Self::Triangle { rect, corner_radius } => {
// pc: #13350 (the triangle fills its box, apex on top); #13355 (the Triangle tool's radius).
let rect = rect.abs();
closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)])
rounded_closed(&[Point::new(rect.center().x, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)], corner_radius)
}
Self::Polygon { rect, sides, star_ratio } => {
let rect = rect.abs();
@@ -156,9 +161,11 @@ impl ShapeGeometry {
pub fn bounds(&self) -> Rect {
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box).
match *self {
Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Triangle { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => {
rect.abs()
}
Self::Rect { rect, .. }
| Self::Ellipse { rect }
| Self::Triangle { rect, .. }
| Self::Polygon { rect, .. }
| Self::Custom { rect, .. } => rect.abs(),
Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius),
Self::Line { from, to, .. } => Rect::from_points(from, to),
}
@@ -312,6 +319,50 @@ fn polygon_points(center: Point, radius: f64, rotation: f64, sides: u32, star_ra
points
}
/// The closed outline through `points` with every corner rounded by `radius`: a circular arc (a cubic) tangent to
/// both edges, whose ends lie no farther from the corner than half the shorter of its two edges. A radius that is
/// 0, negative or not finite, and a corner too flat or too sharp to round, keep the sharp corner.
fn rounded_closed(points: &[Point], radius: f64) -> BezPath {
let n = points.len();
if !(radius.is_finite() && radius > 0.0) || n < 3 {
return closed(points);
}
// Per corner: where the arc meets the incoming edge, the cubic's two control points and where it leaves.
let corners: Vec<(Point, Point, Point, Point)> = (0..n)
.map(|i| {
let (prev, at, next) = (points[(i + n - 1) % n], points[i], points[(i + 1) % n]);
let (to_prev, to_next) = (prev - at, next - at);
let (len_prev, len_next) = (to_prev.hypot(), to_next.hypot());
let angle = if len_prev > 0.0 && len_next > 0.0 { (to_prev.dot(to_next) / (len_prev * len_next)).clamp(-1.0, 1.0).acos() } else { 0.0 };
if !(angle > f64::EPSILON && angle < PI - f64::EPSILON) {
return (at, at, at, at);
}
let half = angle / 2.0;
// The tangent points' distance from the corner, capped at half the shorter edge.
let reach = (radius / half.tan()).min(len_prev.min(len_next) / 2.0);
let (u_prev, u_next) = (to_prev / len_prev, to_next / len_next);
let (enter, leave) = (at + u_prev * reach, at + u_next * reach);
// The arc turns by π − angle; a cubic's handles for a circular arc of turn φ are 4/3·tan(φ/4)·r long.
let arc_radius = reach * half.tan();
let handle = 4.0 / 3.0 * ((PI - angle) / 4.0).tan() * arc_radius;
(enter, enter - u_prev * handle, leave - u_next * handle, leave)
})
.collect();
let mut path = BezPath::new();
for (i, (enter, c1, c2, leave)) in corners.iter().enumerate() {
if i == 0 {
path.move_to(*enter);
} else {
path.line_to(*enter);
}
if enter != leave {
path.curve_to(*c1, *c2, *leave);
}
}
path.close_path();
path
}
fn closed(points: &[Point]) -> BezPath {
let mut path = BezPath::new();
for (i, p) in points.iter().enumerate() {
+6 -6
View File
@@ -24,7 +24,7 @@ pub const FIELD_MAX: f64 = 1e9;
pub const LENGTH_MIN: f64 = 0.01;
/// What the frame's proportions follow.
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CropRatio {
@@ -55,7 +55,7 @@ impl CropRatio {
}
/// The resolution field's unit.
#[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 ResolutionUnit {
@@ -68,7 +68,7 @@ pub enum ResolutionUnit {
/// A length with the unit it was entered in: the W and H of W × H × Resolution mode keep what the user typed ("2 in"
/// stays in inches when the document resizes).
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CropLength {
@@ -97,7 +97,7 @@ impl CropLength {
/// The W, H and Resolution fields of W × H × Resolution mode. Unset W and H are `None`; the resolution is typed text
/// ("300"), empty when unset. Perspective Crop's options bar uses the same fields.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct CropSizeFields {
@@ -112,7 +112,7 @@ pub struct CropSizeFields {
}
/// What the area a turned or extending crop uncovers is filled with.
#[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 CropFill {
@@ -229,7 +229,7 @@ pub const CROP_SIZES: [CropSizePreset; 8] = [
/// options bar edits it in place, the tool reads it each pass and reports key changes (O, ⇧O, H,
/// P, I, X) as [`CropEvent::Settings`](super::CropEvent::Settings). Every field defaults on its
/// own, so older settings load.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct CropSettings {
+33 -11
View File
@@ -1,6 +1,7 @@
//! [`PaintBar`]: the options bar members of the Brush, Pencil, Eraser and Mixer Brush tools after the preset picker.
use std::cell::RefCell;
use std::ops::RangeInclusive;
use std::sync::Arc;
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, Value};
@@ -201,6 +202,25 @@ pub const MIXER_COMBINATIONS: [Option<(f64, f64, f64)>; 13] = [
/// The index of the first combination of each group (Dry, Moist, Wet, Very Wet); a separator goes above each.
pub const MIXER_GROUP_STARTS: [usize; 4] = [1, 4, 7, 10];
/// The percents a field of the bar holds, and whether it takes input.
struct Percents {
range: RangeInclusive<f64>,
enabled: bool,
}
impl Percents {
/// 0 to 100 %.
fn any(enabled: bool) -> Self {
Percents { range: 0.0..=100.0, enabled }
}
/// 1 to 100 %, for Opacity and Flow: a stroke at 0 % paints nothing, so a typed 0 is out of range like 150, and
/// the range alert names 1 %.
fn from_one(enabled: bool) -> Self {
Percents { range: 1.0..=100.0, enabled }
}
}
/// Whether the smoothing options popover is open.
#[derive(Clone, Default)]
struct SmoothingOpen(bool);
@@ -208,7 +228,8 @@ struct SmoothingOpen(bool);
/// The bar's members for one painting tool, after the preset picker that carries the size and the hardness: a rule,
/// Mode, Opacity and the pressure-for-opacity toggle, Flow and the build-up toggle (not the Pencil), Smoothing and its
/// options (the Pencil's Auto Erase in their place), Erase to History for the Eraser, a rule and the
/// pressure-for-size toggle. The Mixer Brush shows its load, combinations and mix values instead.
/// pressure-for-size toggle. Opacity and Flow hold 1 to 100 %, Smoothing 0 to 100 %. The Mixer Brush shows its load,
/// combinations and mix values instead.
#[must_use = "show the bar with `show`"]
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(PaintBar<'static, u32>))]
@@ -269,10 +290,10 @@ impl<'a, M: Value> PaintBar<'a, M> {
pass.check(ui, &words.load_after_stroke, true, None, pass.values.mixer.load_after_stroke, |v, x| v.mixer.load_after_stroke = x);
pass.check(ui, &words.clean_after_stroke, true, None, pass.values.mixer.clean_after_stroke, |v, x| v.mixer.clean_after_stroke = x);
pass.combination(ui, &words);
pass.percent(ui, "mixer-wet", &words.wet, true, pass.values.mixer.wet, |v, x| v.mixer.wet = x);
pass.percent(ui, "mixer-load", &words.load, true, pass.values.mixer.load, |v, x| v.mixer.load = x);
pass.percent(ui, "mixer-mix", &words.mix, true, pass.values.mixer.mix, |v, x| v.mixer.mix = x);
pass.percent(ui, "mixer-flow", &words.flow, true, pass.values.mixer.flow, |v, x| v.mixer.flow = x);
pass.percent(ui, "mixer-wet", &words.wet, Percents::any(true), pass.values.mixer.wet, |v, x| v.mixer.wet = x);
pass.percent(ui, "mixer-load", &words.load, Percents::any(true), pass.values.mixer.load, |v, x| v.mixer.load = x);
pass.percent(ui, "mixer-mix", &words.mix, Percents::any(true), pass.values.mixer.mix, |v, x| v.mixer.mix = x);
pass.percent(ui, "mixer-flow", &words.flow, Percents::any(true), pass.values.mixer.flow, |v, x| v.mixer.flow = x);
pass.check(ui, &words.sample_all_layers, true, None, pass.values.mixer.sample_all_layers, |v, x| v.mixer.sample_all_layers = x);
return;
}
@@ -283,13 +304,13 @@ impl<'a, M: Value> PaintBar<'a, M> {
} else {
pass.mode(ui, &words.mode, modes);
}
pass.percent(ui, "opacity", &words.opacity, sized, pass.values.opacity, |v, x| v.opacity = x);
pass.percent(ui, "opacity", &words.opacity, Percents::from_one(sized), pass.values.opacity, |v, x| v.opacity = x);
pass.toggle(ui, PRESSURE, &words.pressure_opacity, sized, pass.values.pressure_opacity, |v, x| v.pressure_opacity = x);
if tool != PaintTool::Pencil {
pass.percent(ui, "flow", &words.flow, sized && soft, pass.values.flow, |v, x| v.flow = x);
pass.percent(ui, "flow", &words.flow, Percents::from_one(sized && soft), pass.values.flow, |v, x| v.flow = x);
pass.toggle(ui, "sparkles", &words.build_up, sized && soft, pass.values.build_up, |v, x| v.build_up = x);
}
pass.percent(ui, "smoothing", &words.smoothing, true, pass.values.smoothing.amount, |v, x| v.smoothing.amount = x);
pass.percent(ui, "smoothing", &words.smoothing, Percents::any(true), pass.values.smoothing.amount, |v, x| v.smoothing.amount = x);
if tool == PaintTool::Pencil {
Divider::vertical().show(ui);
pass.check(ui, &words.auto_erase, true, Some(&words.auto_erase_tip), pass.values.auto_erase, |v, x| v.auto_erase = x);
@@ -361,15 +382,16 @@ impl<M: Value> Pass<'_, M> {
}
}
/// A percent field over a fraction 0..1.
fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, enabled: bool, current: f64, set: fn(&mut PaintValues<M>, f64)) {
/// A percent field over a fraction 0..1, holding `percents`.
fn percent(&mut self, ui: &mut Ui, salt: &'static str, caption: &Label, percents: Percents, current: f64, set: fn(&mut PaintValues<M>, f64)) {
let Percents { range, enabled } = percents;
// The body may run more than once in a pass and only the run that reads the input reports its events, so every
// run's events and alert are collected.
let collected: RefCell<(EditEvents<Option<f64>>, Option<RangeAlert>)> = RefCell::new((EditEvents::new(), None));
let _ = Field::new(caption.clone()).side(SideLabel::new().scrub(true)).id_salt(salt).enabled(enabled).show(ui, |ui, _| {
let field = NumberField::new(caption.clone(), Bind::given(Some(current * 100.0)))
.unit_kind(UnitKind::Percent)
.range(0.0..=100.0)
.range(range.clone())
.commit_decimals(0)
.scrub_by_label()
.show(ui);
+54 -35
View File
@@ -77,7 +77,8 @@ pub enum BezierTool {
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
/// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is
/// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
/// selected. Holding Space during that drag moves the anchor and both handles; releasing it resumes pulling.
/// A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
/// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the
/// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it
/// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does
@@ -250,16 +251,20 @@ enum Target {
t: f64,
from: Point,
},
/// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of
/// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and
/// `in_ctrl` the in handle ⌥ left once it broke the pair.
/// Add Anchor's drag from a segment: `from` stays the original curve point, while Space moves the anchor by
/// `by` with both handles. `last` tracks pointer travel; `out` is the last out handle, and `in_ctrl` the in
/// handle ⌥ left once it broke the pair.
Pull {
path: u64,
segment: KnotRef,
t: f64,
from: Point,
by: Vec2,
out: Point,
in_ctrl: Option<Point>,
last: Pos2,
/// A translated handle stays put until the pointer or its constraints change.
translated_mods: Option<Mods>,
},
/// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point.
Duplicate {
@@ -305,6 +310,7 @@ struct Pointing<'a> {
start: PressStart,
pos: Pos2,
mods: Mods,
space: bool,
}
/// The kind of a part of the overlay.
@@ -623,7 +629,7 @@ impl<'a> BezierOverlay<'a> {
// Anchor's with ⌥, moves it.
BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => {
let from = Self::segment_point(paths, path, segment, t);
Target::Pull { path, segment, t, from, out: from, in_ctrl: None }
Target::Pull { path, segment, t, from, by: Vec2::ZERO, out: from, in_ctrl: None, last: start.origin, translated_mods: None }
}
BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => {
Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) }
@@ -752,34 +758,46 @@ impl<'a> BezierOverlay<'a> {
PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from }
}
&Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from },
&Target::Pull { path, segment, t, from, in_ctrl, .. } => {
&Target::Pull { path, segment, t, from, by, in_ctrl, .. } => {
let to = from + delta;
let out = if mods.shift { handle_45(from, to) } else { snapped(to) };
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
let out = if mods.shift { handle_45(from + by, to) } else { snapped(to) };
PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl }
}
&Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from },
Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None,
})
}
/// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag
/// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass.
fn edit_pulled(
view: &CanvasView,
snap: Option<&Snap>,
tool: BezierTool,
target: &mut Target,
origin: Pos2,
pointer: Pos2,
mods: Mods,
) -> Option<PathEdit> {
if let Target::Pull { from, out, in_ctrl, .. } = target
&& mods.alt
&& in_ctrl.is_none()
{
*in_ctrl = Some(*from - (*out - *from));
/// Keeps Add Anchor's anchor and handles together while Space is held; otherwise pulls the handles.
/// ⌥ leaves the previous in handle in place until Space moves the whole knot again.
fn edit_pulled(tool: BezierTool, target: &mut Target, at: Pointing<'_>) -> Option<PathEdit> {
let Pointing { view, snap, start, pos, mods, space } = at;
if let Target::Pull { path, segment, t, from, by, out, in_ctrl, last, translated_mods } = target {
if space {
let delta = view.to_doc(pos) - view.to_doc(*last);
*by += delta;
*out += delta;
if let Some(incoming) = in_ctrl {
*incoming += delta;
}
*last = pos;
*translated_mods = Some(mods);
return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl });
}
// Space keeps translation priority; on release, Alt can break the pair without moving its geometry.
if mods.alt && in_ctrl.is_none() {
let anchor = *from + *by;
*in_ctrl = Some(anchor - (*out - anchor));
}
// Space moves by raw travel, including off the snap targets. Releasing it is not a pointer move:
// keep that geometry on every stationary pass, but still read modifier-only constraint changes.
if *last == pos && *translated_mods == Some(mods) {
return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl });
}
*translated_mods = None;
*last = pos;
}
let edit = Self::edit(view, snap, tool, target, origin, pointer, mods);
let edit = Self::edit(view, snap, tool, target, start.origin, pos, mods);
if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) {
*out = *pulled;
}
@@ -846,6 +864,7 @@ impl<'a> BezierOverlay<'a> {
fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, scene: &Scene, paths: &[EditPath]) {
let snap = canvas_snap(&cx.env);
let view = &space.view;
let space_held = space.space_held();
let mut hovered: Option<(u8, BezierHit, Mods)> = None;
let mut pressed = false;
for item in &scene.items {
@@ -853,7 +872,7 @@ impl<'a> BezierOverlay<'a> {
continue;
}
let Some(result) = cx.part_if_declared(item.part()) else { continue };
let (press, hover) = (result.press, result.hover_pos);
let (press, hover) = (result.press, cx.hover_pos(item.part()));
pressed |= press.phase.is_press();
if let Some(at) = hover {
let rank = match item.kind {
@@ -882,10 +901,10 @@ impl<'a> BezierOverlay<'a> {
}
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
let first = matches!(press.phase, PressPhase::DragStart { .. });
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), paths, first);
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, Some(item), paths, first);
}
PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => {
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths);
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths);
}
PressPhase::Cancel { .. } => *cx.press_slot::<Held>() = None,
_ => {}
@@ -904,10 +923,10 @@ impl<'a> BezierOverlay<'a> {
}
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
let first = matches!(press.phase, PressPhase::DragStart { .. });
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, paths, first);
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, None, paths, first);
}
PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => {
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths);
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths);
}
PressPhase::Cancel { .. } => *cx.press_slot::<Held>() = None,
_ => {}
@@ -916,7 +935,7 @@ impl<'a> BezierOverlay<'a> {
if matches!(self.tool, BezierTool::AddAnchor | BezierTool::DeleteAnchor)
&& let Some(result) = cx.part_if_declared(EMPTY)
{
let (press, hover) = (result.press, result.hover_pos);
let (press, hover) = (result.press, cx.hover_pos(EMPTY));
// The part covers the canvas background, so it owns the cursor the host tool shows off the paths too.
if hover.is_some() {
let tool = if self.tool == BezierTool::AddAnchor { PathTool::AddAnchor } else { PathTool::DeleteAnchor };
@@ -945,7 +964,7 @@ impl<'a> BezierOverlay<'a> {
/// One pass of a press dragged to `pos`; `first` on the pass the drag begins.
fn drag(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, item: Option<&Item>, paths: &[EditPath], first: bool) {
let Pointing { view, snap, start, pos, mods } = at;
let Pointing { view, start, pos, mods, .. } = at;
let kept = cx.press_slot::<Held>().take().filter(|held| held.origin == start.origin);
let mut held = match (kept, item) {
(Some(held), _) => held,
@@ -974,7 +993,7 @@ impl<'a> BezierOverlay<'a> {
}
}
_ => {
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) {
if let Some(edit) = Self::edit_pulled(self.tool, &mut held.target, at) {
self.propose(cx, &held.start, edit);
}
}
@@ -985,7 +1004,7 @@ impl<'a> BezierOverlay<'a> {
/// The release of a press at `pos`: a drag commits, a click does what its tool's click does.
fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, click: bool, paths: &[EditPath]) {
let Pointing { view, snap, start, pos, mods } = at;
let Pointing { view, start, pos, mods, .. } = at;
// A press reports its Down, and its drag start, before its release, and the overlay holds the press from
// either: a release with nothing held is of a press the overlay let go (a cancelled one), and does nothing.
let Some(held) = cx.press_slot::<Held>().take().filter(|held| held.origin == start.origin) else { return };
@@ -1003,7 +1022,7 @@ impl<'a> BezierOverlay<'a> {
}
if held.began {
let mut target = held.target.clone();
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) {
if let Some(edit) = Self::edit_pulled(self.tool, &mut target, at) {
self.propose(cx, &held.start, edit);
}
// The copy is what was dragged: it ends up selected, not the source.
+13 -3
View File
@@ -452,7 +452,8 @@ pub enum PathEdit {
},
/// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its
/// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot.
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. `by` moves the new anchor from
/// the original segment point; both handles are absolute document positions, including that move.
#[non_exhaustive]
PullAnchor {
/// The path's host key.
@@ -461,7 +462,9 @@ pub enum PathEdit {
segment: KnotRef,
/// Position along the segment, 0..=1.
t: f64,
/// The new anchor's out handle.
/// The move of the new anchor from the original segment point, in document units.
by: Vec2,
/// The new anchor's out handle, in document coordinates.
out: Point,
/// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`.
in_ctrl: Option<Point>,
@@ -546,7 +549,14 @@ impl PathEdit {
/// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out`
/// and mirrored, or with the in handle at `in_ctrl`.
pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option<Point>) -> Self {
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
Self::pull_anchor_moved(path, segment, t, Vec2::ZERO, out, in_ctrl)
}
/// Add Anchor's insert with its anchor moved by `by` from the original segment point.
/// `out` and `in_ctrl` are absolute document positions; `None` mirrors `out` through the moved anchor.
/// Hosts applying edits themselves must apply `by` to the inserted anchor before setting the handles.
pub fn pull_anchor_moved(path: u64, segment: KnotRef, t: f64, by: Vec2, out: Point, in_ctrl: Option<Point>) -> Self {
PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl }
}
/// The Curvature tool's toggle of `knot` between smooth and corner.
+13 -6
View File
@@ -137,9 +137,9 @@ impl PathEdit {
/// `by`, then the subpath reflowed.
/// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no
/// reflow and no smoothing, so a straight segment gets a corner knot.
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in
/// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when
/// a handle is not finite.
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new anchor moved by `by`, its out handle at
/// `out` and its in handle at `in_ctrl` (a corner), or mirrored through the moved anchor (smooth).
/// Nothing changes when the offset, moved anchor or a resulting handle is not finite.
/// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner
/// becomes smooth, then the subpath reflows.
/// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`;
@@ -206,16 +206,23 @@ impl PathEdit {
k.in_ctrl += *by;
k.out_ctrl += *by;
}
PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => {
PathEdit::PullAnchor { segment, t, by, out, in_ctrl, .. } => {
let finite = |p: &Point| p.x.is_finite() && p.y.is_finite();
if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
if !by.x.is_finite() || !by.y.is_finite() || !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
return false;
}
let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false };
let Some(at) = sp.insert_at(segment.knot, *t) else { return false };
let k = &mut sp.knots[at];
let anchor = k.anchor + *by;
let incoming = in_ctrl.unwrap_or(anchor - (*out - anchor));
if !finite(&anchor) || !finite(&incoming) {
*path = before;
return false;
}
k.anchor = anchor;
k.out_ctrl = *out;
k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor));
k.in_ctrl = incoming;
k.smooth = in_ctrl.is_none();
}
PathEdit::Convert { knot, out, .. } => {
+2 -2
View File
@@ -38,7 +38,7 @@ pub const PATH_OPTIONS_COLOR_KEY: &str = "pathOptions.color";
/// The pen's Path Options, persisted by the app with its preferences (Photoshop's Pen gear popover). Serialised in
/// camelCase; unknown fields are ignored and missing ones take their defaults.
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct PathOptionsSettings {
@@ -58,7 +58,7 @@ pub struct PathOptionsSettings {
}
/// How the direction handles' ends are drawn.
#[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 HandleStyle {
+7 -2
View File
@@ -35,8 +35,9 @@ pub struct ShapeBarOutput {
/// The cells a Shape tool adds to the options bar, in PhotoCraft's order: the "Fill" check box and chip, the
/// "Stroke" chip, the stroke width (0 to 288 px), the Stroke style button; then the kind's cell: Rectangle and
/// Rounded Rectangle "Radius" (0 to 150,000), Polygon and Star "Sides" (3 to 100), Line "Weight" (1 to 10,000). A
/// pattern shown as children of a `Bar`.
/// Rounded Rectangle "Radius" (0 to 150,000), Triangle "Radius" (0 to 150,000, its own
/// [`triangle_corner_radius`](ShapeToolSettings::triangle_corner_radius)), Polygon and Star "Sides" (3 to 100), Line
/// "Weight" (1 to 10,000). A pattern shown as children of a `Bar`.
///
/// - The values are the selected shape layer's when one is selected, else the tool settings' (the app passes the
/// right [`ShapeAppearance`]).
@@ -143,6 +144,10 @@ impl<'a> ShapeBar<'a> {
NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.corner_radius, RADIUS_RANGE),
ShapeChange::CornerRadius as fn(f64) -> ShapeChange,
)),
ShapeKind::Triangle => Some((
NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.triangle_corner_radius, RADIUS_RANGE),
ShapeChange::CornerRadius as fn(f64) -> ShapeChange,
)),
ShapeKind::Polygon | ShapeKind::Star => Some((
NumberCell::count(&units, "sides", &words.sides, f64::from(settings.sides), SIDES_RANGE),
sides_change as fn(f64) -> ShapeChange,
+14 -8
View File
@@ -29,7 +29,7 @@ pub use stroke_cells::{StrokeCells, StrokeCellsOutput};
pub use words::ShapeWords;
/// The drawing mode of the vector tools.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::PlainData)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum VectorMode {
@@ -252,7 +252,8 @@ pub enum ShapeChange {
},
/// A rectangle's four radii (the "Corner radius" field sets all four).
Radii([f64; 4]),
/// A polygon's corner radius, or the options bar's Radius.
/// A polygon's or triangle's corner radius, or the options bar's Radius (the Rectangle's, or the Triangle
/// tool's own).
CornerRadius(f64),
/// A polygon's number of sides.
Sides(u32),
@@ -270,8 +271,8 @@ impl ShapeChange {
pub const ENABLED_STROKE_WIDTH: f64 = 3.0;
}
/// The Shape tools' persisted options-bar values (Fill on, radius, sides, star ratio, weight,
/// stroke width, the Rectangle's gear); the paints are the app's foreground and background.
/// The Shape tools' persisted options-bar values (Fill on, the Rectangle's and the Triangle's radius, sides, star
/// ratio, weight, stroke width, the Rectangle's gear); the paints are the app's foreground and background.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
@@ -280,6 +281,9 @@ pub struct ShapeToolSettings {
pub fill_on: bool,
/// The Rectangle's corner radius.
pub corner_radius: f64,
/// The Triangle's corner radius, one for its three corners: the Triangle tool keeps its own, apart from the
/// Rectangle's (storytold/photocraft#13355).
pub triangle_corner_radius: f64,
/// A polygon's sides or a star's points.
pub sides: u32,
/// A star's inner over outer radius.
@@ -295,12 +299,13 @@ pub struct ShapeToolSettings {
}
impl Default for ShapeToolSettings {
/// Fill on, square corners, 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no
/// Fill on, square corners (Rectangle and Triangle), 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no
/// arrowheads, an unconstrained Rectangle.
fn default() -> Self {
ShapeToolSettings {
fill_on: true,
corner_radius: 0.0,
triangle_corner_radius: 0.0,
sides: 5,
star_ratio: 0.5,
line_weight: 3.0,
@@ -312,10 +317,11 @@ impl Default for ShapeToolSettings {
}
impl ShapeToolSettings {
/// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only.
/// The drag options of `kind` with these values; the gear's constraints apply to the Rectangle only, and a
/// Triangle takes its own corner radius.
pub fn drag_options(&self, kind: ShapeKind) -> ShapeDragOptions {
let options =
ShapeDragOptions::new(kind).corner_radius(self.corner_radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight);
let radius = if kind == ShapeKind::Triangle { self.triangle_corner_radius } else { self.corner_radius };
let options = ShapeDragOptions::new(kind).corner_radius(radius).sides(self.sides).star_ratio(self.star_ratio).line_weight(self.line_weight);
match kind {
ShapeKind::Rectangle => options.constraints(self.rect_box),
_ => options,
+35 -9
View File
@@ -26,6 +26,7 @@ use serde_json::{Value, json};
use super::ShapeKind;
use super::words::CreateShapeWords;
use crate::geometry::shape::{SIDES, ShapeGeometry};
use crate::ui::shape::RADIUS_RANGE;
/// The farthest the click may lie from the origin on either axis, in pixels: the same bound as
/// a side (PhotoCraft's `MAX_PX`, `shape_dialog.rs:19`, checked at `:111`).
@@ -52,7 +53,7 @@ pub struct CreateShapeOptions {
/// Width and height in document pixels (100 × 100 by default).
pub size: (f64, f64),
/// A rectangle's radii, top-left, top-right, bottom-right, bottom-left (from the tool's corner
/// radius).
/// radius). A triangle's one corner radius is all four.
pub radii: [f64; 4],
/// "Link radii": one radius for all four corners; on by default.
pub link_radii: bool,
@@ -102,7 +103,7 @@ impl CreateShapeOptions {
self
}
/// The tool's corner radius (all four corners), sides and star ratio.
/// The tool's corner radius (all four corners; a triangle's three), sides and star ratio.
#[must_use]
pub fn tool(mut self, corner_radius: f64, sides: u32, star_ratio: f64) -> Self {
self.radii = [corner_radius; 4];
@@ -149,8 +150,9 @@ struct Memory {
/// picked for a field is not remembered, storytold/photocraft#7786). Rectangle and Rounded
/// Rectangle: four radii Top Left, Top Right, Bottom Left, Bottom Right in two columns under one
/// "Radius" label, with the "Link radii" toggle between the columns (`LinkMode::Equal`, on by
/// default). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon drag
/// keeps ratio 1. Then "From Center".
/// default). Triangle: one "Radius" for its three corners (0 to 150,000 px, from the Triangle tool's own radius;
/// storytold/photocraft#13355). Polygon and Star: Sides (3–100) and Star Ratio (1–100 %, default 100); the Polygon
/// drag keeps ratio 1. Then "From Center".
/// - A width or height typed past [`CreateShapeOptions::SIZE`] keeps the nearest end and raises the range alert,
/// which the app opens from [`take_range_alert`](Self::take_range_alert) (#13358). A size set out of range
/// through automation shows [`CreateShapeWords::bad_size`] under the fields and disables OK; so does a click
@@ -214,7 +216,11 @@ fn answer(o: &CreateShapeOptions, words: &CreateShapeWords, units: &Units) -> Re
ShapeGeometry::Rect { rect, radii }
}
ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect },
ShapeKind::Triangle => ShapeGeometry::Triangle { rect },
ShapeKind::Triangle => {
let radius = o.radii[0];
let corner_radius = if radius.is_finite() { radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()) } else { 0.0 };
ShapeGeometry::Triangle { rect, corner_radius }
}
ShapeKind::Polygon | ShapeKind::Star => {
let ratio = if o.star_ratio.is_finite() { o.star_ratio.clamp(0.01, 1.0) } else { 1.0 };
ShapeGeometry::Polygon { rect, sides, star_ratio: ratio }
@@ -441,6 +447,20 @@ fn body(
}
});
}
if kind == ShapeKind::Triangle {
Field::new(Label::from(words.radius.as_str().to_owned())).show(ui, |ui, _| {
let radius = values.radii[0];
let field = NumberField::new(words.radius.as_str().to_owned(), Bind::given(Some(radius)))
.range(RADIUS_RANGE)
.unit(numbers.symbol(UnitKind::Pixels))
.commit_decimals(2);
if let Some(value) = field.show(ui).value().copied().flatten()
&& value != radius
{
values.radii = [value.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4];
}
});
}
if matches!(kind, ShapeKind::Polygon | ShapeKind::Star) {
Field::new(Label::from(words.sides.as_str().to_owned())).show(ui, |ui, _| {
let field = NumberField::new(words.sides.as_str().to_owned(), Bind::given(Some(f64::from(values.sides))))
@@ -487,7 +507,7 @@ impl StackDialog for CreateShapeDialog {
type Result = CreatedShape;
/// `width` and `height` in the unit their field shows, `widthUnit` and `heightUnit`, `radii` (top-left,
/// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, `sides`, `starRatio` (in percent, as its
/// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, a triangle's `cornerRadius` (pixels), `sides`, `starRatio` (in percent, as its
/// field shows it) and `fromCenter`.
fn json_fields(&self) -> Option<Value> {
let o = &self.options;
@@ -499,15 +519,16 @@ impl StackDialog for CreateShapeDialog {
"heightUnit": self.units[1],
"radii": o.radii,
"linkRadii": o.link_radii,
"cornerRadius": o.radii[0],
"sides": o.sides,
"starRatio": (o.star_ratio * 100.0).clamp(1.0, 100.0),
"fromCenter": o.from_center,
}))
}
/// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, and
/// Sides and Star Ratio only for a polygon or star; elsewhere they refuse as inactive. Linked radii take four
/// equal values.
/// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle,
/// `cornerRadius` only for a triangle, and Sides and Star Ratio only for a polygon or star; elsewhere they refuse
/// as inactive. Linked radii take four equal values.
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
self.recall(ctx);
let rejects = || FieldRefusal::Rejects(&value).message(field);
@@ -516,6 +537,7 @@ impl StackDialog for CreateShapeDialog {
let polygon = matches!(kind, ShapeKind::Polygon | ShapeKind::Star);
let shown = match field {
"radii" | "linkRadii" => rect,
"cornerRadius" => kind == ShapeKind::Triangle,
"sides" | "starRatio" => polygon,
_ => true,
};
@@ -545,6 +567,10 @@ impl StackDialog for CreateShapeDialog {
o.radii = radii.map(|radius| radius.clamp(0.0, MAX_RADIUS));
}
"linkRadii" => o.link_radii = value.as_bool().ok_or_else(rejects)?,
"cornerRadius" => {
let radius = value.as_f64().filter(|radius| radius.is_finite()).ok_or_else(rejects)?;
o.radii = [radius.clamp(*RADIUS_RANGE.start(), *RADIUS_RANGE.end()); 4];
}
"sides" => {
let sides = value.as_f64().ok_or_else(rejects)?;
o.sides = sides.round().clamp(f64::from(*SIDES.start()), f64::from(*SIDES.end())) as u32;
+3 -2
View File
@@ -115,7 +115,8 @@ impl Default for BoxConstraints {
pub struct ShapeDragOptions {
/// Which shape the drag draws.
pub kind: ShapeKind,
/// The Rectangle's corner radius; over 0 draws four equal radii.
/// The Rectangle's corner radius, over 0 drawing four equal radii; for a Triangle, the radius of its three
/// corners.
pub corner_radius: f64,
/// The polygon's sides or the star's points, in [`SIDES`](crate::geometry::shape::SIDES).
pub sides: u32,
@@ -136,7 +137,7 @@ impl ShapeDragOptions {
ShapeDragOptions { kind, ..ShapeDragOptions::default() }
}
/// The Rectangle's corner radius.
/// The Rectangle's or the Triangle's corner radius.
#[must_use]
pub fn corner_radius(mut self, radius: f64) -> Self {
self.corner_radius = radius;
+2 -2
View File
@@ -150,7 +150,7 @@ impl ShapeDragTool {
/// when a side is under 1 px: [`box_drag`] for the box kinds under the options' constraints, ⇧
/// toggling Square and ⌥ From Center (Rectangle with four equal radii when
/// `corner_radius` > 0, Rounded Rectangle always with them, Triangle filling the box (⇧: the equilateral
/// triangle in the square's circle), Polygon and
/// triangle in the square's circle) with its corners rounded by `corner_radius`, Polygon and
/// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧),
/// [`line_drag`] for a Line (weight at least 1, ⇧ snapping the end by [`line_shift`]), and
/// [`RadialFrame::drag`] in the radial frame.
@@ -194,7 +194,7 @@ impl ShapeDragTool {
ShapeKind::Rectangle => ShapeGeometry::Rect { rect, radii: [0.0; 4] },
ShapeKind::RoundedRectangle => ShapeGeometry::Rect { rect, radii },
ShapeKind::Ellipse => ShapeGeometry::Ellipse { rect },
ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect } },
ShapeKind::Triangle => ShapeGeometry::Triangle { rect: if rule.square { equilateral_in(rect) } else { rect }, corner_radius: radii[0] },
ShapeKind::Polygon => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: 1.0 },
ShapeKind::Star => ShapeGeometry::Polygon { rect, sides: drag.sides, star_ratio: o.star_ratio },
ShapeKind::Custom | ShapeKind::Line => ShapeGeometry::Custom { rect, keep_proportions: mods.shift },
@@ -49,7 +49,7 @@ impl TransformPreset {
/// How the transform resamples the moving pixels: PhotoCraft's three choices (LC11). The app maps
/// them to its engine; [`id`](Self::id) gives PhotoCraft's ids.
#[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 Interpolation {
@@ -100,7 +100,7 @@ pub enum TransformChoice {
/// Free Transform's persisted section: the app keeps it with its preferences. Unknown fields are
/// ignored, missing ones take their defaults.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)]
#[serde(default, rename_all = "camelCase")]
#[non_exhaustive]
pub struct TransformSettings {
+10 -4
View File
@@ -493,7 +493,8 @@ pub struct TransformBox<'a> {
#[prop]
round_handles: bool,
/// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the
/// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's.
/// theme's (`size.handle.md`), as does a side that is zero, negative or not finite. A handle's reach grows with a
/// larger side and stays at least the theme's.
#[prop(quantity = "points, from the host's handle size preference")]
handle_side: Option<f32>,
/// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends
@@ -585,14 +586,19 @@ impl<'a> TransformBox<'a> {
self.color.map_or(StrokeColor::from(theme), StrokeColor::from)
}
/// The host's handle side when it is a finite side above zero; `None` for none or any other value.
fn host_handle_side(&self) -> Option<f32> {
self.handle_side.filter(|side| side.is_finite() && *side > 0.0)
}
/// The side of a corner or side handle: the host's, else the theme's.
fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 {
self.handle_side.unwrap_or(style.handle.side)
self.host_handle_side().unwrap_or(style.handle.side)
}
/// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle.
fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 {
self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES))
self.host_handle_side().map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES))
}
/// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place.
@@ -842,7 +848,7 @@ impl<'a> TransformBox<'a> {
let suspend = suspend_key(snap.as_ref());
for (reference, part) in self.pointer_parts() {
let Some(result) = cx.part_if_declared(reference) else { continue };
let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered));
let (press, hover) = (result.press, cx.hover_pos(reference));
let mods = self.mods.unwrap_or(press.mods);
let acting = drag_mods(mods, suspend);
if let Some(pos) = hover
+301 -5
View File
@@ -1,12 +1,13 @@
//! `BezierOverlay`: the pure path operations, and the overlay's pointer, keyboard and tools through the public API.
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::ui::{
AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef,
PathEdit, PathSelection, PathTool, SegmentMark,
};
use craft_ui::canvas::{Canvas, Guide, ToolHost, tool_pass};
use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHost, tool_pass};
use craft_ui::canvas_controls::Guides;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft_ui::primitives::cancel_press_of;
@@ -176,6 +177,7 @@ struct State {
paths: Vec<EditPath>,
selection: PathSelection,
guides: Vec<Guide>,
snap: Option<Snap>,
tool: BezierTool,
handles: HandlesShown,
anchors: AnchorsShown,
@@ -199,6 +201,8 @@ struct State {
tool_clicks: usize,
/// The anchor tool the canvas runs under the overlay, if any.
canvas_tool: Option<PathTool>,
/// The app-owned momentary navigation set, enabled by tests that exercise Space-to-Hand routing.
momentary: Option<Momentary>,
/// Passes in which that tool ran a gesture.
tool_gestures: usize,
}
@@ -246,6 +250,7 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
paths,
selection: PathSelection::default(),
guides: Vec::new(),
snap: None,
tool: BezierTool::Direct,
handles: HandlesShown::Selected,
anchors: AnchorsShown::All,
@@ -264,6 +269,7 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
lone_selects: 0,
tool_clicks: 0,
canvas_tool: None,
momentary: None,
tool_gestures: 0,
}));
let shown = Rc::clone(&state);
@@ -285,6 +291,10 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
let canvas_id = ui.scope_id().with("document canvas");
let canvas = Canvas::new("Document").id(canvas_id).view(view).precise_cursors(st.precise);
let canvas = if st.pans { canvas.document(Size::new(4000.0, 4000.0)) } else { canvas };
let canvas = match &st.snap {
Some(snap) => canvas.snap(snap.clone()),
None => canvas,
};
let mut reply = None;
let canvas = canvas.show(ui, |ui, body| {
// The guides lie under the paths: a stack position hides the levels of the ones below it.
@@ -298,18 +308,25 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
.segment_mark(st.segment_mark)
.show_at(ui, body.rect);
if let (Some(tool), Some(pass)) = (st.canvas_tool, tool_pass(&body.env)) {
reply = Some(ToolHost::new().run(ui, &pass, &mut AnchorTool::new(tool)));
let mut host = ToolHost::new();
if let Some(momentary) = st.momentary.as_mut() {
host = host.momentary(momentary);
}
reply = Some(host.run(ui, &pass, &mut AnchorTool::new(tool)));
}
output
});
if canvas.output.click_at().is_some() {
st.tool_clicks += 1;
}
if let Some(reply) = reply {
let tool_view = if let Some(reply) = reply {
st.tool_gestures += usize::from(reply.gesture.is_some());
}
reply.view
} else {
None
};
if st.pans {
st.view = canvas.output.view.or(st.view);
st.view = tool_view.or(canvas.output.view).or(st.view);
}
let Some(output) = canvas.inner else { return };
st.id = output.edit.response.id;
@@ -1416,3 +1433,282 @@ fn a_cancelled_press_reports_nothing_on_release() {
assert_eq!(st.changes.len(), changes, "{:?}", st.changes);
assert_eq!(st.paths, before);
}
// Add Anchor owns one drag while Space temporarily translates the new anchor and its handles. Letting Space go
// resumes pulling the handles from that translated anchor; the canvas never takes this owned drag to pan.
#[trial]
fn space_moves_the_pulled_anchor_then_release_resumes_its_handles() {
let space_key = |pressed| egui::Event::Key {
key: egui::Key::Space,
physical_key: Some(egui::Key::Space),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6;
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(0.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(0.0, 30.0));
h.move_to(pulled_at);
let (pulled, view) = {
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
let knot = st.paths[0].subpaths[0].knots[1];
assert!(knot.anchor.distance(p(110.0, 60.0)) < 1e-3);
assert!(close(knot.out_ctrl - knot.anchor, Vec2::new(0.0, 60.0)) && knot.smooth);
(knot, st.view.expect("the canvas showed"))
};
h.fixture.frame(vec![space_key(true)]);
{
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots[1], pulled, "Space down alone must not jump the anchor or handles");
}
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(pulled_at + vec2(15.0, 10.0));
h.move_to(moved_at);
let moved = {
let st = h.state.borrow();
let knot = st.paths[0].subpaths[0].knots[1];
let by = Vec2::new(30.0, 20.0);
assert!(close(knot.anchor - pulled.anchor, by), "the held key moves the new anchor with the pointer: {knot:?}");
assert!(
close(knot.out_ctrl - pulled.out_ctrl, by) && close(knot.in_ctrl - pulled.in_ctrl, by),
"both handles travel with the anchor: {knot:?}"
);
assert!(knot.smooth);
assert_eq!(st.view.expect("the canvas showed").center, view.center, "an overlay-owned drag must not turn into a pan");
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "Space adds no second knot");
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert!(!st.seen.contains(&Seen::Commit) && !st.seen.contains(&Seen::Cancel));
knot
};
h.fixture.frame(vec![space_key(false)]);
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space up alone preserves the current geometry");
let end = moved_at + vec2(20.0, 10.0);
h.move_to(moved_at + vec2(10.0, 5.0));
h.move_to(end);
{
let st = h.state.borrow();
let knot = st.paths[0].subpaths[0].knots[1];
assert!(knot.anchor.distance(moved.anchor) < 1e-6, "released Space leaves the translated anchor in place");
assert!(knot.out_ctrl.distance(view.to_doc(end)) < 1e-6, "the handle follows the pointer again");
assert!(close(knot.in_ctrl - knot.anchor, -(knot.out_ctrl - knot.anchor)) && knot.smooth);
assert!(!close(knot.out_ctrl - knot.anchor, moved.out_ctrl - moved.anchor), "pulling resumes rather than freezing the handles");
assert_eq!(st.view.expect("the canvas showed").center, view.center);
}
h.release_at(end);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)));
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
assert!(st.inserts.is_empty(), "this drag is not an Insert-key report");
drop(st);
space_before_the_first_movement_translates_from_the_press(space_key);
space_release_preserves_raw_geometry_until_constraints_change(space_key);
space_release_applies_only_an_alt_modifier_still_held(space_key);
}
fn space_before_the_first_movement_translates_from_the_press(space_key: fn(bool) -> egui::Event) {
// Space after the press but before the first movement translates from the press, not from a first pulled handle.
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let to = at + vec2(30.0, 20.0);
h.press_at(at);
h.fixture.frame(vec![space_key(true)]);
h.move_to(to);
let translated = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(translated.anchor.distance(p(140.0, 80.0)) < 1e-3, "the first Space move includes all travel from the press: {translated:?}");
assert!(near(translated.in_ctrl, translated.anchor) && near(translated.out_ctrl, translated.anchor));
h.fixture.frame(vec![space_key(false)]).frame(Vec::new());
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], translated);
let end = to + vec2(20.0, 10.0);
h.move_to(end);
let resumed = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(resumed.anchor, translated.anchor) && resumed.out_ctrl.distance(h.state.borrow().view.unwrap().to_doc(end)) < 1e-6);
h.release_at(end);
assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
}
fn space_release_preserves_raw_geometry_until_constraints_change(space_key: fn(bool) -> egui::Event) {
// A real canvas Snap would pull x=160 to the guide at x=165. Space keeps raw translation; release alone must
// not apply that snap, including later stationary passes. Moving or changing Shift/Alt still reads constraints.
let mut targets = SnapTargets::new();
targets.add(SnapTarget::new(craft_behavior::Axis::Y, 165.0, SnapKind::Guide));
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
st.snap = Some(Snap::new(std::sync::Arc::new(targets), SnapOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(20.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(10.0, 30.0));
h.move_to(pulled_at);
let pulled = h.state.borrow().paths[0].subpaths[0].knots[1];
h.fixture.frame(vec![space_key(true)]);
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(moved_at);
let moved = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(moved.anchor, pulled.anchor + Vec2::new(30.0, 20.0)));
assert!(moved.out_ctrl.distance(p(160.0, 140.0)) < 1e-3 && near(moved.in_ctrl, pulled.in_ctrl + Vec2::new(30.0, 20.0)));
h.fixture.frame(vec![space_key(false)]).frame(Vec::new()).frame(Vec::new());
h.move_to(moved_at);
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "no delayed stationary snap after Space release");
// Modifier-only frames travel through the real input/press route: no synthetic PathEdit calls.
h.fixture.hold(egui::Modifiers::SHIFT).frame(Vec::new());
let locked = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(
near(locked.anchor, moved.anchor) && locked.out_ctrl.distance(p(140.0, 140.0)) < 1e-3,
"stationary Shift still locks the handle: {locked:?}"
);
h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new());
let snapped = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(snapped.out_ctrl.distance(p(165.0, 140.0)) < 1e-3, "releasing Shift reevaluates the actual enabled guide snap: {snapped:?}");
h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new());
let alone = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(alone.in_ctrl, snapped.in_ctrl) && !alone.smooth, "stationary Alt still breaks the handle pair: {alone:?}");
let end = moved_at + vec2(20.0, 10.0);
h.move_to(end);
let resumed = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(resumed.anchor, moved.anchor) && resumed.out_ctrl.distance(p(180.0, 150.0)) < 1e-3 && near(resumed.in_ctrl, alone.in_ctrl));
h.fixture.hold(egui::Modifiers::NONE);
h.release_at(end);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
}
fn space_release_applies_only_an_alt_modifier_still_held(space_key: fn(bool) -> egui::Event) {
// Alt held at Space-up breaks the pair, but an Alt tap released entirely during Space must not latch.
for keep_alt in [true, false] {
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(0.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(0.0, 30.0));
h.move_to(pulled_at);
h.fixture.frame(vec![space_key(true)]);
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(moved_at);
let moved = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(moved.smooth, "the translated pair starts smooth");
h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new());
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space keeps translation priority over Alt");
if !keep_alt {
h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new());
}
let modifiers = if keep_alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE };
let space_up = egui::Event::Key { key: egui::Key::Space, physical_key: Some(egui::Key::Space), pressed: false, repeat: false, modifiers };
h.fixture.frame(vec![space_up]).frame(Vec::new());
let released = h.state.borrow().paths[0].subpaths[0].knots[1];
assert_eq!((released.anchor, released.in_ctrl, released.out_ctrl), (moved.anchor, moved.in_ctrl, moved.out_ctrl));
assert_eq!(released.smooth, !keep_alt, "only Alt still held at Space-up breaks the pair");
h.release_at(moved_at);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots[1], released, "mouse-up without travel commits the same geometry and smooth state");
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
}
}
// Without an overlay-owned press, the same held key still gives the canvas its ordinary hand drag.
#[trial]
fn space_still_pans_when_add_anchor_has_no_drag() {
let space_key = |pressed| egui::Event::Key {
key: egui::Key::Space,
physical_key: Some(egui::Key::Space),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let (before, paths, selection) = {
let st = h.state.borrow();
(st.view.expect("the canvas showed"), st.paths.clone(), st.selection.clone())
};
// This empty corner is clear of both paths. Drag toward the document interior, away from the origin clamp.
let at = before.rect.right_bottom() - vec2(24.0, 24.0);
h.move_to(at);
h.fixture.frame(vec![space_key(true)]);
h.drag(at, vec2(-60.0, -40.0));
h.fixture.frame(vec![space_key(false)]).settle();
let st = h.state.borrow();
let after = st.view.expect("the canvas showed");
assert!(
after.center.x > before.center.x && after.center.y > before.center.y && (after.center - before.center).hypot() > 1.0,
"ordinary Space still pans: {:?} -> {:?}",
before.center,
after.center
);
assert_eq!(st.paths, paths, "panning does not edit the paths");
assert_eq!(st.selection, selection);
assert!(st.changes.is_empty() && st.inserts.is_empty() && st.deletes.is_empty());
assert!(!st.seen.contains(&Seen::Begin) && !st.seen.contains(&Seen::Commit));
}
// The translated public edit mirrors around the translated anchor and refuses nonfinite resulting geometry
// without partially inserting a knot. The original zero-translation constructor remains covered above.
#[trial]
fn a_translated_pull_mirrors_around_its_anchor_and_refuses_nonfinite_geometry() {
let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false));
let mut path = straight();
let by = Vec2::new(12.0, 7.0);
let out = p(80.0, 40.0);
assert!(PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path));
let knot = path.subpaths[0].knots[1];
assert!(near(knot.anchor, p(50.0, 0.0) + by) && near(knot.out_ctrl, out) && knot.smooth);
assert!((knot.in_ctrl - knot.anchor + (knot.out_ctrl - knot.anchor)).hypot() < 1e-6, "the mirror is about the moved anchor: {knot:?}");
let huge = f64::MAX * 0.75;
let far_x = f64::MAX * 0.25;
let far = ops_path(EditSubpath::new(vec![Knot::corner(p(far_x, 0.0)), Knot::corner(p(far_x, 100.0))], false));
let at = far.subpaths[0].segment(0).unwrap().eval(0.5);
assert!(at.x.is_finite() && at.y.is_finite(), "the input curve is finite before translation");
for (why, mut path, by, out) in [
("NaN offset", straight(), Vec2::new(f64::NAN, 0.0), p(50.0, 30.0)),
("infinite offset", straight(), Vec2::new(0.0, f64::INFINITY), p(50.0, 30.0)),
("overflowing anchor", far, Vec2::new(f64::MAX, 0.0), p(0.0, 0.0)),
("overflowing mirrored handle", straight(), Vec2::new(huge, 0.0), p(-huge, 0.0)),
] {
let before = path.clone();
assert!(!PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path), "{why}");
assert_eq!(path, before, "{why}: a refused edit changes nothing");
}
}
+50 -3
View File
@@ -1,5 +1,5 @@
//! `PaintBar`: which members each tool disables, the smoothing options, the gestures, the combinations list, what the
//! load swatch shows and a click on its menu.
//! load swatch shows, a click on its menu and the percents each field holds.
use std::cell::RefCell;
use std::rc::Rc;
@@ -13,6 +13,7 @@ use craft_ui::contract::{Entry, ShowContainer as _};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, Room, trial};
use craft_ui::text::RangeAlert;
use egui::{Color32, ColorImage, Key, Modifiers, Pos2, Shape, TextureId};
struct Host {
@@ -21,16 +22,18 @@ struct Host {
edits: Vec<EditEvent<PaintValues<u32>>>,
/// How many passes reported Clean Brush.
cleans: u32,
/// The range alerts the passes reported.
alerts: Vec<RangeAlert>,
}
fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintValues<u32>)) -> (Fixture, Rc<RefCell<Host>>) {
let mut values = PaintValues::new(0u32);
prepare(&mut values);
let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0 }));
let host = Rc::new(RefCell::new(Host { values, eraser, edits: Vec::new(), cleans: 0, alerts: Vec::new() }));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let mut host = shown.borrow_mut();
let Host { values, eraser, edits, cleans } = &mut *host;
let Host { values, eraser, edits, cleans, alerts } = &mut *host;
let modes = [Entry::new(0u32, "Normal"), Entry::new(1u32, "Multiply")];
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
let mut bar = PaintBar::new(tool, &mut *values).modes(&modes);
@@ -40,6 +43,7 @@ fn harness(tool: PaintTool, eraser: EraserMode, prepare: impl FnOnce(&mut PaintV
let out = bar.show(ui);
edits.extend(out.edits);
*cleans += u32::from(out.mixer_clean);
alerts.extend(out.out_of_range);
});
});
// The options bar spans an application window; its members still run past it, and the bar scrolls.
@@ -188,3 +192,46 @@ fn the_load_swatch_shows_each_mixer_load() {
assert_eq!(load_swatch(&mut fixture), (value, pictures), "{load:?}");
}
}
fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
let field = fixture.by_label(label).unwrap_or_else(|| panic!("the bar shows {label}"));
fixture.click(&field);
fixture.key(Key::A, Modifiers::COMMAND);
fixture.type_text(text);
fixture.key(Key::Enter, Modifiers::NONE);
fixture.settle();
}
/// Opacity and Flow hold 1 to 100 % on every tool that shows them (photocraft#16809): a typed 0 or -5 keeps 1 % and
/// 150 keeps 100 %, each reported once with a range that starts at 1 %. Smoothing still takes 0 with no alert.
#[trial]
fn opacity_and_flow_hold_one_to_a_hundred_percent_and_smoothing_still_takes_zero() {
let fields = [
(PaintTool::Brush, "Opacity"),
(PaintTool::Brush, "Flow"),
(PaintTool::Eraser, "Opacity"),
(PaintTool::Eraser, "Flow"),
(PaintTool::Pencil, "Opacity"),
];
for (tool, label) in fields {
for (typed, kept) in [("0", 0.01), ("-5", 0.01), ("150", 1.0)] {
let (mut fixture, host) = harness(tool, EraserMode::Brush, |v| {
v.opacity = 0.5;
v.flow = 0.5;
});
type_into(&mut fixture, label, typed);
let host = host.borrow();
let value = if label == "Opacity" { host.values.opacity } else { host.values.flow };
assert_eq!(value, kept, "{tool:?} {label}: {typed} keeps {kept}");
assert_eq!(host.alerts.len(), 1, "{tool:?} {label}: {typed} is reported once: {:?}", host.alerts);
assert_eq!(host.alerts[0].range, 1.0..=100.0, "{tool:?} {label}: the alert names 1 to 100 %");
}
}
let (mut fixture, host) = harness(PaintTool::Brush, EraserMode::Brush, |v| v.smoothing.amount = 0.5);
page_to_end(&mut fixture);
type_into(&mut fixture, "Smoothing", "0");
let host = host.borrow();
assert_eq!(host.values.smoothing.amount, 0.0, "Smoothing takes 0");
assert!(host.alerts.is_empty(), "and reports nothing: {:?}", host.alerts);
}
+60
View File
@@ -285,3 +285,63 @@ fn a_fixed_size_typed_past_its_range_keeps_the_end_and_reports_it_once_and_an_em
assert_eq!(host.borrow().value.fixed, (None, Some(50.0)), "an emptied field is empty");
assert_eq!(host.borrow().alerts.len(), 1, "an emptied field reports nothing");
}
struct BarHost {
settings: ShapeToolSettings,
look: ShapeAppearance,
alerts: Vec<RangeAlert>,
}
/// The Triangle tool's bar shows a Radius of its own (storytold/photocraft#13355): it starts from
/// `triangle_corner_radius`, not the Rectangle's radius, reports a typed value as `CornerRadius`, and keeps a value
/// past 0–150,000 px at the end with one range alert. The Ellipse's bar has no Radius.
#[trial]
#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")]
fn the_triangle_bar_shows_its_own_radius() {
let kind = Rc::new(RefCell::new(ShapeKind::Triangle));
let mut settings = ShapeToolSettings::default();
settings.corner_radius = 7.0;
settings.triangle_corner_radius = 15.0;
let host = Rc::new(RefCell::new(BarHost { settings, look: ShapeAppearance::new(Paint::None, Paint::None, 0.0), alerts: Vec::new() }));
let (shown, shown_kind) = (Rc::clone(&host), Rc::clone(&kind));
let mut fixture = Fixture::new(move |ui| {
let mut held = shown.borrow_mut();
let BarHost { settings, look, alerts } = &mut *held;
let kind = *shown_kind.borrow();
let out = Bar::new("Shape options", BarKind::Options).show(ui, |ui, _| ShapeBar::new(kind, settings, look, 72.0).show(ui)).inner;
let Some(out) = out else { return };
if let Some(ShapeChange::CornerRadius(radius)) = out.events.iter().rev().find_map(|event| event.value()) {
settings.triangle_corner_radius = *radius;
}
alerts.extend(out.out_of_range);
});
fixture.settle();
let field = fixture.by_label("Radius").expect("the Triangle's Radius");
let value = fixture.tree().value_of(field.node).map(str::to_owned);
assert!(value.as_deref().is_some_and(|v| v.starts_with("15")), "the Triangle's own radius, not the Rectangle's 7: {value:?}");
type_into(&mut fixture, "Radius", "12");
assert_eq!(host.borrow().settings.triangle_corner_radius, 12.0);
assert_eq!(host.borrow().settings.corner_radius, 7.0, "the Rectangle's radius is not touched");
assert!(host.borrow().alerts.is_empty(), "12 is in range");
type_into(&mut fixture, "Radius", "200000");
assert_eq!(host.borrow().settings.triangle_corner_radius, 150_000.0, "a radius past the range keeps its end");
assert_eq!(host.borrow().alerts.len(), 1, "the clamp is reported once");
*kind.borrow_mut() = ShapeKind::Ellipse;
fixture.settle();
assert!(fixture.by_label("Radius").is_none(), "an Ellipse has no Radius");
}
/// The tool settings keep the Triangle's radius apart and read it from settings saved before it existed as 0.
#[trial]
fn the_triangle_radius_is_saved_with_the_tool_settings() {
let mut settings = ShapeToolSettings::default();
assert_eq!(settings.triangle_corner_radius, 0.0, "sharp corners by default");
settings.triangle_corner_radius = 25.0;
let saved = serde_json::to_value(settings).expect("settings serialize");
assert_eq!(saved["triangleCornerRadius"], serde_json::json!(25.0));
let back: ShapeToolSettings = serde_json::from_value(saved).expect("settings read back");
assert_eq!(back.triangle_corner_radius, 25.0);
let old: ShapeToolSettings = serde_json::from_value(serde_json::json!({"cornerRadius": 4.0})).expect("older settings read");
assert_eq!((old.corner_radius, old.triangle_corner_radius), (4.0, 0.0));
}
+121 -1
View File
@@ -1,6 +1,6 @@
//! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point.
use craft_behavior::kurbo::{Point, Rect, Vec2};
use craft_behavior::kurbo::{ParamCurve as _, Point, Rect, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::geometry::shape::ShapeGeometry;
use craft_draw::ui::shape::VectorMode;
@@ -373,3 +373,123 @@ fn create_shape_alerts_once_for_a_size_typed_past_its_range() {
assert!(take(&host).is_none(), "{kind:?}: a width in range raises no alert");
}
}
/// The ends of each piece of `shape`'s outline, in order: for a rounded triangle, where each arc meets an edge.
fn anchors(shape: &ShapeGeometry) -> Vec<Point> {
shape.to_path(0.1).elements().iter().filter_map(|el| el.end_point()).collect()
}
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-3
}
/// A triangle's corner radius rounds each corner with an arc tangent to both edges (storytold/photocraft#13355): radius
/// 20 in the box 400,300 to 600,400 meets the edges at the six points PhotoCraft's engine draws, and the arc at the
/// right-angled apex has its middle 20 px from its centre.
#[trial]
fn a_triangle_corner_radius_rounds_each_corner_tangent_to_its_edges() {
let shape = ShapeGeometry::Triangle { rect: Rect::new(400.0, 300.0, 600.0, 400.0), corner_radius: 20.0 };
let want = [(485.858, 314.142), (514.142, 314.142), (565.858, 365.858), (551.716, 400.0), (448.284, 400.0), (434.142, 365.858)];
let got = anchors(&shape);
assert_eq!(got.len(), want.len(), "two points per rounded corner: {got:?}");
for (g, w) in got.iter().zip(want) {
assert!(near(*g, Point::new(w.0, w.1)), "{got:?}");
}
let apex = shape.to_path(0.1).segments().next().expect("the apex arc");
let middle = apex.eval(0.5);
// The apex's edges meet at 90°: the arc's centre lies 20·√2 below the apex, its middle 20 px above that.
let centre = Point::new(500.0, 300.0 + 20.0 * 2f64.sqrt());
assert!(((middle - centre).hypot() - 20.0).abs() < 0.01, "the arc is circular: its middle is {middle:?}");
assert_eq!(shape.bounds(), Rect::new(400.0, 300.0, 600.0, 400.0), "the bounds stay the box");
}
/// A radius larger than the triangle allows is capped by the shape: each arc ends at most halfway along an edge, the
/// outline stays inside the box, and no number is lost. Radius 0 keeps the sharp corners.
#[trial]
fn a_triangle_radius_past_what_the_shape_holds_is_capped_and_zero_is_sharp() {
let rect = Rect::new(0.0, 0.0, 200.0, 100.0);
for radius in [1.0e6, f64::INFINITY, f64::NAN, -5.0, 0.0] {
let got = anchors(&ShapeGeometry::Triangle { rect, corner_radius: radius });
assert!(got.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{radius}: {got:?}");
assert!(got.iter().all(|p| rect.inflate(1e-9, 1e-9).contains(*p)), "{radius}: the outline stays in the box: {got:?}");
if radius.is_finite() && radius > 0.0 {
assert_eq!(got.len(), 6, "{radius}: still two points per corner");
// The slanted edges (about 141 px) are shorter than the 200 px base: the arcs at their two ends meet
// halfway along each of them.
for middle in [Point::new(50.0, 50.0), Point::new(150.0, 50.0)] {
assert_eq!(got.iter().filter(|p| near(**p, middle)).count(), 2, "{radius}: capped at half a slanted edge: {got:?}");
}
} else {
assert_eq!(got, vec![Point::new(100.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)], "{radius}: sharp corners");
}
}
}
/// A Triangle drag takes the Triangle's own corner radius from the tool settings, not the Rectangle's, and a
/// Rectangle drag keeps the Rectangle's.
#[trial]
#[allow(clippy::field_reassign_with_default, reason = "ShapeToolSettings is non_exhaustive: no struct literal outside its crate")]
fn a_triangle_drag_takes_the_triangle_radius_from_the_settings() {
let mut settings = craft_draw::ui::shape::ShapeToolSettings::default();
settings.corner_radius = 7.0;
settings.triangle_corner_radius = 20.0;
let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Triangle));
shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE);
match shapes.committed() {
Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 20.0),
other => panic!("a triangle: {other:?}"),
}
let mut shapes = Shapes::new(settings.drag_options(ShapeKind::Rectangle));
shapes.drag(PRESS, PRESS + Vec2::new(60.0, 40.0), Modifiers::NONE);
match shapes.committed() {
Some(ShapeGeometry::Rect { radii, .. }) => assert_eq!(radii, [7.0; 4], "the Rectangle keeps its own radius"),
other => panic!("a rectangle: {other:?}"),
}
}
/// Create Triangle starts from the tool's radius, shows it in one Radius field and answers it on OK; automation sets
/// it as `cornerRadius`, kept to 0–150,000 px, and the field is inactive for another kind.
#[trial]
fn create_triangle_takes_one_corner_radius() {
let ctx = egui::Context::default();
let mut host = DialogHost::new();
let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled();
let id = host.open(CreateShapeDialog::new(options));
assert_eq!(fields(&host, id)["cornerRadius"], json!(15.0), "the dialog starts from the tool's radius");
let shape = confirm(&mut host, &ctx).expect("OK answers the triangle");
assert_eq!(shape.geometry, ShapeGeometry::Triangle { rect: Rect::new(10.0, 20.0, 110.0, 120.0), corner_radius: 15.0 });
let id = open_create(&mut host, ShapeKind::Triangle);
assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(200000)), Ok(()));
assert_eq!(fields(&host, id)["cornerRadius"], json!(150000.0), "a radius past the range keeps its end");
assert!(host.set_json_field(&ctx, id, "cornerRadius", json!("abc")).is_err(), "text that is not a number is refused");
assert_eq!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)), Ok(()));
match confirm(&mut host, &ctx).map(|shape| shape.geometry) {
Some(ShapeGeometry::Triangle { corner_radius, .. }) => assert_eq!(corner_radius, 8.0),
other => panic!("a triangle: {other:?}"),
}
let id = open_create(&mut host, ShapeKind::Rectangle);
assert!(host.set_json_field(&ctx, id, "cornerRadius", json!(8)).is_err(), "a rectangle has no single corner radius");
assert!(host.cancel::<CreateShapeDialog>(&ctx));
// The field itself: one Radius field for the triangle, typed values taken.
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(egui::Vec2::new(1200.0, 900.0));
let options = CreateShapeOptions::initial(ShapeKind::Triangle, Point::new(10.0, 20.0)).tool(15.0, 5, 1.0).recalled();
host.borrow_mut().open(CreateShapeDialog::new(options));
fixture.settle();
let names: Vec<String> =
fixture.by_role(Role::SPIN_BUTTON).into_iter().filter_map(|field| fixture.tree().name_of(field.node).map(str::to_owned)).collect();
assert_eq!(names.iter().filter(|name| name.as_str() == "Radius").count(), 1, "one Radius field: {names:?}");
assert!(!names.iter().any(|name| name == "Top Left" || name == "Sides"), "no rectangle radii or sides: {names:?}");
let radius =
fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|field| fixture.tree().name_of(field.node) == Some("Radius")).expect("the Radius field");
fixture.click(&radius).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("30");
fixture.key(Key::Tab, Modifiers::NONE).settle();
let radii = host.borrow().get::<CreateShapeDialog>().map(|dialog| dialog.options().radii);
assert_eq!(radii, Some([30.0; 4]), "the typed radius is the triangle's");
}
+37
View File
@@ -1678,6 +1678,43 @@ fn a_host_handle_side_sets_the_drawn_handle_square() {
assert!(large > small, "a larger side draws a larger square: {large} against {small}");
}
/// A host handle side that is zero, negative or not finite draws the theme's handle and keeps the theme's reach.
#[trial]
fn an_unusable_host_handle_side_uses_the_themes() {
let corner_side = |side: Option<f32>| {
let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side);
let corner = h.screen(Point::new(RECT.x1, RECT.y1));
h.fixture
.frame_shapes()
.iter()
.filter_map(|shape| match shape {
Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()),
_ => None,
})
.collect::<Vec<f32>>()
};
let theme = corner_side(None);
assert!(!theme.is_empty(), "the theme's corner handle is drawn");
// 3 points in from the bottom right corner on both axes: inside the theme's handle reach.
let near = Point::new(RECT.x1 - 3.0, RECT.y1 - 3.0);
for side in [0.0, -6.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert_eq!(corner_side(Some(side)), theme, "a side of {side} draws the theme's corner handle");
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.rules = free_rules();
config.handle_side = Some(side);
});
hover(&mut h, near);
assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} keeps the theme's reach");
// Far outside the theme's reach: an infinite side must not widen the reach to the whole canvas.
let mut far = harness(BoxState::from_rect(RECT), |config| {
config.rules = free_rules();
config.handle_side = Some(side);
});
hover(&mut far, Point::new(RECT.x1 + 60.0, RECT.y1 + 60.0));
assert_ne!(far.host.borrow().hovered, Some(BoxPart::Corner(2)), "a side of {side} does not widen the reach");
}
}
/// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it.
#[trial]
fn a_press_just_inside_a_large_handles_edge_grabs_it() {
Loaded 100 of 655 files, more files were not shown because too many files have changed in this diff. Show more