From 20368232acacc11bb5b83817ca9a62be80c6a6a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 08:56:01 -0800 Subject: [PATCH 001/490] linesweeper: nearly coincident segments no longer loop forever at one y When nearly coincident segments do not compare transitively, handling one intersection queued another pair at the same y again, and the pairs cycled forever through the same positions while segs_needing_positions grew. Five circles of radius 50, each moved by (7e-7, 3.5e-7), hang Sweeper::next_line this way. next_line now handles a pair at most once per sweep line for each pair of positions the two segments hold. A repeat is queued at the pair's next order change instead, when that comes before both segments end. The repeated_intersections_at_one_y test sweeps the five circles. Test builds panic after n^4 intersection events on one sweep line, so the test fails instead of hanging without the change. README.craft.md, SOURCE.json and NOTICE record the change as a local patch. --- NOTICE | 6 +- vendor/linesweeper/README.craft.md | 20 ++++--- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/sweep/sweep_line.rs | 69 +++++++++++++++++++++- 4 files changed, 88 insertions(+), 13 deletions(-) diff --git a/NOTICE b/NOTICE index bd88d43e7a..70c163182c 100644 --- a/NOTICE +++ b/NOTICE @@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and no file changed. Its manifest names Joe Neeman +vendor/linesweeper with its upstream license files and one local patch. 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 and the files -left out. +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local +change and the files left out. Platform lifecycle source provenance diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..3bc5964f7f 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,21 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file +in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local patch. + +## Local patches + +| File | Change | +|---|---| +| `src/sweep/sweep_line.rs` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions the two segments hold. A pair queued again at the same `y` and positions is queued at the pair's next order change instead, when that comes before both segments end. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..3bee04a7b7 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -62,7 +64,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "e9c93858dc54dad40f2c4d4965243b9fc19a5ec64eb8bcd561aedb5c7596bf08" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index b4b1883e29..de6ae66ba9 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -7,6 +7,8 @@ use std::cell::{RefCell, RefMut}; #[cfg(feature = "slow-asserts")] use std::ops::DerefMut; +use rustc_hash::FxHashSet; + use crate::{ curve::{self, CurveInteraction, CurveOrder, Order}, geom::Segment, @@ -433,8 +435,48 @@ impl<'segs> Sweeper<'segs> { } // Process all the intersection events at this y. + // + // Craft patch (repeated intersection): when nearly coincident segments + // do not compare transitively, handling one pair can queue another + // pair at this same y again, and the pairs can cycle forever through + // the same positions. A pair is handled at most once per y for each + // pair of positions it holds in the sweep line; a repeat is queued + // again at the pair's next order change instead, if that comes before + // both ends. + let mut handled = FxHashSet::default(); + #[cfg(test)] + let mut events_at_y = 0usize; while let Some(intersection) = self.events.next_intersection_at_y(y) { - self.handle_intersection(intersection.left, intersection.right); + #[cfg(test)] + { + events_at_y += 1; + let n = self.segments.len(); + assert!( + events_at_y <= n.saturating_pow(4), + "{events_at_y} intersection events at y={y:?} for {n} segments" + ); + } + let (left, right) = (intersection.left, intersection.right); + let positions = (self.line.position(left), self.line.position(right)); + if !handled.insert((left, right, positions)) { + let next_y = self + .compare_segments(left, right) + .iter() + .map(|(_, end, _)| end) + .find(|end| *end > y); + if let Some(next_y) = next_y + && next_y < self.segments[left].end().y + && next_y < self.segments[right].end().y + { + self.events.push(IntersectionEvent { + y: next_y, + left, + right, + }); + } + continue; + } + self.handle_intersection(left, right); self.check_invariants(); } @@ -2055,6 +2097,31 @@ mod tests { insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.1)); } + // Five circles, each moved by (7e-7, 3.5e-7) from the one before, have + // nearly coincident curves whose comparisons are not transitive. Their + // sweep used to queue the same intersections at one y forever. The event + // count check in `next_line` stops a test build at n^4 events on one + // sweep line. + #[test] + fn repeated_intersections_at_one_y() { + use kurbo::{Circle, Shape}; + + let mut circles = BezPath::new(); + for i in 0..5 { + let center = (500.0 + i as f64 * 7e-7, 500.0 + i as f64 * 3.5e-7); + circles.extend(Circle::new(center, 50.0).path_elements(0.1)); + } + let mut segs = Segments::default(); + segs.add_bez_path(&circles).unwrap(); + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + let mut lines = 0; + while sweep.next_line(&mut bufs).is_some() { + lines += 1; + } + assert!(lines > 0); + } + #[test] fn conservative_line_order() { // Here's an example where c0 gets "ish" with c1 in the middle, c0 gets "ish" with c2 From e81c48f1f1cc25fc45b54d4b601ee112ee370297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 09:16:01 -0800 Subject: [PATCH 002/490] linesweeper: a delayed intersection at a segment's end no longer panics Sweeper::handle_intersection delays an intersection when a segment between the pair compares out of order, and queued the delayed event at y1.min(y2) without checking the segments' ends. When that y was the end of one of the two segments, handling the event there panicked in CurveOrder::entry_at, which finds no order entry ending after y. The delayed event is now queued only when its y is before the ends of both segments, the same rule the intersection scans use. The delayed_intersection_at_a_segment_end test sweeps three wide, flat contours (x up to 1e12, y below 1e-3) through Topology::from_path and expects 4 contours; without the change it panics at src/curve/mod.rs:357. README.craft.md, SOURCE.json and NOTICE record the change as a local patch. --- NOTICE | 6 +-- vendor/linesweeper/README.craft.md | 1 + vendor/linesweeper/SOURCE.json | 5 ++- vendor/linesweeper/src/sweep/sweep_line.rs | 43 +++++++++++++++++++--- 4 files changed, 45 insertions(+), 10 deletions(-) diff --git a/NOTICE b/NOTICE index 70c163182c..f914acf874 100644 --- a/NOTICE +++ b/NOTICE @@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and one local patch. 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 two local patches. 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 -change and the files left out. +changes and the files left out. Platform lifecycle source provenance diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index 3bc5964f7f..2d5c5a4f4c 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -16,6 +16,7 @@ holds `upstream_revision`. `local_patches` describes each local patch. | File | Change | |---|---| | `src/sweep/sweep_line.rs` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions the two segments hold. A pair queued again at the same `y` and positions is queued at the pair's next order change instead, when that comes before both segments end. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. | +| `src/sweep/sweep_line.rs` | `Sweeper::handle_intersection` queues a delayed intersection only when its `y` is before the ends of both segments, as the intersection scans do. A delayed intersection at a segment's end used to panic in `CurveOrder::entry_at`. The `delayed_intersection_at_a_segment_end` test sweeps three wide, flat contours whose sweep delayed an intersection to a segment's end. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 3bee04a7b7..b9d1cc8a76 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,8 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y." + "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y.", + "In `src/sweep/sweep_line.rs`, `Sweeper::handle_intersection` queues a delayed intersection only when its y is before the ends of both segments, so a delayed intersection at a segment's end no longer panics in `CurveOrder::entry_at`." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -64,7 +65,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "e9c93858dc54dad40f2c4d4965243b9fc19a5ec64eb8bcd561aedb5c7596bf08" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "75b56bf0262b1989ef056a851522857f97806721d1e2f2f73e4e765ff8b17da7" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index de6ae66ba9..d5bcc02565 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -807,11 +807,20 @@ impl<'segs> Sweeper<'segs> { let (_, y2, j_right_order) = self.compare_segments(seg_j_idx, right).entry_at(self.y); if j_right_order == Order::Left { - self.events.push(IntersectionEvent { - y: y1.min(y2), - left, - right, - }); + // Craft patch (delayed intersection at an end): the + // delayed event is queued only when it comes before + // both ends, as in the scans that queue intersections. + // An event at an end makes `entry_at` panic. + let delayed_y = y1.min(y2); + if delayed_y < self.segments[left].end().y + && delayed_y < self.segments[right].end().y + { + self.events.push(IntersectionEvent { + y: delayed_y, + left, + right, + }); + } return; } @@ -2122,6 +2131,30 @@ mod tests { assert!(lines > 0); } + // Wide, flat shapes (x up to 1e12, y below 1e-3) whose sweep delays an + // intersection to exactly the end of one of its segments. Handling the + // delayed event there used to panic in `CurveOrder::entry_at`. + #[test] + fn delayed_intersection_at_a_segment_end() { + let path = BezPath::from_svg( + "M501064307397.10095,0.0009848607387959033 \ + L106201373767.89085,0.0006710749289289315 \ + C417687393573.9515,0.0004160951440753873 304110132978.1276,0.00038371209900965467 283049238030.7473,0.000948649831345387 Z \ + M198139564203.8839,0.00026113917505891313 \ + Q925286056821.7639,0.0001263989183887222 706548805870.0378,0.0005146463318510499 \ + C481577318901.41956,0.000572151300098751 38743762463.54683,0.000935423896736907 333105974166.1391,0.00039093790825889355 \ + C838434423640.872,0.0005209836434131965 252410595074.9046,0.00021445561842374318 649987299514.814,0.0005284926072103142 Z \ + M425570790862.5174,0.0002275798137344196 \ + C643548474934.2626,0.00016915804040910177 896953683318.0679,0.000915403101629657 231887429918.8749,0.0004275752018309249 \ + Q960890561259.0065,0.0005825265493017958 735584660921.8835,0.000238439768009997 \ + Q676310419912.8419,0.00003744704696150181 803912734785.0077,0.0008084425285905149 Z", + ) + .unwrap(); + let top = + crate::topology::Topology::::from_path(&path, 1.3655076163260652e-2).unwrap(); + assert_eq!(top.contours(|w| *w != 0).contours().count(), 4); + } + #[test] fn conservative_line_order() { // Here's an example where c0 gets "ish" with c1 in the middle, c0 gets "ish" with c2 From 18b61d7ab088a8a53799e2a3dff0f94bf9f7094a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 11:24:24 -0800 Subject: [PATCH 003/490] linesweeper: neighboring segments share stored winding numbers Topology stored a full copy of both sides' winding numbers for every output segment, although a segment's clockwise side is the same value as the previous segment's counter-clockwise side. With a winding number type that holds one entry per covering input, each value was stored twice. Each side is now an Arc, and the sweep gives neighboring segments the same Arc. For 500 squares that all cross each other, building the Topology peaked at 2,769.4 MB and now peaks at 2,102.5 MB, with the same contours. The public accessors do not change. A Topology is Send and Sync only when W is both. --- vendor/linesweeper/README.craft.md | 20 ++-- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/topology.rs | 151 ++++++++++++++++++++++++----- 3 files changed, 146 insertions(+), 31 deletions(-) diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..f24a3828a6 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,21 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file +in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local patch. + +## Local patches + +| File | Change | +|---|---| +| `src/topology.rs` | `Topology` stores each side of an output segment's winding numbers behind an `Arc`, and the sweep gives a segment's clockwise side and the previous segment's counter-clockwise side the same `Arc`. Before, every segment held its own copy of both sides, so a winding number type that allocates (one entry per covering input) stored each value twice. For 500 squares that all cross each other, with a winding number type like `craft-prepress`'s, building the `Topology` peaked at 2,769.4 MB and now peaks at 2,102.5 MB, and `craft_prepress::flatten::geom::regions` peaked at 3,535.2 MB and now peaks at 2,842.1 MB, with the same regions. `winding_clockwise`, `winding_counter_clockwise` and `HalfSegmentWindingNumbers` do not change. A `Topology` is now `Send` and `Sync` only when `W` is both `Send` and `Sync`. Code comments label the changes `Craft patch (winding storage)`. The `neighboring_segments_share_winding_numbers` test checks the sharing, and `staggered_squares_winding_numbers_count_the_covering_squares` checks the areas covered by each number of squares. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..d21764ee7b 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `src/topology.rs`, `Topology` stores each side of an output segment's winding numbers behind an `Arc`, and the sweep gives a segment's clockwise side and the previous segment's counter-clockwise side the same `Arc`. Without it, every segment holds its own copy of both sides: for 500 squares that all cross each other, `Topology::from_paths` with a winding number type that holds one entry per covering input peaks at 2,769.4 MB and `craft_prepress::flatten::geom::regions` at 3,535.2 MB. With it they peak at 2,102.5 MB and 2,842.1 MB, with the same contours and regions. A `Topology` is `Send` and `Sync` only when `W` is both. The tests `topology::tests::neighboring_segments_share_winding_numbers` and `topology::tests::staggered_squares_winding_numbers_count_the_covering_squares` cover it." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -63,7 +65,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3" }, - { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, + { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "ffaab7e48caa441630e794fb2f1e9287aa5f370c3eaf360ee265b5d49fbc02a4" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, { "path": "tests/fonts.rs", "source_sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400", "source_git_blob": null, "sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400" }, diff --git a/vendor/linesweeper/src/topology.rs b/vendor/linesweeper/src/topology.rs index 8420d015a5..3a0ef76bed 100644 --- a/vendor/linesweeper/src/topology.rs +++ b/vendor/linesweeper/src/topology.rs @@ -4,6 +4,7 @@ //! like winding number computations and boolean operations. use std::collections::VecDeque; +use std::sync::Arc; use kurbo::{BezPath, ParamCurve, Rect, Shape}; @@ -161,14 +162,6 @@ pub struct HalfSegmentWindingNumbers { pub clockwise: W, } -impl HalfSegmentWindingNumbers { - /// A half-segment's winding numbers are trivial if they're the same on both sides. - /// In this case, the segment is invisible to the topology of the sets. - fn is_trivial(&self) -> bool { - self.counter_clockwise == self.clockwise - } -} - impl std::fmt::Debug for HalfSegmentWindingNumbers { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( @@ -179,6 +172,52 @@ impl std::fmt::Debug for HalfSegmentWindingNumbers { } } +// Craft patch (winding storage). +/// The winding numbers a topology stores for an output segment: the two sides of +/// [`HalfSegmentWindingNumbers`], each behind an `Arc`. +/// +/// The sweep builds each segment's winding numbers from a running winding number, +/// so a segment's clockwise side is the same value as the counter-clockwise side +/// of the segment before it. The two segments hold clones of one `Arc`, and each +/// distinct winding number is stored once. +#[derive(Clone)] +struct SegmentWindingNumbers { + counter_clockwise: Arc, + clockwise: Arc, +} + +impl SegmentWindingNumbers { + /// A half-segment's winding numbers are trivial if they're the same on both sides. + /// In this case, the segment is invisible to the topology of the sets. + fn is_trivial(&self) -> bool { + Arc::ptr_eq(&self.counter_clockwise, &self.clockwise) + || self.counter_clockwise == self.clockwise + } +} + +impl std::fmt::Debug for SegmentWindingNumbers { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "cw {:?} | cc {:?}", + self.clockwise, self.counter_clockwise + ) + } +} + +// Craft patch (winding storage): serialized as a `HalfSegmentWindingNumbers`, +// which the snapshot tests record. +#[cfg(test)] +impl serde::Serialize for SegmentWindingNumbers { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("HalfSegmentWindingNumbers", 2)?; + s.serialize_field("counter_clockwise", &*self.counter_clockwise)?; + s.serialize_field("clockwise", &*self.clockwise)?; + s.end() + } +} + /// An index into the set of output segments. /// /// There's no compile-time magic preventing misuse of this index, but you @@ -412,7 +451,10 @@ pub struct Topology { /// `HalfSegmentWindingNumbers` for each `HalfOutputSegIdx`. But since the two halves of /// the winding numbers are determined by one another, we only store the winding numbers /// for the start half of the output segment. - winding: OutputSegVec>, + /// + /// Craft patch (winding storage): neighboring segments share each side's + /// value through an `Arc` (see [`SegmentWindingNumbers`]). + winding: OutputSegVec>, /// The output points. points: PointVec, /// The segment endpoints, as indices into `points`. @@ -696,7 +738,7 @@ impl Topology { &mut self, idx: SegIdx, p: PointIdx, - winding: HalfSegmentWindingNumbers, + winding: SegmentWindingNumbers, horizontal: bool, positively_oriented: bool, ) -> OutputSegIdx { @@ -734,8 +776,11 @@ impl Topology { mut scan_west: Option, ) { let y = pos.line().y(); - let mut winding = scan_west - .map(|idx| self.winding[idx].counter_clockwise.clone()) + // Craft patch (winding storage): `winding` and `w` below are shared with + // the segments that store them, and each step makes a new `Arc` instead + // of changing the shared value. + let mut winding: Arc = scan_west + .map(|idx| Arc::clone(&self.winding[idx].counter_clockwise)) .unwrap_or_default(); // A re-usable buffer for holding temporary lists of segment indices. We @@ -771,12 +816,14 @@ impl Topology { // Also, calculate their winding numbers and update `winding`. seg_buf.clear(); for new_seg in connected_segs.connected_down() { - let prev_winding = winding.clone(); + let prev_winding = Arc::clone(&winding); let orientation = segments.positively_oriented(new_seg); - winding += W::single(self.tag[new_seg], !orientation); - let windings = HalfSegmentWindingNumbers { + let mut next = W::clone(&winding); + next += W::single(self.tag[new_seg], !orientation); + winding = Arc::new(next); + let windings = SegmentWindingNumbers { clockwise: prev_winding, - counter_clockwise: winding.clone(), + counter_clockwise: Arc::clone(&winding), }; let half_seg = self.new_half_seg(new_seg, p, windings, false, orientation); self.scan_west[half_seg] = scan_west; @@ -803,14 +850,16 @@ impl Topology { // We don't want to update our "global" winding number state because that's supposed // to keep track of the winding number below the current sweep line. - let mut w = winding.clone(); + let mut w = Arc::clone(&winding); seg_buf.clear(); for (new_seg, same_orientation) in hsegs { - let prev_w = w.clone(); + let prev_w = Arc::clone(&w); let orientation = same_orientation == segments.positively_oriented(new_seg); - w += W::single(self.tag[new_seg], !orientation); - let windings = HalfSegmentWindingNumbers { - counter_clockwise: w.clone(), + let mut next = W::clone(&w); + next += W::single(self.tag[new_seg], !orientation); + w = Arc::new(next); + let windings = SegmentWindingNumbers { + counter_clockwise: Arc::clone(&w), clockwise: prev_w, }; let half_seg = self.new_half_seg(new_seg, p, windings, true, orientation); @@ -917,8 +966,10 @@ impl Topology { // coincident then they'd better both be first halves. debug_assert!(cw_nbr.first_half); self.delete(idx); + // Craft patch (winding storage): share the value instead of + // copying it. self.winding[cw_nbr.idx].counter_clockwise = - self.winding[idx].counter_clockwise.clone(); + Arc::clone(&self.winding[idx].counter_clockwise); if self.winding[cw_nbr.idx].is_trivial() { self.delete(cw_nbr.idx); @@ -2288,6 +2339,62 @@ mod tests { insta::assert_ron_snapshot!(top); } + // Craft patch (winding storage). + /// `n` squares of side `n`, each one step right and down from the last, so the + /// edges of every square cross the edges of every other square. + fn staggered_squares(n: usize) -> Vec { + use kurbo::Shape as _; + (0..n) + .map(|i| { + let (i, n) = (i as f64, n as f64); + kurbo::Rect::new(i, i + 0.25, i + n, i + n + 0.25).to_path(0.1) + }) + .collect() + } + + // Craft patch (winding storage). + #[test] + fn neighboring_segments_share_winding_numbers() { + let paths = staggered_squares(8); + let top = Topology::::from_paths(paths.iter().map(|p| (p, ())), 1e-6).unwrap(); + let mut sides = 0; + let mut stored = std::collections::HashSet::new(); + for idx in top.segment_indices() { + let w = &top.winding[idx]; + for side in [&w.clockwise, &w.counter_clockwise] { + sides += 1; + stored.insert(std::sync::Arc::as_ptr(side)); + } + } + // A segment's clockwise side is the counter-clockwise side of the segment + // before it in the sweep, so most sides share a stored value. + assert!( + stored.len() * 3 <= sides * 2, + "{} winding numbers stored for {sides} sides", + stored.len() + ); + } + + // Craft patch (winding storage). + #[test] + fn staggered_squares_winding_numbers_count_the_covering_squares() { + use kurbo::Shape as _; + let paths = staggered_squares(8); + let top = Topology::::from_paths(paths.iter().map(|p| (p, ())), 1e-6).unwrap(); + for k in 1..=8 { + // The points covered by at least `k` squares form `9 - k` squares of + // side `9 - k`, each one step from the last. + let s = f64::from(9 - k); + let expected = s * s + (s - 1.0) * (2.0 * s - 1.0); + let contours = top.contours(|w| w.abs() >= k); + let area: f64 = contours.contours().map(|c| c.path.area().abs()).sum(); + assert!( + (area - expected).abs() < 1e-9, + "k = {k}: {area} != {expected}" + ); + } + } + #[test] fn diamond() { let segs = [[p(0.0, 0.0), p(1.0, 1.0), p(0.0, 2.0), p(-1.0, 1.0)]]; From d1d19c6edf2c01ca014794e331681643f1837a81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 11:46:48 -0800 Subject: [PATCH 004/490] linesweeper: adding many paths no longer sorts the whole arena on every call Segments::add_bez_path and add_non_closed_bez_path called update_enter_exit, which sorted the whole enter and exit vectors on every call, so adding n paths one at a time took time quadratic in n. - update_enter_exit sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole vector gave before. - Segments::add_bez_paths and add_non_closed_bez_paths add a collection of paths and merge once. On an open subpath, add_bez_paths keeps the paths before it and adds nothing of that path or later ones. - README.craft.md, SOURCE.json and NOTICE record the local patch. --- NOTICE | 6 +- vendor/linesweeper/README.craft.md | 22 +- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/segments.rs | 344 ++++++++++++++++++++++++++++- 4 files changed, 358 insertions(+), 20 deletions(-) diff --git a/NOTICE b/NOTICE index bd88d43e7a..70c163182c 100644 --- a/NOTICE +++ b/NOTICE @@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and no file changed. Its manifest names Joe Neeman +vendor/linesweeper with its upstream license files and one local patch. 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 and the files -left out. +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local +change and the files left out. Platform lifecycle source provenance diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..84022c1664 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,23 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +changes listed under Local changes. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the files under Local changes is byte for byte the +file in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local change. + +## Local changes + +| Change | Code comment label | Touches | Tests | +|---|---|---|---| +| Adding paths one at a time no longer sorts every entrance and exit in the arena on each call: the new entries are sorted and merged into the sorted ones, in the same order as before. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add many paths and merge once; on an open subpath, `add_bez_paths` keeps the paths before it and adds nothing of that path or later ones | `Craft patch (batch paths)` | `src/segments.rs` | `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort`, `segments::tests::paths_added_in_height_order_are_not_sorted_again` | + +Every change here updates this table and `SOURCE.json` in the same commit. `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..6acc2a48d7 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `src/segments.rs`, `update_enter_exit` sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole list gives, instead of sorting the whole list on every call. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add a collection of paths and merge once, as `add_closed_polylines` and `Topology::from_paths` already do, and `add_bez_paths` removes the segments of a path with an open subpath before it returns the error. Without it, adding 2,000 triangles one at a time from the top row down takes 6,006,993 entrance comparisons, and adding n paths one at a time takes time quadratic in n. The tests `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort` and `segments::tests::paths_added_in_height_order_are_not_sorted_again` cover it." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -42,7 +44,7 @@ { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596" }, { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5" }, { "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0" }, - { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc" }, + { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "717ef16f77623ae020307dff376032c9948aff2f7008bd797507b9f67095d6d0" }, { "path": "src/snapshots/linesweeper__tests__empty_horizontals.snap", "source_sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244", "source_git_blob": null, "sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244" }, { "path": "src/snapshots/linesweeper__tests__two_squares.snap", "source_sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846", "source_git_blob": null, "sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846" }, { "path": "src/snapshots/linesweeper__topology__tests__diamond.snap", "source_sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502", "source_git_blob": null, "sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502" }, diff --git a/vendor/linesweeper/src/segments.rs b/vendor/linesweeper/src/segments.rs index 909eb01d2e..37c4f8f573 100644 --- a/vendor/linesweeper/src/segments.rs +++ b/vendor/linesweeper/src/segments.rs @@ -131,6 +131,66 @@ fn pairs(xs: &[T]) -> impl Iterator { xs.windows(2).map(|pair| (&pair[0], &pair[1])) } +// Craft patch (batch paths): counts calls to `enter_order` in tests. +#[cfg(test)] +thread_local! { + static ENTER_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +// Craft patch (batch paths): the order of `Segments::enter`, by entrance +// height and then by horizontal position at that height. +fn enter_order( + segs: &SegVec, + (y1, seg1): &(f64, SegIdx), + (y2, seg2): &(f64, SegIdx), +) -> std::cmp::Ordering { + #[cfg(test)] + ENTER_COMPARISONS.with(|c| c.set(c.get() + 1)); + CheapOrderedFloat::from(*y1) + .cmp(&CheapOrderedFloat::from(*y2)) + .then_with(|| { + CheapOrderedFloat::from(segs[*seg1].at_y(*y1)) + .cmp(&CheapOrderedFloat::from(segs[*seg2].at_y(*y1))) + }) +} + +// Craft patch (batch paths): sorts `v[old_len..]` and merges it into +// `v[..old_len]`, which must already be sorted by `cmp`. The result is the +// order a stable sort of all of `v` gives: on a tie, an entry from before +// `old_len` comes first. Only the part of the sorted prefix that the new +// entries reach is moved, so entries added below every existing one cost a +// sort of the new entries and a binary search. +fn merge_sorted_tail( + v: &mut Vec, + old_len: usize, + mut cmp: impl FnMut(&T, &T) -> std::cmp::Ordering, +) { + let mut tail = v.split_off(old_len); + tail.sort_by(&mut cmp); + let Some(first) = tail.first() else { + return; + }; + let pos = v.partition_point(|e| cmp(e, first) != std::cmp::Ordering::Greater); + if pos == v.len() { + v.append(&mut tail); + return; + } + let suffix = v.split_off(pos); + v.reserve(suffix.len() + tail.len()); + let (mut i, mut j) = (0, 0); + while i < suffix.len() && j < tail.len() { + if cmp(&tail[j], &suffix[i]) == std::cmp::Ordering::Less { + v.push(tail[j]); + j += 1; + } else { + v.push(suffix[i]); + i += 1; + } + } + v.extend_from_slice(&suffix[i..]); + v.extend_from_slice(&tail[j..]); +} + struct SubpathIter<'a, I: Iterator> { inner: &'a mut Peekable, started: bool, @@ -298,6 +358,10 @@ impl Segments { /// Add a Bézier path to this arena. /// /// The path can contain multiple subpaths, and each of them must be closed. + /// + /// Each call merges the path's entrances and exits into the sorted ones + /// already in the arena, which moves every existing entry that sorts after + /// them. To add many paths, call [`Segments::add_bez_paths`] once instead. pub fn add_bez_path(&mut self, p: &BezPath) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); self.add_path_without_updating_enter_exit(p, true)?; @@ -308,6 +372,11 @@ impl Segments { /// Add a Bézier path to this arena. /// /// The path can contain multiple subpaths, and each of them may or may not be closed. + /// + /// Each call merges the path's entrances and exits into the sorted ones + /// already in the arena, which moves every existing entry that sorts after + /// them. To add many paths, call [`Segments::add_non_closed_bez_paths`] + /// once instead. pub fn add_non_closed_bez_path(&mut self, p: &BezPath) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); self.add_path_without_updating_enter_exit(p, false)?; @@ -315,6 +384,71 @@ impl Segments { Ok(()) } + // Craft patch (batch paths): add every path, then sort the entrances and exits once. + /// Add a collection of Bézier paths to this arena. + /// + /// Every subpath must be closed. When every path is closed, this gives the + /// same arena as calling [`Segments::add_bez_path`] on each path in turn, + /// and it sorts the entrances and exits once instead of once per path. + /// + /// If a subpath is not closed, this returns the error for the first such + /// subpath. The paths before the one holding it stay in the arena, and no + /// segment of that path or of any later path is added. + pub fn add_bez_paths<'a>( + &mut self, + ps: impl IntoIterator, + ) -> Result<(), NonClosedPath> { + self.add_paths_updating_enter_exit_once(ps, true) + } + + // Craft patch (batch paths). + /// Add a collection of Bézier paths to this arena. + /// + /// Each subpath may or may not be closed. This gives the same arena as + /// calling [`Segments::add_non_closed_bez_path`] on each path in turn, and + /// it sorts the entrances and exits once instead of once per path. + pub fn add_non_closed_bez_paths<'a>( + &mut self, + ps: impl IntoIterator, + ) -> Result<(), NonClosedPath> { + self.add_paths_updating_enter_exit_once(ps, false) + } + + // Craft patch (batch paths). + fn add_paths_updating_enter_exit_once<'a>( + &mut self, + ps: impl IntoIterator, + must_be_closed: bool, + ) -> Result<(), NonClosedPath> { + let old_len = self.segs.len(); + let mut result = Ok(()); + for p in ps { + let path_start = self.segs.len(); + result = self.add_path_without_updating_enter_exit(p, must_be_closed); + if result.is_err() { + // The failing path's segments are removed, so none is left + // linked to an index past the end of the arena. + self.truncate_unentered(path_start); + break; + } + } + self.update_enter_exit(old_len); + result + } + + // Craft patch (batch paths): drops every segment at index `len` or above. + // `enter` and `exit` are left alone, so this is only for segments that + // `update_enter_exit` has not seen yet. + fn truncate_unentered(&mut self, len: usize) { + self.segs.inner.truncate(len); + self.horizontal_decomps.inner.truncate(len); + self.contour_prev.inner.truncate(len); + self.contour_next.inner.truncate(len); + self.orientation.inner.truncate(len); + self.split_from_predecessor.inner.truncate(len); + self.input_segs.inner.truncate(len); + } + pub(crate) fn add_path_without_updating_enter_exit( &mut self, p: &BezPath, @@ -415,6 +549,9 @@ impl Segments { } pub(crate) fn update_enter_exit(&mut self, old_len: usize) { + // Craft patch (batch paths). + let enter_old_len = self.enter.len(); + let exit_old_len = self.exit.len(); for idx in old_len..self.len() { let seg_idx = SegIdx(idx); let seg = &self.segs[seg_idx]; @@ -428,15 +565,15 @@ impl Segments { // We sort the enter segments by y position, and then by horizontal // start position so that they're fairly likely to get inserted in the // sweep-line in order (which makes the indexing fix-ups faster). - self.enter.sort_by(|(y1, seg1), (y2, seg2)| { - CheapOrderedFloat::from(*y1) - .cmp(&CheapOrderedFloat::from(*y2)) - .then_with(|| { - CheapOrderedFloat::from(self.segs[*seg1].at_y(*y1)) - .cmp(&CheapOrderedFloat::from(self.segs[*seg2].at_y(*y1))) - }) + // + // Craft patch (batch paths): the entries before `old_len` are already + // sorted, so only the new entries are sorted and then merged in. This + // gives the same order as a stable sort of the whole vector. + let segs = &self.segs; + merge_sorted_tail(&mut self.enter, enter_old_len, |a, b| { + enter_order(segs, a, b) }); - self.exit.sort_by(|(y1, _), (y2, _)| { + merge_sorted_tail(&mut self.exit, exit_old_len, |(y1, _), (y2, _)| { CheapOrderedFloat::from(*y1).cmp(&CheapOrderedFloat::from(*y2)) }); } @@ -480,3 +617,194 @@ impl std::ops::Index for Segments { &self.segs[index] } } + +// Craft patch (batch paths). +#[cfg(test)] +mod tests { + use kurbo::BezPath; + + use super::{SegIdx, Segments}; + use crate::num::CheapOrderedFloat; + + // Paths on a small integer grid, so that many segments share entrance + // heights and entrance positions, with lines, quadratics and cubics. + fn grid_paths(count: usize, closed: bool) -> Vec { + let mut state: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = move || { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + ((state >> 33) % 12) as f64 + }; + (0..count) + .map(|i| { + let mut p = BezPath::new(); + p.move_to((next(), next())); + match i % 3 { + 0 => { + p.line_to((next(), next())); + p.line_to((next(), next())); + } + 1 => { + p.quad_to((next(), next()), (next(), next())); + p.line_to((next(), next())); + } + _ => { + p.curve_to((next(), next()), (next(), next()), (next(), next())); + } + } + if closed { + p.close_path(); + } + p + }) + .collect() + } + + fn assert_same_arena(a: &Segments, b: &Segments) { + assert_eq!(a.segs, b.segs); + assert_eq!(a.orientation, b.orientation); + assert_eq!(a.contour_prev, b.contour_prev); + assert_eq!(a.contour_next, b.contour_next); + assert_eq!(a.enter, b.enter); + assert_eq!(a.exit, b.exit); + } + + #[test] + fn add_bez_paths_matches_repeated_add_bez_path() { + let paths = grid_paths(300, true); + let mut one_by_one = Segments::default(); + for p in &paths { + one_by_one.add_bez_path(p).unwrap(); + } + let mut batch = Segments::default(); + batch.add_bez_paths(&paths).unwrap(); + batch.check_invariants(); + assert!(batch.len() > 600); + assert_same_arena(&one_by_one, &batch); + + // A second batch adds to the arena that is already there. + let more = grid_paths(50, true); + for p in &more { + one_by_one.add_bez_path(p).unwrap(); + } + batch.add_bez_paths(&more).unwrap(); + assert_same_arena(&one_by_one, &batch); + } + + #[test] + fn add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path() { + let paths = grid_paths(300, false); + let mut one_by_one = Segments::default(); + for p in &paths { + one_by_one.add_non_closed_bez_path(p).unwrap(); + } + let mut batch = Segments::default(); + batch.add_non_closed_bez_paths(&paths).unwrap(); + batch.check_invariants(); + assert_same_arena(&one_by_one, &batch); + } + + #[test] + fn add_bez_paths_stops_at_an_open_path() { + let mut paths = grid_paths(4, true); + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((1.0, 5.0)); + paths.insert(2, open); + + let mut segments = Segments::default(); + let err = segments.add_bez_paths(&paths).unwrap_err(); + assert_eq!(err.start_point, kurbo::Point::new(0.0, 0.0)); + assert_eq!(err.end_point, kurbo::Point::new(1.0, 5.0)); + + // The two paths before the open one stay, and nothing of the open + // path or the paths after it is added. + segments.check_invariants(); + let mut expected = Segments::default(); + expected.add_bez_paths(&paths[..2]).unwrap(); + assert_same_arena(&expected, &segments); + assert_eq!(segments.input_segs, expected.input_segs); + assert_eq!( + segments.split_from_predecessor, + expected.split_from_predecessor + ); + } + + type Events = Vec<(f64, SegIdx)>; + + // The entrance and exit order that sorting every entry in index order + // gives, as `update_enter_exit` did before it merged new entries in. + fn sorted_from_scratch(s: &Segments) -> (Events, Events) { + let mut enter = Vec::new(); + let mut exit = Vec::new(); + for idx in s.indices() { + let seg = &s[idx]; + enter.push((seg.start().y, idx)); + if !seg.is_horizontal() { + exit.push((seg.end().y, idx)); + } + } + enter.sort_by(|a, b| super::enter_order(&s.segs, a, b)); + exit.sort_by(|(y1, _), (y2, _)| { + CheapOrderedFloat::from(*y1).cmp(&CheapOrderedFloat::from(*y2)) + }); + (enter, exit) + } + + #[test] + fn merged_entrances_and_exits_match_a_full_sort() { + // Paths added one at a time land above, below and among the ones + // already there, with many equal heights and positions. + let mut one_by_one = Segments::default(); + for p in &grid_paths(400, true) { + one_by_one.add_bez_path(p).unwrap(); + let (enter, exit) = sorted_from_scratch(&one_by_one); + assert_eq!(one_by_one.enter, enter); + assert_eq!(one_by_one.exit, exit); + } + + let mut batches = Segments::default(); + let paths = grid_paths(400, false); + for chunk in paths.chunks(37) { + batches.add_non_closed_bez_paths(chunk).unwrap(); + let (enter, exit) = sorted_from_scratch(&batches); + assert_eq!(batches.enter, enter); + assert_eq!(batches.exit, exit); + } + } + + #[test] + fn paths_added_in_height_order_are_not_sorted_again() { + // 2,000 triangles in rows of 400, added one at a time from the top + // row down and left to right. + let triangles: Vec = (0..2000) + .map(|i| { + let x = (i % 400) as f64 * 3.0; + let y = (i / 400) as f64 * 3.0; + let mut p = BezPath::new(); + p.move_to((x, y)); + p.line_to((x + 2.0, y)); + p.line_to((x + 1.0, y + 2.0)); + p.close_path(); + p + }) + .collect(); + let mut segments = Segments::default(); + super::ENTER_COMPARISONS.with(|c| c.set(0)); + for p in &triangles { + segments.add_bez_path(p).unwrap(); + } + let comparisons = super::ENTER_COMPARISONS.with(|c| c.get()); + assert_eq!(segments.len(), 6000); + // Sorting all the entrances on every call compares each existing + // entrance at least once per call, about 6,000,000 comparisons here. + assert!( + comparisons < 64 * 6000, + "{comparisons} entrance comparisons" + ); + let (enter, exit) = sorted_from_scratch(&segments); + assert_eq!(segments.enter, enter); + assert_eq!(segments.exit, exit); + } +} From b84bd0613608059066b370c2f7f639d908696bbf Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 20:57:29 +0100 Subject: [PATCH 005/490] craft-audio: README says opus::wav_order is for mapping family 1 only Co-Authored-By: Claude Opus 5.5 --- crates/audio/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..d8ff8a860e 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -209,7 +209,9 @@ target, call `reset()`, decode from there, and drop the output before the target The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to -WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order. +WAV order. `opus::wav_order` applies only to mapping family 1; other families have no speaker +assignment, and `TrackDecoder` leaves their channels in stream order. `ac3::Decoder` and +`mpa::Decoder` output WAV order. ### Encode a file From 3c5599595697f96bf11d1723f90d24b96db7aad5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:37:31 -0800 Subject: [PATCH 006/490] craft-testkit: fonts renames a test face's family and builds TrueType collections Add the fonts module. rename_family(bytes, from, to) replaces a family name of the same UTF-16 length in the family records (name IDs 1, 16 and 21) and in full names (ID 4) that are the name or start with it followed by a space, in UTF-16BE and ASCII Macintosh Roman records, and writes the name table checksum and head.checkSumAdjustment. collection(faces) builds a TTC 1.0 with each face's own tables, four-byte padding, file-relative offsets, zeroed checkSumAdjustment and checksums of the copied tables. Both return a FontError instead of panicking: names of different lengths, no family record holding the name, a face shorter than its table directory, tables or name strings out of range, shared name storage that a rename would change, a collection given as a face, and output past the 4 GiB that 32-bit offsets reach. The code comes from the rename and collection helpers in VectorCraft, DesignCraft and WordCraft font tests. Their tests need each app's font database and bundled fonts, so they stay in the apps; tests/fonts.rs tests the module on faces built in memory. --- crates/testkit/README.md | 19 ++ crates/testkit/src/fonts.rs | 498 ++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 7 + crates/testkit/tests/fonts.rs | 558 ++++++++++++++++++++++++++++++++++ 4 files changed, 1082 insertions(+) create mode 100644 crates/testkit/src/fonts.rs create mode 100644 crates/testkit/tests/fonts.rs diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e1a254e9f 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -78,11 +78,27 @@ fn no_std_instant_in_code_the_web_build_runs() { } ``` +## Test fonts + +The `fonts` module makes test fonts from font bytes the caller supplies. It reads no file and no environment variable, prints nothing, and builds for `wasm32-unknown-unknown`. + +- **`fonts::rename_family(bytes, from, to)`** returns a copy of one standalone face with the family name `from` replaced by `to`, which must have the same length in UTF-16 code units. It changes the family name records (name IDs 1, 16 and 21) whose value is `from`, and full names (ID 4) that are `from` or start with `from` and a space. At least one family record must hold `from`. It reads UTF-16BE and Macintosh Roman records, writes only ASCII names into Macintosh Roman records, leaves the PostScript name (ID 6), other names and other tables as they are, and writes the `name` table checksum and the `head` table's `checkSumAdjustment`. +- **`fonts::collection(faces)`** returns a TrueType collection (TTC 1.0) holding standalone faces. Each face gets its own copy of every table, tables start on four-byte boundaries, offsets count from the start of the collection, `checkSumAdjustment` is zero, and every table checksum matches the bytes in the collection. + +Both return a `fonts::FontError` instead of panicking: names of different lengths, a name that no family record holds, a face shorter than its table directory, a table or name string out of range, a collection given as a face, or output past the 4 GiB a collection's offsets reach. The layouts come from the OpenType font file and `name` table chapters: and . + +The tests that call the copies in VectorCraft, DesignCraft and WordCraft need each app's font database and its bundled fonts, so they stay in the apps. `tests/fonts.rs` tests the module on faces it assembles from bytes. + ## Origin | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `fonts` | storytold/vectorcraft, `rename` and `collection` | `crates/text/src/tests/sysfonts.rs` | `bada8e1710` | +| `fonts` | storytold/vectorcraft, `renamed` | `crates/testkit/src/fonts.rs` | `bada8e1710` | +| `fonts` | storytold/designcraft, the family renaming and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `8b169f8ee7` | +| `fonts` | storytold/wordcraft, `renamed_to` and `collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` | `f8c66d0692` | +| `fonts` | storytold/wordcraft, `renamed` | `crates/fonts/src/fontdb/user/tests.rs` | `f8c66d0692` | ## Migration @@ -90,3 +106,6 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| VectorCraft | `fonts::rename_family`, `fonts::collection` | `crates/text/src/tests/sysfonts.rs` and `crates/testkit/src/fonts.rs` helpers | Not started | +| DesignCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` helpers | Not started | +| WordCraft | `fonts::rename_family`, `fonts::collection` | `crates/fonts/src/fontdb/tests/sysfonts.rs` and `crates/fonts/src/fontdb/user/tests.rs` helpers | Not started | diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs new file mode 100644 index 0000000000..7231980c7a --- /dev/null +++ b/crates/testkit/src/fonts.rs @@ -0,0 +1,498 @@ +//! Test fonts made from font bytes the caller supplies. +//! +//! [`rename_family`] gives one standalone face a family name of the same length, and [`collection`] +//! builds a TrueType collection (TTC) from standalone faces. Both read the structures they change as +//! the OpenType specification lays them out +//! ( and +//! ), and return a [`FontError`] +//! for input that does not fit them. Other tables are copied as they are and are not checked. +//! +//! The module reads no file and no environment variable, prints nothing, and builds for +//! `wasm32-unknown-unknown`. + +use std::fmt; +use std::ops::Range; + +/// Length of the sfnt header: version, `numTables`, `searchRange`, `entrySelector`, `rangeShift`. +const SFNT_HEADER: usize = 12; +/// Length of one table record: tag, checksum, offset, length. +const TABLE_RECORD: usize = 16; +/// Length of the `name` table header: version, count, `storageOffset`. +const NAME_HEADER: usize = 6; +/// Length of one name record. +const NAME_RECORD: usize = 12; +/// Length of one language-tag record of a version 1 `name` table. +const LANG_TAG_RECORD: usize = 4; +/// Offset of `checkSumAdjustment` in the `head` table. +const HEAD_ADJUSTMENT: usize = 8; +/// The value a standalone font's checksum and its `checkSumAdjustment` add up to. +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; +/// Name IDs that hold a family name: legacy (1), typographic (16) and WWS (21). +const FAMILY_IDS: [u16; 3] = [1, 16, 21]; +/// Name ID of the full font name, which starts with the family name. +const FULL_NAME_ID: u16 = 4; + +/// Why a face could not be renamed or collected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontError { + /// `from` and `to` have different lengths in UTF-16 code units. + UnequalLength, + /// `from` or `to` is empty. + InvalidName, + /// No family record of the face holds `from`. + NameNotFound, + /// The face has no `name` table. + MissingNameTable, + /// A structure the function reads is truncated, out of range or of an unknown version. + MalformedFont, + /// A matching Macintosh Roman record would need a name that is not ASCII. + UnsupportedEncoding, + /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + ConflictingNameStorage, + /// [`collection`] was given no faces. + EmptyCollection, + /// The input is a collection, or an sfnt version other than TrueType or CFF outlines. + UnsupportedFace, + /// The output would not fit in memory or in the 32-bit offsets of a collection. + OutputTooLarge, +} + +impl fmt::Display for FontError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::UnequalLength => "the old and new family names have different lengths", + Self::InvalidName => "a family name is empty", + Self::NameNotFound => "no family name record holds the old name", + Self::MissingNameTable => "the font has no name table", + Self::MalformedFont => "the font's table directory or name table is truncated or out of range", + Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", + Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::EmptyCollection => "a collection needs at least one face", + Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", + Self::OutputTooLarge => "the output is too large", + }) + } +} + +impl std::error::Error for FontError {} + +/// Returns a copy of `bytes`, one standalone face, with the family name `from` replaced by `to`. +/// +/// The records changed are the legacy, typographic and WWS family names (name IDs 1, 16 and 21) +/// whose whole value is `from`, and full names (name ID 4) that are `from` or start with `from` and a +/// space; at least one family record must hold `from`. Copyright, style, PostScript (ID 6) and every +/// other name keep their bytes. Records in UTF-16BE (platform 0, and platform 3 encodings 0, 1 and +/// 10) and Macintosh Roman (platform 1 encoding 0) are read, and only ASCII names are written into +/// Macintosh Roman records; records in other encodings are left as they are. The function then writes the +/// `name` table's checksum and the `head` table's `checkSumAdjustment`. +/// +/// # Errors +/// +/// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have +/// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, +/// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII +/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and +/// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of +/// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory +/// or another table. +pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, FontError> { + if from.is_empty() || to.is_empty() { + return Err(FontError::InvalidName); + } + if from.encode_utf16().count() != to.encode_utf16().count() { + return Err(FontError::UnequalLength); + } + let tables = directory(bytes)?; + let name = tables.iter().find(|t| &t.tag == b"name").ok_or(FontError::MissingNameTable)?; + let head = tables.iter().find(|t| &t.tag == b"head"); + if shares_bytes(&tables, name) || head.is_some_and(|head| shares_bytes(&tables, head)) { + return Err(FontError::MalformedFont); + } + if head.is_some_and(|head| head.length < HEAD_ADJUSTMENT + 4) { + return Err(FontError::MalformedFont); + } + let strings = name_strings(bytes, name)?; + let (edits, kept) = plan_edits(bytes, &strings, from, to)?; + check_kept(&edits, kept)?; + + let mut out = copy_of(bytes)?; + apply_edits(&mut out, name, &edits)?; + let name_sum = checksum(bytes_at(&out, name.offset, name.length)?); + put_u32(&mut out, name.record + 4, name_sum)?; + if let Some(head) = head { + let at = head.offset + HEAD_ADJUSTMENT; + put_u32(&mut out, at, 0)?; + let sum = checksum(&out); + put_u32(&mut out, at, CHECKSUM_TARGET.wrapping_sub(sum))?; + } + Ok(out) +} + +/// Returns a TrueType collection (TTC version 1.0) holding `faces`, each a standalone face, in order. +/// +/// Every face keeps its sfnt header and table order and gets its own copy of each table. Tables +/// start on four-byte boundaries with zero padding between them, offsets count from the start of the +/// collection, and each record keeps the table's unpadded length. Each `head` table's +/// `checkSumAdjustment` is set to zero, as a collection does not use it, and every table checksum is +/// computed from the bytes in the collection. +/// +/// # Errors +/// +/// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is +/// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or +/// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +pub fn collection(faces: &[&[u8]]) -> Result, FontError> { + if faces.is_empty() { + return Err(FontError::EmptyCollection); + } + let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; + let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; + let size = collection_size(&directories)?; + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(b"ttcf"); + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + out.extend_from_slice(&count.to_be_bytes()); + out.resize(SFNT_HEADER + faces.len() * 4, 0); + for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + let directory = offset32(out.len())?; + put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; + write_face(&mut out, face, tables)?; + } + Ok(out) +} + +/// One table record of a face: where the record is and where its table is. +struct Table { + tag: [u8; 4], + /// Offset of the table record in the face. + record: usize, + offset: usize, + length: usize, +} + +/// Reads a standalone face's table directory, checking that every record and table lies in `face`. +fn directory(face: &[u8]) -> Result, FontError> { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + let count = usize::from(u16_at(face, 4)?); + bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; + let mut tables = Vec::with_capacity(count); + for index in 0..count { + let record = SFNT_HEADER + index * TABLE_RECORD; + let tag = <[u8; 4]>::try_from(bytes_at(face, record, 4)?).map_err(|_| FontError::MalformedFont)?; + let offset = usize_from(u32_at(face, record + 8)?)?; + let length = usize_from(u32_at(face, record + 12)?)?; + bytes_at(face, offset, length)?; + tables.push(Table { tag, record, offset, length }); + } + Ok(tables) +} + +/// Whether `table` shares bytes with the table directory or with another table of the face. +fn shares_bytes(tables: &[Table], table: &Table) -> bool { + let end = table.offset + table.length; + let overlaps = |start: usize, other_end: usize| start < end && table.offset < other_end; + overlaps(0, SFNT_HEADER + tables.len() * TABLE_RECORD) + || tables.iter().any(|other| other.record != table.record && overlaps(other.offset, other.offset + other.length)) +} + +/// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. +fn collection_size(directories: &[Vec]) -> Result { + let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; + for tables in directories { + let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; + size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + for table in tables { + let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; + size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; + } + } + if size > u64::from(u32::MAX) { + return Err(FontError::OutputTooLarge); + } + usize::try_from(size).map_err(|_| FontError::OutputTooLarge) +} + +/// Appends one face's directory and tables to a collection being built. +fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), FontError> { + let directory = out.len(); + out.extend_from_slice(bytes_at(face, 0, SFNT_HEADER)?); + out.resize(directory + SFNT_HEADER + tables.len() * TABLE_RECORD, 0); + for (index, table) in tables.iter().enumerate() { + let start = out.len(); + out.extend_from_slice(bytes_at(face, table.offset, table.length)?); + if &table.tag == b"head" { + if table.length < HEAD_ADJUSTMENT + 4 { + return Err(FontError::MalformedFont); + } + put_u32(out, start + HEAD_ADJUSTMENT, 0)?; + } + let sum = checksum(bytes_at(out, start, table.length)?); + out.resize(out.len().div_ceil(4) * 4, 0); + let record = directory + SFNT_HEADER + index * TABLE_RECORD; + put_bytes(out, record, &table.tag)?; + put_u32(out, record + 4, sum)?; + put_u32(out, record + 8, offset32(start)?)?; + put_u32(out, record + 12, offset32(table.length)?)?; + } + Ok(()) +} + +/// How the bytes of a name record are encoded, as far as renaming reads them. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Encoding { + Utf16, + MacRoman, + Other, +} + +impl Encoding { + fn of(platform: u16, encoding: u16) -> Self { + match (platform, encoding) { + (0, _) | (3, 0 | 1 | 10) => Self::Utf16, + (1, 0) => Self::MacRoman, + _ => Self::Other, + } + } +} + +/// One string of the `name` table, with its range in the face. +struct NameString { + encoding: Encoding, + name_id: u16, + range: Range, +} + +/// The strings of a face's `name` table: the name records, then the language tags of version 1. +struct NameStrings { + names: Vec, + lang_tags: Vec>, +} + +/// Reads the name and language-tag records of `table`, checking every string lies in the table. +fn name_strings(face: &[u8], table: &Table) -> Result { + let data = bytes_at(face, table.offset, table.length)?; + let version = u16_at(data, 0)?; + if version > 1 { + return Err(FontError::MalformedFont); + } + let count = usize::from(u16_at(data, 2)?); + let storage = usize::from(u16_at(data, 4)?); + let records_end = NAME_HEADER + count * NAME_RECORD; + bytes_at(data, 0, records_end)?; + let mut header_end = records_end; + let mut lang_tag_records = 0; + if version == 1 { + lang_tag_records = usize::from(u16_at(data, records_end)?); + header_end = records_end + 2 + lang_tag_records * LANG_TAG_RECORD; + } + if storage < header_end || storage > data.len() { + return Err(FontError::MalformedFont); + } + let string = |at: usize| -> Result, FontError> { + let length = usize::from(u16_at(data, at)?); + let start = storage + usize::from(u16_at(data, at + 2)?); + bytes_at(data, start, length)?; + Ok(table.offset + start..table.offset + start + length) + }; + let mut names = Vec::with_capacity(count); + for index in 0..count { + let record = NAME_HEADER + index * NAME_RECORD; + let encoding = Encoding::of(u16_at(data, record)?, u16_at(data, record + 2)?); + let name_id = u16_at(data, record + 6)?; + names.push(NameString { encoding, name_id, range: string(record + 8)? }); + } + let mut lang_tags = Vec::with_capacity(lang_tag_records); + for index in 0..lang_tag_records { + lang_tags.push(string(records_end + 2 + index * LANG_TAG_RECORD)?); + } + Ok(NameStrings { names, lang_tags }) +} + +/// A string the rename writes: its range in the face and its new bytes. +struct Edit { + range: Range, + bytes: Vec, +} + +/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { + let mut edits = Vec::new(); + let mut kept = strings.lang_tags.clone(); + let mut family_found = false; + for string in &strings.names { + let family = FAMILY_IDS.contains(&string.name_id); + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; + match new { + Some(new) => { + family_found |= family; + edits.push(Edit { range: string.range.clone(), bytes: new }); + } + None => kept.push(string.range.clone()), + } + } + if !family_found { + return Err(FontError::NameNotFound); + } + Ok((edits, kept)) +} + +/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let family = FAMILY_IDS.contains(&string.name_id); + let encoded = match string.encoding { + Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, + Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, + Encoding::Other => None, + }; + if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + return Err(FontError::UnequalLength); + } + Ok(encoded) +} + +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + let value = utf16_value(bytes)?; + let new = if family { + (value == from).then(|| to.to_owned()) + } else { + value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) + }; + Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) +} + +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { + if !from.is_ascii() { + return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; + } + let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { + return Ok(None); + }; + if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { + return Ok(None); + } + if !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some([to.as_bytes(), rest].concat())) +} + +/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per +/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length +/// or in an ASCII position cannot hold it. +fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { + let count = from.chars().count(); + let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); + fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) +} + +/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. +fn utf16_value(bytes: &[u8]) -> Result { + let (pairs, rest) = bytes.as_chunks::<2>(); + if !rest.is_empty() { + return Err(FontError::MalformedFont); + } + let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); + char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) +} + +/// Refuses a rename whose strings overlap a string that keeps its bytes. +fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { + kept.retain(|range| !range.is_empty()); + kept.sort_by_key(|range| range.start); + let mut merged: Vec> = Vec::with_capacity(kept.len()); + for range in kept { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + for edit in edits { + let next = merged.partition_point(|range| range.end <= edit.range.start); + if merged.get(next).is_some_and(|range| range.start < edit.range.end) { + return Err(FontError::ConflictingNameStorage); + } + } + Ok(()) +} + +/// Writes the edits into `out`, refusing two edits that write different bytes to the same place. +fn apply_edits(out: &mut [u8], name: &Table, edits: &[Edit]) -> Result<(), FontError> { + let mut ranges: Vec<&Edit> = edits.iter().collect(); + ranges.sort_by_key(|edit| (edit.range.start, edit.range.end)); + ranges.dedup_by(|a, b| a.range == b.range && a.bytes == b.bytes); + let mut written = vec![false; name.length]; + for edit in ranges { + let target = out.get_mut(edit.range.clone()).ok_or(FontError::MalformedFont)?; + let start = edit.range.start.checked_sub(name.offset).ok_or(FontError::MalformedFont)?; + let marks = written.get_mut(start..start + edit.bytes.len()).ok_or(FontError::MalformedFont)?; + for ((byte, mark), &new) in target.iter_mut().zip(marks.iter_mut()).zip(&edit.bytes) { + if *mark && *byte != new { + return Err(FontError::ConflictingNameStorage); + } + *byte = new; + *mark = true; + } + } + Ok(()) +} + +/// The OpenType table checksum: the sum of big-endian 32-bit words, the last one padded with zeros. +fn checksum(data: &[u8]) -> u32 { + data.chunks(4).fold(0u32, |sum, chunk| { + let mut word = [0u8; 4]; + for (to, &from) in word.iter_mut().zip(chunk) { + *to = from; + } + sum.wrapping_add(u32::from_be_bytes(word)) + }) +} + +fn copy_of(bytes: &[u8]) -> Result, FontError> { + let mut out = Vec::new(); + out.try_reserve_exact(bytes.len()).map_err(|_| FontError::OutputTooLarge)?; + out.extend_from_slice(bytes); + Ok(out) +} + +fn bytes_at(data: &[u8], at: usize, length: usize) -> Result<&[u8], FontError> { + let end = at.checked_add(length).ok_or(FontError::MalformedFont)?; + data.get(at..end).ok_or(FontError::MalformedFont) +} + +fn u16_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 2]>::try_from(bytes_at(data, at, 2)?).map_err(|_| FontError::MalformedFont)?; + Ok(u16::from_be_bytes(bytes)) +} + +fn u32_at(data: &[u8], at: usize) -> Result { + let bytes = <[u8; 4]>::try_from(bytes_at(data, at, 4)?).map_err(|_| FontError::MalformedFont)?; + Ok(u32::from_be_bytes(bytes)) +} + +fn put_bytes(data: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), FontError> { + let end = at.checked_add(bytes.len()).ok_or(FontError::MalformedFont)?; + data.get_mut(at..end).ok_or(FontError::MalformedFont)?.copy_from_slice(bytes); + Ok(()) +} + +fn put_u32(data: &mut [u8], at: usize, value: u32) -> Result<(), FontError> { + put_bytes(data, at, &value.to_be_bytes()) +} + +fn usize_from(value: u32) -> Result { + usize::try_from(value).map_err(|_| FontError::MalformedFont) +} + +fn offset32(value: usize) -> Result { + u32::try_from(value).map_err(|_| FontError::OutputTooLarge) +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..fbf29767ce 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -24,7 +24,14 @@ //! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +//! +//! ### Test fonts +//! +//! The [`fonts`] module makes test fonts from font bytes the caller supplies: +//! [`fonts::rename_family`] gives a face a family name of the same length, and +//! [`fonts::collection`] builds a TrueType collection from standalone faces. +pub mod fonts; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs new file mode 100644 index 0000000000..f2722f11d3 --- /dev/null +++ b/crates/testkit/tests/fonts.rs @@ -0,0 +1,558 @@ +//! Tests of `craft_testkit::fonts` on faces assembled here from bytes. +//! +//! The helpers below read the output by the offsets the OpenType specification gives, without the +//! crate's own parser, so a test fails when a field is wrong even if the crate could read it back. + +use craft_testkit::fonts::{FontError, collection, rename_family}; + +const FROM: &str = "Source Sans 3"; +const TO: &str = "Sysfont Sans3"; +const CHECKSUM_TARGET: u32 = 0xB1B0_AFBA; + +fn be16(data: &[u8], at: usize) -> u16 { + u16::from_be_bytes([data[at], data[at + 1]]) +} + +fn be32(data: &[u8], at: usize) -> u32 { + u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) +} + +fn set16(data: &mut [u8], at: usize, value: u16) { + data[at..at + 2].copy_from_slice(&value.to_be_bytes()); +} + +fn set32(data: &mut [u8], at: usize, value: u32) { + data[at..at + 4].copy_from_slice(&value.to_be_bytes()); +} + +/// The table checksum: big-endian 32-bit words added with wrapping, the last padded with zeros. +fn sum(data: &[u8]) -> u32 { + let mut total = 0u32; + let mut at = 0; + while at < data.len() { + let mut word = [0u8; 4]; + for (k, byte) in word.iter_mut().enumerate() { + if let Some(&b) = data.get(at + k) { + *byte = b; + } + } + total = total.wrapping_add(u32::from_be_bytes(word)); + at += 4; + } + total +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_be_bytes).collect() +} + +/// A name record: platform, encoding, name ID, and where its string is in storage. +struct Rec { + platform: u16, + encoding: u16, + name_id: u16, + offset: u16, + length: u16, +} + +/// A `name` table of `version` with the records as given, language tags as (length, offset), then storage. +fn name_table(version: u16, records: &[Rec], lang_tags: &[(u16, u16)], storage: &[u8]) -> Vec { + let mut header = 6 + 12 * records.len(); + if version == 1 { + header += 2 + 4 * lang_tags.len(); + } + let mut table = Vec::new(); + table.extend_from_slice(&version.to_be_bytes()); + table.extend_from_slice(&(records.len() as u16).to_be_bytes()); + table.extend_from_slice(&(header as u16).to_be_bytes()); + for rec in records { + for value in [rec.platform, rec.encoding, 0, rec.name_id, rec.length, rec.offset] { + table.extend_from_slice(&value.to_be_bytes()); + } + } + if version == 1 { + table.extend_from_slice(&(lang_tags.len() as u16).to_be_bytes()); + for &(length, offset) in lang_tags { + table.extend_from_slice(&length.to_be_bytes()); + table.extend_from_slice(&offset.to_be_bytes()); + } + } + table.extend_from_slice(storage); + table +} + +/// Name records with their strings stored one after another: (platform, encoding, name ID, bytes). +fn names(list: &[(u16, u16, u16, Vec)]) -> Vec { + let mut storage = Vec::new(); + let mut records = Vec::new(); + for (platform, encoding, name_id, bytes) in list { + records.push(Rec { platform: *platform, encoding: *encoding, name_id: *name_id, offset: storage.len() as u16, length: bytes.len() as u16 }); + storage.extend_from_slice(bytes); + } + name_table(0, &records, &[], &storage) +} + +/// A 54-byte `head` table whose `checkSumAdjustment` holds a stale value. +fn head() -> Vec { + let mut table = vec![0u8; 54]; + set32(&mut table, 0, 0x0001_0000); + set32(&mut table, 8, 0x1234_5678); + set32(&mut table, 12, 0x5F0F_3CF5); + set16(&mut table, 18, 1000); + table +} + +/// A standalone TrueType face holding `tables` in the order given, each on a four-byte boundary. +fn face(tables: &[(&[u8; 4], Vec)]) -> Vec { + let mut font = Vec::new(); + font.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + font.extend_from_slice(&(tables.len() as u16).to_be_bytes()); + font.extend_from_slice(&[0; 6]); + font.resize(12 + 16 * tables.len(), 0); + for (index, (tag, data)) in tables.iter().enumerate() { + let offset = font.len(); + font.extend_from_slice(data); + font.resize(font.len().div_ceil(4) * 4, 0); + let record = 12 + 16 * index; + font[record..record + 4].copy_from_slice(&tag[..]); + set32(&mut font, record + 4, sum(data)); + set32(&mut font, record + 8, offset as u32); + set32(&mut font, record + 12, data.len() as u32); + } + font +} + +fn family_face(list: &[(u16, u16, u16, Vec)]) -> Vec { + face(&[(b"head", head()), (b"name", names(list))]) +} + +/// A table of the face whose directory starts at `directory`: (record offset, table offset, length). +fn table_at(font: &[u8], directory: usize, tag: &[u8; 4]) -> (usize, usize, usize) { + let count = usize::from(be16(font, directory + 4)); + (0..count) + .map(|i| directory + 12 + 16 * i) + .find(|&record| &font[record..record + 4] == tag) + .map(|record| (record, be32(font, record + 8) as usize, be32(font, record + 12) as usize)) + .unwrap_or_else(|| panic!("no {} table", String::from_utf8_lossy(tag))) +} + +fn table(font: &[u8], tag: &[u8; 4]) -> (usize, usize, usize) { + table_at(font, 0, tag) +} + +/// Every name record of a standalone face: (platform, encoding, name ID, bytes). +fn strings(font: &[u8]) -> Vec<(u16, u16, u16, Vec)> { + let (_, at, _) = table(font, b"name"); + let count = usize::from(be16(font, at + 2)); + let storage = at + usize::from(be16(font, at + 4)); + (0..count) + .map(|i| { + let rec = at + 6 + 12 * i; + let start = storage + usize::from(be16(font, rec + 10)); + let end = start + usize::from(be16(font, rec + 8)); + (be16(font, rec), be16(font, rec + 2), be16(font, rec + 6), font[start..end].to_vec()) + }) + .collect() +} + +fn win(name_id: u16, text: &str) -> (u16, u16, u16, Vec) { + (3, 1, name_id, utf16(text)) +} + +fn mac(name_id: u16, bytes: &[u8]) -> (u16, u16, u16, Vec) { + (1, 0, name_id, bytes.to_vec()) +} + +#[test] +fn rename_handles_utf16_and_ascii() { + let font = family_face(&[win(1, FROM), (0, 3, 1, utf16(FROM)), mac(1, FROM.as_bytes()), win(16, FROM), win(21, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(out.len(), font.len()); + assert_eq!(strings(&out), vec![win(1, TO), (0, 3, 1, utf16(TO)), mac(1, TO.as_bytes()), win(16, TO), win(21, TO)]); +} + +#[test] +fn rename_only_family_records() { + let list = [ + win(0, "Copyright 2026 the Source Sans 3 authors"), + win(1, FROM), + win(2, "Regular"), + win(6, "SourceSans3-Regular"), + win(13, "Source Sans 3 is licensed under the OFL"), + win(16, "Source Sans 3 Extra"), + ]; + let other = utf16(FROM); + let font = face(&[(b"head", head()), (b"name", names(&list)), (b"zzzz", other.clone())]); + let out = rename_family(&font, FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[1] = win(1, TO); + assert_eq!(strings(&out), want); + let (_, at, length) = table(&out, b"zzzz"); + assert_eq!(&out[at..at + length], &other[..], "a table other than name keeps its bytes"); +} + +#[test] +fn rename_full_name_prefix_only() { + let list = + [win(1, FROM), win(4, "Source Sans 3 Bold"), (0, 3, 4, utf16("Source Sans 3Bold")), mac(4, b"My Source Sans 3"), mac(4, FROM.as_bytes())]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(4, "Sysfont Sans3 Bold"), list[2].clone(), list[3].clone(), mac(4, TO.as_bytes())]); +} + +#[test] +fn rename_rejects_non_ascii_mac_roman() { + let font = family_face(&[win(1, FROM), mac(1, FROM.as_bytes())]); + assert_eq!(rename_family(&font, FROM, "Sourcé Sans 3"), Err(FontError::UnsupportedEncoding)); + // "Café Sans 3" in Mac Roman, where é is 0x8E. + let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_unrelated_mac_roman_names() { + // Mac Roman 0x8E is "é". Neither Mac record can hold "Café Sans 3": one is shorter, and the other + // differs from it in an ASCII position. + let list = [win(1, "Café Sans 3"), mac(4, b"Autre \x8E"), mac(16, b"Caf\x8E Sans 4")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); +} + +#[test] +fn rename_keeps_mac_roman_full_name_suffix() { + let list = [win(1, FROM), mac(4, b"Source Sans 3 Cr\x8Ame")]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), mac(4, b"Sysfont Sans3 Cr\x8Ame")]); +} + +#[test] +fn rename_requires_a_family_record() { + let font = family_face(&[win(1, "Other Family"), win(4, "Source Sans 3 Bold")]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_preserves_other_encodings() { + let list = [win(1, FROM), (3, 3, 1, utf16(FROM)), (1, 1, 1, FROM.as_bytes().to_vec()), (2, 1, 1, utf16(FROM))]; + let out = rename_family(&family_face(&list), FROM, TO).unwrap(); + let mut want = list.to_vec(); + want[0] = win(1, TO); + assert_eq!(strings(&out), want); +} + +#[test] +fn rename_rejects_odd_utf16() { + let mut odd = utf16(FROM); + odd.push(0); + let font = family_face(&[(3, 1, 1, odd)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_surrogate() { + let font = family_face(&[(3, 1, 1, vec![0xD8, 0x00, 0x00, b'A']), win(16, FROM)]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_handles_shared_family_storage() { + let storage = utf16("Source Sans 3 Bold"); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 16, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(16, TO), win(4, "Sysfont Sans3 Bold")]); +} + +#[test] +fn rename_rejects_shared_nonfamily_storage() { + let records = + [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, Rec { platform: 3, encoding: 1, name_id: 6, offset: 2, length: 10 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_updates_name_checksum() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (record, at, length) = table(&out, b"name"); + assert_eq!(be32(&out, record + 4), sum(&out[at..at + length])); + assert_ne!(be32(&out, record + 4), be32(&font, record + 4), "the renamed table has a new checksum"); +} + +#[test] +fn rename_updates_head_adjustment() { + let font = family_face(&[win(1, FROM)]); + let out = rename_family(&font, FROM, TO).unwrap(); + let (_, at, _) = table(&out, b"head"); + let mut zeroed = out.clone(); + set32(&mut zeroed, at + 8, 0); + assert_eq!(be32(&out, at + 8), CHECKSUM_TARGET.wrapping_sub(sum(&zeroed))); + assert_eq!(sum(&out), CHECKSUM_TARGET); +} + +#[test] +fn rename_format_one_preserves_language_tags() { + let mut storage = utf16(FROM); + storage.extend(utf16("en-US")); + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(10, 26)], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO)]); + let (_, at, length) = table(&out, b"name"); + assert_eq!(&out[at + length - 10..at + length], &utf16("en-US")[..]); + assert_eq!(be16(&out, at + 18), 1, "the language-tag count stays"); +} + +#[test] +fn rename_keeps_language_tag_storage() { + let records = [Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }]; + let font = face(&[(b"head", head()), (b"name", name_table(1, &records, &[(26, 0)], &utf16(FROM)))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); +} + +#[test] +fn rename_rejects_short_sfnt() { + assert_eq!(rename_family(&[], FROM, TO), Err(FontError::MalformedFont)); + assert_eq!(rename_family(&[0, 1, 0, 0, 0], FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_truncated_directory() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font[..12 + 16 + 8], FROM, TO), Err(FontError::MalformedFont)); + let mut many = font.clone(); + set16(&mut many, 4, 4000); + assert_eq!(rename_family(&many, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_collection() { + let font = family_face(&[win(1, FROM)]); + let ttc = collection(&[&font]).unwrap(); + assert_eq!(rename_family(&ttc, FROM, TO), Err(FontError::UnsupportedFace)); +} + +#[test] +fn rename_rejects_missing_name_table() { + let font = face(&[(b"head", head())]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MissingNameTable)); +} + +#[test] +fn rename_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec()), (b"name", names(&[win(1, FROM)]))]); + assert_eq!(rename_family(&font, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_storage() { + let font = family_face(&[win(1, FROM)]); + let (_, at, length) = table(&font, b"name"); + let mut beyond = font.clone(); + set16(&mut beyond, at + 4, length as u16 + 1); + assert_eq!(rename_family(&beyond, FROM, TO), Err(FontError::MalformedFont)); + let mut inside_header = font.clone(); + set16(&mut inside_header, at + 4, 6); + assert_eq!(rename_family(&inside_header, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_bad_name_record_range() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut long = font.clone(); + set16(&mut long, at + 6 + 8, 28); + assert_eq!(rename_family(&long, FROM, TO), Err(FontError::MalformedFont)); + let mut late = font; + set16(&mut late, at + 6 + 10, 2); + assert_eq!(rename_family(&late, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_name_table_sharing_bytes() { + let font = face(&[(b"head", head()), (b"name", names(&[win(1, FROM)])), (b"zzzz", vec![7; 8])]); + let (_, at, _) = table(&font, b"name"); + let (record, _, _) = table(&font, b"zzzz"); + let mut shared = font.clone(); + set32(&mut shared, record + 8, (at + 18) as u32); + assert_eq!(rename_family(&shared, FROM, TO), Err(FontError::MalformedFont)); + let (_, head_at, _) = table(&font, b"head"); + let mut under_head = font; + set32(&mut under_head, record + 8, (head_at + 8) as u32); + assert_eq!(rename_family(&under_head, FROM, TO), Err(FontError::MalformedFont), "checkSumAdjustment would land in zzzz"); +} + +#[test] +fn rename_rejects_unknown_name_format() { + let font = family_face(&[win(1, FROM)]); + let (_, at, _) = table(&font, b"name"); + let mut two = font; + set16(&mut two, at, 2); + assert_eq!(rename_family(&two, FROM, TO), Err(FontError::MalformedFont)); +} + +#[test] +fn rename_rejects_unequal_lengths() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, FROM, "Other"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_unequal_utf16_lengths() { + // Both names are four bytes of UTF-8, but "𝐀" is two UTF-16 code units and "abcd" is four. + let font = family_face(&[win(1, "𝐀")]); + assert_eq!(rename_family(&font, "𝐀", "abcd"), Err(FontError::UnequalLength)); +} + +#[test] +fn rename_rejects_missing_family() { + let font = family_face(&[win(1, FROM), win(2, "Regular")]); + assert_eq!(rename_family(&font, "Source Sans 4", TO), Err(FontError::NameNotFound)); +} + +#[test] +fn rename_rejects_empty_names() { + let font = family_face(&[win(1, FROM)]); + assert_eq!(rename_family(&font, "", ""), Err(FontError::InvalidName)); + assert_eq!(rename_family(&font, FROM, ""), Err(FontError::InvalidName)); +} + +/// Two faces that differ in every table, with table lengths that are not multiples of four. +fn two_faces() -> (Vec, Vec) { + let a = face(&[(b"head", head()), (b"name", names(&[mac(1, b"Alpha")])), (b"zzzz", vec![1, 2, 3, 4, 5])]); + let mut other_head = head(); + set32(&mut other_head, 4, 0x0002_0000); + let b = face(&[(b"head", other_head), (b"name", names(&[mac(1, b"Beta")])), (b"zzzz", vec![9; 7])]); + (a, b) +} + +/// Each face's directory offset, read from the TTC header. +fn ttc_faces(ttc: &[u8]) -> Vec { + assert_eq!(&ttc[..4], b"ttcf"); + assert_eq!(be32(ttc, 4), 0x0001_0000); + (0..be32(ttc, 8) as usize).map(|i| be32(ttc, 12 + 4 * i) as usize).collect() +} + +/// Every table of a face in a collection: (tag, checksum, offset, length). +fn ttc_tables(ttc: &[u8], directory: usize) -> Vec<([u8; 4], u32, usize, usize)> { + (0..usize::from(be16(ttc, directory + 4))) + .map(|i| { + let r = directory + 12 + 16 * i; + (ttc[r..r + 4].try_into().unwrap(), be32(ttc, r + 4), be32(ttc, r + 8) as usize, be32(ttc, r + 12) as usize) + }) + .collect() +} + +#[test] +fn collection_offsets_are_file_relative() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + let faces = ttc_faces(&ttc); + assert_eq!(faces.len(), 2); + for (directory, input) in faces.into_iter().zip([&a, &b]) { + assert_eq!(&ttc[directory..directory + 12], &input[..12], "the sfnt header is copied"); + for (tag, _, offset, length) in ttc_tables(&ttc, directory) { + let (_, from, from_length) = table(input, &tag); + assert_eq!(length, from_length); + let mut want = input[from..from + from_length].to_vec(); + if &tag == b"head" { + set32(&mut want, 8, 0); + } + assert_eq!(&ttc[offset..offset + length], &want[..], "{} sits at its file offset", String::from_utf8_lossy(&tag)); + } + } +} + +#[test] +fn collection_pads_odd_faces() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + assert_eq!(ttc.len() % 4, 0); + for directory in ttc_faces(&ttc) { + assert_eq!(directory % 4, 0); + for (_, _, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(offset % 4, 0, "tables start on four-byte boundaries"); + let padded = length.div_ceil(4) * 4; + assert!(ttc[offset + length..offset + padded].iter().all(|&b| b == 0), "padding is zero"); + } + } + let lengths: Vec = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| t.3).collect(); + assert!(lengths.iter().any(|length| length % 4 != 0), "the fixture has unpadded lengths"); +} + +#[test] +fn collection_checksums_match_tables() { + let (a, b) = two_faces(); + let ttc = collection(&[&a, &b]).unwrap(); + for directory in ttc_faces(&ttc) { + for (tag, checksum, offset, length) in ttc_tables(&ttc, directory) { + assert_eq!(checksum, sum(&ttc[offset..offset + length])); + if &tag == b"head" { + assert_eq!(be32(&ttc, offset + 8), 0, "checkSumAdjustment is zero in a collection"); + } + } + } +} + +#[test] +fn collection_copies_tables() { + let (a, _) = two_faces(); + let ttc = collection(&[&a, &a]).unwrap(); + let mut ranges: Vec<(usize, usize)> = ttc_faces(&ttc).into_iter().flat_map(|d| ttc_tables(&ttc, d)).map(|t| (t.2, t.2 + t.3)).collect(); + assert_eq!(ranges.len(), 6); + ranges.sort(); + assert!(ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0), "each face has its own tables"); +} + +#[test] +fn collection_rejects_empty() { + assert_eq!(collection(&[]), Err(FontError::EmptyCollection)); +} + +#[test] +fn collection_rejects_nested_ttc() { + let (a, _) = two_faces(); + let ttc = collection(&[&a]).unwrap(); + assert_eq!(collection(&[&a, &ttc]), Err(FontError::UnsupportedFace)); +} + +#[test] +fn collection_rejects_short_directory() { + let (a, _) = two_faces(); + assert_eq!(collection(&[&a[..3]]), Err(FontError::MalformedFont)); + assert_eq!(collection(&[&a[..12 + 16 * 2]]), Err(FontError::MalformedFont)); + let mut many = a.clone(); + set16(&mut many, 4, 400); + assert_eq!(collection(&[&a, &many]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_out_of_range_table() { + let (a, _) = two_faces(); + let (record, _, _) = table(&a, b"zzzz"); + let mut late = a.clone(); + set32(&mut late, record + 8, a.len() as u32); + assert_eq!(collection(&[&late]), Err(FontError::MalformedFont)); + let mut long = a.clone(); + set32(&mut long, record + 12, u32::MAX); + assert_eq!(collection(&[&long]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_short_head() { + let font = face(&[(b"head", head()[..8].to_vec())]); + assert_eq!(collection(&[&font]), Err(FontError::MalformedFont)); +} + +#[test] +fn collection_rejects_offset_overflow() { + // 4,096 references to one face with a 1 MiB table add up to more than 4 GiB of output, which + // 32-bit offsets cannot address. The function refuses before allocating any of it. + let big = face(&[(b"zzzz", vec![0; 1 << 20])]); + let faces = vec![&big[..]; 4096]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} From 97d1335caf05952ef8cc336f905f42541488d660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:10:27 -0800 Subject: [PATCH 007/490] craft-testkit: skip or fail a test that lacks a program, a corpus or the craft-fonts faces Add the skip module to craft-testkit, for the Craft apps and the craft-libs crates to take as a dev-dependency. - skip(reason, required_var) prints one "SKIPPED: " line to stderr and returns false, or fails the test when the variable is exactly 1. Unset, empty, 0, true, " 1" and "1\n" all skip. - or_skip!(probe, var) binds the Ok value of a Result or skips and returns; or_skip!(probe, var, value) returns the given value, for a test that returns a Result. - craft_fonts(present, required) takes both values from the caller's build; craft_fonts_cover(text, faces) checks that one face maps every character of the text that is not whitespace. A carriage return or line feed in a reason is printed as \r or \n, so one skip is one line. The module is native only and does not change the process environment; its tests that read a variable run the test binary again as a child process. --- Cargo.lock | 3 + README.md | 4 +- crates/testkit/Cargo.toml | 5 +- crates/testkit/README.md | 59 ++++++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/skip.rs | 379 +++++++++++++++++++++++++++++++++++++ 6 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 crates/testkit/src/skip.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..182a0deb6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "skrifa 0.47.0", +] [[package]] name = "craft-text" diff --git a/README.md b/README.md index adbb6c120e..6b015e678c 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit `color` and `write`; re-exports them for existing users. - [`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. Not published. + out of range, and `std::time::Instant` in code the web build runs. 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 exactly `1`. 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). diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..de033a3259 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -5,10 +5,13 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Source-level platform regression guards and verification utilities for the Craft application suite" +description = "Source-level platform regression guards, skip-or-fail helpers and verification utilities for the Craft application suite" publish = false [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +skrifa = { version = "0.47", default-features = false, features = ["std"] } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e4cfc02f8 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -27,6 +27,54 @@ Source-level guards provide deterministic syntactic evidence about codebase stru Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. +## skip + +The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack +(a program, a corpus file, the craft-fonts faces) skips or fails under one rule: + +- When the variable the caller names is exactly `1`, the absence fails the test. No skip line is + printed. +- Otherwise, including when the variable is unset, empty, `0`, `true`, ` 1` or `1` followed by a + line feed, the helper prints `SKIPPED: ` and one line feed to stderr, and the test + returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. + +The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, +`CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. +`skip::REQUIRED_VAR` (`CRAFT_TEST_REQUIRED`) is the default name. + +```rust +use craft_testkit::skip::{REQUIRED_VAR, craft_fonts, skip}; + +#[test] +fn renders_with_qpdf() { + let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); + // ... +} + +#[test] +fn draws_japanese() { + if !craft_fonts(HAS_CRAFT_FONTS, CRAFT_FONTS_REQUIRED) { + return; + } + // ... +} +``` + +`or_skip!` evaluates a `Result` once, binds the `Ok` value, and on `Err` skips with the error's +`Display` text as the reason. The two-argument form returns `()`; a test that returns a `Result` +passes the value to return as the third argument, for example `Ok(())`. + +`craft_fonts(present, required)` takes both values from the caller's build: a build constant, an +`option_env!` value, or the table `craft-fonts-build` generates. A required failure names +`CRAFT_FONTS_REQUIRED=1`. + +`craft_fonts_cover(text, faces)` returns `true` when one face maps every character of `text` that +is not whitespace. Each face is font data with its index in a collection (`0` for a single font). A +face that does not parse covers nothing, and coverage is not combined across faces. + +The module does not change the process environment. Its tests that read a real variable run the +test binary again as a child process with that variable set. + ## Consumer Adoption Examples ### 1. PhotoCraft: Adopt `wgsl_float_literals` and `predefined_quit` @@ -83,6 +131,11 @@ fn no_std_instant_in_code_the_web_build_runs() { | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `skip` | storytold/lightcraft | `crates/testkit/src/lib.rs` (`skip!`, `record`) | `7ebbb17a82` | +| `skip` | storytold/pdfcraft | `crates/oracle/src/lib.rs` (`or_skip!`, `REQUIRED_VAR`) | `ee9bf28126` | +| `skip` | storytold/filmcraft | `crates/testkit/src/lib.rs` (`require_*!`), `crates/testkit/src/oracle.rs` (`skip`) | `cff7e1442e` | +| `skip` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`skip`, `skip_with`) | `75a654f4f8` | +| `skip` | storytold/gridcraft | `crates/ui-egui/src/theme.rs` (`craft_fonts_cover`) | `06c2b1440b` | ## Migration @@ -90,3 +143,9 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| LightCraft | `skip` | `lightcraft-testkit`'s `skip!`, which keeps its JSON skip log on top of `skip` | Not started | +| PdfCraft | `skip` | `pdfcraft-oracle`'s `or_skip!`, which reads any value of `PDFCRAFT_ORACLES_REQUIRED` | Not started | +| FilmCraft | `skip` | `filmcraft-testkit`'s `require_*!` and `skip`, which accept `1`, `true`, `yes` and `on` | Not started | +| GridCraft | `skip` | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | +| craft-libs `craft-media-testkit` | `skip` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | +| craft-libs `pdf` tests | `skip` | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..4f989f2694 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, +//! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the +//! variable the caller names is exactly `1`. It is not built for `wasm32`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(not(target_arch = "wasm32"))] +pub mod skip; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs new file mode 100644 index 0000000000..183db3b97d --- /dev/null +++ b/crates/testkit/src/skip.rs @@ -0,0 +1,379 @@ +//! Skip-or-fail for a test that needs something a test environment may lack: a program, a corpus +//! file, the craft-fonts faces. +//! +//! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and +//! passes. When the variable the caller names is exactly `1`, the absence fails the test instead +//! and no skip line is printed. Unset, empty, `0`, `true`, ` 1` and `1\n` all leave the test +//! optional. The caller passes the name its repository uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` +//! or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is the default name. +//! +//! ```no_run +//! use craft_testkit::skip::{REQUIRED_VAR, skip}; +//! +//! fn find_qpdf() -> Result { +//! Err("qpdf is not on PATH".into()) +//! } +//! +//! // A test returning `()`: bind the program or return. +//! let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); +//! # let _ = qpdf; +//! +//! // The same rule without a `Result` to match on. +//! let gpu_available = false; +//! if !gpu_available && !skip("no GPU adapter", REQUIRED_VAR) { +//! return; +//! } +//! ``` +//! +//! A reason that holds a carriage return or a line feed is printed with them written as `\r` and +//! `\n`, so one skip is one line. Each line is written with one call while stderr is locked, so +//! lines from tests running in parallel do not mix; their order is not fixed. + +use std::ffi::OsStr; + +/// The default name of the variable that makes a skip fail the test. +pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; + +/// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. +pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; + +/// Whether the variable `var` is set to exactly `1`. Any other value, a value that is not valid +/// Unicode, and an unset variable return `false`. +pub fn required(var: &str) -> bool { + is_required_value(std::env::var_os(var).as_deref()) +} + +fn is_required_value(value: Option<&OsStr>) -> bool { + value == Some(OsStr::new("1")) +} + +/// Skip the calling test: print `SKIPPED: ` and return `false`, or fail the test when +/// `required_var` is exactly `1`. The caller returns from the test itself: +/// `if !skip(reason, var) { return; }`. +pub fn skip(reason: &str, required_var: &str) -> bool { + skip_with(required(required_var), reason, required_var) +} + +/// Fail the test when `required` is set, otherwise print the skip line and return `false`. It +/// fails the test with a panic. +#[allow(clippy::panic)] +fn skip_with(required: bool, reason: &str, required_var: &str) -> bool { + if required { + panic!("{reason}, and {required_var}=1 forbids skipping this test"); + } + eprint!("{}", skip_line(reason)); + false +} + +/// The skip line for `reason`, with its carriage returns and line feeds escaped, ending in one +/// line feed. +fn skip_line(reason: &str) -> String { + let mut line = String::with_capacity("SKIPPED: \n".len() + reason.len()); + line.push_str("SKIPPED: "); + for c in reason.chars() { + match c { + '\r' => line.push_str("\\r"), + '\n' => line.push_str("\\n"), + c => line.push(c), + } + } + line.push('\n'); + line +} + +/// Whether a test that needs the craft-fonts faces can run. Returns `true` when `present` is set. +/// Without the faces it prints a skip line and returns `false`, or fails the test when `required` +/// is set. The caller passes both values from its build: a build constant, an `option_env!` +/// value, or the table `craft-fonts-build` generates. +pub fn craft_fonts(present: bool, required: bool) -> bool { + present || skip_with(required, "craft-fonts faces unavailable (build with CRAFT_FONTS_DIR)", FONTS_REQUIRED_VAR) +} + +/// Whether one of `faces` maps every character of `text` that is not whitespace. Each face is +/// font data and the index of the face in a collection (`0` for a single font). A face that does +/// not parse covers nothing, and the characters must all come from the same face. Each combining +/// mark is a character of its own. Text that is empty or only whitespace is covered when at least +/// one face parses. +pub fn craft_fonts_cover(text: &str, faces: &[(&[u8], u32)]) -> bool { + use skrifa::MetadataProvider as _; + faces.iter().any(|&(data, index)| { + let Ok(font) = skrifa::FontRef::from_index(data, index) else { + return false; + }; + let map = font.charmap(); + text.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some()) + }) +} + +/// Binds the `Ok` value of a `Result` probe, or skips the calling test under the rule of +/// [`skip`](crate::skip::skip) and returns from it. The probe is evaluated once, and its error is +/// the skip reason, so the error type implements `Display`. +/// +/// `or_skip!(probe, var)` returns `()` and belongs in a test returning `()`. +/// `or_skip!(probe, var, value)` returns `value`, for example `Ok(())` in a test that returns a +/// `Result`. +#[macro_export] +macro_rules! or_skip { + ($probe:expr, $required_var:expr) => { + $crate::or_skip!($probe, $required_var, ()) + }; + ($probe:expr, $required_var:expr, $ret:expr) => { + match $probe { + ::core::result::Result::Ok(value) => value, + ::core::result::Result::Err(absent) => { + let _ = $crate::skip::skip(&::std::string::ToString::to_string(&absent), $required_var); + return $ret; + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::process::{Command, Output}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_SKIP_CHILD"; + /// A variable no test sets, for skips that must stay optional. + const NEVER_SET: &str = "CRAFT_TESTKIT_SKIP_NEVER_SET"; + + /// Runs `child` below in a new process of this test binary, with `REQUIRED_VAR` set to + /// `required` or removed, so no test changes this process's environment. + fn run_child(case: &str, required: Option<&str>) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["skip::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + match required { + Some(value) => cmd.env(REQUIRED_VAR, value), + None => cmd.env_remove(REQUIRED_VAR), + }; + cmd.output().expect("run the test binary") + } + + fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + match case.to_str() { + Some("skip") => { + assert!(!skip("probe absent", REQUIRED_VAR)); + eprintln!("returned from skip"); + } + Some("or_skip") => { + let value: u32 = crate::or_skip!(Err::("probe absent"), REQUIRED_VAR); + eprintln!("ran on with {value}"); + } + Some("threads") => std::thread::scope(|s| { + for i in 0..8 { + s.spawn(move || skip(&format!("thread {i}\r\nsecond half"), REQUIRED_VAR)); + } + }), + other => panic!("unknown child case {other:?}"), + } + } + + /// Unset, empty, `0`, `true`, a leading space and a trailing line feed are optional; only + /// exactly `1` is required. + #[test] + fn only_exactly_1_is_required() { + assert!(!is_required_value(None)); + for value in ["", "0", "true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11"] { + assert!(!is_required_value(Some(OsStr::new(value))), "{value:?}"); + } + assert!(is_required_value(Some(OsStr::new("1")))); + } + + #[cfg(unix)] + #[test] + fn a_value_that_is_not_unicode_is_optional() { + use std::os::unix::ffi::OsStrExt as _; + assert!(!is_required_value(Some(OsStr::from_bytes(b"1\xff")))); + assert!(!is_required_value(Some(OsStr::from_bytes(b"\xff")))); + } + + /// Absence is never silent, and which of the two loud forms it takes is decided by the + /// variable: exactly `1` fails the test, and `0` (fatal under the any-value rule) skips. + #[test] + fn a_missing_oracle_is_fatal_exactly_when_it_is_required() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert!(!skip_with(is_required_value(Some(OsStr::new("0"))), "qpdf is not on PATH", var)); + assert!(!skip_with(is_required_value(Some(OsStr::new(""))), "qpdf is not on PATH", var)); + + let failed = std::panic::catch_unwind(|| skip_with(is_required_value(Some(OsStr::new("1"))), "qpdf is not on PATH", var)); + let message = failed.expect_err("a required absence fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("qpdf is not on PATH"), "{message}"); + assert!(message.contains("CRAFT_PDF_ORACLES_REQUIRED=1"), "{message}"); + } + + #[test] + fn a_skip_line_is_one_line_with_its_reason_escaped() { + assert_eq!(skip_line("qpdf is not on PATH"), "SKIPPED: qpdf is not on PATH\n"); + let line = skip_line("first\r\nsecond\nthird\r"); + assert_eq!(line, "SKIPPED: first\\r\\nsecond\\nthird\\r\n"); + assert_eq!(line.lines().count(), 1); + assert_eq!(skip_line(""), "SKIPPED: \n"); + } + + /// The variable is read from the environment, and only exactly `1` fails the test. + #[test] + fn skip_reads_its_variable_from_the_environment() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + let out = run_child("skip", value); + let err = stderr(&out); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches("SKIPPED: probe absent\n").count(), 1, "{value:?}: {err}"); + assert!(err.contains("returned from skip"), "{value:?}: {err}"); + } + let out = run_child("skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED=1 forbids skipping this test"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("returned from skip"), "{err}"); + } + + #[test] + fn or_skip_returns_from_the_test_when_optional_and_fails_when_required() { + let out = run_child("or_skip", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + + let out = run_child("or_skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_TEST_REQUIRED=1"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + } + + #[test] + fn skip_lines_from_parallel_threads_stay_whole() { + let out = run_child("threads", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + let mut lines: Vec<&str> = err.lines().filter(|l| l.contains("SKIPPED") || l.contains("second half")).collect(); + lines.sort_unstable(); + let expected: Vec = (0..8).map(|i| format!("SKIPPED: thread {i}\\r\\nsecond half")).collect(); + assert_eq!(lines, expected, "{err}"); + } + + #[test] + fn or_skip_yields_the_value_and_evaluates_the_probe_once() { + let probes = Cell::new(0); + let probe = || { + probes.set(probes.get() + 1); + Ok::(7) + }; + let value = crate::or_skip!(probe(), NEVER_SET); + assert_eq!(value, 7); + assert_eq!(probes.get(), 1); + } + + #[test] + fn or_skip_returns_the_given_value_from_a_result_test() { + fn run(probes: &Cell) -> Result { + let value: u32 = crate::or_skip!( + { + probes.set(probes.get() + 1); + Err::("probe absent".into()) + }, + NEVER_SET, + Ok(0) + ); + Ok(value + 1) + } + let probes = Cell::new(0); + assert_eq!(run(&probes), Ok(0)); + assert_eq!(probes.get(), 1); + } + + #[test] + fn craft_fonts_runs_skips_or_fails() { + assert!(craft_fonts(true, false)); + assert!(craft_fonts(true, true)); + assert!(!craft_fonts(false, false)); + let failed = std::panic::catch_unwind(|| craft_fonts(false, true)); + let message = failed.expect_err("missing required faces fail the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("CRAFT_FONTS_REQUIRED=1"), "{message}"); + } + + /// A font holding only a format 12 `cmap` table that maps each range of code points. + fn face(ranges: &[(u32, u32)]) -> Vec { + let subtable_len = 16 + 12 * ranges.len() as u32; + let mut data = Vec::new(); + data.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(b"cmap"); + for v in [0u32, 28, 12 + subtable_len] { + data.extend_from_slice(&v.to_be_bytes()); + } + for v in [0u16, 1, 3, 10] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(&12u32.to_be_bytes()); + data.extend_from_slice(&12u16.to_be_bytes()); + data.extend_from_slice(&0u16.to_be_bytes()); + for v in [subtable_len, 0, ranges.len() as u32] { + data.extend_from_slice(&v.to_be_bytes()); + } + let mut glyph = 1u32; + for &(start, end) in ranges { + for v in [start, end, glyph] { + data.extend_from_slice(&v.to_be_bytes()); + } + glyph += end - start + 1; + } + data + } + + #[test] + fn craft_fonts_cover_the_advertised_scripts() { + let latin_greek_cyrillic = face(&[(0x41, 0x5A), (0x61, 0x7A), (0x391, 0x3C9), (0x410, 0x44F)]); + let faces: &[(&[u8], u32)] = &[(&latin_greek_cyrillic, 0)]; + for sample in ["Craft", "Αλφα", "Привет", "Craft Αλφα Привет"] { + assert!(craft_fonts_cover(sample, faces), "{sample}"); + } + assert!(!craft_fonts_cover("日本", faces)); + assert!(!craft_fonts_cover("Craft!", faces)); + } + + #[test] + fn coverage_needs_one_face_that_parses_and_maps_every_character() { + let a = face(&[(u32::from('A'), u32::from('A'))]); + let b = face(&[(u32::from('B'), u32::from('B'))]); + let e = face(&[(u32::from('e'), u32::from('e'))]); + let e_acute = face(&[(u32::from('e'), u32::from('e')), (0x301, 0x301)]); + let garbage: &[u8] = b"not a font"; + + assert!(!craft_fonts_cover("", &[])); + assert!(!craft_fonts_cover("A", &[])); + assert!(!craft_fonts_cover("", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(&a, 1)]), "a single font has no face 1"); + + assert!(craft_fonts_cover("", &[(&a, 0)])); + assert!(craft_fonts_cover(" \t\n\u{3000}", &[(&a, 0)])); + assert!(craft_fonts_cover(" A A ", &[(&a, 0)])); + assert!(craft_fonts_cover("A", &[(garbage, 0), (&a, 0)])); + + assert!(craft_fonts_cover("A", &[(&a, 0), (&b, 0)])); + assert!(craft_fonts_cover("B", &[(&a, 0), (&b, 0)])); + assert!(!craft_fonts_cover("AB", &[(&a, 0), (&b, 0)]), "each face covers only part of the text"); + + assert!(!craft_fonts_cover("e\u{301}", &[(&e, 0)]), "the combining mark is not mapped"); + assert!(craft_fonts_cover("e\u{301}", &[(&e_acute, 0)])); + } +} From 15cdfd8512bf88736f4f0077741911c96afcd851 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:26:23 -0800 Subject: [PATCH 008/490] craft-testkit: fonts reads Mac Roman names by character and rewrites only the family name rename_family compares a Macintosh Roman record with the family name character by character, using the Unicode mapping of Mac Roman, so a record whose non-ASCII letters differ from the name is left as it is instead of failing the rename with UnsupportedEncoding. A rename now writes only the bytes of the family name at the start of each matching string, and records that point at the same string are read once. A style name that shares the unchanged end of a full name keeps its bytes, and a name table with many records on one long string no longer allocates a copy of the string for each record. --- crates/testkit/src/fonts.rs | 163 ++++++++++++++++++++++------------ crates/testkit/tests/fonts.rs | 24 +++++ 2 files changed, 129 insertions(+), 58 deletions(-) diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 7231980c7a..04345b66a2 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -10,6 +10,7 @@ //! The module reads no file and no environment variable, prints nothing, and builds for //! `wasm32-unknown-unknown`. +use std::collections::HashMap; use std::fmt; use std::ops::Range; @@ -47,7 +48,7 @@ pub enum FontError { MalformedFont, /// A matching Macintosh Roman record would need a name that is not ASCII. UnsupportedEncoding, - /// A string the rename changes shares bytes with a string it keeps, or with a different replacement. + /// Bytes the rename changes are shared with a string it keeps, or with a different replacement. ConflictingNameStorage, /// [`collection`] was given no faces. EmptyCollection, @@ -66,7 +67,7 @@ impl fmt::Display for FontError { Self::MissingNameTable => "the font has no name table", Self::MalformedFont => "the font's table directory or name table is truncated or out of range", Self::UnsupportedEncoding => "a Macintosh Roman name record can only take an ASCII name", - Self::ConflictingNameStorage => "a renamed string shares its bytes with a string that must not change", + Self::ConflictingNameStorage => "the bytes of a renamed family name are shared with a string that must not change", Self::EmptyCollection => "a collection needs at least one face", Self::UnsupportedFace => "the input is not a standalone TrueType or CFF face", Self::OutputTooLarge => "the output is too large", @@ -91,7 +92,7 @@ impl std::error::Error for FontError {} /// [`FontError::InvalidName`] when a name is empty, [`FontError::UnequalLength`] when the names have /// different UTF-16 lengths, [`FontError::NameNotFound`] when no family record holds `from`, /// [`FontError::UnsupportedEncoding`] when a matching Macintosh Roman record would need non-ASCII -/// bytes, [`FontError::ConflictingNameStorage`] when a changed string shares bytes with a kept one, +/// bytes, [`FontError::ConflictingNameStorage`] when changed bytes are shared with a kept string, /// [`FontError::MissingNameTable`], [`FontError::UnsupportedFace`] for a collection, and /// [`FontError::MalformedFont`] when the directory, the `name` table or the `head` table is out of /// range or of an unknown version, or when the `name` or `head` table shares bytes with the directory @@ -244,7 +245,7 @@ fn write_face(out: &mut Vec, face: &[u8], tables: &[Table]) -> Result<(), Fo } /// How the bytes of a name record are encoded, as far as renaming reads them. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Encoding { Utf16, MacRoman, @@ -314,28 +315,42 @@ fn name_strings(face: &[u8], table: &Table) -> Result { Ok(NameStrings { names, lang_tags }) } -/// A string the rename writes: its range in the face and its new bytes. +/// Bytes the rename writes: the range of the family name at the start of a string, and the new name. +/// The rest of the string keeps its bytes. struct Edit { range: Range, bytes: Vec, } -/// Works out the strings to rewrite and the ranges of the strings that must keep their bytes. +/// Works out the family names to rewrite and the ranges of the strings that must keep their bytes. /// Refuses with [`FontError::NameNotFound`] when no family record (IDs 1, 16 and 21) holds `from`. +/// Records that point at the same string are read once. fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Result<(Vec, Vec>), FontError> { let mut edits = Vec::new(); let mut kept = strings.lang_tags.clone(); let mut family_found = false; + let mut read: HashMap<(usize, usize, Encoding, bool), bool> = HashMap::new(); for string in &strings.names { let family = FAMILY_IDS.contains(&string.name_id); - let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; - let new = if family || string.name_id == FULL_NAME_ID { renamed(string, bytes, from, to)? } else { None }; - match new { - Some(new) => { - family_found |= family; - edits.push(Edit { range: string.range.clone(), bytes: new }); + if !family && string.name_id != FULL_NAME_ID { + kept.push(string.range.clone()); + continue; + } + let key = (string.range.start, string.range.end, string.encoding, family); + let edited = match read.get(&key) { + Some(&edited) => edited, + None => { + let edit = renamed(string, face, from, to)?; + let edited = edit.is_some(); + edits.extend(edit); + read.insert(key, edited); + edited } - None => kept.push(string.range.clone()), + }; + if edited { + family_found |= family; + } else { + kept.push(string.range.clone()); } } if !family_found { @@ -344,67 +359,99 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul Ok((edits, kept)) } -/// The new bytes of a family or full-name string, or `None` when it does not hold `from`. -fn renamed(string: &NameString, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { +/// The edit of a family or full-name string, or `None` when it does not hold `from`. +fn renamed(string: &NameString, face: &[u8], from: &str, to: &str) -> Result, FontError> { let family = FAMILY_IDS.contains(&string.name_id); - let encoded = match string.encoding { + let bytes = face.get(string.range.clone()).ok_or(FontError::MalformedFont)?; + let renamed = match string.encoding { Encoding::Utf16 => renamed_utf16(family, bytes, from, to)?, Encoding::MacRoman => renamed_mac_roman(family, bytes, from, to)?, Encoding::Other => None, }; - if encoded.as_ref().is_some_and(|encoded| encoded.len() != bytes.len()) { + let Some((old_length, new)) = renamed else { + return Ok(None); + }; + if new.len() != old_length { return Err(FontError::UnequalLength); } - Ok(encoded) + let start = string.range.start; + Ok(Some(Edit { range: start..start + old_length, bytes: new })) } -/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and a space. -fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - let value = utf16_value(bytes)?; - let new = if family { - (value == from).then(|| to.to_owned()) - } else { - value.strip_prefix(from).filter(|rest| rest.is_empty() || rest.starts_with(' ')).map(|rest| format!("{to}{rest}")) - }; - Ok(new.map(|new| new.encode_utf16().flat_map(u16::to_be_bytes).collect())) -} - -/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, byte by byte; only ASCII names are written. -fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result>, FontError> { - if !from.is_ascii() { - return if mac_roman_may_hold(family, bytes, from) { Err(FontError::UnsupportedEncoding) } else { Ok(None) }; - } - let Some(rest) = bytes.strip_prefix(from.as_bytes()) else { - return Ok(None); - }; - if !(rest.is_empty() || (!family && rest.first() == Some(&b' '))) { - return Ok(None); - } - if !to.is_ascii() { - return Err(FontError::UnsupportedEncoding); - } - Ok(Some([to.as_bytes(), rest].concat())) -} - -/// Whether a Macintosh Roman string could hold a non-ASCII `from`. The encoding has one byte per -/// character and shares its ASCII range with Unicode, so a string that differs from `from` in length -/// or in an ASCII position cannot hold it. -fn mac_roman_may_hold(family: bool, bytes: &[u8], from: &str) -> bool { - let count = from.chars().count(); - let fits = bytes.len() == count || (!family && bytes.get(count) == Some(&b' ')); - fits && bytes.iter().zip(from.chars()).all(|(&byte, c)| !(byte.is_ascii() || c.is_ascii()) || char::from(byte) == c) -} - -/// Decodes a UTF-16BE string, refusing an odd length or an unpaired surrogate. -fn utf16_value(bytes: &[u8]) -> Result { +/// Renames a UTF-16BE family string whose value is `from`, or a full name that starts with `from` and +/// a space. Returns the byte length of `from` in the string and the bytes of `to`. +fn renamed_utf16(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { let (pairs, rest) = bytes.as_chunks::<2>(); if !rest.is_empty() { return Err(FontError::MalformedFont); } let units = pairs.iter().map(|&pair| u16::from_be_bytes(pair)); - char::decode_utf16(units).collect::>().map_err(|_| FontError::MalformedFont) + if char::decode_utf16(units.clone()).any(|c| c.is_err()) { + return Err(FontError::MalformedFont); + } + let count = from.encode_utf16().count(); + if !units.clone().take(count).eq(from.encode_utf16()) { + return Ok(None); + } + match units.clone().nth(count) { + None => {} + Some(unit) if !family && unit == u16::from(b' ') => {} + Some(_) => return Ok(None), + } + Ok(Some((count * 2, to.encode_utf16().flat_map(u16::to_be_bytes).collect()))) } +/// Renames a Macintosh Roman string the way [`renamed_utf16`] does, comparing its decoded characters +/// with `from`. Only ASCII names are written. +fn renamed_mac_roman(family: bool, bytes: &[u8], from: &str, to: &str) -> Result)>, FontError> { + let count = from.chars().count(); + let Some(name) = bytes.get(..count) else { + return Ok(None); + }; + if !name.iter().map(|&byte| mac_roman_char(byte)).eq(from.chars()) { + return Ok(None); + } + match bytes.get(count) { + None => {} + Some(b' ') if !family => {} + Some(_) => return Ok(None), + } + if !from.is_ascii() || !to.is_ascii() { + return Err(FontError::UnsupportedEncoding); + } + Ok(Some((count, to.as_bytes().to_vec()))) +} + +/// The character a Macintosh Roman byte stands for. Bytes below 0x80 are ASCII; the others follow +/// the mapping at . +fn mac_roman_char(byte: u8) -> char { + match byte.checked_sub(0x80) { + None => char::from(byte), + Some(high) => MAC_ROMAN_HIGH.get(usize::from(high)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + } +} + +/// The characters of Macintosh Roman bytes 0x80 to 0xFF. +#[rustfmt::skip] +const MAC_ROMAN_HIGH: [char; 128] = [ + '\u{00C4}', '\u{00C5}', '\u{00C7}', '\u{00C9}', '\u{00D1}', '\u{00D6}', '\u{00DC}', '\u{00E1}', + '\u{00E0}', '\u{00E2}', '\u{00E4}', '\u{00E3}', '\u{00E5}', '\u{00E7}', '\u{00E9}', '\u{00E8}', + '\u{00EA}', '\u{00EB}', '\u{00ED}', '\u{00EC}', '\u{00EE}', '\u{00EF}', '\u{00F1}', '\u{00F3}', + '\u{00F2}', '\u{00F4}', '\u{00F6}', '\u{00F5}', '\u{00FA}', '\u{00F9}', '\u{00FB}', '\u{00FC}', + '\u{2020}', '\u{00B0}', '\u{00A2}', '\u{00A3}', '\u{00A7}', '\u{2022}', '\u{00B6}', '\u{00DF}', + '\u{00AE}', '\u{00A9}', '\u{2122}', '\u{00B4}', '\u{00A8}', '\u{2260}', '\u{00C6}', '\u{00D8}', + '\u{221E}', '\u{00B1}', '\u{2264}', '\u{2265}', '\u{00A5}', '\u{00B5}', '\u{2202}', '\u{2211}', + '\u{220F}', '\u{03C0}', '\u{222B}', '\u{00AA}', '\u{00BA}', '\u{03A9}', '\u{00E6}', '\u{00F8}', + '\u{00BF}', '\u{00A1}', '\u{00AC}', '\u{221A}', '\u{0192}', '\u{2248}', '\u{2206}', '\u{00AB}', + '\u{00BB}', '\u{2026}', '\u{00A0}', '\u{00C0}', '\u{00C3}', '\u{00D5}', '\u{0152}', '\u{0153}', + '\u{2013}', '\u{2014}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{00F7}', '\u{25CA}', + '\u{00FF}', '\u{0178}', '\u{2044}', '\u{20AC}', '\u{2039}', '\u{203A}', '\u{FB01}', '\u{FB02}', + '\u{2021}', '\u{00B7}', '\u{201A}', '\u{201E}', '\u{2030}', '\u{00C2}', '\u{00CA}', '\u{00C1}', + '\u{00CB}', '\u{00C8}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{00CC}', '\u{00D3}', '\u{00D4}', + '\u{F8FF}', '\u{00D2}', '\u{00DA}', '\u{00DB}', '\u{00D9}', '\u{0131}', '\u{02C6}', '\u{02DC}', + '\u{00AF}', '\u{02D8}', '\u{02D9}', '\u{02DA}', '\u{00B8}', '\u{02DD}', '\u{02DB}', '\u{02C7}', +]; + /// Refuses a rename whose strings overlap a string that keeps its bytes. fn check_kept(edits: &[Edit], mut kept: Vec>) -> Result<(), FontError> { kept.retain(|range| !range.is_empty()); diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index f2722f11d3..6ff688c7fa 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -206,6 +206,16 @@ fn rename_rejects_non_ascii_mac_roman() { // "Café Sans 3" in Mac Roman, where é is 0x8E. let font = family_face(&[win(1, "Café Sans 3"), mac(1, b"Caf\x8E Sans 3")]); assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); + let font = family_face(&[win(1, "Café Sans 3"), mac(4, b"Caf\x8E Sans 3 Bold")]); + assert_eq!(rename_family(&font, "Café Sans 3", "Cafe Sans 3"), Err(FontError::UnsupportedEncoding)); +} + +#[test] +fn rename_keeps_mac_roman_names_with_other_letters() { + // Mac Roman 0x80 is "Ä" and 0x8F is "è", so neither Mac record holds "Café Sans 3". + let list = [win(1, "Café Sans 3"), mac(1, b"Caf\x80 Sans 3"), mac(4, b"Caf\x8F Sans 3 Bold")]; + let out = rename_family(&family_face(&list), "Café Sans 3", "Cafe Sans 3").unwrap(); + assert_eq!(strings(&out), vec![win(1, "Cafe Sans 3"), list[1].clone(), list[2].clone()]); } #[test] @@ -274,6 +284,20 @@ fn rename_rejects_shared_nonfamily_storage() { assert_eq!(rename_family(&font, FROM, TO), Err(FontError::ConflictingNameStorage)); } +#[test] +fn rename_keeps_a_style_sharing_the_full_name_suffix() { + // The style name (ID 2) "Bold" is the last 8 bytes of the full name, which the rename does not change. + let storage = [utf16(FROM), utf16("Source Sans 3 Bold")].concat(); + let records = [ + Rec { platform: 3, encoding: 1, name_id: 1, offset: 0, length: 26 }, + Rec { platform: 3, encoding: 1, name_id: 2, offset: 54, length: 8 }, + Rec { platform: 3, encoding: 1, name_id: 4, offset: 26, length: 36 }, + ]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &storage))]); + let out = rename_family(&font, FROM, TO).unwrap(); + assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); From 3a710e4c62a55feb4ad1b250305dbcbc9fb83f7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:41:12 -0800 Subject: [PATCH 009/490] craft-texture: tests check the sRGB pair against the standard, craft-cms, craft-mesh and craft-psd The new tests in crates/texture/tests/srgb.rs compare linear_to_srgb and srgb_to_linear with the IEC 61966-2-1 formulas at every 8-bit and 16-bit code, check both thresholds (0.0031308 and 0.04045) and their neighbors, round trips, and that the outputs do not decrease over the code grids. They pin the behavior outside [0, 1]: negative values stay on the linear segment, values above 1 follow the power segment, infinities keep their sign and NaN stays NaN. craft-mesh's pair and craft-psd's float::srgb_encode must match bit for bit, and craft-cms's srgb_trc() curve within 2.4e-7. craft-cms, craft-mesh and craft-psd are dev-dependencies of craft-texture. --- Cargo.lock | 3 + crates/texture/Cargo.toml | 5 + crates/texture/tests/srgb.rs | 192 +++++++++++++++++++++++++++++++++++ 3 files changed, 200 insertions(+) create mode 100644 crates/texture/tests/srgb.rs diff --git a/Cargo.lock b/Cargo.lock index c11a134ae5..18890555a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2591,6 +2591,9 @@ dependencies = [ name = "craft-texture" version = "0.1.0" dependencies = [ + "craft-cms", + "craft-mesh", + "craft-psd", "rayon", "thiserror 2.0.21", ] diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml index 78868dd879..cb56a4217f 100644 --- a/crates/texture/Cargo.toml +++ b/crates/texture/Cargo.toml @@ -17,3 +17,8 @@ workspace = true [dependencies] rayon = { workspace = true, optional = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-cms = { workspace = true } +craft-mesh = { workspace = true } +craft-psd = { workspace = true } diff --git a/crates/texture/tests/srgb.rs b/crates/texture/tests/srgb.rs new file mode 100644 index 0000000000..8884c6e3f3 --- /dev/null +++ b/crates/texture/tests/srgb.rs @@ -0,0 +1,192 @@ +//! The scalar sRGB pair against IEC 61966-2-1 and against the copies of it in craft-cms, +//! craft-mesh and craft-psd. +//! +//! The encoding is the one the ICC sRGB registry entry gives for IEC 61966-2-1:1999 +//! (); the decoding is the CSS Color 4 sample code +//! (). Outside `[0, 1]` the pair keeps +//! its own rule: negative values stay on the linear segment and values above 1 follow the power +//! segment. + +use craft_texture::{linear_to_srgb, srgb_to_linear}; + +/// The largest difference allowed between the `f32` pair and the `f64` formulas. +const STANDARD_TOLERANCE: f32 = 3.0e-7; +/// The largest difference allowed between the pair and craft-cms's ICC curve, which is evaluated +/// in `f64` and returned as `f32`. +const CMS_TOLERANCE: f32 = 2.4e-7; +/// The 8-bit and 16-bit code ranges. +const DEPTHS: [u32; 2] = [255, 65_535]; + +/// One direction of an sRGB pair. +type Scalar = fn(f32) -> f32; + +fn encode64(c: f64) -> f64 { + if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } +} + +fn decode64(c: f64) -> f64 { + if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} + +/// Every code of a depth with its normalized value. +fn codes(max: u32) -> impl Iterator { + (0..=max).map(move |n| (n, n as f32 / max as f32)) +} + +/// The largest difference between `f` and `g` over every code of a depth, and the code it is at. +fn worst(max: u32, f: impl Fn(f32) -> f32, g: impl Fn(f32) -> f32) -> (f32, u32) { + codes(max).map(|(n, v)| ((f(v) - g(v)).abs(), n)).fold((0.0, 0), |a, b| if b.0 > a.0 { b } else { a }) +} + +/// Inputs outside `[0, 1]` that the crates' copies must also agree on. +const OUTSIDE: [f32; 10] = [-0.0, -1.0e-6, -0.5, -1.0, -100.0, 1.5, 2.0, 100.0, f32::INFINITY, f32::NEG_INFINITY]; + +#[test] +fn encode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, linear_to_srgb, |v| encode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn decode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, srgb_to_linear, |v| decode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn every_encoded_code_round_trips() { + for max in DEPTHS { + for (n, v) in codes(max) { + let back = (linear_to_srgb(srgb_to_linear(v)) * max as f32).round() as u32; + assert_eq!(back, n, "code {n} of {max}"); + } + } +} + +#[test] +fn every_linear_code_round_trips_within_rounding() { + for max in DEPTHS { + let (d, n) = worst(max, |v| srgb_to_linear(linear_to_srgb(v)), |v| v); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} comes back {d} away"); + } +} + +#[test] +fn outputs_do_not_decrease_over_the_code_grids() { + for max in DEPTHS { + for f in [linear_to_srgb, srgb_to_linear] { + let out: Vec = codes(max).map(|(_, v)| f(v)).collect(); + let fall = out.windows(2).position(|w| w[1] < w[0]); + assert_eq!(fall, None, "the output falls after code {fall:?} of {max}"); + } + } +} + +#[test] +fn encode_changes_segment_after_0_0031308() { + let t = 0.003_130_8_f32; + for v in [t.next_down(), t] { + assert_eq!(linear_to_srgb(v), v * 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(linear_to_srgb(above), 1.055 * above.powf(1.0 / 2.4) - 0.055); + for v in [t.next_down(), t, above] { + assert!((linear_to_srgb(v) - encode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn decode_changes_segment_after_0_04045() { + let t = 0.040_45_f32; + for v in [t.next_down(), t] { + assert_eq!(srgb_to_linear(v), v / 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(srgb_to_linear(above), ((above + 0.055) / 1.055).powf(2.4)); + for v in [t.next_down(), t, above] { + assert!((srgb_to_linear(v) - decode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn zero_and_one_map_to_themselves() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(0.0).to_bits(), 0.0_f32.to_bits()); + assert_eq!(f(-0.0).to_bits(), (-0.0_f32).to_bits()); + assert!((f(1.0) - 1.0).abs() <= f32::EPSILON); + } +} + +#[test] +fn values_above_one_follow_the_power_segment() { + for v in [1.000_001_f32, 1.5, 2.0, 10.0] { + let (e, d) = (encode64(f64::from(v)), decode64(f64::from(v))); + assert!((f64::from(linear_to_srgb(v)) - e).abs() <= e * 1.0e-6, "encode {v}"); + assert!((f64::from(srgb_to_linear(v)) - d).abs() <= d * 1.0e-6, "decode {v}"); + } + assert!((linear_to_srgb(2.0) - 1.353_256).abs() < 1.0e-6); + assert!((srgb_to_linear(2.0) - 4.953_846).abs() < 1.0e-5); +} + +#[test] +fn negative_values_stay_on_the_linear_segment() { + for v in [-f32::MIN_POSITIVE, -1.0e-6, -0.003_130_8, -0.040_45, -0.5, -1.0, -100.0] { + assert_eq!(linear_to_srgb(v), v * 12.92, "encode {v}"); + assert_eq!(srgb_to_linear(v), v / 12.92, "decode {v}"); + } + assert!((linear_to_srgb(-1.0) + 12.92).abs() < 1.0e-5); + assert!((srgb_to_linear(-1.0) + 0.077_399_38).abs() < 1.0e-7); +} + +#[test] +fn infinities_keep_their_sign_and_nan_stays_nan() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(f32::INFINITY), f32::INFINITY); + assert_eq!(f(f32::NEG_INFINITY), f32::NEG_INFINITY); + assert!(f(f32::NAN).is_nan()); + } +} + +#[test] +fn mesh_pair_matches_bit_for_bit() { + let pairs: [(Scalar, Scalar); 2] = [(linear_to_srgb, craft_mesh::linear_to_srgb), (srgb_to_linear, craft_mesh::srgb_to_linear)]; + for (ours, mesh) in pairs { + for max in DEPTHS { + for (n, v) in codes(max) { + assert_eq!(ours(v).to_bits(), mesh(v).to_bits(), "code {n} of {max}"); + } + } + for v in OUTSIDE { + assert_eq!(ours(v).to_bits(), mesh(v).to_bits(), "{v}"); + } + assert!(mesh(f32::NAN).is_nan()); + } +} + +#[test] +fn psd_encoder_matches_bit_for_bit() { + for max in DEPTHS { + for (n, v) in codes(max) { + assert_eq!(linear_to_srgb(v).to_bits(), craft_psd::float::srgb_encode(v).to_bits(), "code {n} of {max}"); + } + } + for v in OUTSIDE { + assert_eq!(linear_to_srgb(v).to_bits(), craft_psd::float::srgb_encode(v).to_bits(), "{v}"); + } + assert!(craft_psd::float::srgb_encode(f32::NAN).is_nan()); +} + +#[test] +fn cms_curve_matches_within_rounding() { + let trc = craft_cms::curve::srgb_trc(); + for max in DEPTHS { + let (d, n) = worst(max, srgb_to_linear, |v| trc.eval(v)); + assert!(d <= CMS_TOLERANCE, "decode code {n} of {max} is {d} from craft-cms"); + let (d, n) = worst(max, linear_to_srgb, |v| trc.eval_inverse(v)); + assert!(d <= CMS_TOLERANCE, "encode code {n} of {max} is {d} from craft-cms"); + } +} From a221d6081b113fc30a5ea50732880f55c130593c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:32:46 -0800 Subject: [PATCH 010/490] craft-testkit: parse pinned-corpus manifests and check a corpus folder against them Add craft_testkit::corpus behind the corpus feature (native only, sha2). - Manifest::parse reads one tab-separated row per file: the SHA-256 as 64 hexadecimal digits in either case, a relative path with / between its parts, and optional license and URL columns. It skips blank lines and lines whose first character other than a space or tab is #, and reads LF and CRLF. A row with fewer than 2 or more than 4 columns, a bad digest, a path that is empty, absolute, has an empty, . or .. part or holds \, : or NUL, or a repeated path returns a ManifestError naming the line instead of panicking. - verify checks that each listed file resolves inside the folder after symbolic links are followed, is a regular file (checked before it is opened, so a directory or a named pipe is refused), is within the size limit, and has the listed SHA-256. An empty manifest is an error. - pinned(var, manifest) returns the folder the variable names (default CRAFT_CORPUS) after verify. With the variable unset it prints one "SKIPPED: corpus not given: set to its folder" line and returns None, or fails the test when _REQUIRED is exactly 1. A set but empty variable, a manifest that does not parse or a folder that does not match fails the test. - Limits: a manifest of at most 1 MiB and 10,000 rows, files of at most 8 GiB, hashed 64 KiB at a time. The parser follows the loader in crates/affinity/tests/support/corpus.rs, which has no tests of its own; that crate switches in its own pull request. The README gains the module's description and its Origin and Migration tables. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 5 + crates/testkit/README.md | 30 ++ crates/testkit/src/corpus.rs | 890 +++++++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 6 + 5 files changed, 934 insertions(+) create mode 100644 crates/testkit/src/corpus.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..edc19d31a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "sha2 0.10.9", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..33bf1c9d9d 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,12 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# Pinned-corpus manifests and the `corpus::pinned` test gate (native only). +corpus = ["dep:sha2"] + [dependencies] +sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..ab948e4f2e 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,36 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Pinned corpora: `corpus` + +`craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it. + +A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. + +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. +- `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. +- `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. + +`Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `corpus` | storytold/craft-libs | `crates/affinity/tests/support/corpus.rs:18-35` | `75a654f4` | + +### Migration + +| Consumer | Today | State | +|---|---|---| +| craft-libs `affinity` | `tests/support/corpus.rs` reads `corpus.tsv` (already tab-separated) from `AFFINITY_CORPUS` | Pending: a separate pull request switches it | +| craft-libs `raw` | `docs/raf-corpus.sha256` separates digest and path with two spaces | Pending: the list is converted to tabs in a separate pull request | +| LightCraft | `crates/raw/tests/it/corpus.rs` checks the RAF list | Pending: a separate pull request switches it | +| PhotoCraft | `crates/io/tests/it/corpus.rs` and `xtask/*-corpus.sha256` (two-space lists) | Pending: the lists are converted to tabs in a separate pull request | +| CADCraft | `crates/io/src/roundtrip/tests.rs` scans `CADCRAFT_CORPUS_DIR` without a checksum list | Pending: needs a pinned list first | +| VectorCraft | `crates/affinity/tests/support/corpus.rs` reads a two-space list | Pending: the list is converted to tabs in a separate pull request | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs new file mode 100644 index 0000000000..fb0a4e4d91 --- /dev/null +++ b/crates/testkit/src/corpus.rs @@ -0,0 +1,890 @@ +//! Pinned test corpora: a folder of files listed in a manifest, each checked against its SHA-256. +//! +//! A manifest has one tab-separated row per file: the SHA-256 as 64 hexadecimal digits, the +//! file's path relative to the corpus folder, and optional license and URL columns. In this +//! example each `\t` stands for one tab character: +//! +//! ```text +//! # Public Affinity documents +//! cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe\tafdesignload-color.afdesign\tMIT\thttps://example.org/color.afdesign +//! 9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484\tmore/layer_mode.afdesign +//! ``` +//! +//! [`Manifest::parse`] skips blank lines and lines whose first character other than a space or a +//! tab is `#`. A `#` later in a row is part of that row. It returns a [`ManifestError`] naming the +//! line of a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal +//! digits, a path that is empty, absolute or leaves the folder, or a path listed twice. Paths use +//! `/` between their parts. +//! +//! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after +//! checking every listed file, prints one `SKIPPED:` line and returns `None` when the variable is +//! unset and the corpus is optional, and fails the test otherwise. [`verify`] runs the same check +//! and returns a [`VerifyError`] instead of failing. No function here downloads a file or changes +//! the process environment. +//! +//! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, +//! and files of at most 8 GiB each, read 64 KiB at a time. + +use std::collections::HashSet; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The variable [`pinned`] reads when the caller names none. +pub const DEFAULT_VAR: &str = "CRAFT_CORPUS"; + +/// The suffix [`pinned`] adds to the folder variable's name to form the name of the variable that +/// makes the corpus required. +pub const REQUIRED_SUFFIX: &str = "_REQUIRED"; + +/// The size of each read while a file is hashed. +const CHUNK: usize = 64 * 1024; + +/// Size limits for a manifest and for the files it lists. An input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest manifest in bytes. Default 1 MiB. + pub max_manifest_bytes: usize, + /// The most rows a manifest may list. Default 10,000. + pub max_entries: usize, + /// The largest listed file in bytes. Default 8 GiB. + pub max_file_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: 1024 * 1024, max_entries: 10_000, max_file_bytes: 8 * 1024 * 1024 * 1024 } + } +} + +/// One row of a manifest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + digest: [u8; 32], + path: String, + license: Option, + url: Option, + line: usize, +} + +impl Entry { + /// The file's SHA-256. + pub fn digest(&self) -> &[u8; 32] { + &self.digest + } + + /// The file's path relative to the corpus folder, with `/` between its parts. + pub fn path(&self) -> &str { + &self.path + } + + /// The license column, when the row has one that is not empty. + pub fn license(&self) -> Option<&str> { + self.license.as_deref() + } + + /// The URL column, when the row has one that is not empty. + pub fn url(&self) -> Option<&str> { + self.url.as_deref() + } + + /// The 1-based line of the manifest that holds the row. + pub fn line(&self) -> usize { + self.line + } + + /// The file's path under `dir`. + fn path_in(&self, dir: &Path) -> PathBuf { + let mut path = dir.to_path_buf(); + path.extend(self.path.split('/')); + path + } +} + +/// A parsed manifest: the rows in the order the manifest lists them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Manifest { + entries: Vec, +} + +impl Manifest { + /// Parses `text` under the default [`Limits`]. + pub fn parse(text: &str) -> Result { + Self::parse_with_limits(text, &Limits::default()) + } + + /// Parses `text`. A manifest longer than `limits.max_manifest_bytes` or with more than + /// `limits.max_entries` rows is an error. + pub fn parse_with_limits(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let mut entries: Vec = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for (index, raw) in text.lines().enumerate() { + let line = index + 1; + let content = raw.trim_start_matches([' ', '\t']); + if content.trim().is_empty() || content.starts_with('#') { + continue; + } + if entries.len() == limits.max_entries { + return Err(ManifestError::TooManyEntries { limit: limits.max_entries }); + } + let columns: Vec<&str> = raw.split('\t').collect(); + if !(2..=4).contains(&columns.len()) { + return Err(ManifestError::Columns { line, found: columns.len() }); + } + let digest = parse_digest(columns[0]).ok_or(ManifestError::Digest { line })?; + let path = columns[1]; + check_path(path).map_err(|reason| ManifestError::Path { line, reason })?; + if !seen.insert(path) { + let first = entries.iter().find(|e| e.path == path).map_or(0, |e| e.line); + return Err(ManifestError::Duplicate { line, first }); + } + let optional = |i: usize| columns.get(i).filter(|c| !c.is_empty()).map(|c| (*c).to_owned()); + entries.push(Entry { digest, path: path.to_owned(), license: optional(2), url: optional(3), line }); + } + Ok(Self { entries }) + } + + /// Reads and parses the manifest file at `path`. A path that is not a regular file is refused + /// before it is opened. Reading stops after `limits.max_manifest_bytes` bytes plus one, so an + /// oversized file is not read whole. + pub fn read(path: &Path, limits: &Limits) -> Result { + if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let file = File::open(path).map_err(ManifestError::Io)?; + if !file.metadata().map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let cap = u64::try_from(limits.max_manifest_bytes).unwrap_or(u64::MAX).saturating_add(1); + let mut bytes = Vec::new(); + file.take(cap).read_to_end(&mut bytes).map_err(ManifestError::Io)?; + if bytes.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let text = String::from_utf8(bytes).map_err(|_| ManifestError::NotUtf8)?; + Self::parse_with_limits(&text, limits) + } + + /// The rows, in manifest order. + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// The paths of the rows, in manifest order. + pub fn names(&self) -> impl Iterator { + self.entries.iter().map(Entry::path) + } +} + +/// Decodes 64 ASCII hexadecimal digits, in either case. +fn parse_digest(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut digest = [0u8; 32]; + let (pairs, _) = bytes.as_chunks::<2>(); + for (out, &[high, low]) in digest.iter_mut().zip(pairs) { + let high = char::from(high).to_digit(16)?; + let low = char::from(low).to_digit(16)?; + *out = u8::try_from(high * 16 + low).ok()?; + } + Some(digest) +} + +/// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none +/// empty, `.` or `..`, and no `\`, `:` or NUL anywhere, so the same row means the same file on +/// every platform. +fn check_path(path: &str) -> Result<(), PathError> { + if path.is_empty() { + return Err(PathError::Empty); + } + if path.contains(['\\', ':', '\0']) { + return Err(PathError::Character); + } + for part in path.split('/') { + match part { + "" => return Err(if path.starts_with('/') { PathError::Absolute } else { PathError::EmptyPart }), + "." | ".." => return Err(PathError::DotPart), + _ => {} + } + } + Ok(()) +} + +/// Why a manifest path was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathError { + /// The path is empty. + Empty, + /// The path starts with `/`. + Absolute, + /// The path has an empty part (`a//b`, or a trailing `/`). + EmptyPart, + /// The path has a `.` or `..` part. + DotPart, + /// The path holds a `\`, a `:` or a NUL character. + Character, +} + +impl fmt::Display for PathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Empty => "the path is empty", + Self::Absolute => "the path is absolute", + Self::EmptyPart => "the path has an empty part", + Self::DotPart => "the path has a . or .. part", + Self::Character => "the path holds a \\, a : or a NUL character", + }) + } +} + +/// Why a manifest could not be read or parsed. +#[derive(Debug)] +pub enum ManifestError { + /// The manifest is longer than the limit in bytes. + TooLarge { + /// The limit in bytes. + limit: usize, + }, + /// The manifest lists more rows than the limit. + TooManyEntries { + /// The limit in rows. + limit: usize, + }, + /// A row does not have 2, 3 or 4 tab-separated columns. + Columns { + /// The 1-based line of the row. + line: usize, + /// The number of columns found. + found: usize, + }, + /// A row's digest is not 64 hexadecimal digits. + Digest { + /// The 1-based line of the row. + line: usize, + }, + /// A row's path is refused. + Path { + /// The 1-based line of the row. + line: usize, + /// Why the path is refused. + reason: PathError, + }, + /// A row repeats the path of an earlier row. + Duplicate { + /// The 1-based line of the repeated row. + line: usize, + /// The 1-based line of the earlier row. + first: usize, + }, + /// The manifest path does not name a regular file. + NotAFile, + /// The manifest file is not UTF-8. + NotUtf8, + /// The manifest file could not be read. + Io(io::Error), +} + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "the manifest is longer than {limit} bytes"), + Self::TooManyEntries { limit } => write!(f, "the manifest lists more than {limit} files"), + Self::Columns { line, found } => write!(f, "line {line}: {found} tab-separated columns, expected 2 to 4"), + Self::Digest { line } => write!(f, "line {line}: the SHA-256 is not 64 hexadecimal digits"), + Self::Path { line, reason } => write!(f, "line {line}: {reason}"), + Self::Duplicate { line, first } => write!(f, "line {line}: the path is already listed on line {first}"), + Self::NotAFile => f.write_str("the manifest is not a regular file"), + Self::NotUtf8 => f.write_str("the manifest is not UTF-8"), + Self::Io(error) => write!(f, "the manifest could not be read: {error}"), + } + } +} + +impl std::error::Error for ManifestError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Why a corpus folder does not match its manifest. +#[derive(Debug)] +pub enum VerifyError { + /// The manifest lists no files, so the folder would be accepted without a check. + EmptyManifest, + /// The corpus folder could not be resolved. + Folder { + /// The folder. + dir: PathBuf, + /// The error resolving it. + error: io::Error, + }, + /// A listed file is missing or could not be resolved. + Missing { + /// The path the manifest lists. + path: String, + /// The error resolving it. + error: io::Error, + }, + /// A listed path resolves outside the corpus folder, through a symbolic link. + Escapes { + /// The path the manifest lists. + path: String, + }, + /// A listed path is not a regular file. + NotAFile { + /// The path the manifest lists. + path: String, + }, + /// A listed file is larger than the limit. + TooLarge { + /// The path the manifest lists. + path: String, + /// The limit in bytes. + limit: u64, + }, + /// A listed file could not be read. + Read { + /// The path the manifest lists. + path: String, + /// The read error. + error: io::Error, + }, + /// A listed file's SHA-256 differs from the manifest's. + Modified { + /// The path the manifest lists. + path: String, + }, +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyManifest => f.write_str("the manifest lists no files"), + Self::Folder { dir, error } => write!(f, "corpus folder {}: {error}", dir.display()), + Self::Missing { path, error } => write!(f, "{path}: missing: {error}"), + Self::Escapes { path } => write!(f, "{path}: resolves outside the corpus folder"), + Self::NotAFile { path } => write!(f, "{path}: not a regular file"), + Self::TooLarge { path, limit } => write!(f, "{path}: larger than {limit} bytes"), + Self::Read { path, error } => write!(f, "{path}: {error}"), + Self::Modified { path } => write!(f, "{path}: SHA-256 differs from the manifest"), + } + } +} + +impl std::error::Error for VerifyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Folder { error, .. } | Self::Missing { error, .. } | Self::Read { error, .. } => Some(error), + _ => None, + } + } +} + +/// Checks every file `manifest` lists in `dir` under the default [`Limits`]. +pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { + verify_with_limits(dir, manifest, &Limits::default()) +} + +/// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic +/// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the +/// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { + if manifest.entries.is_empty() { + return Err(VerifyError::EmptyManifest); + } + let root = dir.canonicalize().map_err(|error| VerifyError::Folder { dir: dir.to_path_buf(), error })?; + let mut buf = vec![0u8; CHUNK]; + for entry in &manifest.entries { + verify_entry(&root, entry, limits, &mut buf)?; + } + Ok(()) +} + +fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + let path = || entry.path.clone(); + let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + if !target.starts_with(root) { + return Err(VerifyError::Escapes { path: path() }); + } + let kind = std::fs::metadata(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + if !kind.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + let file = File::open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; + if !meta.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + if meta.len() > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + let mut reader = file.take(limits.max_file_bytes.saturating_add(1)); + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + loop { + let n = match reader.read(buf) { + Ok(0) => break, + Ok(n) => n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VerifyError::Read { path: path(), error }), + }; + total = total.saturating_add(n as u64); + if total > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + hasher.update(&buf[..n]); + } + if hasher.finalize().as_slice() != entry.digest.as_slice() { + return Err(VerifyError::Modified { path: path() }); + } + Ok(()) +} + +/// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file +/// `manifest` lists has been checked with [`verify`]. +/// +/// The corpus is required when the variable named `var` plus [`REQUIRED_SUFFIX`] (by default +/// `CRAFT_CORPUS_REQUIRED`) is exactly `1`; unset, empty, `0`, `true` and any other value leave it +/// optional. +/// +/// - Folder variable unset and the corpus optional: prints one line, +/// `SKIPPED: corpus not given: set to its folder`, to stderr and returns `None`. +/// - Folder variable unset and the corpus required: fails the test. +/// - Folder variable set, even to an empty value: fails the test unless the manifest parses and +/// every listed file matches. +/// +/// It fails the test with a panic whose message names the variable and the failure. +#[allow(clippy::panic)] +pub fn pinned(var: Option<&str>, manifest: &str) -> Option { + let var = var.unwrap_or(DEFAULT_VAR); + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let required = std::env::var_os(&required_var).as_deref() == Some(OsStr::new("1")); + match gate(std::env::var_os(var), required, var, &required_var, manifest) { + Ok(Some(dir)) => Some(dir), + Ok(None) => { + eprintln!("SKIPPED: corpus not given: set {var} to its folder"); + None + } + Err(message) => panic!("{message}"), + } +} + +/// The decision of [`pinned`], without reading the environment or printing: `Ok(None)` skips and +/// `Err` holds the message the test fails with. +fn gate(folder: Option, required: bool, var: &str, required_var: &str, manifest: &str) -> Result, String> { + let Some(folder) = folder else { + return if required { Err(format!("corpus not given: {var} is unset and {required_var}=1 forbids skipping")) } else { Ok(None) }; + }; + if folder.is_empty() { + return Err(format!("{var} is set but empty")); + } + let dir = PathBuf::from(folder); + let manifest = Manifest::parse(manifest).map_err(|e| format!("corpus manifest for {var}: {e}"))?; + verify(&dir, &manifest).map_err(|e| format!("pinned corpus in {} ({var}): {e}", dir.display()))?; + Ok(Some(dir)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Output}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_CORPUS_CHILD"; + /// The folder variable the child's `pinned` reads. + const VAR: &str = "CRAFT_TESTKIT_CORPUS_DIR"; + /// The required variable that goes with [`VAR`]. + const REQUIRED: &str = "CRAFT_TESTKIT_CORPUS_DIR_REQUIRED"; + + const HELLO: &[u8] = b"hello world"; + /// SHA-256 of `hello world`. + const HELLO_SHA: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + const EMPTY_SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// A folder under the system temporary folder, removed on drop. + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("craft_testkit_corpus_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch folder"); + Self(dir) + } + + fn write(&self, rel: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, bytes).expect("write file"); + path + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn parse_err(text: &str) -> ManifestError { + Manifest::parse(text).expect_err("the manifest is refused") + } + + #[test] + fn comments_are_skipped() { + let text = format!("# pinned corpus\n # indented comment\n\t# tab-indented comment\n{HELLO_SHA}\thello.txt\n#{EMPTY_SHA}\tempty.txt\n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.names().collect::>(), ["hello.txt"]); + assert_eq!(manifest.entries()[0].line(), 4); + } + + #[test] + fn a_hash_inside_a_row_is_not_a_comment() { + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tdir/#1.txt\tMIT\thttps://example.org/a#b\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.path(), "dir/#1.txt"); + assert_eq!(entry.url(), Some("https://example.org/a#b")); + } + + #[test] + fn blank_lines_are_skipped() { + let text = format!("\n \n\t\n{HELLO_SHA}\thello.txt\n\n{EMPTY_SHA}\tempty.txt\n \t \n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.entries().len(), 2); + assert_eq!(manifest.entries()[0].line(), 4); + assert_eq!(manifest.entries()[1].line(), 6); + assert_eq!(Manifest::parse("").expect("parse").entries().len(), 0); + } + + #[test] + fn malformed_row_is_error() { + assert!(matches!(parse_err(HELLO_SHA), ManifestError::Columns { line: 1, found: 1 })); + assert!(matches!(parse_err(&format!("# c\n{HELLO_SHA} hello.txt\n")), ManifestError::Columns { line: 2, found: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\ta\tMIT\turl\textra\n")), ManifestError::Columns { line: 1, found: 5 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\t\n")), ManifestError::Path { line: 1, reason: PathError::Empty })); + assert!(matches!(parse_err("\thello.txt\n"), ManifestError::Digest { line: 1 })); + } + + #[test] + fn wrong_digest_length_is_error() { + assert!(matches!(parse_err(&format!("{}\ta\n", &HELLO_SHA[..63])), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}0\ta\n")), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!(" {HELLO_SHA}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn non_hex_digest_is_error() { + let bad = format!("{}g", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{bad}\ta\n")), ManifestError::Digest { line: 1 })); + let sign = format!("+{}", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{sign}\ta\n")), ManifestError::Digest { line: 1 })); + let wide = format!("{}é", &HELLO_SHA[..62]); + assert!(matches!(parse_err(&format!("{wide}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn rows_take_two_to_four_columns_and_empty_optional_columns_are_none() { + let text = format!( + "{HELLO_SHA}\ta.txt\n{HELLO_SHA}\tb.txt\tMIT\n{HELLO_SHA}\tc.txt\tMIT\thttps://example.org/c\n{HELLO_SHA}\td.txt\t\n{HELLO_SHA}\te.txt\t\thttps://example.org/e\n" + ); + let manifest = Manifest::parse(&text).expect("parse"); + let cols: Vec<_> = manifest.entries().iter().map(|e| (e.path(), e.license(), e.url())).collect(); + assert_eq!( + cols, + [ + ("a.txt", None, None), + ("b.txt", Some("MIT"), None), + ("c.txt", Some("MIT"), Some("https://example.org/c")), + ("d.txt", None, None), + ("e.txt", None, Some("https://example.org/e")), + ] + ); + } + + #[test] + fn crlf_lines_and_uppercase_digests_parse() { + let upper = HELLO_SHA.to_ascii_uppercase(); + let manifest = Manifest::parse(&format!("# c\r\n{upper}\thello.txt\tMIT\r\n\r\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.license(), Some("MIT")); + assert_eq!(entry.digest()[..4], [0xb9, 0x4d, 0x27, 0xb9]); + assert_eq!(entry.digest(), Manifest::parse(&format!("{HELLO_SHA}\thello.txt")).expect("parse").entries()[0].digest()); + } + + #[test] + fn duplicate_path_is_error() { + let text = format!("{HELLO_SHA}\ta/b.txt\n# c\n{HELLO_SHA}\ta/b.txt\n"); + assert!(matches!(parse_err(&text), ManifestError::Duplicate { line: 3, first: 1 })); + } + + #[test] + fn paths_that_leave_the_folder_are_errors() { + let cases = [ + ("/etc/passwd", PathError::Absolute), + ("../outside", PathError::DotPart), + ("a/../../outside", PathError::DotPart), + ("./a", PathError::DotPart), + ("a//b", PathError::EmptyPart), + ("a/", PathError::EmptyPart), + ("C:/Windows/win.ini", PathError::Character), + ("C:a", PathError::Character), + ("\\\\server\\share\\a", PathError::Character), + ("a\\..\\..\\b", PathError::Character), + ]; + for (path, expected) in cases { + match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { + ManifestError::Path { line: 1, reason } => assert_eq!(reason, expected, "{path}"), + other => panic!("{path}: {other}"), + } + } + } + + #[test] + fn manifest_limits_are_errors() { + let text = format!("{HELLO_SHA}\ta\n{HELLO_SHA}\tb\n"); + let limits = Limits { max_entries: 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooManyEntries { limit: 1 }))); + let limits = Limits { max_entries: 2, ..Limits::default() }; + assert_eq!(Manifest::parse_with_limits(&text, &limits).expect("parse").entries().len(), 2); + + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooLarge { .. }))); + let limits = Limits { max_manifest_bytes: text.len(), ..Limits::default() }; + assert!(Manifest::parse_with_limits(&text, &limits).is_ok()); + + let scratch = Scratch::new(); + let path = scratch.write("corpus.tsv", text.as_bytes()); + assert_eq!(Manifest::read(&path, &Limits::default()).expect("read").entries().len(), 2); + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::read(&path, &limits), Err(ManifestError::TooLarge { .. }))); + let bad = scratch.write("bad.tsv", b"\xff\xfe"); + assert!(matches!(Manifest::read(&bad, &Limits::default()), Err(ManifestError::NotUtf8))); + assert!(matches!(Manifest::read(&scratch.0.join("absent.tsv"), &Limits::default()), Err(ManifestError::Io(_)))); + } + + fn hello_corpus() -> (Scratch, Manifest) { + let scratch = Scratch::new(); + scratch.write("hello.txt", HELLO); + scratch.write("sub/empty.bin", b""); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\tMIT\n{EMPTY_SHA}\tsub/empty.bin\n")).expect("parse"); + (scratch, manifest) + } + + #[test] + fn a_matching_folder_verifies() { + let (scratch, manifest) = hello_corpus(); + verify(&scratch.0, &manifest).expect("the corpus matches"); + } + + #[test] + fn missing_file_fails() { + let (scratch, manifest) = hello_corpus(); + std::fs::remove_file(scratch.0.join("sub").join("empty.bin")).expect("remove"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Missing { path, .. }) => assert_eq!(path, "sub/empty.bin"), + other => panic!("{other:?}"), + } + assert!(matches!(verify(&scratch.0.join("absent"), &manifest), Err(VerifyError::Folder { .. }))); + } + + #[test] + fn modified_file_fails() { + let (scratch, manifest) = hello_corpus(); + scratch.write("hello.txt", b"hello world!"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Modified { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn an_empty_manifest_or_a_folder_entry_fails() { + let (scratch, _) = hello_corpus(); + assert!(matches!(verify(&scratch.0, &Manifest::default()), Err(VerifyError::EmptyManifest))); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tsub\n")).expect("parse"); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::NotAFile { .. }))); + } + + /// A named pipe is refused before it is opened; opening one for reading waits for a writer. + #[cfg(unix)] + #[test] + fn a_named_pipe_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("pipe"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tpipe\n")).expect("parse"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::NotAFile { path }) => assert_eq!(path, "pipe"), + other => panic!("{other:?}"), + } + } + + /// A manifest path that names a named pipe or a folder is refused before it is opened. + #[cfg(unix)] + #[test] + fn a_manifest_that_is_not_a_file_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("corpus.tsv"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + assert!(matches!(Manifest::read(&scratch.0, &Limits::default()), Err(ManifestError::NotAFile))); + assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); + } + + #[test] + fn file_size_limit_is_error() { + let (scratch, manifest) = hello_corpus(); + let limits = Limits { max_file_bytes: HELLO.len() as u64, ..Limits::default() }; + verify_with_limits(&scratch.0, &manifest, &limits).expect("a file at the limit passes"); + let limits = Limits { max_file_bytes: HELLO.len() as u64 - 1, ..Limits::default() }; + match verify_with_limits(&scratch.0, &manifest, &limits) { + Err(VerifyError::TooLarge { path, limit }) => assert_eq!((path.as_str(), limit), ("hello.txt", 10)), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_file_larger_than_one_read_hashes_whole() { + let scratch = Scratch::new(); + let bytes: Vec = (0..CHUNK * 2 + 7).map(|i| (i % 251) as u8).collect(); + scratch.write("big.bin", &bytes); + let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + let manifest = Manifest::parse(&format!("{hex}\tbig.bin\n")).expect("parse"); + verify(&scratch.0, &manifest).expect("the whole file is hashed"); + scratch.write("big.bin", &bytes[..CHUNK]); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::Modified { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_out_of_the_folder_fails() { + let outside = Scratch::new(); + let target = outside.write("hello.txt", HELLO); + let corpus = Scratch::new(); + std::os::unix::fs::symlink(&target, corpus.0.join("hello.txt")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\n")).expect("parse"); + match verify(&corpus.0, &manifest) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + std::os::unix::fs::symlink(&outside.0, corpus.0.join("out")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tout/hello.txt\n")).expect("parse"); + assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); + } + + #[test] + fn the_gate_skips_only_an_optional_unset_corpus() { + let (scratch, _) = hello_corpus(); + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + assert_eq!(gate(None, false, VAR, REQUIRED, &manifest), Ok(None)); + let required = gate(None, true, VAR, REQUIRED, &manifest).expect_err("required"); + assert!(required.contains(&format!("{REQUIRED}=1")), "{required}"); + let dir = scratch.0.clone().into_os_string(); + assert_eq!(gate(Some(dir.clone()), false, VAR, REQUIRED, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), false, VAR, REQUIRED, &manifest).expect_err("empty"); + assert!(empty.contains("empty"), "{empty}"); + let bad = gate(Some(dir.clone()), false, VAR, REQUIRED, "# c\nnot a row\n").expect_err("bad manifest"); + assert!(bad.contains("line 2"), "{bad}"); + let missing = gate(Some(dir), false, VAR, REQUIRED, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + assert!(missing.contains("absent.bin"), "{missing}"); + } + + /// Runs `child` below in a new process of this test binary with the given variables set and + /// every other corpus variable removed, so no test changes this process's environment. + fn run_child(case: &str, vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["corpus::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + for name in [VAR, REQUIRED, DEFAULT_VAR, "CRAFT_CORPUS_REQUIRED"] { + cmd.env_remove(name); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the test binary") + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + let found = match case.to_str() { + Some("named") => pinned(Some(VAR), &manifest), + Some("default") => pinned(None, &manifest), + other => panic!("unknown child case {other:?}"), + }; + eprintln!("pinned returned {}", found.map_or_else(|| "none".to_owned(), |d| d.display().to_string())); + } + + #[test] + fn required_variable_unset_fails() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1"), Some("1\n")] { + let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); + let out = run_child("named", &vars); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches(&format!("SKIPPED: corpus not given: set {VAR} to its folder\n")).count(), 1, "{value:?}: {err}"); + assert!(err.contains("pinned returned none"), "{value:?}: {err}"); + } + let out = run_child("named", &[(REQUIRED, "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{REQUIRED}=1 forbids skipping")), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("pinned returned"), "{err}"); + } + + #[test] + fn pinned_reads_the_named_folder_and_fails_on_a_bad_one() { + let (scratch, _) = hello_corpus(); + let dir = scratch.0.to_str().expect("a UTF-8 temporary path"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains(&format!("pinned returned {dir}")), "{err}"); + + scratch.write("hello.txt", b"changed"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("hello.txt: SHA-256 differs from the manifest"), "{err}"); + + let out = run_child("named", &[(VAR, "")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); + } + + #[test] + fn pinned_defaults_to_craft_corpus() { + let out = run_child("default", &[]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: corpus not given: set CRAFT_CORPUS to its folder\n"), "{err}"); + + let out = run_child("default", &[("CRAFT_CORPUS_REQUIRED", "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_CORPUS_REQUIRED=1 forbids skipping"), "{err}"); + } +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..bb41162311 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! With the `corpus` feature, `corpus` (native only) parses pinned-corpus manifests and checks a +//! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate +//! `corpus::pinned`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -25,6 +29,8 @@ //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +#[cfg(all(feature = "corpus", not(target_arch = "wasm32")))] +pub mod corpus; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; From 50aabe2c5a62186475489e25c1aec008e2bf8841 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:18:49 -0800 Subject: [PATCH 011/490] craft-xtask: add the workspace version command The version feature adds version::run, which reads the [workspace.package] version of the root Cargo.toml and, with set X.Y.Z[-pre], writes it and runs cargo update --workspace (offline first). The caller passes its workspace root, its Cargo program and the words after version. - validate rejects build metadata, leading zeros, numbers above u64::MAX and numeric prerelease identifiers with a leading zero. - replace also moves the version of each path dependency in [workspace.dependencies] whose requirement is "OLD" or "=OLD". - The manifest is read with a one-pass TOML scanner that keeps comments, quotes and LF, CRLF and CR line endings, and accepts the version as a table key, a dotted key or an inline table. A manifest it cannot read, a duplicate version or an invalid current version is an error before anything is written. - When both updates fail, Cargo.toml and Cargo.lock are put back and the error says so. Both files are replaced through craft-atomic. - Cargo.toml is read up to 1 MiB and Cargo.lock up to 64 MiB by default (Limits). - One set runs at a time in a workspace. A set takes its locks before it reads Cargo.toml and holds them until it returns: on Unix the workspace directory, on Windows workspace.lock opened without delete sharing, plus an owner-labeled lock in target/xtask-version/version-/ and, when it can be opened, one in ~/.cache/craft-xtask/version-/. A set that finds a lock held returns an error naming the other run and writes nothing. lock_dirs returns the lock directories. The version feature turns on lock. From SoundCraft xtask/src/version.rs (6c84416c) and PdfCraft xtask/src/version.rs (3e306453); their tests move in under the same names. --- crates/xtask/Cargo.toml | 5 +- crates/xtask/README.md | 48 +- crates/xtask/src/lib.rs | 5 + crates/xtask/src/version.rs | 1161 +++++++++++++++++++++++++++++++++++ 4 files changed, 1217 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/version.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..45a71758d6 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report and the workspace version command" [lints] workspace = true @@ -16,6 +16,9 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# `cargo xtask version [set X.Y.Z[-pre]]`, with Cargo.toml and Cargo.lock replaced atomically and one +# `set` at a time per workspace through `lock`. +version = ["lock", "dep:craft-atomic"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..4bc5243f0c 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,9 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `version` | `version` | `run`, `run_with`, `Limits`, `lock_dirs`, `read`, `replace`, `validate`: `cargo xtask version [set X.Y.Z[-pre]]` on the root `Cargo.toml` | -No feature is on by default. `report` adds `serde_json` and `craft-atomic`. +No feature is on by default. `report` adds `serde_json` and `craft-atomic`; `version` adds `craft-atomic` and turns on `lock`. ## Use @@ -91,6 +92,47 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Version + +```rust,no_run +use std::path::Path; +use craft_xtask::runner; + +/// `rest` holds the words after `version`. +fn version(rest: &[&str]) -> Result<(), String> { + let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + craft_xtask::version::run(&root, &cargo, rest) +} +``` + +- `cargo xtask version` prints the `version` of `[workspace.package]`. +- `cargo xtask version set X.Y.Z[-pre]` checks the new version, writes it into `Cargo.toml`, runs + `cargo update --workspace --offline` in the root and, when that fails, `cargo update --workspace`, + and prints `version: OLD -> NEW`. It also moves the `version` of each path dependency in + `[workspace.dependencies]` whose requirement is `"OLD"` or `"=OLD"`; registry dependencies and path + dependencies at other versions keep theirs. +- A version is `MAJOR.MINOR.PATCH` with an optional `-pre.release`: no leading zeros, numbers up to + `u64::MAX`, and no build metadata (`+...`). +- When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they were (a lock file that did + not exist is removed) and the error says so. Both files are replaced atomically through + `craft-atomic`. +- Setting the current version prints `version: OLD (unchanged)` and writes only its lock file. +- One `set` runs at a time in a workspace. Before it reads `Cargo.toml`, it takes its locks and + holds them until it returns. On Unix it locks the workspace directory itself; on Windows it locks + `workspace.lock` in the first directory below, opened so that the file cannot be deleted while it + is held. Every process that writes the workspace shares that lock, and `cargo clean` cannot remove + it. It also takes the locks in `lock_dirs(root)`: + `target/xtask-version/version-/` (required; its owner file names the + run) and `~/.cache/craft-xtask/version-/` (when its file can be + opened). A `set` that finds a lock held returns an error naming the other run and writes + nothing. +- The root manifest is read with a scanner that keeps comments, quotes and line endings (LF, CRLF and + CR) and accepts the version as `[workspace.package]` `version`, a dotted key or an inline table. A + manifest it cannot read, a duplicate version, a version that is not a one-line string, or a current + version that is not valid is an error before anything is written. `Cargo.toml` is read up to 1 MiB + and `Cargo.lock` up to 64 MiB by default; `run_with` takes other `Limits`. + ## Origin | Part | Source | @@ -98,6 +140,9 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | +| `version`: `read`, `validate` with the overflow and prerelease checks, the restore after a failed update, and the tests `reads_the_workspace_version`, `replaces_only_the_workspace_version`, `keeps_crlf_line_endings`, `validates_versions`, `rejects_what_cargo_rejects`, `a_failed_update_restores_the_manifest` | SoundCraft `xtask/src/version.rs` at [6c84416](https://github.com/storytold/soundcraft/blob/6c84416c3cffb72d8d350ddfefc4fc9ee954ca1a/xtask/src/version.rs) | +| `version`: the path dependency pins and the test `moves_the_workspace_crates_pins_with_it` | PdfCraft `xtask/src/version.rs` at [3e30645](https://github.com/storytold/pdfcraft/blob/3e3064532f04fd6ec769c6bd7b2c97464757970e/xtask/src/version.rs) | +| `version`: the TOML scanner, the `=OLD` pins, the `Cargo.lock` restore, the size limits, the unchanged-version case and the one-`set`-at-a-time lock | written here | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | ## Migration @@ -108,6 +153,7 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| SoundCraft, PdfCraft | Planned: `xtask/src/version.rs` moves to `version`, with the app's root and `CARGO` passed to `run`. `the_real_manifest_has_a_valid_version`, and PdfCraft's `workspace_rust_version_covers_the_ui_crate`, stay in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..c65a545f23 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,9 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - `version` (feature `version`): `cargo xtask version [set X.Y.Z[-pre]]`, which reads and sets the +//! `[workspace.package]` version of the root `Cargo.toml` and moves the workspace crates' path +//! dependency pins with it. //! //! ```no_run //! use std::path::Path; @@ -40,6 +43,8 @@ pub mod lock; #[cfg(feature = "report")] pub mod report; pub mod runner; +#[cfg(feature = "version")] +pub mod version; /// Keeps the tests that start child processes apart from the tests that check whether a slot is free. /// A child holds copies of the parent's open files, and so its file locks, until it starts its program. diff --git a/crates/xtask/src/version.rs b/crates/xtask/src/version.rs new file mode 100644 index 0000000000..ed166f0c70 --- /dev/null +++ b/crates/xtask/src/version.rs @@ -0,0 +1,1161 @@ +//! `cargo xtask version [set X.Y.Z[-pre]]`: the workspace version in the root `Cargo.toml`. +//! +//! The version is the `version` key of `[workspace.package]`; member crates inherit it with +//! `version.workspace = true`. [`read`] returns it, [`validate`] checks a new one and [`replace`] +//! returns the manifest with the new version, together with the `version` of every path dependency +//! in `[workspace.dependencies]` whose requirement is the old version (`"OLD"` or `"=OLD"`). +//! [`run`] is the command: the caller passes its workspace root, the Cargo program to run and the +//! words after `version`. +//! +//! The manifest is read with a small TOML scanner that keeps every byte outside the changed strings, +//! comments and line endings included. The root version may be written in any TOML form +//! (`[workspace.package]` with `version = "…"`, a dotted key, an inline table), with double or +//! single quotes. A manifest the scanner cannot read, a duplicate key, a version that is not a +//! one-line string, or a current version that is not valid returns an error before anything is +//! written. + +use std::collections::HashSet; +use std::ffi::OsStr; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The largest root `Cargo.toml` [`run`] reads, in bytes. +pub const DEFAULT_MAX_MANIFEST_BYTES: u64 = 1 << 20; +/// The largest `Cargo.lock` [`run`] keeps in memory to put back after a failed `cargo update`, in bytes. +pub const DEFAULT_MAX_LOCK_BYTES: u64 = 64 << 20; +/// How deeply arrays and inline tables may nest in the manifest. +const MAX_DEPTH: usize = 64; +const USAGE: &str = "usage: cargo xtask version [set X.Y.Z[-pre]]"; +const ROOT_VERSION: [&str; 3] = ["workspace", "package", "version"]; + +/// Size limits for [`run_with`]. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest root `Cargo.toml` that is read; a larger one is an error before anything is written. + pub max_manifest_bytes: u64, + /// The largest `Cargo.lock` that is kept to put back after a failed update; a larger one is an + /// error before anything is written. + pub max_lock_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: DEFAULT_MAX_MANIFEST_BYTES, max_lock_bytes: DEFAULT_MAX_LOCK_BYTES } + } +} + +impl Limits { + /// Sets the largest root `Cargo.toml` that is read. + pub fn with_max_manifest_bytes(mut self, bytes: u64) -> Self { + self.max_manifest_bytes = bytes; + self + } + + /// Sets the largest `Cargo.lock` that is kept for a restore. + pub fn with_max_lock_bytes(mut self, bytes: u64) -> Self { + self.max_lock_bytes = bytes; + self + } +} + +/// The `version` of `[workspace.package]`. +pub fn read(manifest: &str) -> Result { + let entries = scan(manifest)?; + Ok(root_version(&entries)?.text.clone()) +} + +/// `manifest` with the workspace version set to `new`, and every path dependency in +/// `[workspace.dependencies]` whose `version` is the old version (`"OLD"` or `"=OLD"`) moved with +/// it. Registry dependencies and path dependencies at other versions keep their requirement, and +/// every other byte is unchanged. +pub fn replace(manifest: &str, new: &str) -> Result { + validate(new)?; + let entries = scan(manifest)?; + let root = root_version(&entries)?; + let old = root.text.as_str(); + validate(old).map_err(|e| format!("the current [workspace.package] version is not valid: {e}"))?; + let mut edits = vec![(root, new.to_owned())]; + edits.extend(path_pins(&entries, old).into_iter().map(|(pin, prefix)| (pin, format!("{prefix}{new}")))); + edits.sort_by_key(|(s, _)| s.span.start); + let mut out = String::with_capacity(manifest.len() + edits.len() * new.len()); + let mut at = 0; + for (s, text) in edits { + out.push_str(slice(manifest, at..s.span.start)?); + let q = char::from(s.quote); + out.push(q); + out.push_str(&text); + out.push(q); + at = s.span.end; + } + out.push_str(slice(manifest, at..manifest.len())?); + Ok(out) +} + +/// Semver without build metadata: `MAJOR.MINOR.PATCH` plus an optional `-pre.release` tag. +/// +/// The three numbers have no leading zero and fit in a `u64`. Each prerelease identifier is +/// nonempty ASCII letters, digits and `-`, and a numeric one has no leading zero. +pub fn validate(v: &str) -> Result<(), String> { + let bad = || Err(format!("`{v}` is not a version like 1.2.3 or 1.2.3-rc.1")); + let (core, pre) = match v.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (v, None), + }; + let nums: Vec<&str> = core.split('.').collect(); + if nums.len() != 3 + || nums.iter().any(|n| !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0')) || n.parse::().is_err()) + { + return bad(); + } + let bad_id = |id: &str| { + id.is_empty() + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + || (id.len() > 1 && id.starts_with('0') && id.bytes().all(|b| b.is_ascii_digit())) + }; + if let Some(p) = pre + && (p.is_empty() || p.split('.').any(bad_id)) + { + return bad(); + } + Ok(()) +} + +/// `cargo xtask version [set X.Y.Z[-pre]]` with the default [`Limits`]. +/// +/// `root` is the workspace root, `cargo_program` the Cargo to run there (an app usually passes its +/// `CARGO` variable, or `cargo`), and `args` the words after `version`. +/// +/// - With no words, prints the version. +/// - With `set NEW`, writes the new version into `Cargo.toml` (see [`replace`]), runs +/// `cargo update --workspace --offline` and, when that fails, `cargo update --workspace`, then prints +/// `version: OLD -> NEW`. When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they +/// were and the error says so. Setting the current version prints `version: OLD (unchanged)` and +/// writes only its lock file. One `set` runs at a time in a workspace: it holds its locks (see +/// [`lock_dirs`]) from reading `Cargo.toml` until it returns, and a `set` that finds a lock held +/// returns an error naming the other run and writes nothing. +/// - Other words return the usage error. +pub fn run(root: &Path, cargo_program: &OsStr, args: &[&str]) -> Result<(), String> { + run_with(root, cargo_program, args, &Limits::default()) +} + +/// [`run`] with the caller's [`Limits`]. +pub fn run_with(root: &Path, cargo_program: &OsStr, args: &[&str], limits: &Limits) -> Result<(), String> { + run_to(root, args, limits, None, &mut io::stdout(), || update_lock(root, cargo_program)) +} + +/// The directories of the owner-labeled locks that a `set` in the workspace at `root` holds. +/// +/// Before these, a `set` locks the workspace directory itself on Unix, and on Windows +/// `workspace.lock` in the first directory, opened so that it cannot be deleted while held. Every +/// process that writes the workspace shares that lock, and `cargo clean` cannot remove it. +/// +/// The first directory is `target/xtask-version/version-` in the +/// workspace: its lock is required and its owner file names the run that holds it. The second, when +/// there is a home directory, is `~/.cache/craft-xtask/version-`; a +/// `set` also takes the lock there when it can open the lock file. +/// +/// The locks are not on `Cargo.toml` or `Cargo.lock` because a lock on Windows is mandatory and +/// would stop the replacement of `Cargo.toml` and Cargo's own use of `Cargo.lock`. +pub fn lock_dirs(root: &Path) -> Result, String> { + let canonical = std::fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; + let name = format!("version-{:016x}", fnv1a(canonical.to_string_lossy().as_bytes())); + // A `target` linked from several workspaces holds one directory per workspace. + let mut dirs = vec![canonical.join("target").join("xtask-version").join(&name)]; + dirs.extend(std::env::home_dir().filter(|h| h.is_absolute()).map(|h| h.join(".cache").join("craft-xtask").join(name))); + Ok(dirs) +} + +/// The 64-bit FNV-1a hash, which stays the same across Rust releases. +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) +} + +/// [`run_with`] that prints to `out`, refreshes `Cargo.lock` with `update`, and keeps its locks in +/// `lock_at` (or [`lock_dirs`] when `None`). +fn run_to( + root: &Path, + args: &[&str], + limits: &Limits, + lock_at: Option<&[PathBuf]>, + out: &mut dyn Write, + update: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + let new = match args { + [] => None, + ["set", new] => Some(*new), + _ => return Err(USAGE.into()), + }; + let manifest = root.join("Cargo.toml"); + let load = || -> Result<(String, String), String> { + let text = + String::from_utf8(read_bounded(&manifest, limits.max_manifest_bytes)?).map_err(|_| format!("{}: not UTF-8", manifest.display()))?; + let old = read(&text)?; + Ok((text, old)) + }; + let Some(new) = new else { + return say(out, &load()?.1); + }; + validate(new)?; + // Held from the read of `Cargo.toml` through any restore, so that two `set` runs never interleave + // and an unchanged version is not reported while another run may still put an older one back. + let _held = lock_workspace(root, lock_at, new)?; + let (text, old) = load()?; + let updated = replace(&text, new)?; + if old == new { + return say(out, &format!("version: {old} (unchanged)")); + } + let lock_path = root.join("Cargo.lock"); + let lock = match std::fs::symlink_metadata(&lock_path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + _ => Some(read_bounded(&lock_path, limits.max_lock_bytes)?), + }; + write_file(&manifest, updated.as_bytes())?; + if let Err(e) = update() { + return Err(restore(&manifest, &text, &old, &lock_path, lock.as_deref(), e)); + } + say(out, &format!("version: {old} -> {new}")) +} + +/// The locks a `set` holds until it returns. +struct WorkspaceLock { + _base: File, + _held: Vec, +} + +/// The lock that every process writing the workspace at `root` shares and that `cargo clean` cannot +/// remove while it is held, or `None` when another process holds it. On Unix it is a lock on the +/// workspace directory itself. On Windows it is `workspace.lock` in `dir`, opened without delete +/// sharing, so the file cannot be deleted while it is open. +fn base_lock(root: &Path, dir: &Path) -> Result, String> { + let fail = |e: io::Error| format!("could not take the version lock, nothing was written: {e}"); + #[cfg(windows)] + let file = { + use std::os::windows::fs::OpenOptionsExt; + const FILE_SHARE_READ: u32 = 0x1; + const FILE_SHARE_WRITE: u32 = 0x2; + let _ = root; + std::fs::create_dir_all(dir).map_err(fail)?; + std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .open(dir.join("workspace.lock")) + .map_err(fail)? + }; + #[cfg(not(windows))] + let file = { + let _ = dir; + File::open(root).map_err(fail)? + }; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(e)) => Err(fail(e)), + } +} + +/// Takes the workspace's `version set` locks without waiting: [`base_lock`], then the owner-labeled +/// locks in `lock_at` (or [`lock_dirs`]). The lock in the first directory is required; a later +/// directory whose lock file cannot be opened is skipped. When another run holds any of them, +/// releases the others and returns an error that names that run. +fn lock_workspace(root: &Path, lock_at: Option<&[PathBuf]>, new: &str) -> Result { + let dirs = match lock_at { + Some(dirs) => dirs.to_vec(), + None => lock_dirs(root)?, + }; + let label = format!("pid {} in {}: cargo xtask version set {new}", std::process::id(), root.display()); + let busy = |dir: &Path| { + let config = crate::lock::LockConfig::new(dir, 1, ""); + let other = crate::lock::holders(&config).ok().and_then(|h| h.into_iter().next()).unwrap_or_else(|| "another run".to_owned()); + format!("another `cargo xtask version set` is running in this workspace ({other}); nothing was written, try again when it ends") + }; + let first = dirs.first().ok_or_else(|| "could not take the version lock: no lock directory".to_owned())?; + let Some(base) = base_lock(root, first)? else { + return Err(busy(first)); + }; + let mut held = Vec::new(); + for (i, dir) in dirs.iter().enumerate() { + let config = crate::lock::LockConfig::new(dir, 1, label.clone()); + match crate::lock::try_acquire(&config) { + Ok(Some(h)) => held.push(h), + Ok(None) => return Err(busy(dir)), + Err(e) if i == 0 => return Err(format!("could not take the version lock, nothing was written: {e}")), + Err(_) => {} + } + } + Ok(WorkspaceLock { _base: base, _held: held }) +} + +fn say(out: &mut dyn Write, line: &str) -> Result<(), String> { + writeln!(out, "{line}").map_err(|e| format!("write the output: {e}")) +} + +/// Puts `Cargo.toml` and `Cargo.lock` back after `cargo update` failed with `error`. +fn restore(manifest: &Path, text: &str, old: &str, lock_path: &Path, lock: Option<&[u8]>, error: String) -> String { + let mut msg = match write_file(manifest, text.as_bytes()) { + Ok(()) => format!("{error}; Cargo.toml restored to {old}"), + Err(r) => format!("{error}; could not restore Cargo.toml: {r}"), + }; + let lock_back = match lock { + Some(bytes) => write_file(lock_path, bytes), + None => match std::fs::remove_file(lock_path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(format!("remove {}: {e}", lock_path.display())), + _ => Ok(()), + }, + }; + if let Err(r) = lock_back { + msg.push_str(&format!("; could not restore Cargo.lock: {r}")); + } + msg +} + +/// The file at `path`, or an error when it is larger than `max` bytes. +fn read_bounded(path: &Path, max: u64) -> Result, String> { + let too_big = |len: u64| format!("{}: {len} bytes, more than the {max}-byte limit", path.display()); + let file = File::open(path).map_err(|e| format!("read {}: {e}", path.display()))?; + let len = file.metadata().map_err(|e| format!("read {}: {e}", path.display()))?.len(); + if len > max { + return Err(too_big(len)); + } + let mut bytes = Vec::new(); + file.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| format!("read {}: {e}", path.display()))?; + if bytes.len() as u64 > max { + return Err(too_big(bytes.len() as u64)); + } + Ok(bytes) +} + +/// Replaces `path` atomically: a half-written root manifest breaks every build in the workspace. +fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + craft_atomic::atomic_write(path, bytes).map_err(|e| format!("write {}: {e}", path.display())) +} + +/// Refreshes the workspace members' entries in `Cargo.lock`, without upgrading dependencies. +fn update_lock(root: &Path, cargo_program: &OsStr) -> Result<(), String> { + let update = |offline: bool| { + let mut c = Command::new(cargo_program); + c.current_dir(root).args(["update", "--workspace"]); + if offline { + c.arg("--offline"); + } + crate::runner::run(c, if offline { "cargo update --workspace --offline" } else { "cargo update --workspace" }) + }; + update(true).or_else(|_| update(false)) +} + +fn slice(s: &str, r: Range) -> Result<&str, String> { + s.get(r).ok_or_else(|| "Cargo.toml: an edit does not fall on a character boundary".to_owned()) +} + +/// A one-line string value: the byte range of its quoted token, its text and its quote character. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Str { + span: Range, + text: String, + quote: u8, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Value { + Str(Str), + /// A multi-line string. + LongStr, + /// A number, boolean, date, array or inline table. + Other, +} + +/// A key of the manifest with its full dotted path (table, dotted key and inline tables). +#[derive(Debug, Clone, PartialEq, Eq)] +struct Entry { + path: Vec, + value: Value, +} + +/// The `[workspace.package]` version string. +fn root_version(entries: &[Entry]) -> Result<&Str, String> { + let mut found = entries.iter().filter(|e| e.path.iter().map(String::as_str).eq(ROOT_VERSION)); + let first = found.next().ok_or("no `version` in [workspace.package] of the root Cargo.toml")?; + if found.next().is_some() { + return Err("[workspace.package] version is set more than once in Cargo.toml".into()); + } + match &first.value { + Value::Str(s) if s.text.is_empty() => Err("empty [workspace.package] version".into()), + Value::Str(s) => Ok(s), + Value::LongStr => Err("[workspace.package] version is a multi-line string; write it as `version = \"X.Y.Z\"`".into()), + Value::Other => Err("[workspace.package] version is not a string".into()), + } +} + +/// The `version` strings of path dependencies in `[workspace.dependencies]` that require `old`, each +/// with the operator in front of the version (`""` or `"="`). +fn path_pins<'a>(entries: &'a [Entry], old: &str) -> Vec<(&'a Str, String)> { + let dep = |e: &'a Entry| match e.path.as_slice() { + [w, d, name, key] if w == "workspace" && d == "dependencies" => Some((name.as_str(), key.as_str(), &e.value)), + _ => None, + }; + let with_path: HashSet<&str> = entries.iter().filter_map(dep).filter(|(_, k, _)| *k == "path").map(|(n, _, _)| n).collect(); + entries + .iter() + .filter_map(dep) + .filter_map(|(name, key, value)| match value { + Value::Str(s) if key == "version" => Some((name, s)), + _ => None, + }) + .filter_map(|(name, s)| { + let prefix = s.text.strip_suffix(old)?; + matches!(prefix.trim(), "" | "=").then(|| (name, s, prefix.to_owned())) + }) + .filter(|(name, _, _)| with_path.contains(name)) + .map(|(_, s, prefix)| (s, prefix)) + .collect() +} + +/// Every key of `manifest` whose value is not inside an array. +fn scan(manifest: &str) -> Result, String> { + let mut s = Scanner { s: manifest, b: manifest.as_bytes(), i: 0, table: Vec::new(), out: Vec::new() }; + loop { + s.skip_blank()?; + match s.peek() { + None => return Ok(s.out), + Some(b'[') => s.header()?, + Some(_) => s.key_value()?, + } + s.end_of_line()?; + } +} + +/// A single pass over the manifest that records each key and the byte range of each one-line string. +struct Scanner<'a> { + s: &'a str, + b: &'a [u8], + i: usize, + table: Vec, + out: Vec, +} + +impl Scanner<'_> { + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + fn at(&self, text: &str) -> bool { + self.b.get(self.i..).is_some_and(|rest| rest.starts_with(text.as_bytes())) + } + + fn err(&self, what: &str) -> String { + let before = self.b.get(..self.i).unwrap_or(self.b); + let breaks = before.iter().enumerate().filter(|&(at, &b)| b == b'\n' || (b == b'\r' && before.get(at + 1) != Some(&b'\n'))).count(); + let line = 1 + breaks; + format!("Cargo.toml line {line}: {what}") + } + + fn expect(&mut self, c: u8) -> Result<(), String> { + if self.peek() == Some(c) { + self.i += 1; + Ok(()) + } else { + Err(self.err(&format!("expected `{}`", char::from(c)))) + } + } + + fn skip_spaces(&mut self) { + while matches!(self.peek(), Some(b' ' | b'\t')) { + self.i += 1; + } + } + + fn skip_comment(&mut self) { + if self.peek() == Some(b'#') { + while !matches!(self.peek(), None | Some(b'\n' | b'\r')) { + self.i += 1; + } + } + } + + /// Skips a line ending: LF, CRLF or a lone CR. + fn newline(&mut self) -> bool { + match self.peek() { + Some(b'\n') => self.i += 1, + Some(b'\r') => self.i += if self.b.get(self.i + 1) == Some(&b'\n') { 2 } else { 1 }, + _ => return false, + } + true + } + + /// Skips spaces, comments and line endings. + fn skip_blank(&mut self) -> Result<(), String> { + loop { + self.skip_spaces(); + self.skip_comment(); + if !self.newline() { + return Ok(()); + } + } + } + + fn end_of_line(&mut self) -> Result<(), String> { + self.skip_spaces(); + self.skip_comment(); + if self.peek().is_none() || self.newline() { Ok(()) } else { Err(self.err("expected the end of the line")) } + } + + /// `[table]` or `[[array.of.tables]]`. + fn header(&mut self) -> Result<(), String> { + self.i += 1; + let array = self.peek() == Some(b'['); + if array { + self.i += 1; + } + let mut path = self.key()?; + self.expect(b']')?; + if array { + self.expect(b']')?; + path.push("[]".to_owned()); + } + self.table = path; + Ok(()) + } + + fn key_value(&mut self) -> Result<(), String> { + let key = self.key()?; + self.expect(b'=')?; + let mut path = self.table.clone(); + path.extend(key); + self.value(Some(path), 0) + } + + /// A dotted key, with the spaces around it. + fn key(&mut self) -> Result, String> { + let mut parts = Vec::new(); + loop { + self.skip_spaces(); + parts.push(self.simple_key()?); + self.skip_spaces(); + if self.peek() != Some(b'.') { + return Ok(parts); + } + self.i += 1; + } + } + + fn simple_key(&mut self) -> Result { + match self.peek() { + Some(b'"') if !self.at("\"\"\"") => Ok(self.basic()?.text), + Some(b'\'') if !self.at("'''") => Ok(self.literal()?.text), + _ => { + let start = self.i; + while self.peek().is_some_and(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { + self.i += 1; + } + if start == self.i { + return Err(self.err("expected a key")); + } + slice(self.s, start..self.i).map(str::to_owned) + } + } + } + + /// A value; it is recorded under `path` unless `path` is `None` (inside an array). + fn value(&mut self, path: Option>, depth: usize) -> Result<(), String> { + if depth > MAX_DEPTH { + return Err(self.err("arrays and inline tables nest too deeply")); + } + self.skip_spaces(); + let value = match self.peek() { + Some(b'"') if self.at("\"\"\"") => self.long_string(b'"').map(|()| Value::LongStr)?, + Some(b'\'') if self.at("'''") => self.long_string(b'\'').map(|()| Value::LongStr)?, + Some(b'"') => Value::Str(self.basic()?), + Some(b'\'') => Value::Str(self.literal()?), + Some(b'[') => self.array(depth).map(|()| Value::Other)?, + Some(b'{') => self.inline_table(path.as_deref(), depth).map(|()| Value::Other)?, + _ => self.scalar().map(|()| Value::Other)?, + }; + if let Some(path) = path { + self.out.push(Entry { path, value }); + } + Ok(()) + } + + /// A number, boolean or date; only its extent matters. + fn scalar(&mut self) -> Result<(), String> { + let start = self.i; + let ends = |b: u8| matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b',' | b']' | b'}' | b'#'); + while self.peek().is_some_and(|b| !ends(b)) { + self.i += 1; + } + // A date and a time may be separated by one space: `1979-05-27 07:32:00Z`. + let date = self.i - start == 10 && self.b.get(start + 4) == Some(&b'-'); + if date && self.peek() == Some(b' ') && self.b.get(self.i + 1).is_some_and(u8::is_ascii_digit) { + self.i += 1; + while self.peek().is_some_and(|b| !ends(b)) { + self.i += 1; + } + } + if start == self.i { Err(self.err("expected a value")) } else { Ok(()) } + } + + fn array(&mut self, depth: usize) -> Result<(), String> { + self.i += 1; + loop { + self.skip_blank()?; + if self.peek() == Some(b']') { + self.i += 1; + return Ok(()); + } + self.value(None, depth + 1)?; + self.skip_blank()?; + match self.peek() { + Some(b',') => self.i += 1, + Some(b']') => { + self.i += 1; + return Ok(()); + } + _ => return Err(self.err("expected `,` or `]` in an array")), + } + } + } + + /// An inline table; line breaks inside it are accepted. + fn inline_table(&mut self, path: Option<&[String]>, depth: usize) -> Result<(), String> { + self.i += 1; + loop { + self.skip_blank()?; + if self.peek() == Some(b'}') { + self.i += 1; + return Ok(()); + } + let key = self.key()?; + self.expect(b'=')?; + let child = path.map(|p| p.iter().cloned().chain(key).collect()); + self.value(child, depth + 1)?; + self.skip_blank()?; + match self.peek() { + Some(b',') => self.i += 1, + Some(b'}') => { + self.i += 1; + return Ok(()); + } + _ => return Err(self.err("expected `,` or `}` in an inline table")), + } + } + } + + /// A one-line `"…"` string, with its escapes decoded. + fn basic(&mut self) -> Result { + let start = self.i; + self.i += 1; + let mut text = String::new(); + loop { + match self.peek() { + None | Some(b'\n' | b'\r') => return Err(self.err("unterminated string")), + Some(b'"') => break, + Some(b'\\') => text.push(self.escape()?), + Some(_) => { + let run = self.i; + while self.peek().is_some_and(|b| !matches!(b, b'"' | b'\\' | b'\n' | b'\r')) { + self.i += 1; + } + text.push_str(slice(self.s, run..self.i)?); + } + } + } + self.i += 1; + Ok(Str { span: start..self.i, text, quote: b'"' }) + } + + fn escape(&mut self) -> Result { + self.i += 1; + let c = self.peek().ok_or_else(|| self.err("unterminated string"))?; + self.i += 1; + let digits = match c { + b'"' => return Ok('"'), + b'\\' => return Ok('\\'), + b'b' => return Ok('\u{8}'), + b't' => return Ok('\t'), + b'n' => return Ok('\n'), + b'f' => return Ok('\u{c}'), + b'r' => return Ok('\r'), + b'e' => return Ok('\u{1b}'), + b'u' => 4, + b'U' => 8, + _ => return Err(self.err("unknown escape in a string")), + }; + let hex = self.s.get(self.i..self.i + digits).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())); + let ch = hex.and_then(|h| u32::from_str_radix(h, 16).ok()).and_then(char::from_u32).ok_or_else(|| self.err("invalid unicode escape"))?; + self.i += digits; + Ok(ch) + } + + /// A one-line `'…'` string. + fn literal(&mut self) -> Result { + let start = self.i; + self.i += 1; + while self.peek().is_some_and(|b| !matches!(b, b'\'' | b'\n' | b'\r')) { + self.i += 1; + } + if self.peek() != Some(b'\'') { + return Err(self.err("unterminated string")); + } + let text = slice(self.s, start + 1..self.i)?.to_owned(); + self.i += 1; + Ok(Str { span: start..self.i, text, quote: b'\'' }) + } + + /// A `"""…"""` or `'''…'''` string; only its extent matters. + fn long_string(&mut self, q: u8) -> Result<(), String> { + self.i += 3; + loop { + match self.peek() { + None => return Err(self.err("unterminated multi-line string")), + Some(b'\\') if q == b'"' => self.i += 2, + Some(c) if c == q && self.b.get(self.i..self.i + 3) == Some(&[q, q, q][..]) => { + self.i += 3; + // Up to two more quotes belong to the string. + for _ in 0..2 { + if self.peek() == Some(q) { + self.i += 1; + } + } + return Ok(()); + } + Some(_) => self.i += 1, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + const MANIFEST: &str = "[workspace]\nmembers = [\"a\"]\n\n[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace.dependencies]\nfoo = { version = \"1\" }\n"; + + /// A workspace folder holding `manifest` as its `Cargo.toml` and, when given, `lock` as its `Cargo.lock`. + fn workspace(manifest: &str, lock: Option<&str>) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Cargo.toml"), manifest).unwrap(); + if let Some(lock) = lock { + std::fs::write(dir.path().join("Cargo.lock"), lock).unwrap(); + } + dir + } + + /// The lock directory of the tests' runs: inside the test's own workspace folder, which is removed + /// with it. + fn test_lock_dir(root: &Path) -> PathBuf { + root.join("target").join("xtask-version") + } + + fn run_limited(root: &Path, args: &[&str], limits: &Limits, update: impl FnOnce() -> Result<(), String>) -> Result<(), String> { + run_to(root, args, limits, Some(&[test_lock_dir(root)]), &mut Vec::new(), update) + } + + fn run_in(root: &Path, args: &[&str], update: impl FnOnce() -> Result<(), String>) -> (Result<(), String>, String) { + let mut out = Vec::new(); + let result = run_to(root, args, &Limits::default(), Some(&[test_lock_dir(root)]), &mut out, update); + (result, String::from_utf8(out).unwrap()) + } + + fn file(root: &Path, name: &str) -> Option { + std::fs::read_to_string(root.join(name)).ok() + } + + #[test] + fn reads_the_workspace_version() { + assert_eq!(read(MANIFEST).unwrap(), "0.1.0"); + assert!(read("[package]\nversion = \"1.0.0\"\n").is_err()); + } + + #[test] + fn replaces_only_the_workspace_version() { + let out = replace(MANIFEST, "1.2.3-rc.1").unwrap(); + assert_eq!(read(&out).unwrap(), "1.2.3-rc.1"); + assert_eq!(out, MANIFEST.replace("version = \"0.1.0\"", "version = \"1.2.3-rc.1\"")); + assert!(out.contains("foo = { version = \"1\" }")); + // Setting the old version back gives the same bytes. + assert_eq!(replace(&out, "0.1.0").unwrap(), MANIFEST); + } + + #[test] + fn keeps_crlf_line_endings() { + let crlf = MANIFEST.replace('\n', "\r\n"); + let out = replace(&crlf, "2.0.0").unwrap(); + assert_eq!(out, crlf.replace("\"0.1.0\"", "\"2.0.0\"")); + } + + #[test] + fn validates_versions() { + for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", ""] { + assert!(validate(bad).is_err(), "{bad}"); + } + assert!(replace(MANIFEST, "nope").is_err()); + } + + #[test] + fn rejects_what_cargo_rejects() { + for bad in ["1.0.0-01", "1.0.0-rc.01", "1.0.0-0.00", "1.0.0-rc.1.007", "99999999999999999999.0.0", "1.18446744073709551616.0"] { + assert!(validate(bad).is_err(), "{bad}"); + assert!(replace(MANIFEST, bad).is_err(), "{bad}"); + } + for ok in ["1.0.0-0", "1.0.0-rc.0", "1.0.0-0a", "1.0.0-01a", "1.0.0-99999999999999999999", "18446744073709551615.0.0"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + } + + #[test] + fn moves_the_workspace_crates_pins_with_it() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n[workspace.dependencies]\n\ + own = { path = \"crates/own\", version = \"0.1.0\" }\n\ + exact = { path = \"crates/exact\", version = \"=0.1.0\" }\n\ + dep = { version = \"0.1.0\" }\n\ + other = { path = \"crates/other\", version = \"0.2\" }\n\ + newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert!(out.contains("own = { path = \"crates/own\", version = \"0.2.0\" }"), "{out}"); + assert!(out.contains("exact = { path = \"crates/exact\", version = \"=0.2.0\" }"), "{out}"); + assert!(out.contains("dep = { version = \"0.1.0\" }"), "a registry dependency keeps its version"); + assert!(out.contains("other = { path = \"crates/other\", version = \"0.2\" }")); + assert!(out.contains("newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }")); + } + + #[test] + fn a_failed_update_restores_the_manifest() { + // Two sets in one workspace: a child started by another test must not hold the first one's lock. + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + let (err, out) = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + let err = err.unwrap_err(); + assert!(err.contains("restored to 0.1.0"), "{err}"); + assert_eq!(out, "", "a failed set printed success"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let (ok, out) = run_in(dir.path(), &["set", "2.0.0"], || Ok(())); + assert_eq!(ok, Ok(())); + assert_eq!(out, "version: 0.1.0 -> 2.0.0\n"); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + } + + #[test] + fn the_real_manifest_has_a_valid_version() { + let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.toml")).unwrap(); + let version = read(&text).unwrap(); + validate(&version).unwrap(); + // craft-libs pins its own crates with `version = "=X.Y.Z"`; a set moves those pins too. + let out = replace(&text, "99.0.0").unwrap(); + let pins = text.matches(&format!("version = \"={version}\"")).count(); + assert!(pins > 0, "the root manifest has no `=` pin of its own version"); + assert_eq!(out.matches("version = \"=99.0.0\"").count(), pins, "{out}"); + assert_eq!(replace(&out, &version).unwrap(), text); + } + + #[test] + fn reads_commented_and_single_quoted_versions() { + let manifest = "[workspace.package] # shared\nversion = '1.2.3' # the release\nedition = \"2024\"\n"; + assert_eq!(read(manifest).unwrap(), "1.2.3"); + let out = replace(manifest, "1.3.0").unwrap(); + assert_eq!(out, "[workspace.package] # shared\nversion = '1.3.0' # the release\nedition = \"2024\"\n"); + let spaced = "[ workspace . package ]\n\"version\"=\"1.2.3\"#c\n"; + assert_eq!(replace(spaced, "1.2.4").unwrap(), "[ workspace . package ]\n\"version\"=\"1.2.4\"#c\n"); + } + + #[test] + fn accepts_dotted_workspace_package_version() { + for manifest in [ + "[workspace]\npackage.version = \"0.3.0\"\n", + "workspace.package.version = \"0.3.0\"\n", + "[workspace]\npackage = { version = \"0.3.0\", edition = \"2024\" }\n", + ] { + assert_eq!(read(manifest).unwrap(), "0.3.0", "{manifest}"); + assert_eq!(replace(manifest, "0.4.0").unwrap(), manifest.replace("0.3.0", "0.4.0")); + } + } + + #[test] + fn leaves_member_version_workspace_alone() { + let manifest = "[package]\nname = \"a\"\nversion.workspace = true\n\n[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\na = { path = \"a\", version.workspace = true }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert_eq!(out, manifest.replace("version = \"0.1.0\"", "version = \"0.2.0\"")); + assert!(read("[package]\nversion.workspace = true\n").is_err()); + } + + #[test] + fn moves_multiline_path_dependency_pin() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\n\ + spread = {\n path = \"crates/spread\",\n version = \"0.1.0\",\n}\n\ + dotted.path = \"crates/dotted\"\ndotted.version = \"0.1.0\"\n\n\ + [workspace.dependencies.own]\nversion = \"0.1.0\"\n# the crate\npath = \"crates/own\"\n\n\ + [workspace.dependencies.registry]\nversion = \"0.1.0\"\n"; + let out = replace(manifest, "0.1.1").unwrap(); + let expected = manifest.replacen("0.1.0", "0.1.1", 4); + assert_eq!(out, expected); + assert!(out.ends_with("[workspace.dependencies.registry]\nversion = \"0.1.0\"\n"), "{out}"); + } + + #[test] + fn preserves_mixed_and_cr_line_endings() { + let mixed = "[workspace]\r\nmembers = [\r\"a\",\n]\r\n[workspace.package]\rversion = \"0.1.0\"\r\n# end\r"; + let out = replace(mixed, "0.2.0").unwrap(); + assert_eq!(out, mixed.replace("0.1.0", "0.2.0")); + let cr = MANIFEST.replace('\n', "\r"); + assert_eq!(read(&cr).unwrap(), "0.1.0"); + assert_eq!(replace(&cr, "2.0.0").unwrap(), cr.replace("\"0.1.0\"", "\"2.0.0\"")); + } + + #[test] + fn ignores_brackets_and_keys_inside_strings_and_arrays() { + let manifest = "[workspace]\nmembers = [\n [\"nested\"],\n \"b\",\n]\nnote = \"\"\"\n[workspace.package]\nversion = \"9.9.9\"\n\"\"\"\n\ + title = '[workspace.package]'\n\n[workspace.package]\nversion = \"0.1.0\"\n"; + assert_eq!(read(manifest).unwrap(), "0.1.0"); + assert_eq!(replace(manifest, "0.2.0").unwrap(), manifest.replace("\"0.1.0\"", "\"0.2.0\"")); + } + + #[test] + fn rejects_unsupported_and_ambiguous_manifests() { + let deep = format!("[workspace.package]\nversion = \"0.1.0\"\nx = {}{}\n", "[".repeat(100), "]".repeat(100)); + for (manifest, what) in [ + ("[workspace.package]\nversion = \"0.1.0\"\n[workspace]\npackage.version = \"0.2.0\"\n", "more than once"), + ("[workspace.package]\nversion = \"\"\"0.1.0\"\"\"\n", "multi-line"), + ("[workspace.package]\nversion = 1\n", "not a string"), + ("[workspace.package]\nversion = \"\"\n", "empty"), + ("[workspace.package]\nversion = \"0.1.0\n", "unterminated"), + ("[workspace.package]\nversion = \"0.1.0\" extra\n", "end of the line"), + ("[workspace.package\nversion = \"0.1.0\"\n", "expected `]`"), + ("[workspace.package]\nversion = \"\\q\"\n", "escape"), + (deep.as_str(), "nest too deeply"), + ] { + let Err(e) = replace(manifest, "1.0.0") else { panic!("accepted {manifest:?}") }; + assert!(e.contains(what), "{manifest:?}: {e}"); + } + let Err(e) = replace("[workspace.package]\nversion = \"1.0\"\n", "1.0.1") else { panic!("an invalid current version was replaced") }; + assert!(e.contains("current"), "{e}"); + } + + #[test] + fn rejects_oversized_manifest_before_write() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let limits = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64 - 1); + let result = run_limited(dir.path(), &["set", "2.0.0"], &limits, || { + ran.set(true); + Ok(()) + }); + let Err(e) = result else { panic!("an oversized manifest was read") }; + assert!(e.contains("limit"), "{e}"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let exact = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64); + assert_eq!(run_limited(dir.path(), &[], &exact, || Ok(())), Ok(())); + + let dir = workspace(MANIFEST, Some("lock")); + let small_lock = Limits::default().with_max_lock_bytes(3); + let Err(e) = run_limited(dir.path(), &["set", "2.0.0"], &small_lock, || Ok(())) else { panic!("an oversized lock was read") }; + assert!(e.contains("Cargo.lock") && e.contains("limit"), "{e}"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn restores_lockfile_after_failed_update() { + let dir = workspace(MANIFEST, Some("old lock\r\n")); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "half-updated lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.unwrap_err().contains("restored to 0.1.0")); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\r\n")); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + + // A lock that the failed update created is removed again. + let dir = workspace(MANIFEST, None); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "new lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.is_err()); + assert!(!lock.exists()); + } + + #[test] + fn setting_current_version_does_not_run_cargo() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "0.1.0"], || { + ran.set(true); + Ok(()) + }); + assert_eq!(result, Ok(())); + assert_eq!(out, "version: 0.1.0 (unchanged)\n"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock"), None); + } + + #[test] + fn lock_dirs_cover_the_workspace_and_the_account() { + let (a, b) = (workspace(MANIFEST, None), workspace(MANIFEST, None)); + let dirs_a = lock_dirs(a.path()).unwrap(); + assert_eq!(lock_dirs(&a.path().join(".")).unwrap(), dirs_a, "two spellings of one root"); + assert_ne!(lock_dirs(b.path()).unwrap(), dirs_a); + let canonical = std::fs::canonicalize(a.path()).unwrap(); + assert_eq!(dirs_a[0].parent(), Some(canonical.join("target").join("xtask-version").as_path())); + // Both directories are named for the workspace, so a `target` shared by two workspaces keeps + // their locks apart. + let name = dirs_a[0].file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.starts_with("version-"), "{name}"); + assert!(dirs_a.iter().all(|d| d.file_name() == dirs_a[0].file_name())); + for dir in &dirs_a[1..] { + assert!(dir.is_absolute() && dir.parent().is_some_and(|p| p.ends_with("craft-xtask")), "{}", dir.display()); + assert!(!dir.starts_with(&canonical), "{}", dir.display()); + } + assert!(dirs_a.len() <= 2); + assert!(lock_dirs(&a.path().join("missing")).is_err()); + // FNV-1a's published test value, so the name stays the same across builds. + assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c); + } + + #[test] + fn a_held_workspace_lock_refuses_the_set_whatever_the_lock_directories() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let other = base_lock(dir.path(), &test_lock_dir(dir.path())).unwrap().expect("free lock"); + // A run whose owner-labeled lock directories differ from the holder's still meets its lock. + let elsewhere = tempfile::tempdir().unwrap(); + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[elsewhere.path().join("lock")]), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("another `cargo xtask version set`"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + } + + #[test] + fn the_workspace_lock_is_required_and_a_later_one_is_optional() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + // A directory cannot be made under a file. + let blocked = dir.path().join("Cargo.toml").join("lock"); + let first = test_lock_dir(dir.path()); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[first.clone(), blocked.clone()]), &mut Vec::new(), || Ok(())); + assert_eq!(result, Ok(())); + assert!(first.join("ci.lock").exists()); + + // A run holding the lock in a later directory refuses the set too. + let later = dir.path().join("later"); + let other = crate::lock::try_acquire(&crate::lock::LockConfig::new(&later, 1, "pid 8 in /w: cargo xtask version set 4.0.0")) + .unwrap() + .expect("free lock"); + let ran = Cell::new(false); + let dirs = [first.clone(), blocked.clone(), later.clone()]; + let result = run_to(dir.path(), &["set", "3.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("pid 8 in /w"))); + assert!(!ran.get()); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + drop(other); + // The lock taken in the first directory before the refusal was released. + assert!(crate::lock::try_acquire(&crate::lock::LockConfig::new(&first, 1, "x")).unwrap().is_some()); + + // Without the first lock, nothing is written. + let dir = workspace(MANIFEST, None); + let blocked = dir.path().join("Cargo.toml").join("lock"); + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[blocked, test_lock_dir(dir.path())]), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("could not take the version lock"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn prints_the_version_and_rejects_other_words() { + let dir = workspace(MANIFEST, None); + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + for args in [&["set"][..], &["set", "1.0.0", "2.0.0"], &["get"], &["set", "1.0.0+meta"]] { + let (result, out) = run_in(dir.path(), args, || panic!("cargo ran for {args:?}")); + assert!(result.is_err(), "{args:?}"); + assert_eq!(out, ""); + } + assert_eq!(run_in(dir.path(), &["get"], || Ok(())).0, Err(USAGE.to_owned())); + assert!(run_in(&dir.path().join("missing"), &[], || Ok(())).0.unwrap_err().starts_with("read ")); + } + + #[test] + fn leaves_no_staging_files() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("lock")); + let names = || { + let mut n: Vec = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + n.sort(); + n + }; + let lock_files = || { + std::fs::read_dir(test_lock_dir(dir.path())).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::>() + }; + let no_owner = |files: Vec| files.iter().all(|f| !f.ends_with(".owner")); + let _ = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "the owner file outlived the run: {:?}", lock_files()); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "{:?}", lock_files()); + } + + #[test] + fn concurrent_set_is_refused_before_anything_is_written() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let config = crate::lock::LockConfig::new(test_lock_dir(dir.path()), 1, "pid 7 in /w: cargo xtask version set 9.0.0"); + let other = crate::lock::try_acquire(&config).unwrap().expect("free lock"); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "2.0.0"], || { + ran.set(true); + Err("cargo update failed".into()) + }); + let err = result.unwrap_err(); + assert!(err.contains("another `cargo xtask version set`") && err.contains("pid 7 in /w"), "{err}"); + assert_eq!(out, ""); + assert!(!ran.get(), "cargo update ran while another set held the lock"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + // Reading the version does not take the lock. Setting the current one does: the other run may + // still put an older version back. + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + let (unchanged, out) = run_in(dir.path(), &["set", "0.1.0"], || Ok(())); + assert!(unchanged.is_err_and(|e| e.contains("pid 7 in /w")), "{out}"); + assert_eq!(out, ""); + // An invalid version is refused before the lock. + assert!(run_in(dir.path(), &["set", "nope"], || Ok(())).0.unwrap_err().contains("not a version")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())), (Ok(()), "version: 0.1.0 -> 2.0.0\n".to_owned())); + } + + #[test] + fn replaces_the_existing_manifest() { + let dir = workspace(MANIFEST, None); + // An open reader of the old manifest does not stop the replacement. + let reader = File::open(dir.path().join("Cargo.toml")).unwrap(); + assert_eq!(run_in(dir.path(), &["set", "3.0.0"], || Ok(())).0, Ok(())); + drop(reader); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "3.0.0"); + } +} From 466471e920cce1d66e7f4ec2f3641b07b05a38f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:44:14 -0800 Subject: [PATCH 012/490] craft-xtask: pack PNG images into .ico and .icns files The icon module packs the PNGs an app renders into a Windows .ico (icon::ico::pack) or a macOS .icns (icon::icns::pack). The app keeps its ico and icns commands, its size lists and its paths. - Every PNG is checked whole: signature, chunk lengths, types and CRCs, a 13-byte IHDR with valid fields, PLTE and IDAT order, no unknown critical chunk, and a final IEND with nothing after it. ICO entries must be 8-bit RGBA, the 32 bits per pixel a PNG entry of an ICO holds. - Images are written in increasing size whatever the input order, and two images of one size are an error. - Limits bounds the image count (16), each PNG (16 MiB) and the packed file (128 MiB). Lengths and offsets are checked against 32 bits and the output is reserved before any byte is written. read_pngs reads the input files within the same limits. - ico::read_file and icns::read_file check a committed icon at the path the app passes, for its committed_icon_is_valid test. A file with no images or no elements is an error. From DeckCraft xtask/src/ico.rs (ae9d525b), craft-launcher xtask/src/icns.rs (019330f9) and MaterialCraft xtask/src/ico.rs (6e952a9a); their tests move in under the same names, with complete PNG fixtures in place of the IHDR-only test bytes. DeckCraft, CADCraft, craft-launcher and MaterialCraft are the planned consumers; no app switches here. --- README.md | 2 +- crates/xtask/Cargo.toml | 2 +- crates/xtask/README.md | 52 +++ crates/xtask/src/icon.rs | 594 ++++++++++++++++++++++++++++++++++ crates/xtask/src/icon/icns.rs | 246 ++++++++++++++ crates/xtask/src/icon/ico.rs | 284 ++++++++++++++++ crates/xtask/src/lib.rs | 4 + 7 files changed, 1182 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/icon.rs create mode 100644 crates/xtask/src/icon/icns.rs create mode 100644 crates/xtask/src/icon/ico.rs diff --git a/README.md b/README.md index 34bba45518..60493521a7 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. - [`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), 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 diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..2cead82ec1 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true rust-version.workspace = true repository.workspace = true -description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report, and .ico and .icns packing" [lints] workspace = true diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..273cd9aaaf 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,6 +9,7 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `icon` | always | `ico::pack`, `icns::pack`, `png_size`, `png_info`, `read_pngs`, `Limits`, and `ico::read_file` and `icns::read_file` for an app's test of its committed icons | No feature is on by default. `report` adds `serde_json` and `craft-atomic`. @@ -91,6 +92,49 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Icons + +```rust,no_run +use std::path::Path; +use craft_xtask::icon::{self, Limits, ico}; + +fn cmd_ico(out: &Path, inputs: &[&Path]) -> Result<(), icon::Error> { + let limits = Limits::default(); + let pngs = icon::read_pngs(inputs, &limits)?; + let file = ico::pack(&pngs, &limits)?; + std::fs::write(out, &file).map_err(|e| icon::Error::io(out, &e))?; + Ok(()) +} +``` + +The app renders the PNGs and chooses the sizes, the paths and the command name. Both formats store +each PNG as is; no image is decoded. + +- Every PNG is checked whole: the signature, each chunk's length and CRC, a first `IHDR` of 13 bytes + with valid fields, at most one `PLTE` before the first `IDAT`, at least one `IDAT` with no other + chunk between two of them, no other critical chunk, and a final empty `IEND` with nothing after + it. Images must be square and at least 1 px. +- `ico::pack` takes 1 to 256 px images in 8-bit RGBA, the form a PNG entry of an `.ico` holds + ([ICO format, part 4](https://devblogs.microsoft.com/oldnewthing/20101022-00/?p=12473/)). A 256 px + side is written as 0. +- `icns::pack` takes 16, 32, 64, 128, 256, 512 and 1024 px images and writes each into every slot of + its size: 16 `icp4`; 32 `icp5`, `ic11`; 64 `icp6`, `ic12`; 128 `ic07`; 256 `ic08`, `ic13`; 512 + `ic09`, `ic14`; 1024 `ic10` ([ICNS format](https://hexbase.dev/formats/icns/)). +- Both write the images in increasing size, whatever the input order. Two images of one size are an + error. +- `Limits` bounds the image count (default 16), each PNG (16 MiB) and the packed file (128 MiB). The + formats' 32-bit offsets and lengths also cap a file at 4 GiB - 1 byte. Sizes are checked and the + file's memory reserved before any byte is written. `read_pngs` stops reading a file one byte past + the smaller of the PNG limit and what the total limit has left. +- `ico::read_file` and `icns::read_file` read a file within the same limits and check its structure. + `ico::read` accepts only the entries `ico::pack` writes. Both readers hold each image to the PNG + limit. `icns::read` returns at most four elements for each image `Limits` allows, and returns + elements that are not PNGs as stored. An app's `committed_icon_is_valid` test passes its own icon + path, for example `assets/app-icon/.ico`. + +Errors are `icon::Error`: `Empty`, `TooManyImages`, `InvalidPng`, `NotSquare`, `UnsupportedSize`, +`DuplicateSize`, `TooLarge`, `Allocation`, `InvalidIcon` or `Io`. + ## Origin | Part | Source | @@ -98,7 +142,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | +| `icon::ico`: `pack`, `png_size` and the tests `packs_directory_and_payloads`, `rejects_bad_input`, `committed_icon_is_valid` | DeckCraft `xtask/src/ico.rs` at [ae9d525](https://github.com/storytold/deckcraft/blob/ae9d525bce365083bb62b4754bdd346feb2a79b0/xtask/src/ico.rs); CADCraft's copy differs only in its icon path | +| `icon::icns`: `pack`, the slot table and the tests `fills_every_slot_of_each_size`, `rejects_bad_input`, `committed_icon_is_valid`, `packs_icns_elements` | craft-launcher `xtask/src/icns.rs` at [019330f](https://github.com/storytold/craft-launcher/blob/019330f99aa90a3d6501e134fc48df8d719e15a2/xtask/src/icns.rs); MaterialCraft `xtask/src/ico.rs` at [6e952a9](https://github.com/storytold/materialcraft/blob/6e952a9a10f9bce77f330e430a828c066be6ad9b/xtask/src/ico.rs) | +| `icon`: the test `rejects_non_png` | VectorCraft `xtask/src/ico.rs` at [4373205](https://github.com/storytold/vectorcraft/blob/437320509da102f5d9aca44d411ffb254f071932/xtask/src/ico.rs) | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| The whole-PNG check, the RGBA check for `.ico`, the size order and duplicate check, `Limits`, the checked lengths and offsets, `read_pngs` and the readers | written here | ## Migration @@ -108,6 +156,10 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| DeckCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. | +| CADCraft | Planned: `xtask/src/ico.rs` moves to `icon::ico`. The `ico` command and `packaging/icons.sh` stay in the app. | +| craft-launcher | Planned: `xtask/src/ico.rs` and `icns.rs` move to `icon`. The `ico` and `icns` commands stay in the app. | +| MaterialCraft | Planned: `pack_ico` and `pack_icns` move to `icon`. The `ico` and `icns` commands stay in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/icon.rs b/crates/xtask/src/icon.rs new file mode 100644 index 0000000000..dfdd907cbb --- /dev/null +++ b/crates/xtask/src/icon.rs @@ -0,0 +1,594 @@ +//! Icon packing: PNG images into a Windows `.ico` ([`ico`]) or a macOS `.icns` ([`icns`]). +//! +//! Both formats store each PNG as is, so no image is decoded. The app renders the PNGs, chooses the +//! sizes, the input and output paths and the command name, and calls [`ico::pack`] or +//! [`icns::pack`]: +//! +//! ```no_run +//! use std::path::Path; +//! use craft_xtask::icon::{self, Limits, ico}; +//! +//! fn cmd_ico(out: &Path, inputs: &[&Path]) -> Result<(), icon::Error> { +//! let limits = Limits::default(); +//! let pngs = icon::read_pngs(inputs, &limits)?; +//! let file = ico::pack(&pngs, &limits)?; +//! std::fs::write(out, &file).map_err(|e| icon::Error::io(out, &e))?; +//! Ok(()) +//! } +//! ``` +//! +//! Every PNG is checked before anything is written: the signature, every chunk's length and CRC, +//! a first `IHDR` chunk of 13 bytes with valid fields, at least one `IDAT` chunk and a final `IEND` +//! chunk with nothing after it. The pixel data is not decompressed. Images are written in increasing +//! size, whatever the order of the input, and two images of one size are an error. + +pub mod icns; +pub mod ico; + +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +/// The PNG file signature. +const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n"; + +/// The largest chunk length and image side the PNG format allows (2^31 - 1). +const PNG_MAX_U31: u32 = 0x7fff_ffff; + +/// Size limits for the images and the packed file. Every input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The most images in one icon file. Default 16. + pub max_images: usize, + /// The most bytes in one PNG. Default 16 MiB. + pub max_png_bytes: usize, + /// The most bytes in the packed file, and in the PNGs that [`read_pngs`] reads together. + /// Default 128 MiB. The formats' 32-bit offsets and lengths also cap a packed file at + /// 4 GiB - 1 byte. + pub max_total_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { max_images: 16, max_png_bytes: 16 << 20, max_total_bytes: 128 << 20 } + } +} + +/// Why an icon could not be packed, read or checked. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// No images were given. + Empty, + /// More images than [`Limits::max_images`], or than the format can hold. + TooManyImages { + /// The number of images given. + count: usize, + /// The most allowed. + max: usize, + }, + /// The bytes are not a complete, well-formed PNG, or not the PNG kind the format needs. + InvalidPng(String), + /// The image is not square, or a side is 0. + NotSquare { + /// The width from `IHDR`. + width: u32, + /// The height from `IHDR`. + height: u32, + }, + /// The format has no entry for an image of this size. + UnsupportedSize { + /// `"ICO"` or `"ICNS"`. + format: &'static str, + /// The image's side in pixels. + size: u32, + }, + /// Two images have the same size. + DuplicateSize(u32), + /// An input or the packed file is over a limit. + TooLarge(String), + /// The memory for the packed file could not be reserved. + Allocation(usize), + /// An icon file that was read is not well formed. + InvalidIcon(String), + /// A file could not be read or written. + Io { + /// The file. + path: PathBuf, + /// The error the OS returned. + cause: String, + }, +} + +impl Error { + /// An [`Error::Io`] for `path`. + pub fn io(path: &Path, e: &io::Error) -> Self { + Error::Io { path: path.to_path_buf(), cause: e.to_string() } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Empty => f.write_str("need at least one PNG"), + Error::TooManyImages { count, max } => write!(f, "{count} images given, at most {max} allowed"), + Error::InvalidPng(m) => write!(f, "not a valid PNG: {m}"), + Error::NotSquare { width, height } => write!(f, "icon images must be square and at least 1 px, got {width}x{height}"), + Error::UnsupportedSize { format: "ICO", size } => write!(f, "ICO images must be 1 to 256 px, got {size}"), + Error::UnsupportedSize { format, size } => { + write!(f, "{format} images must be 16, 32, 64, 128, 256, 512 or 1024 px, got {size}") + } + Error::DuplicateSize(size) => write!(f, "two images are {size} px; give each size once"), + Error::TooLarge(m) => write!(f, "too large: {m}"), + Error::Allocation(n) => write!(f, "could not reserve {n} bytes for the icon file"), + Error::InvalidIcon(m) => write!(f, "not a valid icon file: {m}"), + Error::Io { path, cause } => write!(f, "{}: {cause}", path.display()), + } + } +} + +impl std::error::Error for Error {} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// The `IHDR` fields of a PNG that [`png_info`] checked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PngInfo { + /// Width in pixels, 1 to 2^31 - 1. + pub width: u32, + /// Height in pixels, 1 to 2^31 - 1. + pub height: u32, + /// Bits per sample or per palette index. + pub bit_depth: u8, + /// 0 gray, 2 RGB, 3 palette, 4 gray and alpha, 6 RGBA. + pub color_type: u8, +} + +impl PngInfo { + /// 8-bit RGBA, the 32 bits per pixel that a PNG entry of an ICO file holds. + pub fn is_rgba8(&self) -> bool { + self.color_type == 6 && self.bit_depth == 8 + } +} + +/// Width and height from a PNG's `IHDR` chunk, after [`png_info`] has checked the whole PNG. +pub fn png_size(png: &[u8]) -> Result<(u32, u32), Error> { + png_info(png).map(|i| (i.width, i.height)) +} + +/// Checks the structure of a whole PNG and returns its `IHDR` fields. +/// +/// The checks are the signature; every chunk's length (at most 2^31 - 1), type (four ASCII letters, +/// the third uppercase) and CRC; a first `IHDR` chunk of 13 bytes with a width and height of 1 to 2^31 - 1, a valid +/// color type and bit depth pair, compression and filter method 0 and interlace method 0 or 1; at +/// most one `PLTE` chunk, of 1 to 256 entries (2^bit depth in a palette image), before the first +/// `IDAT` chunk, required in a palette image and absent from a gray one; at least one `IDAT` chunk, +/// all of them consecutive; no critical chunk other than these four; and an empty `IEND` chunk at the +/// end with nothing after it. +pub fn png_info(png: &[u8]) -> Result { + let bad = |m: &str| Error::InvalidPng(m.to_string()); + if png.get(..8) != Some(PNG_SIGNATURE.as_slice()) { + return Err(bad("no PNG signature")); + } + let mut at = 8usize; + let mut info = None; + // `idat_done` is set by the first chunk after a run of IDAT chunks. + let (mut plte, mut idat, mut idat_done) = (false, false, false); + loop { + let header = png.get(at..at + 8).ok_or_else(|| bad("truncated chunk header"))?; + let len = be32(&header[..4]); + let kind: [u8; 4] = [header[4], header[5], header[6], header[7]]; + if len > PNG_MAX_U31 { + return Err(bad("chunk length over 2^31 - 1")); + } + if !kind.iter().all(u8::is_ascii_alphabetic) || !kind[2].is_ascii_uppercase() { + return Err(bad("chunk type is not four ASCII letters with an uppercase third letter")); + } + let data_end = (at + 8).checked_add(len as usize).ok_or_else(|| bad("chunk length overflows"))?; + let crc_end = data_end.checked_add(4).ok_or_else(|| bad("chunk length overflows"))?; + let (Some(body), Some(stored)) = (png.get(at + 4..data_end), png.get(data_end..crc_end)) else { + return Err(bad("truncated chunk")); + }; + if crc32(body) != be32(stored) { + return Err(Error::InvalidPng(format!("bad CRC in the {} chunk", String::from_utf8_lossy(&kind)))); + } + let data = &body[4..]; + if idat && &kind != b"IDAT" { + idat_done = true; + } + match (&kind, info) { + (b"IHDR", None) => info = Some(ihdr(data)?), + (_, None) => return Err(bad("the first chunk is not IHDR")), + (b"IHDR", Some(_)) => return Err(bad("a second IHDR chunk")), + (b"PLTE", Some(i)) => { + if plte || idat { + return Err(bad("a second PLTE chunk, or a PLTE chunk after IDAT")); + } + if matches!(i.color_type, 0 | 4) { + return Err(bad("a PLTE chunk in a gray image")); + } + // A palette image indexes at most 2^bit_depth entries. + let max_entries = if i.color_type == 3 { 1usize << i.bit_depth } else { 256 }; + if data.is_empty() || data.len() > 3 * max_entries || data.len() % 3 != 0 { + return Err(Error::InvalidPng(format!("PLTE chunk is not 1 to {max_entries} entries of 3 bytes"))); + } + plte = true; + } + (b"IDAT", Some(i)) => { + if i.color_type == 3 && !plte { + return Err(bad("a palette image without a PLTE chunk before its IDAT")); + } + if idat_done { + return Err(bad("IDAT chunks are not consecutive")); + } + idat = true; + } + (b"IEND", Some(i)) => { + if len != 0 { + return Err(bad("IEND chunk with data")); + } + if !idat { + return Err(bad("no IDAT chunk")); + } + if crc_end != png.len() { + return Err(bad("bytes after the IEND chunk")); + } + return Ok(i); + } + // An uppercase first letter marks a critical chunk, which a decoder must understand. + (k, Some(_)) if k[0].is_ascii_uppercase() => { + return Err(Error::InvalidPng(format!("unknown critical chunk {}", String::from_utf8_lossy(k)))); + } + _ => {} + } + at = crc_end; + } +} + +/// The checked fields of an `IHDR` chunk's 13 data bytes. +fn ihdr(data: &[u8]) -> Result { + let bad = |m: &str| Error::InvalidPng(m.to_string()); + let [w0, w1, w2, w3, h0, h1, h2, h3, bit_depth, color_type, compression, filter, interlace] = data else { + return Err(bad("IHDR chunk is not 13 bytes")); + }; + let (width, height) = (u32::from_be_bytes([*w0, *w1, *w2, *w3]), u32::from_be_bytes([*h0, *h1, *h2, *h3])); + if width == 0 || height == 0 || width > PNG_MAX_U31 || height > PNG_MAX_U31 { + return Err(Error::InvalidPng(format!("image size {width}x{height} is outside 1 to 2^31 - 1"))); + } + let depths: &[u8] = match color_type { + 0 => &[1, 2, 4, 8, 16], + 3 => &[1, 2, 4, 8], + 2 | 4 | 6 => &[8, 16], + _ => return Err(Error::InvalidPng(format!("color type {color_type}"))), + }; + if !depths.contains(bit_depth) { + return Err(Error::InvalidPng(format!("bit depth {bit_depth} with color type {color_type}"))); + } + if *compression != 0 || *filter != 0 || *interlace > 1 { + return Err(bad("unknown compression, filter or interlace method")); + } + Ok(PngInfo { width, height, bit_depth: *bit_depth, color_type: *color_type }) +} + +/// Reads the PNGs at `paths`, in order, within `limits`: at most [`Limits::max_images`] files, each +/// at most [`Limits::max_png_bytes`] and together at most [`Limits::max_total_bytes`]. A file over a +/// limit is an error before more than one byte past the limit is read. The bytes are not checked; +/// [`ico::pack`] and [`icns::pack`] check them. +pub fn read_pngs>(paths: &[P], limits: &Limits) -> Result>, Error> { + if paths.len() > limits.max_images { + return Err(Error::TooManyImages { count: paths.len(), max: limits.max_images }); + } + let mut out = Vec::with_capacity(paths.len()); + let mut left = limits.max_total_bytes; + for path in paths { + let path = path.as_ref(); + // Each read stops at the smaller of the file limit and what the total limit has left. + let png = match read_bounded(path, limits.max_png_bytes.min(left)) { + Err(Error::TooLarge(_)) if left < limits.max_png_bytes => { + return Err(Error::TooLarge(format!("the PNGs hold more than {} bytes together", limits.max_total_bytes))); + } + r => r?, + }; + left -= png.len(); + out.push(png); + } + Ok(out) +} + +/// The bytes of the file at `path`, or [`Error::TooLarge`] when it holds more than `max` bytes. +pub(crate) fn read_bounded(path: &Path, max: usize) -> Result, Error> { + let too_large = || Error::TooLarge(format!("{} holds more than {max} bytes", path.display())); + let file = File::open(path).map_err(|e| Error::io(path, &e))?; + let len = file.metadata().map_err(|e| Error::io(path, &e))?.len(); + if len > max as u64 { + return Err(too_large()); + } + let mut buf = Vec::new(); + // `len` is at most `max`, a usize. The file can grow after the size check, so the read stops one + // byte past the limit. + buf.try_reserve_exact(len as usize).map_err(|_| Error::Allocation(len as usize))?; + file.take((max as u64).saturating_add(1)).read_to_end(&mut buf).map_err(|e| Error::io(path, &e))?; + if buf.len() > max { + return Err(too_large()); + } + Ok(buf) +} + +/// Checks every PNG against `limits`, returns each one's side in pixels with its index, sorted by +/// size, and rejects two images of one size. `check` checks each square image's `IHDR` fields and +/// side for the format; `format_max` is the most images the format can hold. +fn sorted_sizes>( + pngs: &[P], + limits: &Limits, + format_max: usize, + check: impl Fn(&PngInfo) -> Result<(), Error>, +) -> Result, Error> { + if pngs.is_empty() { + return Err(Error::Empty); + } + let max = limits.max_images.min(format_max); + if pngs.len() > max { + return Err(Error::TooManyImages { count: pngs.len(), max }); + } + let mut sizes = Vec::with_capacity(pngs.len()); + for (i, png) in pngs.iter().enumerate() { + let png = png.as_ref(); + if png.len() > limits.max_png_bytes { + return Err(Error::TooLarge(format!("image {} holds {} bytes, more than {}", i + 1, png.len(), limits.max_png_bytes))); + } + let info = png_info(png)?; + if info.width != info.height { + return Err(Error::NotSquare { width: info.width, height: info.height }); + } + check(&info)?; + sizes.push((info.width, i)); + } + sizes.sort_unstable(); + if let Some(w) = sizes.windows(2).find(|w| w[0].0 == w[1].0) { + return Err(Error::DuplicateSize(w[0].0)); + } + Ok(sizes) +} + +/// Checks a packed file's size against `limits` and the formats' 32-bit fields, and reserves it. +fn reserve(total: u64, limits: &Limits) -> Result, Error> { + if total > u64::from(u32::MAX) { + return Err(Error::TooLarge(format!("the icon file would hold {total} bytes, more than 32-bit offsets reach"))); + } + if total > limits.max_total_bytes as u64 { + return Err(Error::TooLarge(format!("the icon file would hold {total} bytes, more than {}", limits.max_total_bytes))); + } + let total = total as usize; + let mut out = Vec::new(); + out.try_reserve_exact(total).map_err(|_| Error::Allocation(total))?; + Ok(out) +} + +/// A big-endian u32 from the first four bytes of `b`, which holds at least four. +fn be32(b: &[u8]) -> u32 { + u32::from_be_bytes([b[0], b[1], b[2], b[3]]) +} + +/// The CRC-32 table of the PNG specification (polynomial 0xedb88320). +const CRC_TABLE: [u32; 256] = { + let mut table = [0u32; 256]; + let mut n = 0; + while n < 256 { + let mut c = n as u32; + let mut k = 0; + while k < 8 { + c = if c & 1 != 0 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 }; + k += 1; + } + table[n] = c; + n += 1; + } + table +}; + +/// The CRC-32 that a PNG chunk stores over its type and data. +fn crc32(bytes: &[u8]) -> u32 { + !bytes.iter().fold(u32::MAX, |c, &b| CRC_TABLE[((c ^ u32::from(b)) & 0xff) as usize] ^ (c >> 8)) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A complete PNG of `width` x `height` transparent pixels, with its pixel data in stored + /// (uncompressed) deflate blocks. + pub(crate) fn png_of(width: u32, height: u32, bit_depth: u8, color_type: u8) -> Vec { + let channels: usize = match color_type { + 2 => 3, + 4 => 2, + 6 => 4, + _ => 1, + }; + let row = (width as usize * channels * usize::from(bit_depth)).div_ceil(8) + 1; + let raw = vec![0u8; row * height as usize]; + let mut z = vec![0x78, 0x01]; + let mut blocks = raw.chunks(0xffff).peekable(); + while let Some(block) = blocks.next() { + let n = block.len() as u16; + z.push(u8::from(blocks.peek().is_none())); + z.extend_from_slice(&n.to_le_bytes()); + z.extend_from_slice(&(!n).to_le_bytes()); + z.extend_from_slice(block); + } + let (mut a, mut b) = (1u32, 0u32); + for &x in &raw { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + z.extend_from_slice(&((b << 16) | a).to_be_bytes()); + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&width.to_be_bytes()); + ihdr.extend_from_slice(&height.to_be_bytes()); + ihdr.extend_from_slice(&[bit_depth, color_type, 0, 0, 0]); + let mut png = PNG_SIGNATURE.to_vec(); + let mut chunks = vec![(*b"IHDR", ihdr)]; + if color_type == 3 { + chunks.push((*b"PLTE", vec![0, 0, 0])); + } + chunks.push((*b"IDAT", z)); + chunks.push((*b"IEND", Vec::new())); + for (kind, data) in chunks { + push_chunk(&mut png, &kind, &data); + } + png + } + + /// A square 8-bit RGBA PNG of `size` px. + pub(crate) fn rgba(size: u32) -> Vec { + png_of(size, size, 8, 6) + } + + pub(crate) fn push_chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { + png.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend_from_slice(kind); + png.extend_from_slice(data); + let crc = crc32(&png[start..]); + png.extend_from_slice(&crc.to_be_bytes()); + } + + /// A 1x1 transparent RGBA PNG written by an independent encoder (Python's `struct`, `zlib.crc32` + /// and `zlib.compress` at level 0) from the layout in the W3C PNG specification. + const ONE_PIXEL_PNG: [u8; 73] = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, + 0xfa, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, + 0xae, 0x42, 0x60, 0x82, + ]; + + #[test] + fn crc_matches_the_standard_check_values() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + assert_eq!(crc32(b"IEND"), 0xae42_6082); + } + + #[test] + fn fixtures_match_an_independent_encoder() { + assert_eq!(rgba(1), ONE_PIXEL_PNG); + assert_eq!(png_info(&ONE_PIXEL_PNG), Ok(PngInfo { width: 1, height: 1, bit_depth: 8, color_type: 6 })); + } + + #[test] + fn rejects_non_png() { + assert!(matches!(png_size(b"GIF89a"), Err(Error::InvalidPng(_)))); + assert!(matches!(png_size(&[]), Err(Error::InvalidPng(_)))); + assert_eq!(png_size(&rgba(48)), Ok((48, 48))); + assert_eq!(png_size(&png_of(3, 5, 1, 3)), Ok((3, 5))); + } + + #[test] + fn rejects_a_header_only_png() { + // The 33-byte prefix the app copies' tests used: signature and IHDR, without the IHDR's CRC, + // an IDAT or an IEND. + let full = rgba(16); + for cut in [24, 29, 33, full.len() - 12, full.len() - 1] { + assert!(matches!(png_info(&full[..cut]), Err(Error::InvalidPng(_))), "accepted {cut} of {} bytes", full.len()); + } + } + + #[test] + fn rejects_a_wrong_ihdr_length() { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &[0, 0, 0, 16, 0, 0, 0, 16, 8, 6, 0, 0]); + push_chunk(&mut png, b"IDAT", &[0]); + push_chunk(&mut png, b"IEND", &[]); + assert_eq!(png_info(&png), Err(Error::InvalidPng("IHDR chunk is not 13 bytes".into()))); + } + + #[test] + fn rejects_a_bad_crc_and_trailing_bytes() { + let mut png = rgba(16); + png[29] ^= 1; // the IHDR's CRC + assert!(matches!(png_info(&png), Err(Error::InvalidPng(m)) if m.contains("CRC"))); + let mut png = rgba(16); + png.push(0); + assert_eq!(png_info(&png), Err(Error::InvalidPng("bytes after the IEND chunk".into()))); + } + + #[test] + fn rejects_bad_ihdr_fields() { + let mut zero = PNG_SIGNATURE.to_vec(); + push_chunk(&mut zero, b"IHDR", &[0, 0, 0, 0, 0, 0, 0, 1, 8, 6, 0, 0, 0]); + assert!(matches!(png_info(&zero), Err(Error::InvalidPng(_)))); + for (depth, color) in [(8, 1), (4, 6), (16, 3), (8, 7)] { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, depth, color, 0, 0, 0]); + assert!(matches!(png_info(&png), Err(Error::InvalidPng(_))), "accepted depth {depth} color {color}"); + } + let mut no_plte = PNG_SIGNATURE.to_vec(); + push_chunk(&mut no_plte, b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 3, 0, 0, 0]); + push_chunk(&mut no_plte, b"IDAT", &[0]); + push_chunk(&mut no_plte, b"IEND", &[]); + assert!(matches!(png_info(&no_plte), Err(Error::InvalidPng(m)) if m.contains("PLTE"))); + } + + #[test] + fn rejects_chunks_out_of_order() { + let build = |ihdr: [u8; 13], chunks: &[(&[u8; 4], &[u8])]| { + let mut png = PNG_SIGNATURE.to_vec(); + push_chunk(&mut png, b"IHDR", &ihdr); + for (kind, data) in chunks { + push_chunk(&mut png, kind, data); + } + push_chunk(&mut png, b"IEND", &[]); + png + }; + let rgba = [0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]; + let gray = [0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]; + let palette = [0, 0, 0, 1, 0, 0, 0, 1, 8, 3, 0, 0, 0]; + assert!(png_info(&build(rgba, &[(b"IDAT", &[0]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build(palette, &[(b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build([0, 0, 0, 1, 0, 0, 0, 1, 1, 3, 0, 0, 0], &[(b"PLTE", &[0; 6]), (b"IDAT", &[0])])).is_ok()); + assert!(png_info(&build(rgba, &[(b"zzZz", &[]), (b"IDAT", &[0])])).is_ok()); + let bad = [ + build(rgba, &[(b"IDAT", &[0]), (b"tEXt", b"a\0b"), (b"IDAT", &[0])]), + build(rgba, &[(b"IDAT", &[0]), (b"PLTE", &[0, 0, 0])]), + build(rgba, &[(b"PLTE", &[0, 0, 0]), (b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])]), + build(rgba, &[(b"PLTE", &[0, 0]), (b"IDAT", &[0])]), + build(gray, &[(b"PLTE", &[0, 0, 0]), (b"IDAT", &[0])]), + build([0, 0, 0, 1, 0, 0, 0, 1, 1, 3, 0, 0, 0], &[(b"PLTE", &[0; 9]), (b"IDAT", &[0])]), + build(rgba, &[(b"IDAT", &[0]), (b"ZZZZ", &[])]), + build(rgba, &[(b"zzzz", &[]), (b"IDAT", &[0])]), + ]; + for (n, png) in bad.iter().enumerate() { + assert!(matches!(png_info(png), Err(Error::InvalidPng(_))), "accepted case {n}"); + } + } + + #[test] + fn read_pngs_stops_at_the_limits() { + let dir = tempfile::tempdir().expect("temporary directory"); + let (a, b) = (dir.path().join("a.png"), dir.path().join("b.png")); + std::fs::write(&a, rgba(16)).expect("write a"); + std::fs::write(&b, rgba(32)).expect("write b"); + let limits = Limits::default(); + assert_eq!(read_pngs(&[&a, &b], &limits), Ok(vec![rgba(16), rgba(32)])); + + let small = Limits { max_png_bytes: rgba(16).len(), ..limits }; + assert!(matches!(read_pngs(&[&a, &b], &small), Err(Error::TooLarge(m)) if m.contains("b.png"))); + let one = Limits { max_images: 1, ..limits }; + assert_eq!(read_pngs(&[&a, &b], &one), Err(Error::TooManyImages { count: 2, max: 1 })); + let total = Limits { max_total_bytes: rgba(16).len() + 1, ..limits }; + assert!(matches!(read_pngs(&[&a, &b], &total), Err(Error::TooLarge(m)) if m.contains("together"))); + let first = Limits { max_total_bytes: rgba(16).len() - 1, ..limits }; + assert!(matches!(read_pngs(&[&a], &first), Err(Error::TooLarge(m)) if m.contains("together"))); + assert!(matches!(read_pngs(&[dir.path().join("missing.png")], &limits), Err(Error::Io { .. }))); + } + + #[test] + fn reserve_rejects_sizes_past_32_bits_and_the_limit() { + let limits = Limits { max_total_bytes: usize::MAX, ..Limits::default() }; + assert!(matches!(reserve(u64::from(u32::MAX) + 1, &limits), Err(Error::TooLarge(_)))); + assert!(matches!(reserve(101, &Limits { max_total_bytes: 100, ..limits }), Err(Error::TooLarge(_)))); + assert_eq!(reserve(100, &Limits { max_total_bytes: 100, ..limits }).map(|v| v.capacity() >= 100), Ok(true)); + } +} diff --git a/crates/xtask/src/icon/icns.rs b/crates/xtask/src/icon/icns.rs new file mode 100644 index 0000000000..27e773fd13 --- /dev/null +++ b/crates/xtask/src/icon/icns.rs @@ -0,0 +1,246 @@ +//! macOS `.icns` files of PNG images, written on any OS. +//! +//! The file starts with the magic `icns` and the file's length, followed by elements: a four-letter +//! type, the element's length including its 8-byte header, and a PNG. Both lengths are big-endian +//! ([ICNS format](https://hexbase.dev/formats/icns/)). Each PNG fills every slot of its pixel size in +//! [`SLOTS`]: a 32 px image is both the 32 pt icon (`icp5`) and the 16 pt @2x one (`ic11`). + +use std::path::Path; + +use super::{Error, Limits, read_bounded, reserve, sorted_sizes}; + +/// The PNG element types, by pixel size, in the order they are written. +pub const SLOTS: [(u32, [u8; 4]); 11] = [ + (16, *b"icp4"), + (32, *b"icp5"), + (32, *b"ic11"), // 16 @2x + (64, *b"icp6"), + (64, *b"ic12"), // 32 @2x + (128, *b"ic07"), + (256, *b"ic08"), + (256, *b"ic13"), // 128 @2x + (512, *b"ic09"), + (512, *b"ic14"), // 256 @2x + (1024, *b"ic10"), // 512 @2x +]; + +/// The number of different sizes in [`SLOTS`], and so the most images an `.icns` file holds. +pub const MAX_IMAGES: usize = 7; + +/// The most elements [`read`] returns for each image [`Limits::max_images`] allows. A file from +/// [`pack`] holds at most 2 per image, and other tools also write a table of contents and other +/// elements that are not images. +pub const ELEMENTS_PER_IMAGE: usize = 4; + +/// The magic and length at the start of the file, and the type and length of each element, in bytes. +const HEADER: u64 = 8; + +/// The element types of [`SLOTS`] that an image of `size` px fills. +fn types(size: u32) -> impl Iterator { + let slots: &'static [(u32, [u8; 4]); 11] = &SLOTS; + slots.iter().filter(move |(s, _)| *s == size).map(|(_, kind)| kind) +} + +/// An `.icns` file holding `pngs`: each square, one of the sizes in [`SLOTS`] and a different size +/// from the others. The elements are written in increasing size, whatever the order of `pngs`, and +/// in [`SLOTS`] order within a size. +pub fn pack>(pngs: &[P], limits: &Limits) -> Result, Error> { + let sizes = sorted_sizes(pngs, limits, MAX_IMAGES, |info| match types(info.width).next() { + Some(_) => Ok(()), + None => Err(Error::UnsupportedSize { format: "ICNS", size: info.width }), + })?; + let total = sizes.iter().fold(HEADER, |t, &(size, i)| { + let element = HEADER.saturating_add(pngs[i].as_ref().len() as u64); + t.saturating_add(element.saturating_mul(types(size).count() as u64)) + }); + let mut out = reserve(total, limits)?; + // `reserve` checked that the whole file, and so every element, fits in a u32. + out.extend_from_slice(b"icns"); + out.extend_from_slice(&(total as u32).to_be_bytes()); + for &(size, i) in &sizes { + let png = pngs[i].as_ref(); + let len = (HEADER + png.len() as u64) as u32; + for kind in types(size) { + out.extend_from_slice(kind); + out.extend_from_slice(&len.to_be_bytes()); + out.extend_from_slice(png); + } + } + Ok(out) +} + +/// One element of an `.icns` file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Element { + /// The four-letter type, for example `ic10`. + pub kind: [u8; 4], + /// The data after the 8-byte element header. + pub data: Vec, +} + +/// The elements of an `.icns` file, in file order. +/// +/// The checks are the magic `icns`, a stated length equal to the file's length and at most +/// [`Limits::max_total_bytes`], 1 to [`ELEMENTS_PER_IMAGE`] times [`Limits::max_images`] +/// elements, and elements of at least 8 bytes, with at most [`Limits::max_png_bytes`] of data, that +/// end exactly at the end of the file. The data is returned as stored: files written by other tools also hold elements that are not +/// PNGs, such as a table of contents. Pass an element's data to [`png_info`](super::png_info) to check +/// it. +pub fn read(icns: &[u8], limits: &Limits) -> Result, Error> { + let bad = Error::InvalidIcon; + if icns.len() > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the icon file holds {} bytes, more than {}", icns.len(), limits.max_total_bytes))); + } + let [b'i', b'c', b'n', b's', l0, l1, l2, l3, ..] = icns else { + return Err(bad("no icns header".into())); + }; + let stated = u32::from_be_bytes([*l0, *l1, *l2, *l3]) as usize; + if stated != icns.len() { + return Err(bad(format!("the header says {stated} bytes but the file holds {}", icns.len()))); + } + let max_elements = limits.max_images.saturating_mul(ELEMENTS_PER_IMAGE); + let mut out = Vec::new(); + let mut at = 8; + while at < icns.len() { + if out.len() == max_elements { + return Err(Error::TooLarge(format!("the icon file holds more than {max_elements} elements"))); + } + let header = icns.get(at..at + 8).ok_or_else(|| bad(format!("truncated element at byte {at}")))?; + let kind = [header[0], header[1], header[2], header[3]]; + let len = u32::from_be_bytes([header[4], header[5], header[6], header[7]]) as usize; + let data = at + .checked_add(len) + .filter(|_| len >= 8) + .and_then(|end| icns.get(at + 8..end)) + .ok_or_else(|| bad(format!("the element at byte {at} has a bad length {len}")))?; + if data.len() > limits.max_png_bytes { + return Err(Error::TooLarge(format!("the element at byte {at} holds {} bytes, more than {}", data.len(), limits.max_png_bytes))); + } + out.push(Element { kind, data: data.to_vec() }); + at += len; + } + if out.is_empty() { + return Err(bad("the icon file holds no elements".into())); + } + Ok(out) +} + +/// [`read`] on the file at `path`, which is read only up to [`Limits::max_total_bytes`]. An app's +/// test of its committed icon passes the icon's path. +pub fn read_file(path: &Path, limits: &Limits) -> Result, Error> { + read(&read_bounded(path, limits.max_total_bytes)?, limits) +} + +#[cfg(test)] +mod tests { + use super::super::png_size; + use super::super::tests::{png_of, rgba}; + use super::*; + + fn kinds(icns: &[u8]) -> Vec { + read(icns, &Limits::default()).unwrap().iter().map(|e| String::from_utf8_lossy(&e.kind).into_owned()).collect() + } + + #[test] + fn fills_every_slot_of_each_size() { + let (a, b) = (rgba(32), rgba(1024)); + let icns = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + assert_eq!(&icns[..4], b"icns"); + assert_eq!(u32::from_be_bytes(icns[4..8].try_into().unwrap()) as usize, icns.len()); + let e = read(&icns, &Limits::default()).unwrap(); + assert_eq!(kinds(&icns), ["icp5", "ic11", "ic10"]); + assert_eq!(e[0].data, a); + assert_eq!(e[1].data, a); + assert_eq!(e[2].data, b); + } + + #[test] + fn packs_icns_elements() { + let (a, b) = (rgba(16), rgba(32)); + let icns = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + // The header and the first element's header, byte for byte from the documented layout. + let total = (8 + (8 + a.len()) + 2 * (8 + b.len())) as u32; + let mut want = b"icns".to_vec(); + want.extend_from_slice(&total.to_be_bytes()); + want.extend_from_slice(b"icp4"); + want.extend_from_slice(&((a.len() + 8) as u32).to_be_bytes()); + assert_eq!(&icns[..16], &want[..]); + assert_eq!(icns.len(), total as usize); + let at = 16 + a.len(); + assert_eq!(&icns[at..at + 4], b"icp5"); + assert_eq!(u32::from_be_bytes(icns[at + 4..at + 8].try_into().unwrap()) as usize, b.len() + 8); + assert_eq!(kinds(&icns), ["icp4", "icp5", "ic11"]); + } + + #[test] + fn writes_every_size_in_slot_order() { + let sizes = [1024, 512, 256, 128, 64, 32, 16]; + let icns = pack(&sizes.map(rgba), &Limits::default()).unwrap(); + let want: Vec = SLOTS.iter().map(|(_, k)| String::from_utf8_lossy(k).into_owned()).collect(); + assert_eq!(kinds(&icns), want); + for e in read(&icns, &Limits::default()).unwrap() { + let size = SLOTS.iter().find(|(_, k)| *k == e.kind).map(|(s, _)| *s).unwrap(); + assert_eq!(png_size(&e.data), Ok((size, size))); + } + } + + #[test] + fn rejects_bad_input() { + let limits = Limits::default(); + assert_eq!(pack::>(&[], &limits), Err(Error::Empty)); + assert_eq!(pack(&[rgba(48)], &limits), Err(Error::UnsupportedSize { format: "ICNS", size: 48 })); + assert!(matches!(pack(&[b"GIF89a".to_vec()], &limits), Err(Error::InvalidPng(_)))); + assert_eq!(pack(&[png_of(32, 16, 8, 6)], &limits), Err(Error::NotSquare { width: 32, height: 16 })); + assert_eq!(pack(&[rgba(32), rgba(32)], &limits), Err(Error::DuplicateSize(32))); + // Each image fills two slots here, so the file holds twice its PNG bytes. + let one = rgba(32).len() as u64; + let tight = Limits { max_total_bytes: (8 + 2 * (8 + one) - 1) as usize, ..limits }; + assert!(matches!(pack(&[rgba(32)], &tight), Err(Error::TooLarge(_)))); + assert!(pack(&[rgba(32)], &Limits { max_total_bytes: tight.max_total_bytes + 1, ..limits }).is_ok()); + } + + #[test] + fn read_rejects_bad_files() { + let limits = Limits::default(); + let icns = pack(&[rgba(16)], &limits).unwrap(); + assert!(matches!(read(b"GIF89a", &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(b"icns\0\0\0\x08", &limits), Err(Error::InvalidIcon(m)) if m.contains("no elements"))); + assert!(matches!(read(&icns[..icns.len() - 1], &limits), Err(Error::InvalidIcon(_)))); + let mut short = icns.clone(); + short[12..16].copy_from_slice(&4u32.to_be_bytes()); + assert!(matches!(read(&short, &limits), Err(Error::InvalidIcon(_)))); + let mut long = icns.clone(); + long[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(read(&long, &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&icns, &Limits { max_total_bytes: 8, ..limits }), Err(Error::TooLarge(_)))); + let small = Limits { max_png_bytes: rgba(16).len() - 1, ..limits }; + assert!(matches!(read(&icns, &small), Err(Error::TooLarge(m)) if m.contains("byte 8"))); + } + + #[test] + fn read_stops_at_the_element_limit() { + let empty_elements = |n: u32| { + let mut f = b"icns".to_vec(); + f.extend_from_slice(&(8 + 8 * n).to_be_bytes()); + for _ in 0..n { + f.extend_from_slice(b"TOC "); + f.extend_from_slice(&8u32.to_be_bytes()); + } + f + }; + let one = Limits { max_images: 1, ..Limits::default() }; + assert_eq!(read(&empty_elements(4), &one).map(|e| e.len()), Ok(4)); + assert!(matches!(read(&empty_elements(5), &one), Err(Error::TooLarge(m)) if m.contains("4 elements"))); + } + + #[test] + fn committed_icon_is_valid() { + // An app passes its own committed icon, for example `/assets/app-icon/.icns`. + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("app.icns"); + let limits = Limits::default(); + std::fs::write(&path, pack(&[rgba(16), rgba(1024)], &limits).unwrap()).expect("write the icon"); + let elements = read_file(&path, &limits).unwrap(); + assert!(elements.iter().any(|e| &e.kind == b"ic10"), "expected a 1024 px image in {}", path.display()); + } +} diff --git a/crates/xtask/src/icon/ico.rs b/crates/xtask/src/icon/ico.rs new file mode 100644 index 0000000000..d45264b001 --- /dev/null +++ b/crates/xtask/src/icon/ico.rs @@ -0,0 +1,284 @@ +//! Windows `.ico` files of PNG images. +//! +//! The file starts with a 6-byte header (reserved 0, type 1 for an icon, the image count) and one +//! 16-byte directory entry per image (width, height, palette size 0, reserved 0, 1 plane, 32 bits per +//! pixel, the PNG's byte length and its offset from the start of the file), all little-endian. The +//! PNGs follow in the order of the entries. A side of 256 px is written as 0 in the one-byte width +//! and height. Each PNG must be 8-bit RGBA, the 32 bits per pixel that Windows reads from a PNG entry +//! ([ICO format, part 4](https://devblogs.microsoft.com/oldnewthing/20101022-00/?p=12473/)). + +use std::path::Path; + +use super::{Error, Limits, png_info, read_bounded, reserve, sorted_sizes}; + +/// The most images an ICO file holds: its image count is 16 bits. +pub const MAX_IMAGES: usize = u16::MAX as usize; + +/// The largest image side, in pixels. +pub const MAX_SIZE: u32 = 256; + +/// The header and one directory entry, in bytes. +const HEADER: u64 = 6; +const ENTRY: u64 = 16; + +/// An ICO file holding `pngs`: each square, 1 to 256 px, 8-bit RGBA and a different size from the +/// others. The entries are written in increasing size, whatever the order of `pngs`. +pub fn pack>(pngs: &[P], limits: &Limits) -> Result, Error> { + let sizes = sorted_sizes(pngs, limits, MAX_IMAGES, |info| { + if info.width > MAX_SIZE { + return Err(Error::UnsupportedSize { format: "ICO", size: info.width }); + } + if !info.is_rgba8() { + return Err(Error::InvalidPng(format!("ICO images must be 8-bit RGBA, got color type {} at {} bits", info.color_type, info.bit_depth))); + } + Ok(()) + })?; + let dir_end = HEADER + ENTRY * sizes.len() as u64; + let total = pngs.iter().fold(dir_end, |t, png| t.saturating_add(png.as_ref().len() as u64)); + let mut out = reserve(total, limits)?; + // `reserve` checked that the whole file, and so every length and offset, fits in a u32, and + // `sorted_sizes` that the count fits in a u16. + out.extend_from_slice(&0u16.to_le_bytes()); // reserved + out.extend_from_slice(&1u16.to_le_bytes()); // type: icon + out.extend_from_slice(&(sizes.len() as u16).to_le_bytes()); + let mut offset = dir_end; + for &(size, i) in &sizes { + let len = pngs[i].as_ref().len() as u64; + let dim = if size == MAX_SIZE { 0 } else { size as u8 }; + out.extend_from_slice(&[dim, dim, 0, 0]); // width, height, palette size, reserved + out.extend_from_slice(&1u16.to_le_bytes()); // color planes + out.extend_from_slice(&32u16.to_le_bytes()); // bits per pixel + out.extend_from_slice(&(len as u32).to_le_bytes()); + out.extend_from_slice(&(offset as u32).to_le_bytes()); + offset += len; + } + for &(_, i) in &sizes { + out.extend_from_slice(pngs[i].as_ref()); + } + Ok(out) +} + +/// One image of an ICO file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + /// The side in pixels, with a stored 0 read as 256. + pub size: u32, + /// The PNG. + pub png: Vec, +} + +/// The images of an ICO file of PNG entries, in directory order. +/// +/// The checks are the header (reserved 0, type 1, 1 to [`Limits::max_images`] images), the file +/// size against [`Limits::max_total_bytes`], and for each entry: a PNG of at most +/// [`Limits::max_png_bytes`], square dimensions, palette size 0, reserved 0, 1 plane and 32 bits per +/// pixel, as [`pack`] writes them, a size no other entry has, and an 8-bit RGBA PNG that +/// [`png_info`](super::png_info) accepts, of the size the entry states, lying wholly after the +/// directory and inside the file. The PNGs together hold at most [`Limits::max_total_bytes`]. +pub fn read(ico: &[u8], limits: &Limits) -> Result, Error> { + let bad = Error::InvalidIcon; + if ico.len() > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the icon file holds {} bytes, more than {}", ico.len(), limits.max_total_bytes))); + } + let [0, 0, 1, 0, c0, c1, ..] = ico else { + return Err(bad("no ICO header (reserved 0, type 1)".into())); + }; + let count = usize::from(u16::from_le_bytes([*c0, *c1])); + if count == 0 { + return Err(bad("no images".into())); + } + if count > limits.max_images { + return Err(Error::TooManyImages { count, max: limits.max_images }); + } + let dir_end = 6 + 16 * count; + let dir = ico.get(6..dir_end).ok_or_else(|| bad(format!("the directory of {count} entries is truncated")))?; + let mut out = Vec::with_capacity(count); + let mut copied = 0usize; + for (n, e) in dir.as_chunks::<16>().0.iter().enumerate() { + let (w, h) = (e[0], e[1]); + if w != h { + return Err(bad(format!("entry {} is {w}x{h}, not square", n + 1))); + } + if e[2..8] != [0, 0, 1, 0, 32, 0] { + return Err(bad(format!("entry {} is not palette size 0, reserved 0, 1 plane and 32 bits per pixel", n + 1))); + } + let size = if w == 0 { MAX_SIZE } else { u32::from(w) }; + let len = u32::from_le_bytes([e[8], e[9], e[10], e[11]]) as usize; + let offset = u32::from_le_bytes([e[12], e[13], e[14], e[15]]) as usize; + if len > limits.max_png_bytes { + return Err(Error::TooLarge(format!("entry {} holds {len} bytes, more than {}", n + 1, limits.max_png_bytes))); + } + let png = offset + .checked_add(len) + .filter(|_| offset >= dir_end) + .and_then(|end| ico.get(offset..end)) + .ok_or_else(|| bad(format!("entry {} points outside the file", n + 1)))?; + let info = png_info(png)?; + if (info.width, info.height) != (size, size) { + return Err(bad(format!("entry {} says {size} px but its PNG is {}x{}", n + 1, info.width, info.height))); + } + if !info.is_rgba8() { + return Err(bad(format!("the PNG of entry {} is not 8-bit RGBA", n + 1))); + } + if out.iter().any(|e: &Entry| e.size == size) { + return Err(Error::DuplicateSize(size)); + } + // Entries can point at overlapping bytes, so the copies are counted against the limit. + copied = copied.saturating_add(len); + if copied > limits.max_total_bytes { + return Err(Error::TooLarge(format!("the entries hold more than {} bytes together", limits.max_total_bytes))); + } + out.push(Entry { size, png: png.to_vec() }); + } + Ok(out) +} + +/// [`read`] on the file at `path`, which is read only up to [`Limits::max_total_bytes`]. An app's +/// test of its committed icon passes the icon's path. +pub fn read_file(path: &Path, limits: &Limits) -> Result, Error> { + read(&read_bounded(path, limits.max_total_bytes)?, limits) +} + +#[cfg(test)] +mod tests { + use super::super::tests::{png_of, push_chunk, rgba}; + use super::*; + + fn u32_le(b: &[u8]) -> u32 { + u32::from_le_bytes(b.try_into().unwrap()) + } + + #[test] + fn packs_directory_and_payloads() { + let (a, b) = (rgba(16), rgba(256)); + let ico = pack(&[a.clone(), b.clone()], &Limits::default()).unwrap(); + // Header and entries, byte for byte from the documented layout. + let (la, lb) = ((a.len() as u32).to_le_bytes(), (b.len() as u32).to_le_bytes()); + let off_b = (38 + a.len() as u32).to_le_bytes(); + let mut want = vec![0, 0, 1, 0, 2, 0]; + want.extend_from_slice(&[16, 16, 0, 0, 1, 0, 32, 0]); + want.extend_from_slice(&la); + want.extend_from_slice(&[38, 0, 0, 0]); + want.extend_from_slice(&[0, 0, 0, 0, 1, 0, 32, 0]); // 256 px is stored as 0 + want.extend_from_slice(&lb); + want.extend_from_slice(&off_b); + assert_eq!(&ico[..38], &want[..]); + assert_eq!(u32_le(&ico[34..38]), 38 + a.len() as u32); + assert_eq!(&ico[38..38 + a.len()], &a[..]); + assert_eq!(&ico[38 + a.len()..], &b[..]); + } + + #[test] + fn writes_entries_in_increasing_size() { + let (a, b, c) = (rgba(48), rgba(16), rgba(32)); + let ico = pack(&[&a[..], &b[..], &c[..]], &Limits::default()).unwrap(); + let sizes: Vec = read(&ico, &Limits::default()).unwrap().iter().map(|e| e.size).collect(); + assert_eq!(sizes, [16, 32, 48]); + assert_eq!(ico, pack(&[b, c, a], &Limits::default()).unwrap()); + } + + #[test] + fn rejects_bad_input() { + let limits = Limits::default(); + assert_eq!(pack::>(&[], &limits), Err(Error::Empty)); + assert_eq!(pack(&[rgba(512)], &limits), Err(Error::UnsupportedSize { format: "ICO", size: 512 })); + assert!(matches!(pack(&[b"GIF89a".to_vec()], &limits), Err(Error::InvalidPng(_)))); + assert_eq!(pack(&[png_of(16, 32, 8, 6)], &limits), Err(Error::NotSquare { width: 16, height: 32 })); + assert_eq!(pack(&[rgba(16), rgba(32), rgba(16)], &limits), Err(Error::DuplicateSize(16))); + assert_eq!(pack(&[rgba(16), rgba(32)], &Limits { max_images: 1, ..limits }), Err(Error::TooManyImages { count: 2, max: 1 })); + assert!(matches!(pack(&[rgba(16)], &Limits { max_png_bytes: 10, ..limits }), Err(Error::TooLarge(_)))); + assert!(matches!(pack(&[rgba(16)], &Limits { max_total_bytes: 40, ..limits }), Err(Error::TooLarge(_)))); + } + + #[test] + fn rejects_a_png_that_is_not_rgba8() { + let limits = Limits::default(); + for (depth, color) in [(8, 2), (16, 6), (8, 3), (8, 0), (8, 4)] { + assert!(matches!(pack(&[png_of(16, 16, depth, color)], &limits), Err(Error::InvalidPng(m)) if m.contains("RGBA"))); + } + } + + #[test] + fn reads_what_it_packs() { + let pngs = [rgba(1), rgba(16), rgba(256)]; + let ico = pack(&pngs, &Limits::default()).unwrap(); + let entries = read(&ico, &Limits::default()).unwrap(); + let got: Vec<(u32, &[u8])> = entries.iter().map(|e| (e.size, &e.png[..])).collect(); + assert_eq!(got, [(1, &pngs[0][..]), (16, &pngs[1][..]), (256, &pngs[2][..])]); + } + + #[test] + fn read_rejects_bad_files() { + let limits = Limits::default(); + let ico = pack(&[rgba(16), rgba(32)], &limits).unwrap(); + assert!(matches!(read(b"GIF89a", &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&ico[..30], &limits), Err(Error::InvalidIcon(_)))); + assert!(matches!(read(&ico[..ico.len() - 1], &limits), Err(Error::InvalidIcon(_)))); + let mut wrong_size = ico.clone(); + wrong_size[6] = 17; + wrong_size[7] = 17; + assert!(matches!(read(&wrong_size, &limits), Err(Error::InvalidIcon(m)) if m.contains("17 px"))); + let mut into_directory = ico.clone(); + into_directory[18..22].copy_from_slice(&6u32.to_le_bytes()); + assert!(matches!(read(&into_directory, &limits), Err(Error::InvalidIcon(_)))); + for (at, value) in [(8, 1), (9, 1), (10, 0), (12, 24)] { + let mut field = ico.clone(); + field[at] = value; + assert!(matches!(read(&field, &limits), Err(Error::InvalidIcon(m)) if m.contains("32 bits")), "accepted byte {at} = {value}"); + } + let mut gray = ico.clone(); + let png = png_of(16, 16, 8, 0); + gray.splice(38..38 + rgba(16).len(), png.iter().copied()); + let delta = png.len() as i64 - rgba(16).len() as i64; + gray[14..18].copy_from_slice(&(png.len() as u32).to_le_bytes()); + let off = (u32_le(&gray[34..38]) as i64 + delta) as u32; + gray[34..38].copy_from_slice(&off.to_le_bytes()); + assert!(matches!(read(&gray, &limits), Err(Error::InvalidIcon(m)) if m.contains("RGBA"))); + let mut huge = ico.clone(); + huge[14..18].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(matches!(read(&huge, &limits), Err(Error::TooLarge(_)))); + assert!(matches!(read(&huge, &Limits { max_png_bytes: usize::MAX, ..limits }), Err(Error::InvalidIcon(_)))); + assert_eq!(read(&ico, &Limits { max_images: 1, ..limits }), Err(Error::TooManyImages { count: 2, max: 1 })); + let small = Limits { max_png_bytes: rgba(32).len() - 1, ..limits }; + assert!(matches!(read(&ico, &small), Err(Error::TooLarge(m)) if m.contains("entry 2"))); + // Entry 2 made a second 16 px entry that points at entry 1's PNG. + let mut shared = ico.clone(); + shared[22..24].copy_from_slice(&[16, 16]); + shared.copy_within(14..22, 30); + assert_eq!(read(&shared, &limits), Err(Error::DuplicateSize(16))); + } + + #[test] + fn read_counts_overlapping_entries_against_the_limit() { + // A 32 px PNG that carries a whole 16 px PNG in an ancillary chunk, and a 16 px entry that + // points inside it. + let (inner, outer) = (rgba(16), rgba(32)); + let mut png = outer[..33].to_vec(); + push_chunk(&mut png, b"zzZz", &inner); + png.extend_from_slice(&outer[33..]); + let mut ico = vec![0, 0, 1, 0, 2, 0]; + for (size, len, offset) in [(16u8, inner.len(), 38 + 33 + 8), (32, png.len(), 38)] { + ico.extend_from_slice(&[size, size, 0, 0, 1, 0, 32, 0]); + ico.extend_from_slice(&(len as u32).to_le_bytes()); + ico.extend_from_slice(&(offset as u32).to_le_bytes()); + } + ico.extend_from_slice(&png); + let fits = Limits { max_total_bytes: ico.len(), ..Limits::default() }; + assert!(matches!(read(&ico, &fits), Err(Error::TooLarge(m)) if m.contains("together"))); + let sizes: Vec = read(&ico, &Limits::default()).unwrap().iter().map(|e| e.size).collect(); + assert_eq!(sizes, [16, 32]); + } + + #[test] + fn committed_icon_is_valid() { + // An app passes its own committed icon, for example `/assets/app-icon/.ico`. + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("app.ico"); + let limits = Limits::default(); + let pngs = [16, 24, 32, 48, 64, 128, 256].map(rgba); + std::fs::write(&path, pack(&pngs, &limits).unwrap()).expect("write the icon"); + let entries = read_file(&path, &limits).unwrap(); + assert!(entries.len() >= 4, "expected several sizes in {}", path.display()); + assert!(matches!(read_file(&path, &Limits { max_total_bytes: 64, ..limits }), Err(Error::TooLarge(_)))); + } +} diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..19a9532a4e 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,9 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - [`icon`]: PNG images packed into a Windows `.ico` ([`icon::ico::pack`]) or a macOS `.icns` +//! ([`icon::icns::pack`]), with [`icon::png_size`] and readers for an app's test of its committed +//! icons. //! //! ```no_run //! use std::path::Path; @@ -35,6 +38,7 @@ //! } //! ``` +pub mod icon; #[cfg(feature = "lock")] pub mod lock; #[cfg(feature = "report")] From f97614d97e8e3eb5479de930624fd08045898c62 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 00:00:42 +0100 Subject: [PATCH 013/490] craft-audio: README says Opus family 0 is mono or stereo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Family 0 has a speaker assignment (RFC 7845 §5.1.1.1); opus_layout maps it to MONO or STEREO. Only families other than 0 and 1 are unassigned. Co-Authored-By: Claude Fable 5.2 --- crates/audio/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index d8ff8a860e..31a3384160 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -209,9 +209,9 @@ target, call `reset()`, decode from there, and drop the output before the target The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to -WAV order. `opus::wav_order` applies only to mapping family 1; other families have no speaker -assignment, and `TrackDecoder` leaves their channels in stream order. `ac3::Decoder` and -`mpa::Decoder` output WAV order. +WAV order. `opus::wav_order` applies only to mapping family 1. Family 0 is mono or stereo, which is +already in WAV order. Other families have no speaker assignment, and `TrackDecoder` leaves their +channels in stream order. `ac3::Decoder` and `mpa::Decoder` output WAV order. ### Encode a file From 7e243276880416fdd34cae02b5dfbb5efcf86d98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:59:56 -0800 Subject: [PATCH 014/490] craft-xtask: add the display-name scanner for words the app lists `craft_xtask::names` reads the words an app lists in its Rust string literals (escapes decoded, test-only code skipped), the package description of a `Cargo.toml` and text files, and returns each finding with its path and line. The app passes the word list, the inputs, the literals and exceptions that may keep a word, and its allow marker. No app switches yet; the crate README lists the planned switches and the results that change for each app. --- crates/xtask/README.md | 93 +- crates/xtask/src/lib.rs | 3 + crates/xtask/src/names.rs | 1790 +++++++++++++++++++++++++++++++++++++ 3 files changed, 1885 insertions(+), 1 deletion(-) create mode 100644 crates/xtask/src/names.rs diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..2ae5c66e5a 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -7,6 +7,7 @@ The crate is native only and is a dependency of an app's `xtask` package only. | Module | Feature | Contents | |---|---|---| | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | +| `names` | always | `Policy`, `Input`, `scan`, `scan_source`, `literals`, `test_path`: the display-name scanner, which looks for the words an app lists in its string literals, `Cargo.toml` descriptions and text files | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | @@ -59,6 +60,86 @@ or file could not be opened or locked) or `Report` (the run passed but the repor written). A report that cannot be written after a failed run is printed to stderr, and the run keeps its `Step` error. +## Names + +The app owns its word list, the paths it scans, the literals and exceptions that may keep a word, +the marker, the command or test that runs the scan, and the message it prints. The library reads the +files and returns the findings: + +```rust,no_run +use std::path::Path; +use craft_xtask::names::{self, Input, Policy}; + +const BANNED: &[&str] = &["Amber Tool", "AzureKit"]; +const ALLOWED: &[&str] = &["AzureKit Design"]; +const POLICY: Policy<'static> = Policy { allowed: ALLOWED, ..Policy::new(BANNED) }; + +#[test] +fn production_display_names_stay_neutral() { + let base = Path::new(env!("CARGO_MANIFEST_DIR")); + let inputs = [Input::rust(Path::new("src")), Input::rust(Path::new("../engine/src/cmd"))]; + let found = names::scan(base, &inputs, &POLICY).unwrap(); + let list: Vec = found.iter().map(ToString::to_string).collect(); + assert!(list.is_empty(), "Banned display names:\n{}", list.join("\n")); +} +``` + +- `Input::rust` takes a Rust file or a folder, which is read recursively for `.rs` files that + `Policy::skip` keeps, given their path below the folder (`test_path` by default: `tests.rs`, + `*_tests.rs` and files under a `tests` folder). Links to folders are not followed. A file input + is read whatever its name. +- `Input::manifest` reads the values at the key paths `package.description` and + `workspace.package.description` of a `Cargo.toml`: the table header (`[package]`, + `[workspace.package]`) joined with the key, which may be bare, quoted or dotted. Headers and keys + inside strings and arrays do not count, and a key inside an inline table is not read. A + `description` under any other table, or before the first header, is not read. A TOML string, + single-line or multi-line, is decoded, and a comment after it is not read; any other value is + read as the rest of its line. `Input::text` reads every line of a text file, and + `Input::text_mark_above` also lets a `#` line with the marker exempt the line below it. Inputs + must not include binary files. +- In Rust, the scanner reads `"…"` and `r"…"` literals with any number of `#`, decodes every escape + (`\n`, `\x7A`, `\u{…}`, a backslash before a line break) and reads CRLF as LF. `b"…"`, `br"…"`, + `c"…"` and `cr"…"` are read when `Policy::literals` asks for them. Comments, character, byte and + lifetime tokens, and the rest of a module after `#![cfg(test)]` are skipped. So is the code under + `#[cfg(test)]`, comments in the attribute included: a `const`, `static` or `let` up to its `;`, + another item up to the `}` that closes it or the `;` that ends it, and a field, argument, arm or + statement up to its `,` or `;`. A block expression (a block, a macro's braces, a labeled block, or + `if`, `match`, `loop`, `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as + an arm's expression after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` + branches. When a method call, field or `?` follows that `}`, it runs up to its `,` or `;` + instead. Other `cfg` expressions and macros are not evaluated. A source the lexer cannot read + (an unterminated literal or comment, an unknown escape, unbalanced delimiters) is an error. +- A word matches as a whole word: the characters next to it are not letters, digits or `_`, in any + script. `MatchCase::Exact` compares characters exactly, and `MatchCase::AsciiInsensitive` ignores + the case of ASCII letters. `allowed` and `exceptions` exempt a whole decoded literal or + description or trimmed text line, never part of one. +- In Rust, the marker counts only inside a comment on a line the literal spans. In a manifest it + counts anywhere on a line the description spans, and in a text file anywhere on the line. +- `scan` reads each file once, in path order, and returns the findings in path order, then source + order, then the order of `banned`. A `Finding` has the path, the first line of the literal or + description, the word, the decoded text or text line and the kind; its `Display` text is + `path:line: "word" in "text"`. `scan_source` scans one source already in memory, and + `literals` returns a source's literals. +- `names::Error` is `Policy` (no banned words, an empty word or an empty marker), `Io` (with the + path), `InvalidUtf8`, `FileTooLarge`, `TotalTooLarge`, `TooDeep`, `Conflict` (a file given as two + kinds of input) or `Syntax` (with the path and line). `DEFAULT_LIMITS` is 8 MiB per file, 512 MiB + per scan and folders 64 deep; a file over the limit is rejected before it is read. + +The source copies differ in a few rules. An app that switches lists the results that change: + +- The eight `display_names.rs` tests compare exactly (`MatchCase::Exact`), read byte and C strings + like other strings, skip only `#[cfg(test)] mod` (GridCraft skips any `#[cfg(test)]` item up to + its `}` or `;`), pass `\x` and `\u{…}` through undecoded, can take the quote in `'\"'` as the + start of a string (LightCraft, FigCraft, PhotoCraft), follow folder links, skip a file root named + like a test file, and stop with a panic on a file they cannot read (FigCraft returns the error). + Each finds more or less here accordingly. +- VectorCraft's `brands` check compares ASCII letters without case (`MatchCase::AsciiInsensitive`) + and reads byte and C strings (`Literals`). It also takes a non-ASCII letter or `_` next to a word + as a word boundary, takes its marker anywhere on a line, literals included, reads an escape as a + space, reads manifest lines that start with `description` as they are (comments included, one + line of a multi-line value), and skips a file it cannot read. +- PhotoCraft's check of its locale catalogs stays in the app. + ## Lock `RunOptions::with_lock(LockConfig::new(dir, slots, owner_label))` takes one of `slots` lock files in @@ -98,7 +179,15 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | -| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `names`: the literal lexer, whole-word matching, allowed literals, the tree walk and the tests `production_display_names_stay_neutral`, `guard_distinguishes_labels_from_identifiers_and_comments`, `guard_scans_production_after_test_only_items`, `guard_skips_escaped_character_literals`, `guard_decodes_whitespace_escapes` | CADCraft `crates/ui-egui/tests/display_names.rs` at [8e69890](https://github.com/storytold/cadcraft/blob/8e6989022398ff5f79adaab77d19fdd7137591f3/crates/ui-egui/tests/display_names.rs) and DeckCraft at [b0c77eb](https://github.com/storytold/deckcraft/blob/b0c77ebd6a6fe6c9037cfbe1c8a7f397304b2205/crates/ui-egui/tests/display_names.rs) | +| `names`: the test `guard_scans_after_escaped_character_literals` | AniCraft `crates/engine/tests/display_names.rs` at [3435e98](https://github.com/storytold/anicraft/blob/3435e9868150312e54694c0a70082609b2fe8573/crates/engine/tests/display_names.rs) | +| `names`: read errors returned, and the test `source_read_failures_are_reported` | FigCraft `crates/mcp/tests/display_names.rs` at [bad07e4](https://github.com/storytold/figcraft/blob/bad07e4433240cad046589129c084bd2fc36f097/crates/mcp/tests/display_names.rs) | +| `names`: the tests `guard_scans_production_after_test_only_items_and_parses_raw_labels`, `guard_skips_escaped_character_literals_without_hiding_labels`, and `exceptions` for a group-label prefix | WordCraft `crates/ui-egui/tests/display_names.rs` at [323cf78](https://github.com/storytold/wordcraft/blob/323cf78232ff3c07f9dbb7989ed729d5851c9773/crates/ui-egui/tests/display_names.rs) | +| `names`: `exceptions` for a message prefix | LightCraft `crates/ui-egui/tests/display_names.rs` at [6b2b7e6](https://github.com/storytold/lightcraft/blob/6b2b7e6d1117e683a1701568e56f979d061e4699/crates/ui-egui/tests/display_names.rs) | +| `names`: a single file as a root | GridCraft `crates/ui-egui/tests/display_names.rs` at [f204433](https://github.com/storytold/gridcraft/blob/f2044337c7e195bdf6bec1b3914937a3dd386749/crates/ui-egui/tests/display_names.rs) | +| `names`: allowed literals | PhotoCraft `crates/ui-egui/tests/display_names.rs` at [d6557b9](https://github.com/storytold/photocraft/blob/d6557b9a8b40f0542a99e7382ec2b5250548e27b/crates/ui-egui/tests/display_names.rs) | +| `names`: `MatchCase::AsciiInsensitive`, manifest descriptions, text files, the marker and the line above it, the literal's first line, and the tests `rust_literals_skip_comments_identifiers_tests_and_marked_lines`, `whole_words_only`, `docs_packaging_and_manifests`, `scope`, `injected_strings_fail_the_gate`, `the_tree_is_clean` | VectorCraft `xtask/src/brands.rs` at [107078a](https://github.com/storytold/vectorcraft/blob/107078ad10870f8a8fdeade9bd5627a3eea34a67/xtask/src/brands.rs) | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `names`, the full escape decoder, byte and C strings as an option, every `#[cfg(test)]` item form and `#![cfg(test)]`, the syntax errors, the marker only in comments, word boundaries in every script, the limits, the sorted findings and the skipped folder links | written here | ## Migration @@ -107,6 +196,8 @@ No app uses this crate yet. | App | Status | |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | +| AniCraft, CADCraft, DeckCraft, FigCraft, GridCraft, LightCraft, PhotoCraft, WordCraft | Planned: the lexer and matcher of `display_names.rs` move to `names`, with `MatchCase::Exact`. `BANNED`, `ALLOWED`, `ROOTS`, the prefix exceptions (LightCraft, WordCraft), PhotoCraft's catalog test and the tests named after them stay in the app. | +| VectorCraft | Planned: `cargo xtask brands` calls `names::scan` with `MatchCase::AsciiInsensitive`, byte and C strings, `brand-ok` and its desktop entry as `Input::text_mark_above`. The word list, the file selection from `git ls-files` and the message stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..7abdc46b08 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -9,6 +9,8 @@ //! - [`runner`]: the gate's step runner. [`runner::run_steps`] runs the steps in order, stops at the //! first failure and prints the `ok`, `FAIL` and `skip` summary. [`runner::root`], //! [`runner::cargo`], [`runner::run`] and [`runner::nextest_or_test`] build and run the commands. +//! - [`names`]: the display-name scanner. [`names::scan`] looks for the words an app lists in its +//! Rust string literals, `Cargo.toml` descriptions and text files, and returns what it finds. //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. @@ -37,6 +39,7 @@ #[cfg(feature = "lock")] pub mod lock; +pub mod names; #[cfg(feature = "report")] pub mod report; pub mod runner; diff --git a/crates/xtask/src/names.rs b/crates/xtask/src/names.rs new file mode 100644 index 0000000000..57d4f89de8 --- /dev/null +++ b/crates/xtask/src/names.rs @@ -0,0 +1,1790 @@ +//! The display-name scanner: words an app must not show users, looked for in the text users read. +//! +//! The app supplies the words, the files and folders to read, the literals that may keep a word, +//! and the marker that exempts a line. The library reads: +//! +//! - [`Kind::Rust`]: the string literals of Rust sources, with escapes decoded, outside comments and +//! test-only code. A folder is read recursively for `.rs` files. +//! - [`Kind::Manifest`]: the package descriptions of a `Cargo.toml`. +//! - [`Kind::Text`] and [`Kind::TextMarkAbove`]: every line of a text file. +//! +//! It returns the [`Finding`]s; the app prints them and decides the exit status. The scan is +//! lexical: it does not resolve macros or evaluate `cfg` expressions other than `cfg(test)`, and it +//! cannot tell whether a literal is shown. It never starts a process or calls git. + +use std::collections::HashSet; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +/// The limits [`Policy::new`] sets: 8 MiB per file, 512 MiB in all, folders 64 deep. +pub const DEFAULT_LIMITS: Limits = Limits { max_file_bytes: 8 << 20, max_total_bytes: 512 << 20, max_depth: 64 }; + +/// How a banned word is compared with the text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MatchCase { + /// Character for character. + Exact, + /// ASCII letters compare without case; other characters compare exactly. + AsciiInsensitive, +} + +/// Which Rust literal forms besides `"…"` and `r"…"` are read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Literals { + /// `b"…"` and `br"…"`. + pub byte_strings: bool, + /// `c"…"` and `cr"…"`. + pub c_strings: bool, +} + +/// Bounds on what [`scan`] reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest file read, in bytes. + pub max_file_bytes: u64, + /// The most bytes read by one scan, across all files. + pub max_total_bytes: u64, + /// The deepest folder read below a [`Kind::Rust`] folder input. + pub max_depth: usize, +} + +/// The app's rules for one scan. +#[derive(Clone, Copy)] +pub struct Policy<'a> { + /// The words users must not see. A word matches only as a whole word: the characters next to it + /// are not letters, digits or `_`. + pub banned: &'a [&'a str], + /// How the words are compared. + pub case: MatchCase, + /// Whole literals (or text lines, trimmed) that may keep a banned word. + pub allowed: &'a [&'a str], + /// Functions that return `true` for a whole literal or trimmed text line that may keep a banned + /// word. + pub exceptions: &'a [fn(&str) -> bool], + /// A marker that exempts a line. In Rust it counts only inside a comment on a line the literal + /// spans; in a text file it counts anywhere on the line, and in [`Kind::TextMarkAbove`] files also + /// on a `#` line just above. + pub allow_marker: Option<&'a str>, + /// The optional Rust literal forms. + pub literals: Literals, + /// Returns `true` for a Rust file in a folder input to leave out, given its path below that + /// folder. [`test_path`] is the default. A file input is read whatever this returns. + pub skip: fn(&Path) -> bool, + /// Bounds on what is read. + pub limits: Limits, +} + +impl<'a> Policy<'a> { + /// A policy with these banned words, exact comparison, no allowed literals, exceptions or + /// marker, only `"…"` and `r"…"` literals, [`test_path`] and [`DEFAULT_LIMITS`]. + pub const fn new(banned: &'a [&'a str]) -> Self { + Policy { + banned, + case: MatchCase::Exact, + allowed: &[], + exceptions: &[], + allow_marker: None, + literals: Literals { byte_strings: false, c_strings: false }, + skip: test_path, + limits: DEFAULT_LIMITS, + } + } + + /// The banned words in `text`, in the order of [`Policy::banned`]. Empty when `text` is allowed + /// or an exception returns `true` for it. + pub fn words_in(&self, text: &str) -> Vec<&'a str> { + if self.allowed.contains(&text) || self.exceptions.iter().any(|exempt| exempt(text)) { + return Vec::new(); + } + self.banned.iter().copied().filter(|word| contains_word(text, word, self.case)).collect() + } + + fn validate(&self) -> Result<(), Error> { + if self.banned.is_empty() { + return Err(Error::Policy("the list of banned words is empty")); + } + if self.banned.iter().any(|word| word.trim().is_empty()) { + return Err(Error::Policy("a banned word is empty")); + } + if self.allow_marker.is_some_and(|marker| marker.trim().is_empty()) { + return Err(Error::Policy("the allow marker is empty")); + } + if self.limits.max_file_bytes == 0 || self.limits.max_total_bytes == 0 { + return Err(Error::Policy("a byte limit is zero")); + } + Ok(()) + } +} + +/// The apps' rule for test code: a file named `tests.rs` or ending in `_tests.rs`, or a file under +/// a folder named `tests`. +pub fn test_path(path: &Path) -> bool { + let file = path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default(); + file == "tests.rs" || file.ends_with("_tests.rs") || path.parent().is_some_and(|dir| dir.components().any(|part| part.as_os_str() == "tests")) +} + +/// What a path holds and how it is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Kind { + /// A Rust file, or a folder whose `.rs` files are read. + Rust, + /// A `Cargo.toml`, whose `package.description` and `workspace.package.description` values are + /// read, decoded when they are TOML strings. + Manifest, + /// A text file, every line. + Text, + /// A text file whose comments take whole `#` lines (a desktop entry): a `#` line with the marker + /// also exempts the line below it. + TextMarkAbove, +} + +/// One path to scan, relative to the base folder [`scan`] takes, or absolute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Input<'a> { + /// How the path is read. + pub kind: Kind, + /// The file or, for [`Kind::Rust`], folder. + pub path: &'a Path, +} + +impl<'a> Input<'a> { + /// A Rust file or folder. + pub fn rust(path: &'a Path) -> Self { + Input { kind: Kind::Rust, path } + } + + /// A `Cargo.toml`. + pub fn manifest(path: &'a Path) -> Self { + Input { kind: Kind::Manifest, path } + } + + /// A text file. + pub fn text(path: &'a Path) -> Self { + Input { kind: Kind::Text, path } + } + + /// A text file whose `#` lines can mark the line below them. + pub fn text_mark_above(path: &'a Path) -> Self { + Input { kind: Kind::TextMarkAbove, path } + } +} + +/// A banned word found in a file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + /// The file, as the input named it, joined with the path below a folder input. + pub path: PathBuf, + /// The 1-based line the literal starts on, or the text line. + pub line: usize, + /// The banned word, as [`Policy::banned`] lists it. + pub word: String, + /// The decoded literal or description, or the trimmed text line. + pub text: String, + /// How the file was read. + pub kind: Kind, +} + +impl fmt::Display for Finding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{}: {:?} in {:?}", self.path.display(), self.line, self.word, self.text) + } +} + +/// A Rust source the scanner cannot read as tokens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SyntaxError { + /// The 1-based line the problem starts on. + pub line: usize, + /// What is wrong. + pub message: &'static str, +} + +impl fmt::Display for SyntaxError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "line {}: {}", self.line, self.message) + } +} + +/// Why a scan did not finish. +#[derive(Debug)] +pub enum Error { + /// The policy cannot be used. + Policy(&'static str), + /// A file or folder could not be read. + Io { + /// The path, as reported. + path: PathBuf, + /// The cause. + source: io::Error, + }, + /// A file is not UTF-8. + InvalidUtf8 { + /// The path, as reported. + path: PathBuf, + }, + /// A file is larger than [`Limits::max_file_bytes`]. + FileTooLarge { + /// The path, as reported. + path: PathBuf, + /// The limit, in bytes. + limit: u64, + }, + /// Reading this file took the scan past [`Limits::max_total_bytes`]. + TotalTooLarge { + /// The path, as reported. + path: PathBuf, + /// The limit, in bytes. + limit: u64, + }, + /// A folder is deeper than [`Limits::max_depth`]. + TooDeep { + /// The path, as reported. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A file is given as two kinds of input. + Conflict { + /// The path, as reported. + path: PathBuf, + }, + /// A Rust source could not be read as tokens. + Syntax { + /// The path, as reported. + path: PathBuf, + /// Where and what. + error: SyntaxError, + }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Policy(m) => write!(f, "policy: {m}"), + Error::Io { path, source } => write!(f, "{}: {source}", path.display()), + Error::InvalidUtf8 { path } => write!(f, "{}: not UTF-8", path.display()), + Error::FileTooLarge { path, limit } => write!(f, "{}: larger than {limit} bytes", path.display()), + Error::TotalTooLarge { path, limit } => write!(f, "{}: the scan read more than {limit} bytes", path.display()), + Error::TooDeep { path, limit } => write!(f, "{}: more than {limit} folders deep", path.display()), + Error::Conflict { path } => write!(f, "{}: given as two kinds of input", path.display()), + Error::Syntax { path, error } => write!(f, "{}: {error}", path.display()), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// Every finding in `inputs`, read from `base`. Files are read once each, in path order, and the +/// findings come in path order, then in source order, then in the order of [`Policy::banned`]. +/// +/// A [`Kind::Rust`] folder is read recursively for `.rs` files that [`Policy::skip`] keeps; links to +/// folders are not followed. A file input is read whatever its name. Every error stops the scan: a +/// missing input, a file that cannot be read, is not UTF-8 or is over a limit, and a Rust source the +/// lexer cannot read. Inputs must not include binary files. +pub fn scan(base: &Path, inputs: &[Input<'_>], policy: &Policy<'_>) -> Result, Error> { + policy.validate()?; + let mut files = Vec::new(); + for input in inputs { + if input.kind == Kind::Rust { + collect_rust(base, input.path, policy, &mut files)?; + } else { + files.push((input.path.to_path_buf(), input.kind)); + } + } + files.sort(); + files.dedup(); + if let Some(pair) = files.windows(2).find(|pair| pair[0].0 == pair[1].0) { + return Err(Error::Conflict { path: pair[0].0.clone() }); + } + let mut total = 0; + let mut findings = Vec::new(); + for (path, kind) in &files { + let source = read_limited(&base.join(path), path, &policy.limits, &mut total)?; + findings.extend(scan_source(path, &source, *kind, policy)?); + } + Ok(findings) +} + +/// The findings in one source that is already in memory. `path` is only reported. A +/// [`Kind::Rust`] source is a single file here. +pub fn scan_source(path: &Path, source: &str, kind: Kind, policy: &Policy<'_>) -> Result, Error> { + policy.validate()?; + let finding = + |line: usize, word: &str, text: &str| Finding { path: path.to_path_buf(), line, word: word.to_string(), text: text.to_string(), kind }; + let mut out = Vec::new(); + if kind == Kind::Rust { + let lexed = lex(source, policy.literals, policy.allow_marker).map_err(|error| Error::Syntax { path: path.to_path_buf(), error })?; + for lit in &lexed.literals { + if (lit.first_line..=lit.last_line).any(|line| lexed.marked_lines.contains(&line)) { + continue; + } + out.extend(policy.words_in(&lit.text).into_iter().map(|word| finding(lit.first_line, word, &lit.text))); + } + return Ok(out); + } + let lines: Vec<&str> = source.lines().collect(); + let marked = |line: &str| policy.allow_marker.is_some_and(|marker| line.contains(marker)); + if kind == Kind::Manifest { + for (first, last, text) in descriptions(source) { + if lines.get(first - 1..last.min(lines.len())).is_some_and(|span| span.iter().any(|line| marked(line))) { + continue; + } + out.extend(policy.words_in(&text).into_iter().map(|word| finding(first, word, &text))); + } + return Ok(out); + } + for (i, line) in lines.iter().enumerate() { + let above = i.checked_sub(1).and_then(|j| lines.get(j)).is_some_and(|l| l.trim_start().starts_with('#') && marked(l)); + if marked(line) || (kind == Kind::TextMarkAbove && above) { + continue; + } + let text = line.trim(); + out.extend(policy.words_in(text).into_iter().map(|word| finding(i + 1, word, text))); + } + Ok(out) +} + +/// The package descriptions of a `Cargo.toml`, the values at the key paths `package.description` +/// and `workspace.package.description`: the 1-based first and last line of each, and its text. A +/// TOML string is decoded; any other value is the rest of its line, trimmed. Table headers count +/// outside strings and arrays; keys inside inline tables are not read. +fn descriptions(source: &str) -> Vec<(usize, usize, String)> { + let mut out = Vec::new(); + let (mut offset, mut number, mut resume, mut depth) = (0, 0, 0, 0); + // The current table's key path, or `None` under an array of tables or an unreadable header. + let mut table = Some(Vec::new()); + for line in source.split_inclusive('\n') { + let start = offset; + offset += line.len(); + number += 1; + if start < resume { + continue; + } + let top = depth == 0; + resume = toml_line_end(source, start, line.len(), &mut depth); + if !top { + continue; + } + // A byte order mark may start the file. + let body = if start == 0 { line.strip_prefix('\u{feff}').unwrap_or(line) } else { line }; + let trimmed = body.trim_start_matches([' ', '\t']); + if trimmed.starts_with('[') { + table = toml_header(trimmed); + depth = 0; + continue; + } + let Some((key, value)) = toml_key(body).and_then(|(key, rest)| Some((key, rest.strip_prefix('=')?.trim_start()))) else { + continue; + }; + let path: Vec<&str> = table.iter().flatten().chain(&key).map(String::as_str).collect(); + if table.is_none() || !matches!(path.as_slice(), ["package", "description"] | ["workspace", "package", "description"]) { + continue; + } + let at = start + line.len() - value.len(); + let (text, len) = toml_string(source.get(at..).unwrap_or_default()).unwrap_or_else(|| (value.trim().to_string(), value.trim_end().len())); + resume = resume.max(at + len); + let last = number + source.get(at..at + len).unwrap_or_default().matches('\n').count(); + out.push((number, last, text)); + } + out +} + +/// The key path of a TOML table header (`[a.b]`) at the start of `line`, or `None` for an array of +/// tables (`[[a.b]]`) or a header that cannot be read. +fn toml_header(line: &str) -> Option> { + let (parts, rest) = toml_key(line.strip_prefix('[').filter(|rest| !rest.starts_with('['))?)?; + let rest = rest.strip_prefix(']')?.trim_start_matches([' ', '\t']); + (rest.is_empty() || rest.starts_with(['#', '\r', '\n'])).then_some(parts) +} + +/// The parts of the TOML key (bare, quoted or dotted) at the start of `text`, after any spaces, and +/// the text after the key and the spaces that follow it. +fn toml_key(text: &str) -> Option<(Vec, &str)> { + let mut parts = Vec::new(); + let mut rest = text; + loop { + rest = rest.trim_start_matches([' ', '\t']); + if rest.starts_with("\"\"\"") || rest.starts_with("'''") { + return None; + } + let len = if rest.starts_with(['"', '\'']) { + let (part, len) = toml_string(rest)?; + parts.push(part); + len + } else { + let len = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-').len(); + parts.push(rest.get(..len).filter(|part| !part.is_empty())?.to_string()); + len + }; + rest = rest.get(len..)?.trim_start_matches([' ', '\t']); + match rest.strip_prefix('.') { + Some(after) => rest = after, + None => return Some((parts, rest)), + } + } +} + +/// The end of the TOML line of `len` bytes at `start`, or past the last string that starts on it, +/// so that the later lines of a multi-line string are not read as keys. `depth` counts the arrays +/// and inline tables open after the line, outside strings and comments. +fn toml_line_end(source: &str, start: usize, len: usize, depth: &mut usize) -> usize { + let (mut at, mut end) = (start, start + len); + while at < end { + let Some(c) = source.get(at..).and_then(|rest| rest.chars().next()) else { break }; + match c { + '#' => break, + '[' | '{' => { + *depth += 1; + at += 1; + } + ']' | '}' => { + *depth = depth.saturating_sub(1); + at += 1; + } + '"' | '\'' => match toml_string(source.get(at..).unwrap_or_default()) { + Some((_, string)) => { + at += string; + if at > end { + // The string closes on a later line: read the rest of that line too. + end = source.get(at..).and_then(|rest| rest.find('\n')).map_or(source.len(), |i| at + i + 1); + } + } + None => break, + }, + _ => at += c.len_utf8(), + } + } + end +} + +/// The TOML string at the start of `value`, decoded, and its length in bytes. `None` when `value` +/// does not start with a complete, valid string. +fn toml_string(value: &str) -> Option<(String, usize)> { + let delim = ["\"\"\"", "'''", "\"", "'"].into_iter().find(|d| value.starts_with(d))?; + let (basic, multi) = (delim.starts_with('"'), delim.len() == 3); + let mut at = delim.len(); + if multi { + let after = value.get(at..)?; + at += if after.starts_with("\r\n") { 2 } else { usize::from(after.starts_with('\n')) }; + } + let mut text = String::new(); + loop { + let rest = value.get(at..)?; + let c = rest.chars().next()?; + if rest.starts_with(delim) { + if !multi { + return Some((text, at + 1)); + } + // Up to two quotes just before the closing three belong to the text. + let extra = rest.chars().take_while(|&q| q == c).count().saturating_sub(3).min(2); + text.extend(std::iter::repeat_n(c, extra)); + return Some((text, at + extra + 3)); + } + match c { + '\\' if basic => at = toml_escape(value, at + 1, multi, &mut text)?, + '\n' if !multi => return None, + '\r' if rest.starts_with("\r\n") => at += 1, + _ => { + text.push(c); + at += c.len_utf8(); + } + } + } +} + +/// The escape after a backslash at `at` in a TOML basic string, decoded into `text`, and the index +/// after it. +fn toml_escape(value: &str, at: usize, multi: bool, text: &mut String) -> Option { + let rest = value.get(at..)?; + let c = rest.chars().next()?; + let simple = match c { + 'b' => Some('\u{8}'), + 't' => Some('\t'), + 'n' => Some('\n'), + 'f' => Some('\u{c}'), + 'r' => Some('\r'), + 'e' => Some('\u{1b}'), + '"' | '\\' => Some(c), + _ => None, + }; + if let Some(decoded) = simple { + text.push(decoded); + return Some(at + 1); + } + let digits = match c { + 'x' => 2, + 'u' => 4, + 'U' => 8, + _ => 0, + }; + if digits > 0 { + let hex = rest.get(1..1 + digits).filter(|hex| hex.chars().all(|h| h.is_ascii_hexdigit()))?; + text.push(u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)?); + return Some(at + 1 + digits); + } + // A backslash at the end of a line in a multi-line string: the line break and the whitespace + // after it are left out. + if multi && rest.trim_start_matches([' ', '\t']).starts_with(['\n', '\r']) { + return Some(at + rest.len() - rest.trim_start_matches([' ', '\t', '\n', '\r']).len()); + } + None +} + +/// A Rust string literal. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Literal { + /// The 1-based line of its opening quote. + pub first_line: usize, + /// The 1-based line of its closing quote. + pub last_line: usize, + /// Its text, with escapes decoded (not in raw literals) and CRLF read as LF. + pub text: String, +} + +/// The string literals of a Rust source outside comments and test-only code, in source order. +/// +/// Test-only code is the code under `#[cfg(test)]` and the rest of a module that starts with +/// `#![cfg(test)]`. Under `#[cfg(test)]`, a `const`, `static` or `let` runs up to its `;`, another +/// item up to its closing `}` or its `;`, and a field, argument, arm or statement up to its `,` or +/// `;`. A block expression (a block, a macro's braces, a labeled block, or `if`, `match`, `loop`, +/// `while`, `for`, `unsafe`, `async` or `const`), as the whole statement or as an arm's expression +/// after `=>`, ends at its `}`, or at the last `}` of an `if` with `else` branches. When a method +/// call, field or `?` follows that `}`, it runs up to its `,` or `;` instead. Character, byte and +/// lifetime tokens are read, so a quote in them does not start a string. +pub fn literals(source: &str, kinds: Literals) -> Result, SyntaxError> { + lex(source, kinds, None).map(|lexed| lexed.literals) +} + +fn contains_word(text: &str, word: &str, case: MatchCase) -> bool { + match case { + MatchCase::Exact => text.match_indices(word).any(|(at, _)| whole_word(text, at, word.len())), + MatchCase::AsciiInsensitive => { + let lower = text.to_ascii_lowercase(); + let word = word.to_ascii_lowercase(); + lower.match_indices(&word).any(|(at, _)| whole_word(text, at, word.len())) + } + } +} + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn whole_word(text: &str, at: usize, len: usize) -> bool { + let before = text.get(..at).and_then(|s| s.chars().next_back()); + let after = text.get(at + len..).and_then(|s| s.chars().next()); + !before.is_some_and(is_word) && !after.is_some_and(is_word) +} + +fn io_error(path: &Path) -> impl FnOnce(io::Error) -> Error + '_ { + move |source| Error::Io { path: path.to_path_buf(), source } +} + +fn collect_rust(base: &Path, path: &Path, policy: &Policy<'_>, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { + let meta = fs::metadata(base.join(path)).map_err(io_error(path))?; + if meta.is_dir() { + walk(base, path, path, policy, 0, out) + } else { + out.push((path.to_path_buf(), Kind::Rust)); + Ok(()) + } +} + +fn walk(base: &Path, input: &Path, dir: &Path, policy: &Policy<'_>, depth: usize, out: &mut Vec<(PathBuf, Kind)>) -> Result<(), Error> { + if depth > policy.limits.max_depth { + return Err(Error::TooDeep { path: dir.to_path_buf(), limit: policy.limits.max_depth }); + } + let mut entries = fs::read_dir(base.join(dir)).and_then(|entries| entries.collect::>>()).map_err(io_error(dir))?; + entries.sort_by_key(fs::DirEntry::file_name); + for entry in entries { + let path = dir.join(entry.file_name()); + let file_type = entry.file_type().map_err(io_error(&path))?; + if file_type.is_dir() { + walk(base, input, &path, policy, depth + 1, out)?; + continue; + } + if !path.extension().is_some_and(|ext| ext == "rs") || (policy.skip)(path.strip_prefix(input).unwrap_or(&path)) { + continue; + } + // A link to a folder is not followed; a link to a file is read like the file. + let is_file = if file_type.is_symlink() { fs::metadata(base.join(&path)).map_err(io_error(&path))?.is_file() } else { file_type.is_file() }; + if is_file { + out.push((path, Kind::Rust)); + } + } + Ok(()) +} + +fn read_limited(full: &Path, path: &Path, limits: &Limits, total: &mut u64) -> Result { + let file = File::open(full).map_err(io_error(path))?; + let len = file.metadata().map_err(io_error(path))?.len(); + if len > limits.max_file_bytes { + return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); + } + let mut bytes = Vec::with_capacity(usize::try_from(len).unwrap_or(0)); + file.take(limits.max_file_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?; + let read = u64::try_from(bytes.len()).unwrap_or(u64::MAX); + if read > limits.max_file_bytes { + return Err(Error::FileTooLarge { path: path.to_path_buf(), limit: limits.max_file_bytes }); + } + *total = total.saturating_add(read); + if *total > limits.max_total_bytes { + return Err(Error::TotalTooLarge { path: path.to_path_buf(), limit: limits.max_total_bytes }); + } + let mut text = String::from_utf8(bytes).map_err(|_| Error::InvalidUtf8 { path: path.to_path_buf() })?; + if text.starts_with('\u{feff}') { + text.remove(0); + } + Ok(text) +} + +struct Lexed { + literals: Vec, + marked_lines: HashSet, +} + +/// The literal forms, which differ in the escapes they take and in whether the scan reads them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Form { + Str, + Char, + Byte, + C, +} + +/// The keywords that start an item, whose header can hold commas. +const ITEM_KEYWORDS: &[&str] = + &["const", "enum", "extern", "fn", "impl", "let", "macro_rules", "mod", "static", "struct", "trait", "type", "union", "use"]; + +/// The keywords of items that end at their `;`, whatever braces their value holds. +const SEMICOLON_KEYWORDS: &[&str] = &["const", "let", "static"]; + +/// The keywords that start an expression ending at the `}` of its block (or of its last `else`). +const BLOCK_KEYWORDS: &[&str] = &["async", "const", "for", "if", "loop", "match", "unsafe", "while"]; + +/// Test-only code being skipped. +#[derive(Debug, Clone, Copy)] +enum TestRegion { + /// An item, field, argument, arm or statement under `#[cfg(test)]`, at this delimiter depth. + /// `start` is the index where its code (or an arm's expression, after `=>`) starts; `opened` is + /// set once its first `{` is read, `item` once an item keyword (`fn`, `impl`, `mod`…) is read, + /// and `semi` while the last such keyword is `const`, `let` or `static`, whose items end at their + /// `;`. Without an item keyword, `block` is set when that first `{` starts a block expression (a + /// block, a macro's braces, or `if`, `match`, `loop` and the like), which ends at its `}` unless + /// an `else` follows. A `.` or `?` after that `}` clears `block`, so the expression ends at its + /// `;` or `,`. + Item { level: usize, start: usize, opened: bool, item: bool, semi: bool, block: bool }, + /// The rest of the module that `#![cfg(test)]` starts, at this delimiter depth. + Inner { level: usize }, +} + +struct Lexer<'s> { + chars: Vec, + at: usize, + line: usize, + kinds: Literals, + marker: Option<&'s str>, + /// Open delimiters and the line of each. + delims: Vec<(char, usize)>, + test: Option, + out: Lexed, +} + +fn lex(source: &str, kinds: Literals, marker: Option<&str>) -> Result { + let mut lexer = Lexer { + chars: source.chars().collect(), + at: 0, + line: 1, + kinds, + marker, + delims: Vec::new(), + test: None, + out: Lexed { literals: Vec::new(), marked_lines: HashSet::new() }, + }; + lexer.run()?; + Ok(lexer.out) +} + +impl Lexer<'_> { + fn peek(&self, ahead: usize) -> Option { + self.chars.get(self.at + ahead).copied() + } + + fn next(&mut self) -> Option { + let c = self.peek(0)?; + self.at += 1; + Some(c) + } + + fn error(line: usize, message: &'static str) -> SyntaxError { + SyntaxError { line, message } + } + + fn run(&mut self) -> Result<(), SyntaxError> { + while let Some(c) = self.peek(0) { + match c { + '\n' => { + self.line += 1; + self.at += 1; + } + '/' if self.peek(1) == Some('/') => self.line_comment(), + '/' if self.peek(1) == Some('*') => self.block_comment()?, + '"' => { + self.at += 1; + self.string(Form::Str)?; + } + '\'' => self.quote(Form::Char)?, + '#' => self.hash(), + '{' | '(' | '[' => self.open(c), + '}' | ')' | ']' => self.close(c)?, + ';' => self.item_end(false), + ',' => self.item_end(true), + '=' if self.peek(1) == Some('>') => self.arrow(), + c if c.is_ascii_digit() => self.number(), + c if is_word(c) => self.word()?, + _ => self.at += 1, + } + } + match self.delims.last() { + Some(&(_, line)) => Err(Self::error(line, "unclosed delimiter")), + None => Ok(()), + } + } + + fn comment_text(&mut self, first: usize, start: usize) { + if let Some(marker) = self.marker { + let text: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); + let marked = text.split('\n').enumerate().filter(|(_, line)| line.contains(marker)); + self.out.marked_lines.extend(marked.map(|(i, _)| first + i)); + } + } + + fn line_comment(&mut self) { + let start = self.at; + while self.peek(0).is_some_and(|c| c != '\n') { + self.at += 1; + } + self.comment_text(self.line, start); + } + + fn block_comment(&mut self) -> Result<(), SyntaxError> { + let (first, start) = (self.line, self.at); + self.at += 2; + let mut depth = 1_usize; + while depth > 0 { + match (self.next(), self.peek(0)) { + (None, _) => return Err(Self::error(first, "unterminated block comment")), + (Some('/'), Some('*')) => { + self.at += 1; + depth += 1; + } + (Some('*'), Some('/')) => { + self.at += 1; + depth -= 1; + } + (Some('\n'), _) => self.line += 1, + _ => {} + } + } + self.comment_text(first, start); + Ok(()) + } + + fn reads(&self, form: Form) -> bool { + match form { + Form::Str => true, + Form::Byte => self.kinds.byte_strings, + Form::C => self.kinds.c_strings, + Form::Char => false, + } + } + + fn push(&mut self, first: usize, text: String, form: Form) { + if self.reads(form) && self.test.is_none() { + self.out.literals.push(Literal { first_line: first, last_line: self.line, text }); + } + } + + /// A `"…"` body after its opening quote. + fn string(&mut self, form: Form) -> Result<(), SyntaxError> { + let first = self.line; + let mut text = String::new(); + loop { + match self.next() { + None => return Err(Self::error(first, "unterminated string literal")), + Some('"') => break, + Some('\\') => self.escape(form, &mut text, first)?, + Some('\r') if self.peek(0) == Some('\n') => {} + Some('\n') => { + self.line += 1; + text.push('\n'); + } + Some(c) => text.push(c), + } + } + self.push(first, text, form); + Ok(()) + } + + /// The escape after a backslash, decoded into `text`. + fn escape(&mut self, form: Form, text: &mut String, first: usize) -> Result<(), SyntaxError> { + let decoded = match self.next() { + None => return Err(Self::error(first, "unterminated escape")), + Some('n') => '\n', + Some('r') => '\r', + Some('t') => '\t', + Some('0') => '\0', + Some(c @ ('\\' | '\'' | '"')) => c, + Some('x') => self.hex_escape(form)?, + Some('u') if form != Form::Byte => self.unicode_escape()?, + Some('\n') if form != Form::Char => { + self.continuation(); + return Ok(()); + } + Some('\r') if form != Form::Char && self.peek(0) == Some('\n') => { + self.at += 1; + self.continuation(); + return Ok(()); + } + Some(_) => return Err(Self::error(self.line, "unknown character escape")), + }; + text.push(decoded); + Ok(()) + } + + /// A backslash before a line break: the break and the whitespace after it are left out. + fn continuation(&mut self) { + self.line += 1; + while let Some(c @ (' ' | '\t' | '\n' | '\r')) = self.peek(0) { + self.line += usize::from(c == '\n'); + self.at += 1; + } + } + + fn hex_escape(&mut self, form: Form) -> Result { + let digits = (self.peek(0).and_then(|c| c.to_digit(16)), self.peek(1).and_then(|c| c.to_digit(16))); + let (Some(high), Some(low)) = digits else { + return Err(Self::error(self.line, "a \\x escape needs two hex digits")); + }; + self.at += 2; + let value = high * 16 + low; + match (value, form) { + (0..=0x7f, _) => Ok(char::from_u32(value).unwrap_or(char::REPLACEMENT_CHARACTER)), + (_, Form::Byte | Form::C) => Ok(char::REPLACEMENT_CHARACTER), + _ => Err(Self::error(self.line, "a \\x escape above 0x7F")), + } + } + + fn unicode_escape(&mut self) -> Result { + let bad = Self::error(self.line, "an invalid \\u{...} escape"); + if self.next() != Some('{') || self.peek(0) == Some('_') { + return Err(bad); + } + let (mut value, mut digits) = (0_u32, 0_usize); + loop { + match self.next() { + Some('}') => break, + Some('_') => {} + Some(c) if digits < 6 => { + value = value * 16 + c.to_digit(16).ok_or_else(|| bad.clone())?; + digits += 1; + } + _ => return Err(bad), + } + } + if digits == 0 { + return Err(bad); + } + char::from_u32(value).ok_or(bad) + } + + /// A quote: a character or byte literal, or the start of a lifetime or label. + fn quote(&mut self, form: Form) -> Result<(), SyntaxError> { + match (self.peek(1), self.peek(2)) { + (Some('\\'), _) => { + let first = self.line; + self.at += 2; + self.escape(form, &mut String::new(), first)?; + if self.next() != Some('\'') { + return Err(Self::error(first, "unterminated character literal")); + } + } + (Some(c), Some('\'')) if c != '\'' && c != '\n' => self.at += 3, + _ => self.at += 1, + } + Ok(()) + } + + fn number(&mut self) { + while self.peek(0).is_some_and(is_word) { + self.at += 1; + } + } + + /// An identifier, or the prefix of a byte, C or raw literal. + fn word(&mut self) -> Result<(), SyntaxError> { + let start = self.at; + self.number(); + let word: String = self.chars.get(start..self.at).unwrap_or_default().iter().collect(); + // `const { .. }` is a block expression, not an item. + let const_block = word == "const" && self.chars.get(self.skip_space(self.at)) == Some(&'{'); + if let Some(TestRegion::Item { level, opened: false, item, semi, .. }) = &mut self.test + && *level == self.delims.len() + && ITEM_KEYWORDS.contains(&word.as_str()) + && !const_block + { + *item = true; + *semi = SEMICOLON_KEYWORDS.contains(&word.as_str()); + } + match (word.as_str(), self.peek(0)) { + ("b", Some('\'')) => self.quote(Form::Byte), + ("b", Some('"')) => { + self.at += 1; + self.string(Form::Byte) + } + ("c", Some('"')) => { + self.at += 1; + self.string(Form::C) + } + ("r", Some('"' | '#')) => self.raw(Form::Str), + ("br", Some('"' | '#')) => self.raw(Form::Byte), + ("cr", Some('"' | '#')) => self.raw(Form::C), + _ => Ok(()), + } + } + + /// A raw literal after its `r`, or a raw identifier (`r#name`), which is left to the caller. + fn raw(&mut self, form: Form) -> Result<(), SyntaxError> { + let hashes = self.chars.get(self.at..).unwrap_or_default().iter().take_while(|&&c| c == '#').count(); + if self.peek(hashes) != Some('"') { + return Ok(()); + } + let first = self.line; + self.at += hashes + 1; + let mut text = String::new(); + loop { + match self.next() { + None => return Err(Self::error(first, "unterminated raw string literal")), + Some('"') if (0..hashes).all(|n| self.peek(n) == Some('#')) => break, + Some('\r') if self.peek(0) == Some('\n') => {} + Some(c) => { + self.line += usize::from(c == '\n'); + text.push(c); + } + } + } + self.at += hashes; + self.push(first, text, form); + Ok(()) + } + + /// The index after the whitespace and comments at `at`. + fn skip_space(&self, mut at: usize) -> usize { + loop { + match (self.chars.get(at), self.chars.get(at + 1)) { + (Some(c), _) if c.is_whitespace() => at += 1, + (Some('/'), Some('/')) => { + while self.chars.get(at).is_some_and(|&c| c != '\n') { + at += 1; + } + } + (Some('/'), Some('*')) => { + let mut depth = 0_usize; + loop { + match (self.chars.get(at), self.chars.get(at + 1)) { + (None, _) => return at, + (Some('/'), Some('*')) => { + depth += 1; + at += 2; + } + (Some('*'), Some('/')) => { + depth -= 1; + at += 2; + if depth == 0 { + break; + } + } + _ => at += 1, + } + } + } + _ => return at, + } + } + } + + /// The end of a `#[cfg(test)]` or `#![cfg(test)]` attribute at the current `#`, and whether it + /// is the inner form. + fn cfg_test_end(&self) -> Option<(usize, bool)> { + let mut at = self.at + 1; + let inner = self.chars.get(at) == Some(&'!'); + at += usize::from(inner); + for token in ["[", "cfg", "(", "test", ")", "]"] { + at = self.skip_space(at); + let end = at + token.chars().count(); + if !self.chars.get(at..end).is_some_and(|got| got.iter().copied().eq(token.chars())) { + return None; + } + if token.starts_with(is_word) && self.chars.get(end).is_some_and(|&c| is_word(c)) { + return None; + } + at = end; + } + Some((at, inner)) + } + + fn hash(&mut self) { + let Some((end, inner)) = self.cfg_test_end() else { + self.at += 1; + return; + }; + let skipped = self.chars.get(self.at..end).unwrap_or_default(); + self.line += skipped.iter().filter(|&&c| c == '\n').count(); + self.at = end; + if self.test.is_none() { + let level = self.delims.len(); + self.test = Some(if inner { + TestRegion::Inner { level } + } else { + TestRegion::Item { level, start: end, opened: false, item: false, semi: false, block: false } + }); + } + } + + /// A `=>` at the level of a test-only arm: its expression starts after it. + fn arrow(&mut self) { + self.at += 2; + if let Some(TestRegion::Item { level, item: false, .. }) = self.test + && level == self.delims.len() + { + self.test = Some(TestRegion::Item { level, start: self.at, opened: false, item: false, semi: false, block: false }); + } + } + + /// Whether the code at `start` is a block expression whose first `{` is at the current index: + /// the block itself, a macro's braces, a labeled block or loop, or a block keyword's expression. + /// Outer attributes before it are passed over. + fn starts_block(&self, start: usize) -> bool { + let mut at = self.skip_space(start); + while self.chars.get(at) == Some(&'#') { + at = self.skip_space(at + 1); + if self.chars.get(at) != Some(&'[') { + return false; + } + let mut depth = 0_usize; + loop { + match self.chars.get(at) { + None => return false, + Some('[') => depth += 1, + Some(']') => { + depth -= 1; + if depth == 0 { + break; + } + } + _ => {} + } + at += 1; + } + at = self.skip_space(at + 1); + } + at == self.at || self.chars.get(at) == Some(&'\'') || BLOCK_KEYWORDS.contains(&self.word_at(at).as_str()) || self.macro_braces(at) + } + + /// Whether the code at `at` is a macro path, `!` and the `{` at the current index. + fn macro_braces(&self, mut at: usize) -> bool { + if self.chars.get(at..at + 2) == Some(&[':', ':'][..]) { + at = self.skip_space(at + 2); + } + loop { + let len = self.word_at(at).chars().count(); + if len == 0 { + return false; + } + at = self.skip_space(at + len); + if self.chars.get(at..at + 2) != Some(&[':', ':'][..]) { + break; + } + at = self.skip_space(at + 2); + } + self.chars.get(at) == Some(&'!') && self.skip_space(at + 1) == self.at + } + + fn word_at(&self, at: usize) -> String { + self.chars.get(at..).unwrap_or_default().iter().take_while(|&&c| is_word(c)).collect() + } + + fn open(&mut self, c: char) { + if let Some(TestRegion::Item { level, start, opened: false, item, semi, .. }) = self.test + && level == self.delims.len() + && c == '{' + { + let block = !item && self.starts_block(start); + self.test = Some(TestRegion::Item { level, start, opened: true, item, semi, block }); + } + self.delims.push((c, self.line)); + self.at += 1; + } + + fn close(&mut self, c: char) -> Result<(), SyntaxError> { + let expected = match self.delims.pop() { + Some(('{', _)) => '}', + Some(('(', _)) => ')', + Some(_) => ']', + None => return Err(Self::error(self.line, "unmatched closing delimiter")), + }; + if c != expected { + return Err(Self::error(self.line, "mismatched closing delimiter")); + } + self.at += 1; + let depth = self.delims.len(); + let ends = match self.test { + Some(TestRegion::Item { level, start, opened, item, semi, block }) => { + let block_end = opened && depth == level && c == '}'; + if block_end && !item && block && self.postfix_follows() { + // A method call, field or `?` continues the expression to its `;` or `,`. + self.test = Some(TestRegion::Item { level, start, opened, item, semi, block: false }); + false + } else { + depth < level || (block_end && if item { !semi } else { block && self.word_at(self.skip_space(self.at)) != "else" }) + } + } + Some(TestRegion::Inner { level }) => depth < level, + None => false, + }; + if ends { + self.test = None; + } + Ok(()) + } + + /// Whether a `?` or a `.` (not `..`) follows the current index, past whitespace and comments. + fn postfix_follows(&self) -> bool { + let at = self.skip_space(self.at); + match self.chars.get(at) { + Some('?') => true, + Some('.') => self.chars.get(at + 1) != Some(&'.'), + _ => false, + } + } + + /// A `;` ends a test-only statement, or an item that has no body or ends at its `;`, and a `,` + /// inside a delimiter ends a test-only field, argument or arm. A `,` in an item's header + /// (`impl`, a `where` clause) does not. + fn item_end(&mut self, comma: bool) { + if let Some(TestRegion::Item { level, opened, item, semi, .. }) = self.test + && level == self.delims.len() + && if comma { level > 0 && !item } else { !item || !opened || semi } + { + self.test = None; + } + self.at += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BANNED: &[&str] = &["Amber Tool", "AzureKit", "BlueCore"]; + const ALLOWED: &[&str] = &["AzureKit Design"]; + const POLICY: Policy<'static> = Policy { allowed: ALLOWED, ..Policy::new(BANNED) }; + + fn banned_display(text: &str) -> bool { + !POLICY.words_in(text).is_empty() + } + + fn literals(source: &str) -> Vec { + super::literals(source, Literals::default()).unwrap().into_iter().map(|lit| lit.text).collect() + } + + fn write(dir: &Path, path: &str, text: &str) { + let path = dir.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + fn hits(findings: &[Finding]) -> Vec<(String, usize, &str)> { + findings.iter().map(|f| (f.path.to_string_lossy().replace('\\', "/"), f.line, f.word.as_str())).collect() + } + + #[test] + fn production_display_names_stay_neutral() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path().join("crates/ui"); + write(&base, "src/lib.rs", "pub const LABEL: &str = \"Open\";\n#[cfg(test)]\nmod tests { const S: &str = \"AzureKit\"; }\n"); + write(&base, "src/tests.rs", "const S: &str = \"AzureKit\";\n"); + write(&base, "src/panel_tests.rs", "const S: &str = \"BlueCore\";\n"); + write(&base, "src/tests/helper.rs", "const S: &str = \"Amber Tool\";\n"); + write(&base, "src/notes.txt", "AzureKit\n"); + write(dir.path(), "crates/engine/src/cmd/file.rs", "pub const DESIGN: &str = \"AzureKit Design\";\n"); + let roots = [Path::new("src"), Path::new("../engine/src/cmd")]; + let inputs: Vec> = roots.iter().map(|root| Input::rust(root)).collect(); + let found = scan(&base, &inputs, &POLICY).unwrap(); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.azureKit")); + assert!(!banned_display("tool.guidedBlueCore")); + assert!(!banned_display("insert.amberTool")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); + } + + #[test] + fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); + } + + #[test] + fn guard_skips_escaped_character_literals() { + assert_eq!(literals(r#"let q = '\"'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\''; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\\'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\u{22}'; "label""#), ["label"]); + } + + #[test] + fn guard_decodes_whitespace_escapes() { + assert_eq!(literals(r#""one\ntwo\tthree\rfour\0""#), ["one\ntwo\tthree\rfour\0"]); + assert_eq!(literals("\"joined\\\n label\""), ["joinedlabel"]); + for name in BANNED { + let source = format!("\"\\t{name}\\n\""); + assert!(literals(&source).iter().any(|label| banned_display(label))); + } + } + + #[test] + fn guard_scans_after_escaped_character_literals() { + let source = r###"let a = '\"'; let b = '\''; let c = '\\'; + let d = '\u{22}'; let e = '\x22'; + let label = "Amber Tool"; + fn lifetime<'a>(value: &'a str) { 'outer: loop { break 'outer; } let _ = "BlueCore"; } + "###; + assert_eq!(literals(source), ["Amber Tool", "BlueCore"]); + } + + #[test] + fn guard_scans_production_after_test_only_items_and_parses_raw_labels() { + let source = r###"#[cfg(test)] mod tests { let _ = "AzureKit"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"BlueCore"#; } + "###; + assert_eq!(literals(source), ["BlueCore"]); + assert!(literals(source).iter().any(|label| banned_display(label))); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"AzureKit\"; }"), ["AzureKit"]); + } + + #[test] + fn guard_skips_escaped_character_literals_without_hiding_labels() { + let source = r#"let quote = '\"'; let label = "BlueCore"; // "ignored""#; + assert_eq!(literals(source), ["BlueCore"]); + assert!(literals(source).iter().any(|label| banned_display(label))); + assert_eq!(literals(r#"let quote = '\"'; // "BlueCore""#), Vec::::new()); + } + + #[test] + fn source_read_failures_are_reported() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "src/lib.rs", "const S: &str = \"Open\";\n"); + // A file cannot be read as a folder, and a missing root is an error, not an empty scan. + for root in ["src/lib.rs/not-a-folder.rs", "missing"] { + let err = scan(dir.path(), &[Input::rust(Path::new(root))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::Io { .. }), "{root}: {err}"); + } + let err = scan(dir.path(), &[Input::text(Path::new("missing.txt"))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::Io { .. }), "{err}"); + } + + const DENY: &[&str] = &["azurekit", "bluecore", "copperline", "dunemark", "emberly", "fernwave", "glintpad"]; + const VECTOR: Policy<'static> = Policy { + case: MatchCase::AsciiInsensitive, + allow_marker: Some("name-ok"), + literals: Literals { byte_strings: true, c_strings: true }, + ..Policy::new(DENY) + }; + + fn rust_hits(src: &str) -> Vec<(usize, &str)> { + let found = scan_source(Path::new("lib.rs"), src, Kind::Rust, &VECTOR).unwrap(); + found.iter().map(|f| (f.line, DENY.iter().copied().find(|w| *w == f.word).unwrap())).collect() + } + + #[test] + fn rust_literals_skip_comments_identifiers_tests_and_marked_lines() { + let src = r##"// BlueCore in a comment +/// AzureKit in a doc comment +/* block AzureKit /* nested */ Copperline */ +fn f() { let a = "Made for BlueCore users"; let k = "copyEmberly"; let q = '"'; let l: &'static str = r#"raw "Dunemark" text"#; } +const OLD: &str = "BlueCore Defaults"; // name-ok: legacy alias +fn g() -> &'static str { "line\nEMBERLY" } +#[cfg(test)] +mod tests { + fn t() { let x = "AzureKit"; if true { let y = "Copperline"; } } +} +#[cfg(test)] +mod other; +fn h() { let s = b"Fernwave"; let m = "multi +line Glintpad"; } +"##; + assert_eq!(rust_hits(src), [(4, "bluecore"), (4, "dunemark"), (6, "emberly"), (13, "fernwave"), (13, "glintpad")]); + let lits = super::literals(src, VECTOR.literals).unwrap(); + let multi = lits.iter().find(|l| l.text.contains("Glintpad")).unwrap(); + assert_eq!((multi.first_line, multi.last_line), (13, 14)); + } + + #[test] + fn whole_words_only() { + assert_eq!(VECTOR.words_in("AzureKit's app"), ["azurekit"]); + assert_eq!(VECTOR.words_in("an BLUECORE-style UI"), ["bluecore"]); + assert!(VECTOR.words_in("bluecores bluecoreish copyEmberly emberlyMode").is_empty()); + } + + #[test] + fn docs_packaging_and_manifests() { + let scan = |text: &str, kind: Kind| -> Vec<(usize, String)> { + scan_source(Path::new("f"), text, kind, &VECTOR).unwrap().into_iter().map(|f| (f.line, f.word)).collect() + }; + let one = |line: usize, word: &str| vec![(line, word.to_string())]; + assert_eq!(scan("Keywords=vector;bluecore;\n", Kind::Text), one(1, "bluecore")); + assert_eq!(scan("Like AzureKit apps\nnot here: AzureKit # name-ok\n", Kind::Text), one(1, "azurekit")); + let desktop = "# shared type (name-ok)\nMimeType=application/bluecore;\n# a comment\nMimeType=application/bluecore;\n"; + assert_eq!(scan(desktop, Kind::TextMarkAbove), one(4, "bluecore"), "a `#` line marks the line below it only"); + assert_eq!( + scan(desktop, Kind::Text), + [(2, "bluecore".to_string()), (4, "bluecore".to_string())], + "only mark-above files take a mark from above" + ); + assert_eq!(scan("x = 1 # name-ok\nBlueCore\n", Kind::TextMarkAbove), one(2, "bluecore"), "a code line's comment marks that line only"); + let manifest = "[package]\nname = \"azurekit-thing\"\ndescription = \"BlueCore-style UI\"\n"; + assert_eq!(scan(manifest, Kind::Manifest), one(3, "bluecore")); + let multi = + "[package]\ndescription = \"\"\"\nA BlueCore\n-style UI\"\"\"\nkeywords = [\"azurekit\"]\ndescription = '''one line''' # azurekit\n"; + assert_eq!(scan(multi, Kind::Manifest), one(2, "bluecore"), "a multi-line value is read whole; a comment is not read"); + assert_eq!(scan("[package]\ndescription = '''\nAzureKit'''\nname = \"bluecore\"\n", Kind::Manifest), one(2, "azurekit")); + let escaped = "[package]\ndescription = \"\"\"say \\\"\"\" and\nBlueCore \\\\\"\"\"\nname = \"azurekit\"\n"; + assert_eq!(scan(escaped, Kind::Manifest), one(2, "bluecore"), "an escaped quote does not close the description"); + assert_eq!( + scan("[package]\ndescription = \"Blue\\u0043ore and Azure\\U0000004Bit\"\n", Kind::Manifest), + [(2, "azurekit".to_string()), (2, "bluecore".to_string())] + ); + assert_eq!(scan("[package]\ndescription = \"\"\"Blue\\\n Core\"\"\"\n", Kind::Manifest), one(2, "bluecore")); + assert!(scan("[package]\ndescription = \"Neutral\" # BlueCore\ndescriptions = \"AzureKit\"\n", Kind::Manifest).is_empty()); + let notes = "[package]\nnotes = \"\"\"\n[dependencies]\ndescription = \"BlueCore\"\n\"\"\" # \"\"\"\nquoted = 'a \"\"\" b'\ndescription = \"AzureKit\"\n"; + assert_eq!(scan(notes, Kind::Manifest), one(7, "azurekit"), "lines inside another key's string are not keys or headers"); + let keys = "package.description = 'BlueCore'\n[package]\n\"description\" = \"AzureKit\"\n'description'='Copperline'\n# description = \"Dunemark\"\nother.description = \"Emberly\"\n"; + assert_eq!(scan(keys, Kind::Manifest), [(1, "bluecore".to_string()), (3, "azurekit".to_string()), (4, "copperline".to_string())]); + let marked = + "[package]\ndescription = \"\"\"\nBlueCore long\n\"\"\" # name-ok\nname = \"y\"\n[workspace.package]\ndescription = \"BlueCore\"\n"; + assert_eq!(scan(marked, Kind::Manifest), one(7, "bluecore"), "a marker on any line of the value counts"); + let text = scan_source(Path::new("Cargo.toml"), "[package]\ndescription = '''\nBlueCore\nstyle'''\n", Kind::Manifest, &VECTOR).unwrap(); + assert_eq!(text[0].text, "BlueCore\nstyle"); + } + + #[test] + fn only_package_descriptions_are_read() { + let scan = |text: &str| -> Vec<(usize, String)> { + scan_source(Path::new("Cargo.toml"), text, Kind::Manifest, &VECTOR).unwrap().into_iter().map(|f| (f.line, f.word)).collect() + }; + let other = "description = \"Glintpad\"\n[dependencies.foo]\ndescription = \"BlueCore\"\n[package.metadata.x]\ndescription = \"AzureKit\"\n\ + [[bin]]\ndescription = \"Copperline\"\n[[package]]\ndescription = \"Copperline\"\n[package]\nmetadata.description = \"Dunemark\"\n\ + dependencies = { description = \"Dunemark\" }\n[workspace]\ndescription = \"Emberly\"\n"; + assert!(scan(other).is_empty(), "{:?}", scan(other)); + assert_eq!(scan("\u{feff}[package]\ndescription = \"BlueCore\"\n"), [(2, "bluecore".to_string())], "a byte order mark is skipped"); + assert_eq!(scan("\u{feff}package.description = \"AzureKit\"\n"), [(1, "azurekit".to_string())]); + let tables = "[ \"package\" ] # x\ndescription = \"BlueCore\"\n[dependencies.foo]\nx = [\n [\"package\"]\n]\ndescription = \"AzureKit\"\n\ + [workspace . 'package']\ndescription = \"Fernwave\"\n[dependencies]\nworkspace.package.description = \"Emberly\"\n\ + y = [ \"\"\"\n]\n\"\"\", ]\n[package]\ndescription = \"Glintpad\"\n"; + assert_eq!( + scan(tables), + [(2, "bluecore".to_string()), (9, "fernwave".to_string()), (16, "glintpad".to_string())], + "a line inside an array is not a header, and an array closed after a multi-line string is closed" + ); + } + + #[test] + fn scope() { + for (path, test) in [ + ("src/cmd/file.rs", false), + ("src/tests_file.rs", false), + ("src/text_tests.rs", true), + ("src/cms/tests.rs", true), + ("tests/command_sweep.rs", true), + ("src/tests/helper.rs", true), + ("../engine/tests/a.rs", true), + ] { + assert_eq!(test_path(Path::new(path)), test, "{path}"); + } + let dir = tempfile::tempdir().unwrap(); + for file in ["src/a.rs", "src/b.txt", "src/c.rs.bak", "src/d/e.rs", "src/tests/f.rs", "src/g_tests.rs"] { + write(dir.path(), file, "\"AzureKit\"\n"); + } + let found = scan(dir.path(), &[Input::rust(Path::new("src"))], &POLICY).unwrap(); + assert_eq!(hits(&found), [("src/a.rs".to_string(), 1, "AzureKit"), ("src/d/e.rs".to_string(), 1, "AzureKit")]); + let named = scan(dir.path(), &[Input::rust(Path::new("src/g_tests.rs"))], &POLICY).unwrap(); + assert_eq!(hits(&named), [("src/g_tests.rs".to_string(), 1, "AzureKit")], "a file input is read whatever its name"); + write(dir.path(), "tests/app/src/lib.rs", "\"AzureKit\"\n"); + let below = scan(dir.path(), &[Input::rust(Path::new("tests/app/src"))], &POLICY).unwrap(); + assert_eq!(hits(&below), [("tests/app/src/lib.rs".to_string(), 1, "AzureKit")], "folders above the input do not count"); + } + + #[test] + fn injected_strings_fail_the_gate() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "crates/x/src/lib.rs", "pub const LABEL: &str = \"Export for BlueCore\"; // a comment: AzureKit\n"); + write(root, "crates/x/Cargo.toml", "[package]\nname = \"x\"\ndescription = \"A Copperline-style crate\"\n"); + write(root, "docs/x.md", "Works like Copperline.\n"); + write(root, "docs/x.txt", "Works like Copperline.\n"); + write(root, "packaging/x.desktop", "Keywords=vector;bluecore;\n"); + let marked = "# shared type (name-ok)\nMimeType=application/bluecore;\n"; + write(root, "packaging/linux/app.desktop", marked); + write(root, "packaging/x.yaml", marked); + write(root, "README.md", "AzureKit trademark notice\n"); + let path = Path::new; + let inputs = [ + Input::rust(path("crates")), + Input::manifest(path("crates/x/Cargo.toml")), + Input::text(path("docs/x.txt")), + Input::text(path("packaging/x.desktop")), + Input::text_mark_above(path("packaging/linux/app.desktop")), + Input::text(path("packaging/x.yaml")), + ]; + let found = scan(root, &inputs, &VECTOR).unwrap(); + let expected = [ + ("crates/x/Cargo.toml", 3, "copperline"), + ("crates/x/src/lib.rs", 1, "bluecore"), + ("docs/x.txt", 1, "copperline"), + ("packaging/x.desktop", 1, "bluecore"), + ("packaging/x.yaml", 2, "bluecore"), + ]; + assert_eq!(hits(&found), expected.map(|(p, l, w)| (p.to_string(), l, w))); + } + + #[test] + fn the_tree_is_clean() { + // This crate's own sources hold none of the synthetic words outside their tests, and the + // lexer reads every one of them. + let base = Path::new(env!("CARGO_MANIFEST_DIR")); + let found = scan(base, &[Input::rust(Path::new("src"))], &VECTOR).unwrap(); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn escapes_are_decoded_before_matching() { + for source in [r#""A\x7AureKit""#, r#""A\u{7A}ureKit""#, r#""A\u{7_A}ureKit""#, r#""Azure\u{4B}it""#] { + assert_eq!(literals(source), ["AzureKit"], "{source}"); + } + assert_eq!(literals(r#""Blue\x43ore""#), ["BlueCore"]); + // A continuation leaves out the line break and the indentation, and adds no space. + assert_eq!(literals("\"Blue\\\n Core\""), ["BlueCore"]); + assert_eq!(literals("\"Blue\\\r\n\tCore\""), ["BlueCore"]); + assert_eq!(literals(r#""say \"BlueCore\" \\ ok""#), [r#"say "BlueCore" \ ok"#]); + } + + #[test] + fn test_only_items_of_every_form_are_skipped() { + let source = r#"#[cfg(test)] pub mod t { const S: &str = "AzureKit"; } +#[cfg(test)] fn f() { let _ = "AzureKit"; } +#[cfg(test)] const C: &str = "AzureKit"; +#[cfg(test)] static D: [&str; 2] = ["AzureKit", "AzureKit"]; +#[cfg(test)] +#[allow(dead_code)] +fn g() -> [u8; 2] { let _ = "AzureKit"; [0, 1] } +# [ cfg ( test ) ] mod spaced { "AzureKit"; } +struct S { #[cfg(test)] probe: &'static str, label: &'static str } +fn h() { let s = S { #[cfg(test)] probe: "AzureKit", label: "one" }; } +#[cfg(test)] mod declared; +mod generic { + #[cfg(test)] + impl Probe for Pair where A: Clone, B: Copy { fn p() { let _ = "AzureKit"; } } +} +mod inner { + #![cfg(test)] + fn i() { let _ = "AzureKit"; } +} +#[cfg(test)] const PICK: &str = if true { "AzureKit" } else { "AzureKit" }; +#[cfg(/* a reason */ test)] const NOTED: &str = "AzureKit"; +#[cfg( // a reason + test)] const NOTED_LINE: &str = "AzureKit"; +#[cfg(test)] const fn k() -> u8 { 1 } +#[cfg(not(test))] const E: &str = "two"; +#[cfg(tests)] const F: &str = "three"; +fn live() { let _ = "four"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four"]); + assert_eq!(literals("#![cfg(test)]\nfn a() { \"AzureKit\"; }\nfn b() { \"AzureKit\"; }\n"), Vec::::new()); + } + + #[test] + fn test_only_arms_and_statements_end_after_their_last_block() { + let source = r#"fn pick(x: u8, c: bool) -> &'static str { + match x { + #[cfg(test)] 0 => if c { "AzureKit" } else { "AzureKit" }, + #[cfg(test)] 1 => if c { "AzureKit" } else if !c { "AzureKit" } else { "AzureKit" } + #[cfg(test)] 2 => { "AzureKit" } + 3 => "one", + #[cfg(test)] 4 => Probe { a: "AzureKit" }.label("AzureKit"), + #[cfg(test)] Probe { a: 5 } => "AzureKit", + #[cfg(test)] 6 => match c { true => "AzureKit", false => "AzureKit" } + #[cfg(test)] #[allow(unused)] 7 => unsafe { "AzureKit" } + _ => "two", + } +} +fn statements(c: bool) { + #[cfg(test)] if c { "AzureKit"; } else { "AzureKit"; } + let _ = "three"; + #[cfg(test)] { "AzureKit"; } + #[cfg(test)] probe! { "AzureKit" } + #[cfg(test)] crate::probe! /* noted */ { "AzureKit" } + let _ = "four"; + #[cfg(test)] Probe { a: "AzureKit" }.run("AzureKit"); + #[cfg(test)] 'outer: loop { "AzureKit"; } + #[cfg(test)] const { "AzureKit"; } + let _ = "five"; +} +fn tail() -> Probe { + #[cfg(test)] Probe { a: "AzureKit" }.with("AzureKit") +} +fn after() { let _ = "six"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six"]); + } + + #[test] + fn test_only_blocks_keep_their_method_calls_and_question_marks() { + let source = r#"fn statements(c: bool) -> Result<(), Probe> { + #[cfg(test)] { "x" }.replace("x", "AzureKit"); + let _ = "one"; + #[cfg(test)] unsafe { probe("x") }?; + #[cfg(test)] unsafe { probe("x") }?.with("AzureKit"); + let _ = "two"; + #[cfg(test)] { "x" } /* noted */ .replace("x", "AzureKit"); + #[cfg(test)] { "x" } // noted + .replace("x", "AzureKit"); + #[cfg(test)] match c { _ => probe("x") }?.with("AzureKit"); + #[cfg(test)] probe! { "x" }.with("AzureKit"); + #[cfg(test)] { (1, "x") }.0.with("AzureKit"); + let _ = "three"; + #[cfg(test)] { "AzureKit"; } + ..; + let _ = "four"; + Ok(()) +} +fn pick(x: u8, c: bool) -> String { + match x { + #[cfg(test)] 8 => if c { "x" } else { "y" }.to_string().replace("x", "AzureKit"), + 9 => "five".into(), + #[cfg(test)] 10 => { "x" }.replace("x", "AzureKit"), + _ => "six".into(), + } +} +fn tail() -> String { + #[cfg(test)] { "x" }.replace("x", "AzureKit") +} +fn after() { let _ = "seven"; } +"#; + assert_eq!(literals(source), ["one", "two", "three", "four", "five", "six", "seven"]); + } + + #[test] + fn the_marker_counts_only_in_a_comment() { + let policy = Policy { allow_marker: Some("name-ok"), ..POLICY }; + let rust = |src: &str| scan_source(Path::new("lib.rs"), src, Kind::Rust, &policy).unwrap().len(); + assert_eq!(rust("let label = \"AzureKit name-ok\";"), 1); + assert_eq!(rust("let label = \"AzureKit\"; // name-ok: compatibility"), 0); + assert_eq!(rust("let label = \"AzureKit\"; /* name-ok */"), 0); + assert_eq!(rust("/* name-ok */ let label = \"AzureKit\";"), 0); + assert_eq!(rust("/* name-ok\n */ let label = \"AzureKit\";"), 1, "a block comment marks only its lines that hold the marker"); + assert_eq!(rust("/* a\n b name-ok */ let label = \"AzureKit\";"), 0); + assert_eq!(rust("/* a\n\n name-ok */ let label = \"AzureKit\";"), 0, "the marker's line is the comment's third"); + assert_eq!(rust("/* a\n name-ok\n */ let label = \"AzureKit\nx\";"), 1); + assert_eq!(rust("let a = \"name-ok\"; let b = \"AzureKit\";"), 1); + assert_eq!(rust("// name-ok\nlet label = \"AzureKit\";"), 1, "the line above does not count in Rust"); + assert_eq!(rust("let label = \"Azure\nKit\nAzureKit\"; // name-ok"), 0, "a mark on any line of the literal counts"); + } + + #[test] + fn letters_of_any_script_are_part_of_a_word() { + for policy in [POLICY, Policy { case: MatchCase::AsciiInsensitive, ..POLICY }] { + assert!(policy.words_in("éAzureKit").is_empty()); + assert!(policy.words_in("AzureKitß").is_empty()); + assert!(policy.words_in("AzureKit_2").is_empty()); + assert_eq!(policy.words_in("é AzureKit, é"), ["AzureKit"]); + } + } + + #[test] + fn case_follows_the_policy() { + assert!(POLICY.words_in("azurekit").is_empty()); + assert_eq!(Policy { case: MatchCase::AsciiInsensitive, ..POLICY }.words_in("azureKIT and amber TOOL"), ["Amber Tool", "AzureKit"]); + } + + #[test] + fn allowed_literals_and_exceptions_match_whole_text() { + fn group(text: &str) -> bool { + text.strip_prefix("AzureKit Design › ").is_some_and(|rest| !banned_display(rest)) + } + let policy = Policy { exceptions: &[group], ..POLICY }; + assert!(policy.words_in("AzureKit Design").is_empty()); + assert_eq!(policy.words_in("AzureKit Design extra"), ["AzureKit"]); + assert!(policy.words_in("AzureKit Design › Layout").is_empty()); + assert_eq!(policy.words_in("AzureKit Design › BlueCore Styles"), ["AzureKit", "BlueCore"]); + } + + #[test] + fn byte_and_c_strings_are_read_only_when_asked() { + let source = r##"let a = b"AzureKit"; let b = br#"AzureKit"#; let c = c"BlueCore"; let d = cr"BlueCore"; let e = b'"'; let f = b'\xFF'; let g = r#"plain"#;"##; + assert_eq!(literals(source), ["plain"]); + let bytes = super::literals(source, Literals { byte_strings: true, c_strings: false }).unwrap(); + assert_eq!(bytes.iter().map(|l| l.text.as_str()).collect::>(), ["AzureKit", "AzureKit", "plain"]); + let both = super::literals(source, Literals { byte_strings: true, c_strings: true }).unwrap(); + assert_eq!(both.len(), 5); + assert_eq!(literals("let r#type = 1; let s = \"BlueCore\";"), ["BlueCore"]); + } + + #[test] + fn raw_strings_close_at_the_same_number_of_hashes() { + assert_eq!(literals(r###"r##"a "# b"## "next""###), [r##"a "# b"##, "next"]); + assert_eq!(literals(r#"r"\x41""#), [r"\x41"]); + } + + #[test] + fn malformed_source_is_an_error() { + for (source, line) in [ + ("let a = \"open", 1), + ("\n let a = r#\"open\"", 2), + ("/* /* */", 1), + ("fn f() { }}", 1), + ("fn f() {\n", 1), + ("fn f( ]", 1), + (r#""\q""#, 1), + (r#""\x80""#, 1), + (r#""\x4""#, 1), + (r#""\u{D800}""#, 1), + (r#""\u{1234567}""#, 1), + (r#""\u{}""#, 1), + (r"let c = '\q';", 1), + (r"let c = '\n", 1), + ] { + let err = super::literals(source, Literals::default()).unwrap_err(); + assert_eq!(err.line, line, "{source}: {err}"); + } + let err = scan_source(Path::new("bad.rs"), "\"open", Kind::Rust, &POLICY).unwrap_err(); + assert!(matches!(err, Error::Syntax { .. }), "{err}"); + } + + #[test] + fn lines_count_crlf_and_words_at_literal_edges() { + let src = "fn a() {}\r\n\r\nconst A: &str = \"AzureKit\";\r\nconst B: &str = \"x\r\ny BlueCore\";\r\n"; + let found = scan_source(Path::new("lib.rs"), src, Kind::Rust, &POLICY).unwrap(); + assert_eq!(found.iter().map(|f| (f.line, f.word.as_str())).collect::>(), [(3, "AzureKit"), (4, "BlueCore")]); + assert_eq!(found[1].text, "x\ny BlueCore"); + let text = scan_source(Path::new("a.txt"), "one\r\nBlueCore\r\n", Kind::Text, &POLICY).unwrap(); + assert_eq!((text[0].line, text[0].text.as_str()), (2, "BlueCore")); + } + + #[test] + fn unreadable_and_oversized_inputs_are_errors() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::create_dir_all(root.join("bad")).unwrap(); + fs::write(root.join("bad/lib.rs"), b"const S: &str = \"\xff\";").unwrap(); + let err = scan(root, &[Input::rust(Path::new("bad"))], &POLICY).unwrap_err(); + assert!(matches!(err, Error::InvalidUtf8 { .. }), "{err}"); + + write(root, "big/lib.rs", &"/* */".repeat(40)); + let small = Policy { limits: Limits { max_file_bytes: 199, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("big"))], &small).unwrap_err(); + assert!(matches!(err, Error::FileTooLarge { limit: 199, .. }), "{err}"); + let exact = Policy { limits: Limits { max_file_bytes: 200, ..DEFAULT_LIMITS }, ..POLICY }; + assert!(scan(root, &[Input::rust(Path::new("big"))], &exact).unwrap().is_empty()); + + write(root, "two/a.rs", "\"one\""); + write(root, "two/b.rs", "\"two\""); + let total = Policy { limits: Limits { max_total_bytes: 9, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("two"))], &total).unwrap_err(); + assert!(matches!(&err, Error::TotalTooLarge { path, .. } if path.ends_with("b.rs")), "{err}"); + + write(root, "deep/a/b/c/lib.rs", "\"one\""); + let shallow = Policy { limits: Limits { max_depth: 2, ..DEFAULT_LIMITS }, ..POLICY }; + let err = scan(root, &[Input::rust(Path::new("deep"))], &shallow).unwrap_err(); + assert!(matches!(err, Error::TooDeep { limit: 2, .. }), "{err}"); + let enough = Policy { limits: Limits { max_depth: 3, ..DEFAULT_LIMITS }, ..POLICY }; + assert!(scan(root, &[Input::rust(Path::new("deep"))], &enough).unwrap().is_empty()); + } + + #[cfg(unix)] + #[test] + fn folder_links_are_not_followed() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "outside/lib.rs", "\"AzureKit\""); + write(root, "src/lib.rs", "\"BlueCore\""); + std::os::unix::fs::symlink(root.join("outside"), root.join("src/linked")).unwrap(); + std::os::unix::fs::symlink(root.join("outside/lib.rs"), root.join("src/file_link.rs")).unwrap(); + std::os::unix::fs::symlink(root.join("gone"), root.join("src/dangling.txt")).unwrap(); + std::os::unix::fs::symlink(root.join("gone"), root.join("src/tests.rs")).unwrap(); + let found = scan(root, &[Input::rust(Path::new("src"))], &POLICY).unwrap(); + assert_eq!(hits(&found), [("src/file_link.rs".to_string(), 1, "AzureKit"), ("src/lib.rs".to_string(), 1, "BlueCore")]); + } + + #[test] + fn findings_are_sorted_and_files_read_once() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, "src/b.rs", "\"BlueCore\"\n\"AzureKit BlueCore Amber Tool\""); + write(root, "src/a.rs", "\"AzureKit\""); + let src = Path::new("src"); + let inputs = [Input::rust(Path::new("src/b.rs")), Input::rust(src), Input::rust(src)]; + let found = scan(root, &inputs, &POLICY).unwrap(); + let expected = [ + ("src/a.rs", 1, "AzureKit"), + ("src/b.rs", 1, "BlueCore"), + ("src/b.rs", 2, "Amber Tool"), + ("src/b.rs", 2, "AzureKit"), + ("src/b.rs", 2, "BlueCore"), + ]; + assert_eq!(hits(&found), expected.map(|(p, l, w)| (p.to_string(), l, w))); + assert_eq!(found[0].to_string(), format!("{}:1: \"AzureKit\" in \"AzureKit\"", Path::new("src").join("a.rs").display())); + let twice = [Input::rust(src), Input::text(Path::new("src/a.rs"))]; + let err = scan(root, &twice, &POLICY).unwrap_err(); + assert!(matches!(&err, Error::Conflict { path } if path.ends_with("a.rs")), "{err}"); + } + + #[test] + fn policies_that_match_nothing_are_errors() { + let empty: &[&str] = &[]; + for policy in [Policy::new(empty), Policy::new(&["AzureKit", " "]), Policy { allow_marker: Some(""), ..POLICY }] { + let err = scan_source(Path::new("f"), "", Kind::Text, &policy).unwrap_err(); + assert!(matches!(err, Error::Policy(_)), "{err}"); + } + } +} From 6701acfcf1f13757f4485755722dc27d97fe57c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:03:39 -0800 Subject: [PATCH 015/490] craft-testkit: bound collection and use-path allocations and fix guard edge cases - fonts::collection counts the table directories from each face's numTables before reading any record, then adds the tables one face at a time, so oversized input returns OutputTooLarge without keeping a directory for every face. - fonts::rename_family keeps the rest of each renamed full name, so a family name stored inside that suffix is refused with ConflictingNameStorage. - The guards read `use<...>` as a capturing bound, not a declaration, and keep use paths of at most eight segments, so a long prefix shared by many names is not copied into each. - std_instant finds the modules of a file that a #[path] attribute names next to that file, separately from a plain load of the same file. - predefined_quit reports ::quit. - wgsl_float_literals ends line comments and counts lines at every WGSL line break, and skips digits inside Unicode identifiers. --- crates/testkit/README.md | 2 +- crates/testkit/src/fonts.rs | 59 ++++++--- crates/testkit/src/guards.rs | 233 +++++++++++++++++++++++---------- crates/testkit/tests/fonts.rs | 34 +++++ crates/testkit/tests/guards.rs | 68 ++++++++++ 5 files changed, 303 insertions(+), 93 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 1e1a254e9f..fd2c621ec7 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -6,7 +6,7 @@ Source-level platform regression guards and verification utilities for the Craft `craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: -1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. +1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. diff --git a/crates/testkit/src/fonts.rs b/crates/testkit/src/fonts.rs index 04345b66a2..cfc3096a0c 100644 --- a/crates/testkit/src/fonts.rs +++ b/crates/testkit/src/fonts.rs @@ -143,24 +143,26 @@ pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result, Font /// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is /// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or /// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the -/// 4 GiB that its 32-bit offsets reach or cannot be allocated. +/// 4 GiB that its 32-bit offsets reach or cannot be allocated. The headers and table directories are +/// counted from each face's `numTables` before any table record is read, so faces whose directories +/// alone pass 4 GiB return [`FontError::OutputTooLarge`] even when a table record is out of range. pub fn collection(faces: &[&[u8]]) -> Result, FontError> { if faces.is_empty() { return Err(FontError::EmptyCollection); } - let directories = faces.iter().map(|face| directory(face)).collect::, _>>()?; let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?; - let size = collection_size(&directories)?; + let size = collection_size(faces)?; let mut out = Vec::new(); out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?; out.extend_from_slice(b"ttcf"); out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); out.extend_from_slice(&count.to_be_bytes()); out.resize(SFNT_HEADER + faces.len() * 4, 0); - for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() { + for (index, face) in faces.iter().enumerate() { + let tables = directory(face)?; let directory = offset32(out.len())?; put_u32(&mut out, SFNT_HEADER + index * 4, directory)?; - write_face(&mut out, face, tables)?; + write_face(&mut out, face, &tables)?; } Ok(out) } @@ -176,11 +178,7 @@ struct Table { /// Reads a standalone face's table directory, checking that every record and table lies in `face`. fn directory(face: &[u8]) -> Result, FontError> { - let version = bytes_at(face, 0, 4)?; - if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { - return Err(FontError::UnsupportedFace); - } - let count = usize::from(u16_at(face, 4)?); + let count = table_count(face)?; bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?; let mut tables = Vec::with_capacity(count); for index in 0..count { @@ -194,6 +192,15 @@ fn directory(face: &[u8]) -> Result, FontError> { Ok(tables) } +/// Reads a standalone face's sfnt version and `numTables`, without reading the table records. +fn table_count(face: &[u8]) -> Result { + let version = bytes_at(face, 0, 4)?; + if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) { + return Err(FontError::UnsupportedFace); + } + Ok(usize::from(u16_at(face, 4)?)) +} + /// Whether `table` shares bytes with the table directory or with another table of the face. fn shares_bytes(tables: &[Table], table: &Table) -> bool { let end = table.offset + table.length; @@ -203,18 +210,24 @@ fn shares_bytes(tables: &[Table], table: &Table) -> bool { } /// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches. -fn collection_size(directories: &[Vec
]) -> Result { - let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?; - for tables in directories { - let directory = SFNT_HEADER + tables.len() * TABLE_RECORD; - size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; - for table in tables { - let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4; - size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?; - } +/// +/// The headers and table directories are added up first, from each face's `numTables` alone, so that +/// input whose directories already pass the limit is refused before any table record is read. The +/// tables are then added one face at a time, and no face's directory is kept. +fn collection_size(faces: &[&[u8]]) -> Result { + let add = |size: u64, bytes: usize| -> Result { + let size = size.checked_add(u64::try_from(bytes).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?; + if size > u64::from(u32::MAX) { Err(FontError::OutputTooLarge) } else { Ok(size) } + }; + let mut size = add(0, SFNT_HEADER)?; + size = add(size, faces.len().checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + for face in faces { + size = add(size, SFNT_HEADER + table_count(face)? * TABLE_RECORD)?; } - if size > u64::from(u32::MAX) { - return Err(FontError::OutputTooLarge); + for face in faces { + for table in directory(face)? { + size = add(size, table.length.div_ceil(4).checked_mul(4).ok_or(FontError::OutputTooLarge)?)?; + } } usize::try_from(size).map_err(|_| FontError::OutputTooLarge) } @@ -342,6 +355,10 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul None => { let edit = renamed(string, face, from, to)?; let edited = edit.is_some(); + if let Some(edit) = &edit { + // The rest of a full name, after the family name, must keep its bytes. + kept.push(edit.range.end..string.range.end); + } edits.extend(edit); read.insert(key, edited); edited diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 77006af6f3..8a68eb0b72 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -114,6 +114,11 @@ impl AsFileSource for &(&str, String) { /// read as far as this depth, so hostile nesting cannot exhaust the stack. const MAX_NESTING: usize = 64; +/// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most +/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves +/// is not copied into each of them. +const MAX_USE_PATH: usize = 8; + /// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text /// except string contents, which `cfg` predicates compare. #[derive(Debug, Clone, PartialEq, Eq)] @@ -344,6 +349,29 @@ fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) } +/// Whether the path that ends at `toks[i]` starts right after the `<` of a qualified path, as in +/// `::quit`, rather than after the `<` of generic arguments (`Vec::new`, +/// `f::`). +fn opens_qualified_path(toks: &[Token], i: usize) -> bool { + let mut start = i; + while start >= 2 && toks[start - 1].is_punct(':') && toks[start - 2].is_punct(':') { + if start >= 3 && matches!(toks[start - 3].kind, Kind::Ident(_)) { + start -= 3; + } else { + start -= 2; + break; + } + } + start >= 1 + && toks[start - 1].is_punct('<') + && match start.checked_sub(2).map(|j| &toks[j].kind) { + None => true, + Some(Kind::Ident(s)) => KEYWORDS.contains(&s.as_str()), + Some(Kind::Punct(c)) => !matches!(*c, ':' | '>'), + Some(_) => false, + } +} + /// One name a `use` declaration brings into scope. #[derive(Debug)] struct UseLeaf { @@ -361,7 +389,8 @@ fn use_leaves(toks: &[Token]) -> Vec { let mut leaves = Vec::new(); let mut i = 0; while i < toks.len() { - if toks[i].is_ident("use") && !continues_a_path(toks, i) { + // `use<...>` is a precise capturing bound on `impl Trait`, not a `use` declaration. + if toks[i].is_ident("use") && !continues_a_path(toks, i) && !toks.get(i + 1).is_some_and(|t| t.is_punct('<')) { let start = i; let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); let mut pos = i + 1; @@ -389,24 +418,30 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, sta *pos += 2; continue; } - let mut path = prefix.clone(); - if name != "self" { - path.push(name.clone()); - } - let mut bound = path.last().cloned(); - if toks.get(*pos).is_some_and(|t| t.is_ident("as")) - && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) - { - bound = Some(alias.clone()); - *pos += 2; - } - if let Some(bound) = bound.filter(|b| b != "_") { - out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + let length = prefix.len() + usize::from(name != "self"); + let alias = match (toks.get(*pos), toks.get(*pos + 1).map(|t| &t.kind)) { + (Some(t), Some(Kind::Ident(alias))) if t.is_ident("as") => { + *pos += 2; + Some(alias) + } + _ => None, + }; + if length <= MAX_USE_PATH { + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let bound = alias.cloned().or_else(|| path.last().cloned()); + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + } } break; } Kind::Punct('*') => { - out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + if prefix.len() <= MAX_USE_PATH { + out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + } *pos += 1; break; } @@ -797,19 +832,20 @@ fn join_path(parent: &str, child: &str) -> String { /// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. /// -/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file -/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// The modules of `lib.rs`, `main.rs` and `mod.rs`, and with `path_loaded`, of a file that a `#[path]` +/// attribute names, are in the file's folder, and those of any other file are in the folder named after +/// its stem. Each inline module around the declaration adds a folder named /// after it, or with a `path` attribute, moves to that path relative to the current folder (without the /// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that /// path relative to the current folder, again without the stem folder. -fn module_files(parent: &str, decl: &ModDecl) -> Vec { +fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec { let (dir, file) = match parent.rsplit_once('/') { Some(("", file)) => ("/", file), Some(split) => split, None => ("", parent), }; let mut folder = dir.to_string(); - let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + let mut stem = (!path_loaded && !matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); for inline in &decl.inline { if let Some(attr) = &inline.path_attribute { folder = join_path(&folder, attr); @@ -839,67 +875,88 @@ fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { for (i, path) in paths.iter().enumerate() { index.entry(path.as_str()).or_default().push(i); } - // The files each declaration names, in the order of `decls`. - let children: Vec)>> = decls - .iter() - .enumerate() - .map(|(parent, file_decls)| { - file_decls - .iter() - .map(|decl| { - let files = - module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); - (decl.native, files) - }) - .collect() + // rustc reads a file that a `#[path]` attribute names as if it were a `mod.rs`, so the modules it + // declares are in its own folder rather than its stem folder. Each file is therefore two nodes: node + // `2 * file` for the file loaded by a plain `mod name;` (or as a crate root), and node `2 * file + 1` + // for the file loaded through a `#[path]` attribute. Each node lists the nodes its declarations name, + // with whether the declaration is in a native-only item. + let edges: Vec> = (0..paths.len() * 2) + .map(|node| { + let (parent, path_loaded) = (node / 2, node % 2 == 1); + let mut targets = Vec::new(); + for decl in &decls[parent] { + let by_path = usize::from(decl.module.path_attribute.is_some()); + for candidate in module_files(&paths[parent], decl, path_loaded) { + for &j in index.get(candidate.as_str()).into_iter().flatten() { + targets.push((decl.native, 2 * j + by_path)); + } + } + } + targets }) .collect(); + // The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a + // node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is + // narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds. + let mut loaded: Vec = (0..paths.len() * 2).map(|node| node % 2 == 0).collect(); + let mut named = vec![false; paths.len()]; + for _ in 0..MAX_MODULE_ROUNDS { + let mut reached = vec![false; paths.len() * 2]; + for (node, targets) in edges.iter().enumerate() { + if loaded[node] { + for &(_, target) in targets { + reached[target] = true; + } + } + } + named = (0..paths.len()).map(|j| reached[2 * j] || reached[2 * j + 1]).collect(); + let next: Vec = (0..paths.len() * 2).map(|node| reached[node] || (node % 2 == 0 && !named[node / 2])).collect(); + if next == loaded { + break; + } + loaded = next; + } + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item // of such a file names. - let mut named = vec![false; paths.len()]; - for (_, files) in children.iter().flatten() { - for &j in files { - named[j] = true; - } - } - let mut web = vec![false; paths.len()]; - let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); - for &j in &queue { - web[j] = true; + let mut web = vec![false; paths.len() * 2]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).map(|j| 2 * j).collect(); + for &node in &queue { + web[node] = true; } while let Some(parent) = queue.pop() { - for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { - for &j in files { - if !web[j] { - web[j] = true; - queue.push(j); - } + for &(_, target) in edges[parent].iter().filter(|(is_native, _)| !is_native) { + if !web[target] { + web[target] = true; + queue.push(target); } } } - // Files a native-only declaration names, and their descendants. - let mut native = vec![false; paths.len()]; - let mut mark = |files: &[usize], queue: &mut Vec| { - for &j in files { - if !native[j] { - native[j] = true; - queue.push(j); - } + // Files a native-only declaration of a loaded node names, and their descendants. + let mut native = vec![false; paths.len() * 2]; + let starts = edges.iter().enumerate().filter(|&(node, _)| loaded[node]).flat_map(|(_, targets)| targets.iter()); + for &(_, target) in starts.filter(|(is_native, _)| *is_native) { + if !native[target] { + native[target] = true; + queue.push(target); } - }; - for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { - mark(files, &mut queue); } while let Some(parent) = queue.pop() { - for (_, files) in &children[parent] { - mark(files, &mut queue); + for &(_, target) in &edges[parent] { + if !native[target] { + native[target] = true; + queue.push(target); + } } } - native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() + (0..paths.len()).map(|j| (native[2 * j] || native[2 * j + 1]) && !web[2 * j] && !web[2 * j + 1]).collect() } +/// The most rounds [`native_only_files`] spends narrowing the set of loaded files. +const MAX_MODULE_ROUNDS: usize = 16; + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -919,7 +976,8 @@ fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeS /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. /// /// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace -/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type +/// or line breaks around `::` do not hide a call. A qualified path such as `::quit` +/// is reported too. It also follows a `use` that renames muda's type /// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's /// `PredefinedMenuItem` is not followed. Each finding names the line where the /// type's name starts, once per line, in line order. @@ -943,7 +1001,10 @@ where for (i, tok) in toks.iter().enumerate() { let Kind::Ident(name) = &tok.kind else { continue }; let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i)); - if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit"); + // `::quit`, a qualified path to the same function. + let qualified = || toks.get(i + 1).is_some_and(|t| t.is_punct('>')) && quit(i + 2) && opens_qualified_path(&toks, i); + if named && (quit(i + 1) || qualified()) { lines.insert(tok.line); } } @@ -974,8 +1035,8 @@ where /// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the /// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside /// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or -/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's -/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in +/// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration /// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way /// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` /// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline @@ -1050,7 +1111,11 @@ where findings } -/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, and write each WGSL line break as +/// `\n`: line feed, vertical tab, form feed, carriage return, carriage return and line feed as one +/// break, next line (U+0085), line separator (U+2028) and paragraph separator (U+2029) +/// (). A line comment ends at any of them, and `str::lines` +/// then counts lines the way WGSL does. fn mask_wgsl_comments(code: &str) -> String { let chars: Vec = code.chars().collect(); let len = chars.len(); @@ -1061,10 +1126,15 @@ fn mask_wgsl_comments(code: &str) -> String { while i < len { let c = chars[i]; let next = chars.get(i + 1).copied(); - if c == '\n' { + let line_break = match c { + '\r' if next == Some('\n') => 2, + '\n' | '\u{000B}' | '\u{000C}' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => 1, + _ => 0, + }; + if line_break > 0 { in_line = false; out.push('\n'); - i += 1; + i += line_break; } else if in_line { out.push(' '); i += 1; @@ -1183,7 +1253,9 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. -/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. A `//` comment +/// ends at any WGSL line break, a lone carriage return included, and finding lines count every one of them. +/// * **Identifiers**: digits inside an identifier, `π1e39` included, are not a literal. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } @@ -1205,7 +1277,14 @@ where let mut i = 0; while i < code.len() { let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + // Outside comments, a character that is not ASCII and not blankspace (U+200E, U+200F) is part of an + // identifier, as in `π1e39`. + let word_before = digit_or_dot + && i > 0 + && (code[i - 1].is_ascii_alphanumeric() + || code[i - 1] == b'_' + || code[i - 1] == b'.' + || (!code[i - 1].is_ascii() && !line[..i].ends_with(['\u{200E}', '\u{200F}']))); if !digit_or_dot || word_before { i += 1; continue; @@ -1392,3 +1471,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> files.sort_by(|a, b| a.0.cmp(&b.0)); Ok(files) } + +#[cfg(test)] +mod tests { + use super::{MAX_USE_PATH, lex_rust, use_leaves}; + + #[test] + fn use_leaves_keep_no_path_longer_than_the_limit() { + let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH)); + let paths: Vec> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect(); + assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]); + } +} diff --git a/crates/testkit/tests/fonts.rs b/crates/testkit/tests/fonts.rs index 6ff688c7fa..56e20b79ac 100644 --- a/crates/testkit/tests/fonts.rs +++ b/crates/testkit/tests/fonts.rs @@ -298,6 +298,16 @@ fn rename_keeps_a_style_sharing_the_full_name_suffix() { assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]); } +#[test] +fn rename_rejects_a_family_name_in_the_full_name_suffix() { + // The full name "A A" is stored once, and the family name (ID 1) is its last "A". Renaming the + // family would change the full name's suffix " A". + let records = + [Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 6 }, Rec { platform: 3, encoding: 1, name_id: 1, offset: 4, length: 2 }]; + let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16("A A")))]); + assert_eq!(rename_family(&font, "A", "B"), Err(FontError::ConflictingNameStorage)); +} + #[test] fn rename_updates_name_checksum() { let font = family_face(&[win(1, FROM), win(2, "Regular")]); @@ -580,3 +590,27 @@ fn collection_rejects_offset_overflow() { let faces = vec![&big[..]; 4096]; assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); } + +#[test] +fn collection_rejects_directories_past_the_offset_limit() { + // 65,536 references to one face with 4,096 empty tables: the table directories alone take more + // than 4 GiB. The function refuses without keeping a directory for every face. + let tables: Vec<(&[u8; 4], Vec)> = (0..4096).map(|_| (b"zzzz", Vec::new())).collect(); + let many = face(&tables); + let faces = vec![&many[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} + +#[test] +fn collection_counts_directories_before_reading_records() { + // The same number of directories, each with every table record out of range. The size limit is + // found from the faces' table counts before any table record is read. + let mut directory = vec![0u8; 12 + 16 * 4096]; + set32(&mut directory, 0, 0x0001_0000); + set16(&mut directory, 4, 4096); + for index in 0..4096 { + set32(&mut directory, 12 + 16 * index + 8, u32::MAX); + } + let faces = vec![&directory[..]; 65536]; + assert_eq!(collection(&faces), Err(FontError::OutputTooLarge)); +} diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 169fdd5734..e568422645 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -412,6 +412,21 @@ fn menu() { assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); } +#[test] +fn predefined_quit_reports_a_qualified_path() { + let source = r#" +use muda::PredefinedMenuItem as Item; +fn menu() { + let a = ::quit(None); + let b = < PredefinedMenuItem >::quit(None); + let c = ::quit(None); + let d = Vec::::quit(None); + let e = Wrapper::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]); +} + #[test] fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { let source = r#" @@ -566,6 +581,12 @@ use std::time::{ assert_eq!(findings[0].text, "Instant"); } +#[test] +fn std_instant_reads_a_use_after_a_precise_capturing_bound() { + let source = "fn clock() -> impl Fn() + use<> {\n use std::{time::Instant};\n || { let _ = Instant::now(); }\n}\n"; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2]); +} + #[test] fn std_instant_does_not_count_brace_character_literals_as_braces() { let source = r#" @@ -601,6 +622,15 @@ fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); } +#[test] +fn a_long_use_path_shared_by_many_names_is_read_without_copying_it_to_each() { + // 10,000 path segments shared by 10,000 names, followed by a `use` the guard reports. + let names: Vec = (0..10_000).map(|n| format!("x{n}")).collect(); + let source = format!("use {}{{{}}};\nuse std::time::Instant;\n", "a::".repeat(10_000), names.join(", ")); + assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]); + assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty()); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -733,6 +763,28 @@ mod platform { assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); } +#[test] +fn std_instant_finds_the_modules_of_a_path_attribute_file_next_to_it() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +#[path = "platform/native.rs"] +mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform/native.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/web.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs"]); +} + +#[test] +fn std_instant_resolves_a_file_loaded_both_plainly_and_by_path_attribute_once_for_each() { + // `platform.rs` is a web module, and a native-only `#[path]` declaration loads it again. Its + // `mod clock;` is `src/platform/clock.rs` for the first and `src/clock.rs` for the second. + let lib = "mod platform;\n#[cfg(unix)]\n#[path = \"platform.rs\"]\nmod native;\n"; + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib), ("src/platform.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/clock.rs", clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs"]); +} + #[test] fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); @@ -807,6 +859,22 @@ fn wgsl_half_floats_use_the_f16_range() { assert_eq!(findings[0].text, "70000.0"); } +#[test] +fn wgsl_line_comments_end_and_lines_count_at_every_line_break() { + let shader = "// note\rconst A: f32 = 4e38;\r\nconst B: f32 = 5e38;\n// x\u{2028}const C: f32 = 6e38;\u{2029}const D: f32 = 7e38;\u{000B}// y\u{0085}const E: f32 = 8e38;\u{000C}const F: f32 = 9e38;"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3, 5, 6, 8, 9]); + assert_eq!(findings[0].text, "4e38"); +} + +#[test] +fn wgsl_digits_inside_unicode_identifiers_are_not_literals() { + let shader = "const π1e39 = 1.0;\nconst é2e40: f32 = 2.0;\nconst A: f32 =\u{200E}1e39;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3]); + assert_eq!(findings[0].text, "1e39"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { From cf0f8cc77d1d0dfc31793d64cfd709cf4b10bb57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:40:24 -0800 Subject: [PATCH 016/490] craft-xtask: fix the Windows lock test, close piped stdin, ignore stderr write failures The test for a held workspace lock gave the second run a different first lock directory. On Windows the shared lock is workspace.lock in that first directory, so the set ran and the test failed. On Windows the run now shares the first directory and differs only in the later ones. run_cancelable closes a piped stdin after starting the child, as Command::status does for run, so a child that reads stdin to the end can exit. Diagnostics in runner.rs and lock.rs are written with a fallible write, so a closed stderr no longer panics before a command starts. --- crates/xtask/src/lib.rs | 7 ++++ crates/xtask/src/lock.rs | 8 ++-- crates/xtask/src/runner.rs | 73 +++++++++++++++++++++++++++++++++++-- crates/xtask/src/version.rs | 9 ++++- 4 files changed, 87 insertions(+), 10 deletions(-) diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index c65a545f23..dd5f905e0d 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -46,6 +46,13 @@ pub mod runner; #[cfg(feature = "version")] pub mod version; +/// Writes one diagnostic line to stderr. A failed write, such as one to a closed pipe, is ignored, so a +/// diagnostic never stops a run. +pub(crate) fn note(line: std::fmt::Arguments<'_>) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "{line}"); +} + /// Keeps the tests that start child processes apart from the tests that check whether a slot is free. /// A child holds copies of the parent's open files, and so its file locks, until it starts its program. #[cfg(test)] diff --git a/crates/xtask/src/lock.rs b/crates/xtask/src/lock.rs index 965b71408d..61fda1786d 100644 --- a/crates/xtask/src/lock.rs +++ b/crates/xtask/src/lock.rs @@ -112,7 +112,7 @@ fn record_owner(lock: &Path, label: &str) -> PathBuf { if let (Err(e), Err(w)) = (&removed, &written) && e.kind() != std::io::ErrorKind::NotFound { - eprintln!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display()); + crate::note(format_args!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display())); } owner_file } @@ -152,9 +152,9 @@ fn read_owner(path: &Path) -> Option { /// before any wait. pub fn acquire(config: &LockConfig, cancel: Option<&Cancel>) -> Result { acquire_with(config, cancel, || { - eprintln!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots); + crate::note(format_args!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots)); for h in holders(config).unwrap_or_default() { - eprintln!(" running: {h}"); + crate::note(format_args!(" running: {h}")); } }) } @@ -170,7 +170,7 @@ fn acquire_with(config: &LockConfig, cancel: Option<&Cancel>, on_wait: impl FnOn return Err(Error::Canceled { step: None }); } if let Some(held) = try_acquire(config)? { - eprintln!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64()); + crate::note(format_args!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64())); return Ok(held); } } diff --git a/crates/xtask/src/runner.rs b/crates/xtask/src/runner.rs index 459e9e8869..421a047c43 100644 --- a/crates/xtask/src/runner.rs +++ b/crates/xtask/src/runner.rs @@ -394,7 +394,7 @@ pub fn cargo(root: &Path) -> Command { /// /// Returns an error when the command cannot be started or exits with a failure status. pub fn run(mut cmd: Command, label: &str) -> Result<(), String> { - eprintln!("$ {label}"); + crate::note(format_args!("$ {label}")); let status = cmd.status().map_err(|e| spawn_error(label, &e))?; exit_result(label, status) } @@ -407,10 +407,10 @@ pub fn run(mut cmd: Command, label: &str) -> Result<(), String> { /// `kill -s KILL`. On Windows it ends the process tree with `taskkill /T /F`. When that tool cannot /// be run, only the child itself is ended. pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result<(), String> { - eprintln!("$ {label}"); + crate::note(format_args!("$ {label}")); #[cfg(unix)] std::os::unix::process::CommandExt::process_group(&mut cmd, 0); - let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?; + let mut child = spawn(&mut cmd, label)?; loop { if let Some(status) = child.try_wait().map_err(|e| format!("{label}: {e}"))? { return exit_result(label, status); @@ -444,6 +444,14 @@ fn end_tree(child: &mut Child) -> io::Result<()> { } } +/// Starts `cmd` and closes its stdin when the caller piped it, as `Command::status` does in [`run`], so +/// a child that reads stdin to the end can exit. +fn spawn(cmd: &mut Command, label: &str) -> Result { + let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?; + drop(child.stdin.take()); + Ok(child) +} + fn spawn_error(label: &str, e: &io::Error) -> String { format!("{label}: failed to spawn: {e}") } @@ -486,7 +494,7 @@ fn select_test( TestMode::PreferNextest => { let found = probe(); if !found { - eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + crate::note(format_args!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)")); } found } @@ -744,6 +752,8 @@ mod tests { const TREE_CHILD: &str = "CRAFT_XTASK_TREE_CHILD"; const BLOCKED_CHILD: &str = "CRAFT_XTASK_BLOCKED_CHILD"; const BYTES_CHILD: &str = "CRAFT_XTASK_BYTES_CHILD"; + const STDIN_CHILD: &str = "CRAFT_XTASK_STDIN_CHILD"; + const CLOSED_STDERR_CHILD: &str = "CRAFT_XTASK_CLOSED_STDERR_CHILD"; const RAW_BYTES: &[u8] = b"\xff\xfe\x00 not UTF-8 \x80\xc3\n"; /// This test binary, run as a child that runs only the ignored test `name`. @@ -785,6 +795,61 @@ mod tests { io::Read::read_to_end(&mut lines, &mut Vec::new()).expect("pipe end"); } + #[test] + fn spawn_closes_a_piped_stdin() { + let _guard = crate::spawn_guard(); + let mut cmd = test_child("runner::tests::stdin_child", STDIN_CHILD); + cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()); + // The child reads stdin to the end, so it exits only once the pipe is closed. A failed check + // drops the child's stdin with it, so the child still exits. + let mut child = spawn(&mut cmd, "stdin").expect("child"); + assert!(child.stdin.is_none(), "the child's stdin is still open"); + assert!(child.wait().expect("child").success()); + } + + #[test] + fn diagnostics_to_a_closed_stderr_do_not_panic() { + let _guard = crate::spawn_guard(); + let (reader, writer) = io::pipe().expect("pipe"); + drop(reader); + let mut child = test_child("runner::tests::closed_stderr_child", CLOSED_STDERR_CHILD); + child.stdout(Stdio::null()).stderr(writer); + let status = child.status().expect("child"); + assert!(status.success(), "the child failed with a closed stderr: {status}"); + } + + /// Reads stdin to the end; run by `spawn_closes_a_piped_stdin`. + #[test] + #[ignore = "child process of spawn_closes_a_piped_stdin"] + fn stdin_child() { + if std::env::var_os(STDIN_CHILD).is_some() { + io::Read::read_to_end(&mut io::stdin(), &mut Vec::new()).expect("stdin"); + } + } + + /// Prints every diagnostic to a stderr whose reading end is closed; run by + /// `diagnostics_to_a_closed_stderr_do_not_panic`. + #[test] + #[ignore = "child process of diagnostics_to_a_closed_stderr_do_not_panic"] + fn closed_stderr_child() { + if std::env::var_os(CLOSED_STDERR_CHILD).is_none() { + return; + } + let missing = "craft-xtask-test-no-such-program"; + assert!(run(Command::new(missing), "missing").is_err_and(|e| e.contains("failed to spawn"))); + assert!(run_cancelable(Command::new(missing), "missing", &Cancel::new()).is_err_and(|e| e.contains("failed to spawn"))); + assert!(select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &["--lib"], || false).is_ok()); + #[cfg(feature = "lock")] + { + let dir = tempfile::tempdir().expect("temp dir"); + let config = crate::lock::LockConfig::new(dir.path(), 1, "holder"); + let _held = crate::lock::try_acquire(&config).expect("lock").expect("free slot"); + let cancel = Cancel::new(); + cancel.cancel(); + assert_eq!(crate::lock::acquire(&config, Some(&cancel)).err(), Some(Error::Canceled { step: None })); + } + } + /// Starts a blocked child of its own, says `ready`, and blocks; run by `run_cancelable_ends_the_process_tree`. #[test] #[ignore = "child process of run_cancelable_ends_the_process_tree"] diff --git a/crates/xtask/src/version.rs b/crates/xtask/src/version.rs index ed166f0c70..6abde1dbfd 100644 --- a/crates/xtask/src/version.rs +++ b/crates/xtask/src/version.rs @@ -1029,10 +1029,15 @@ mod tests { let _guard = crate::spawn_guard(); let dir = workspace(MANIFEST, Some("old lock\n")); let other = base_lock(dir.path(), &test_lock_dir(dir.path())).unwrap().expect("free lock"); - // A run whose owner-labeled lock directories differ from the holder's still meets its lock. + // A run whose owner-labeled lock directories differ from the holder's still meets its lock. On + // Windows that lock is `workspace.lock` in the first directory, so only the later ones differ. let elsewhere = tempfile::tempdir().unwrap(); + #[cfg(windows)] + let dirs = [test_lock_dir(dir.path()), elsewhere.path().join("lock")]; + #[cfg(not(windows))] + let dirs = [elsewhere.path().join("lock")]; let ran = Cell::new(false); - let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[elsewhere.path().join("lock")]), &mut Vec::new(), || { + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || { ran.set(true); Ok(()) }); From a01bfbd6de1a407ba70be794248473b209f26a32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:52:25 -0800 Subject: [PATCH 017/490] craft-testkit: add the mcp feature, an MCP stdio test client with deadlines and line limits McpChild::spawn(path, args, env) starts an MCP server with an environment list for the child only; McpChild::connect uses any reader and writer. initialize(version), request, call_tool, list_tools, notify, take_notifications and close(), which returns the exit status and whether the child had to be stopped. Every wait has a deadline and every stdout line a length limit, both in McpLimits with documented defaults (64 MiB, 30 s, 60 s for initialize, 2 s close grace). A deadline, an over-long line, a stdout line that is not JSON-RPC 2.0 or a malformed reply closes the connection and stops the child; an error reply returns its code, message and data and leaves the connection usable. The child's pings get an empty result and its other requests error -32601. stderr goes to the null device unless a bounded tail is asked for. The cases of craft-ai-integrations' child_tests.rs are moved in under their own names; tests that start a real child run in a harness = false target that re-runs itself as the server. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 16 + crates/testkit/README.md | 62 ++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/mcp.rs | 878 ++++++++++++++++++++++++ crates/testkit/tests/mcp.rs | 435 ++++++++++++ crates/testkit/tests/mcp_child.rs | 17 + crates/testkit/tests/mcp_child/child.rs | 160 +++++ 8 files changed, 1577 insertions(+) create mode 100644 crates/testkit/src/mcp.rs create mode 100644 crates/testkit/tests/mcp.rs create mode 100644 crates/testkit/tests/mcp_child.rs create mode 100644 crates/testkit/tests/mcp_child/child.rs diff --git a/Cargo.lock b/Cargo.lock index fab3c89a3d..5ec7cc7b14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2576,6 +2576,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "serde_json", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..7819ddd0ed 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,23 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# `mcp::McpChild`: an MCP stdio test client. +mcp = ["dep:serde_json"] + [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +serde_json = { workspace = true, optional = true } + +[[test]] +name = "mcp" +required-features = ["mcp"] + +[[test]] +name = "mcp_child" +harness = false +required-features = ["mcp"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index ff159f4da1..2143dc5b11 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,68 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`, under any name. The parts of a path may be split by whitespace, comments or line breaks. Other crates' `Instant` (such as `web_time::Instant` or `tokio::time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`; code before that attribute or after its item on the same line is still checked. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## MCP test client: `mcp` + +The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The module is built on every target except `wasm32`, and it opens no network connection. + +`McpChild::spawn(path, args, env)` starts an MCP server program with its stdin and stdout piped. The variables in `env` are set for the child only; the test process's environment is not changed. `McpChild::connect(reader, writer, limits)` talks to a server that runs in the test process. Each message is one line of JSON-RPC 2.0, as the [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) describes. + +| Call | What it does | +|---|---| +| `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), waits for the reply, then sends `notifications/initialized`. A reply with another version returns `UnsupportedVersion` and closes the connection. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | +| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | +| `notify(method, params)` | Sends a notification, which has no id and gets no reply. | +| `take_notifications()` | Returns the notifications kept so far without waiting. | +| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. | + +While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error, close the connection and stop the child; later calls return `Closed`. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics. + +`McpLimits` holds the limits. These defaults are the crate's own values: + +| Field | Default | Range | +|---|---|---| +| `max_line_bytes` | 64 MiB, for one stdout line and for the whole `list_tools` result | at least 1 | +| `request_timeout` | 30 s | more than zero, at most 1 hour | +| `initialize_timeout` | 60 s | more than zero, at most 1 hour | +| `close_grace` | 2 s | at most 1 hour | +| `max_pages` | 64 | at least 1 | +| `max_notifications` | 0 (notifications are not kept); the oldest is dropped when the queue is full | at most 4096 | +| `stderr_tail_bytes` | 0 (stderr goes to the null device); otherwise the last bytes written are kept | at most 16 MiB | + +`McpLimits::timeouts_from_var(name)` sets both deadlines from a variable that holds a whole number of seconds from 1 to 3600; `mcp::TIMEOUT_VAR` (`CRAFT_TEST_MCP_TIMEOUT_SECS`) is the default name. Any other value returns an error. + +```rust +use craft_testkit::mcp::{McpChild, PROTOCOL_VERSION}; + +let mut mcp = McpChild::spawn(env!("CARGO_BIN_EXE_my-cli"), ["mcp"], [("MYCRAFT_CONFIG_DIR", dir.path())])?; +mcp.initialize(PROTOCOL_VERSION)?; +let result = mcp.call_tool("doc.new", serde_json::json!({}))?; +assert_eq!(result["isError"], false); +assert!(mcp.close()?.status.is_some_and(|s| s.success())); +``` + +The tests that start a real child are in `tests/mcp_child.rs`, a target with `harness = false`: the child is that test program, and the standard harness writes its own lines on stdout. Both test targets build to nothing on `wasm32`. + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `mcp` | storytold/craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs` (`Conn`, `request`, `call_tool`, `MAX_LINE`, deadlines) and the 14 tests of `child_tests.rs`, written again here | `e8b31cb0` | +| `mcp` | storytold/vectorcraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | `460d2119` | +| `mcp` | storytold/photocraft | `apps/photocraft-cli/tests/it/cli.rs` (`mcp_recv`) | `58d11d91` | + +### Migration + +| Consumer | Helper | State | +|---|---|---| +| VectorCraft | `apps/vectorcraft-cli/tests/it/mcp_e2e.rs` | Not switched | +| PhotoCraft | `apps/photocraft-cli/tests/it/cli.rs` | Not switched | +| CADCraft, DeckCraft, DesignCraft, EffectCraft | the MCP helpers in their CLI tests | Not switched | +| FigCraft, FilmCraft, GridCraft, LightCraft, PdfCraft, SoundCraft | the MCP helpers in their CLI tests | Not switched | +| craft-ai-integrations | `crates/ai-mcp/src/apps/child.rs`, production code | Kept as it is | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..2697566098 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! With the `mcp` feature, on targets other than `wasm32`, `mcp::McpChild` runs an MCP server as a +//! child process and talks to it over stdin and stdout, with a deadline on every wait and a length +//! limit on every line it reads. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))] +pub mod mcp; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs new file mode 100644 index 0000000000..eedf52c694 --- /dev/null +++ b/crates/testkit/src/mcp.rs @@ -0,0 +1,878 @@ +//! A test client for an MCP server that runs as a child process and exchanges JSON-RPC 2.0 +//! messages, one per line, on the child's stdin and stdout. +//! +//! [`McpChild::spawn`] starts the program with an environment list for the child only; +//! [`McpChild::connect`] uses any reader and writer, for a server that runs in the test process. +//! Every wait has a deadline and every line read from the child has a length limit, both set in +//! [`McpLimits`]. A child that does not answer makes the call return [`McpError::Deadline`]; the +//! call does not hang. +//! +//! After a deadline, a protocol error, an over-long line or the end of the child's output, the +//! connection is closed: the child is stopped and reaped, and later calls return +//! [`McpError::Closed`]. A JSON-RPC error reply returns [`McpError::Rpc`] and the connection stays +//! usable. A tool result with `isError: true` is a successful reply and is returned unchanged. + +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::process::{Child, ChildStderr, Command, ExitStatus, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TryRecvError, TrySendError, sync_channel}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use serde_json::{Map, Value, json}; + +/// The MCP revision the Craft applications' servers speak today. +pub const PROTOCOL_VERSION: &str = "2025-06-18"; +/// The default name of the variable read by [`McpLimits::timeouts_from_var`]. +pub const TIMEOUT_VAR: &str = "CRAFT_TEST_MCP_TIMEOUT_SECS"; +/// The longest deadline or close grace period [`McpLimits`] accepts. +pub const MAX_TIMEOUT: Duration = Duration::from_secs(3600); +/// The most notifications [`McpLimits::max_notifications`] may keep. +pub const MAX_NOTIFICATIONS: usize = 4096; +/// The most bytes of stderr [`McpLimits::stderr_tail_bytes`] may keep. +pub const MAX_STDERR_TAIL: usize = 16 << 20; + +/// Parsed messages the reader thread holds before the client takes them. When the queue is full, +/// the reader thread waits, and so does a child writing more. +const READ_QUEUE: usize = 4; +/// Lines waiting for the writer thread. A full queue means the child stopped reading its input. +const WRITE_QUEUE: usize = 64; +/// How often [`McpChild::close`] checks whether the child has exited. +const EXIT_POLL: Duration = Duration::from_millis(10); +/// Bytes of an unreadable stdout line quoted in a protocol error. +const PREVIEW: usize = 80; +/// The JSON-RPC error code for a method the client does not offer. +const METHOD_NOT_FOUND: i64 = -32601; + +/// Limits and deadlines of one connection. [`McpChild::spawn`] and [`McpChild::connect`] return +/// [`McpError::Setup`] for a value out of range. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct McpLimits { + /// The longest stdout line read, without its newline, and the most bytes of JSON + /// [`McpChild::list_tools`] returns in all. Default 64 MiB; must be at least 1. + pub max_line_bytes: usize, + /// How long [`McpChild::request`], [`McpChild::call_tool`] and each page of + /// [`McpChild::list_tools`] wait for the reply. Default 30 s; from 1 ns to [`MAX_TIMEOUT`]. + pub request_timeout: Duration, + /// How long [`McpChild::initialize`] waits. Default 60 s; from 1 ns to [`MAX_TIMEOUT`]. + pub initialize_timeout: Duration, + /// How long [`McpChild::close`] waits for the child to exit after closing its stdin before it + /// stops the child. Default 2 s; at most [`MAX_TIMEOUT`]. + pub close_grace: Duration, + /// The most pages [`McpChild::list_tools`] reads. Default 64; must be at least 1. + pub max_pages: usize, + /// The most notifications kept for [`McpChild::take_notifications`]; when the queue is full, + /// the oldest is dropped. Default 0, which keeps none; at most [`MAX_NOTIFICATIONS`]. + pub max_notifications: usize, + /// The most bytes of the child's stderr kept, the last ones written. Default 0, which sends + /// stderr to the null device; at most [`MAX_STDERR_TAIL`]. Not used by [`McpChild::connect`]. + pub stderr_tail_bytes: usize, +} + +impl Default for McpLimits { + fn default() -> Self { + Self { + max_line_bytes: 64 << 20, + request_timeout: Duration::from_secs(30), + initialize_timeout: Duration::from_secs(60), + close_grace: Duration::from_secs(2), + max_pages: 64, + max_notifications: 0, + stderr_tail_bytes: 0, + } + } +} + +impl McpLimits { + /// Sets [`McpLimits::request_timeout`] and [`McpLimits::initialize_timeout`] from the variable + /// `name` ([`TIMEOUT_VAR`] by default), a whole number of seconds from 1 to 3600. An unset + /// variable leaves the limits unchanged; any other value, and a name that is empty or holds `=` + /// or NUL, returns [`McpError::Setup`]. + pub fn timeouts_from_var(mut self, name: &str) -> Result { + if name.is_empty() || name.contains(['=', '\0']) { + return Err(McpError::Setup(format!("{name:?} is not a variable name"))); + } + let Some(value) = std::env::var_os(name) else { return Ok(self) }; + let timeout = parse_timeout_secs(name, &value)?; + self.request_timeout = timeout; + self.initialize_timeout = timeout; + Ok(self) + } + + fn validate(&self) -> Result<(), McpError> { + if self.max_line_bytes == 0 { + return Err(McpError::Setup("max_line_bytes must be at least 1".into())); + } + check_timeout("request_timeout", self.request_timeout)?; + check_timeout("initialize_timeout", self.initialize_timeout)?; + if self.close_grace > MAX_TIMEOUT { + return Err(McpError::Setup(format!("close_grace must be at most {MAX_TIMEOUT:?}"))); + } + if self.max_pages == 0 { + return Err(McpError::Setup("max_pages must be at least 1".into())); + } + if self.max_notifications > MAX_NOTIFICATIONS { + return Err(McpError::Setup(format!("max_notifications must be at most {MAX_NOTIFICATIONS}"))); + } + if self.stderr_tail_bytes > MAX_STDERR_TAIL { + return Err(McpError::Setup(format!("stderr_tail_bytes must be at most {MAX_STDERR_TAIL}"))); + } + Ok(()) + } +} + +fn check_timeout(what: &str, timeout: Duration) -> Result<(), McpError> { + if timeout.is_zero() || timeout > MAX_TIMEOUT { + return Err(McpError::Setup(format!("{what} must be more than zero and at most {MAX_TIMEOUT:?}"))); + } + Ok(()) +} + +fn parse_timeout_secs(name: &str, value: &OsStr) -> Result { + let bad = || McpError::Setup(format!("{name} must be a whole number of seconds from 1 to {}, not {value:?}", MAX_TIMEOUT.as_secs())); + let text = value.to_str().ok_or_else(bad)?; + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return Err(bad()); + } + let secs: u64 = text.parse().map_err(|_| bad())?; + if secs == 0 || secs > MAX_TIMEOUT.as_secs() { + return Err(bad()); + } + Ok(Duration::from_secs(secs)) +} + +/// Why a call failed. +#[derive(Debug)] +#[non_exhaustive] +pub enum McpError { + /// A limit, a timeout, an environment pair or a variable is not valid. Nothing was started. + Setup(String), + /// The program could not be started. + Spawn { + /// The program as given to [`McpChild::spawn`]. + program: OsString, + /// The error from the operating system. + source: io::Error, + }, + /// Reading from, writing to or waiting for the child failed. + Io { + /// What failed, such as "writing to the child". + what: &'static str, + /// The underlying error. + source: io::Error, + }, + /// The reply to `method` did not arrive within `after`. + Deadline { + /// The method of the request. + method: String, + /// The deadline that passed. + after: Duration, + }, + /// The child wrote a stdout line longer than `limit` bytes. + LineTooLong { + /// [`McpLimits::max_line_bytes`]. + limit: usize, + }, + /// The child closed its stdout. + Ended, + /// The child wrote something on stdout that is not a JSON-RPC 2.0 message, or a reply that + /// does not hold exactly one of `result` and `error`. + Protocol(String), + /// The child answered `method` with a JSON-RPC error. The connection stays usable. + Rpc { + /// The method of the request. + method: String, + /// The error's `code`. + code: i64, + /// The error's `message`. + message: String, + /// The error's `data`, when present. + data: Option, + }, + /// The child answered `initialize` with a protocol version other than the one asked for. + UnsupportedVersion { + /// The version sent in `initialize`. + requested: String, + /// The version in the child's reply. + returned: String, + }, + /// [`McpChild::list_tools`] read [`McpLimits::max_pages`] pages and the list went on. + TooManyPages { + /// [`McpLimits::max_pages`]. + limit: usize, + }, + /// The tools [`McpChild::list_tools`] read add up to more than `limit` bytes of JSON. + ToolListTooLarge { + /// [`McpLimits::max_line_bytes`]. + limit: usize, + }, + /// An earlier failure closed the connection; this is its message. + Closed(String), +} + +impl fmt::Display for McpError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Setup(why) => write!(f, "invalid MCP test setup: {why}"), + Self::Spawn { program, source } => write!(f, "could not start {}: {source}", program.to_string_lossy()), + Self::Io { what, source } => write!(f, "{what} failed: {source}"), + Self::Deadline { method, after } => write!(f, "the child did not answer `{method}` within {after:?}"), + Self::LineTooLong { limit } => write!(f, "the child wrote a line longer than {limit} bytes"), + Self::Ended => write!(f, "the child closed its output"), + Self::Protocol(why) => write!(f, "MCP protocol error: {why}"), + Self::Rpc { method, code, message, .. } => write!(f, "`{method}` returned error {code}: {message}"), + Self::UnsupportedVersion { requested, returned } => { + write!(f, "asked for MCP version {requested}, and the child answered with {returned}") + } + Self::TooManyPages { limit } => write!(f, "the tool list did not end within {limit} pages"), + Self::ToolListTooLarge { limit } => write!(f, "the tool list is larger than {limit} bytes"), + Self::Closed(why) => write!(f, "the MCP connection is closed: {why}"), + } + } +} + +impl std::error::Error for McpError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Spawn { source, .. } | Self::Io { source, .. } => Some(source), + _ => None, + } + } +} + +/// How [`McpChild::close`] ended the child. +#[derive(Debug)] +pub struct CloseOutcome { + /// The child's exit status; `None` for a connection made with [`McpChild::connect`]. + pub status: Option, + /// The child was stopped because it did not exit within [`McpLimits::close_grace`], or an + /// earlier failure stopped it. + pub forced: bool, + /// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr. + pub stderr: Vec, +} + +/// What the reader and writer threads hand to the client. +enum Incoming { + Message(Value), + TooLong, + Ended, + Invalid(String), + ReadFailed(io::Error), + WriteFailed(io::Error), +} + +enum LineError { + TooLong, + Io(io::Error), +} + +/// Reads one line of at most `cap` bytes, without its newline. `Ok(None)` at the end of the +/// stream. A line is rejected as soon as it passes `cap`, without waiting for its newline, and at +/// most `cap` bytes of it are kept. +fn read_line_capped(r: &mut impl BufRead, cap: usize) -> Result>, LineError> { + let mut line = Vec::new(); + loop { + let buf = match r.fill_buf() { + Ok(buf) => buf, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => return Err(LineError::Io(e)), + }; + if buf.is_empty() { + return Ok(if line.is_empty() { None } else { Some(line) }); + } + let (chunk, used, done) = match buf.iter().position(|b| *b == b'\n') { + Some(i) => (&buf[..i], i + 1, true), + None => (buf, buf.len(), false), + }; + if line.len().saturating_add(chunk.len()) > cap { + return Err(LineError::TooLong); + } + line.extend_from_slice(chunk); + r.consume(used); + if done { + return Ok(Some(line)); + } + } +} + +/// Parses one stdout line as a JSON-RPC 2.0 message object. +fn parse_line(line: &[u8]) -> Incoming { + let preview = || String::from_utf8_lossy(&line[..line.len().min(PREVIEW)]).into_owned(); + match serde_json::from_slice::(line) { + Ok(v) if v.get("jsonrpc").and_then(Value::as_str) == Some("2.0") => Incoming::Message(v), + Ok(_) => Incoming::Invalid(format!("a stdout line is not a JSON-RPC 2.0 message: {}", preview())), + Err(e) => Incoming::Invalid(format!("a stdout line is not JSON ({e}): {}", preview())), + } +} + +fn start_thread(name: &str, f: impl FnOnce() + Send + 'static) -> Result<(), McpError> { + std::thread::Builder::new().name(name.into()).spawn(f).map(drop).map_err(|source| McpError::Io { what: "starting a client thread", source }) +} + +/// The last bytes of the child's stderr, kept by a thread that reads it until it ends. +struct StderrTail { + bytes: Arc>>, + done: Receiver<()>, +} + +impl StderrTail { + fn start(mut stderr: ChildStderr, keep: usize) -> Result { + let bytes: Arc>> = Arc::default(); + let (done_tx, done) = sync_channel(1); + let store = Arc::clone(&bytes); + start_thread("craft-testkit-mcp-stderr", move || { + let mut chunk = [0u8; 8192]; + loop { + let n = match stderr.read(&mut chunk) { + Ok(0) => break, + Ok(n) => n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, + }; + let mut tail = store.lock().unwrap_or_else(PoisonError::into_inner); + tail.extend(chunk.iter().take(n)); + let extra = tail.len().saturating_sub(keep); + tail.drain(..extra); + } + let _ = done_tx.try_send(()); + })?; + Ok(Self { bytes, done }) + } + + fn copy(&self) -> Vec { + self.bytes.lock().unwrap_or_else(PoisonError::into_inner).iter().copied().collect() + } +} + +/// A connection to an MCP server. Dropping it stops and reaps a child that is still running. +pub struct McpChild { + /// Lines for the writer thread. `None` once the connection is closed, which ends the thread + /// and closes the child's stdin. + writer: Option>>, + rx: Receiver, + next_id: u64, + limits: McpLimits, + child: Option, + /// The exit status of a child already reaped, and whether it was stopped. + exit: Option<(ExitStatus, bool)>, + closed: Option, + notifications: VecDeque, + stderr: Option, +} + +impl fmt::Debug for McpChild { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("McpChild").field("next_id", &self.next_id).field("closed", &self.closed).finish_non_exhaustive() + } +} + +impl McpChild { + /// Starts `path` with `args` and, for the child only, the variables in `env`, with + /// [`McpLimits::default`]. The process's own environment is not changed. + pub fn spawn( + path: impl AsRef, + args: impl IntoIterator>, + env: impl IntoIterator, + ) -> Result + where + K: AsRef, + V: AsRef, + { + Self::spawn_with_limits(path, args, env, McpLimits::default()) + } + + /// [`McpChild::spawn`] with the given limits. A variable name that is empty or holds `=` or + /// NUL, or a value that holds NUL, returns [`McpError::Setup`]. + pub fn spawn_with_limits( + path: impl AsRef, + args: impl IntoIterator>, + env: impl IntoIterator, + limits: McpLimits, + ) -> Result + where + K: AsRef, + V: AsRef, + { + limits.validate()?; + let program = path.as_ref(); + let mut cmd = Command::new(program); + cmd.args(args); + for (key, value) in env { + let (key, value) = (key.as_ref(), value.as_ref()); + let key_bytes = key.as_encoded_bytes(); + if key_bytes.is_empty() || key_bytes.contains(&b'=') || key_bytes.contains(&0) { + return Err(McpError::Setup(format!("{key:?} is not a variable name"))); + } + if value.as_encoded_bytes().contains(&0) { + return Err(McpError::Setup(format!("the value of {key:?} holds NUL"))); + } + cmd.env(key, value); + } + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()); + cmd.stderr(if limits.stderr_tail_bytes == 0 { Stdio::null() } else { Stdio::piped() }); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + /// Starts a console program without opening a console window. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|source| McpError::Spawn { program: program.to_os_string(), source })?; + let started = Self::attach(&mut child, limits); + match started { + Ok(mut conn) => { + conn.child = Some(child); + Ok(conn) + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + Err(e) + } + } + } + + fn attach(child: &mut Child, limits: McpLimits) -> Result { + let missing = || McpError::Io { what: "connecting to the child", source: io::Error::other("a pipe was not opened") }; + let stdin = child.stdin.take().ok_or_else(missing)?; + let stdout = child.stdout.take().ok_or_else(missing)?; + let stderr = match child.stderr.take() { + Some(stderr) if limits.stderr_tail_bytes > 0 => Some(StderrTail::start(stderr, limits.stderr_tail_bytes)?), + _ => None, + }; + let mut conn = Self::start(stdout, stdin, limits)?; + conn.stderr = stderr; + Ok(conn) + } + + /// Connects to a server that reads `writer` and writes `reader`, such as one running on a + /// thread of the test. [`McpLimits::stderr_tail_bytes`] is not used. + pub fn connect(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { + limits.validate()?; + Self::start(reader, writer, limits) + } + + fn start(reader: impl Read + Send + 'static, writer: impl Write + Send + 'static, limits: McpLimits) -> Result { + let (tx, rx) = sync_channel(READ_QUEUE); + let write_failed = tx.clone(); + let cap = limits.max_line_bytes; + start_thread("craft-testkit-mcp-read", move || { + let mut r = BufReader::new(reader); + loop { + let incoming = match read_line_capped(&mut r, cap) { + Ok(None) => Incoming::Ended, + Ok(Some(line)) if line.iter().all(u8::is_ascii_whitespace) => continue, + Ok(Some(line)) => parse_line(&line), + Err(LineError::TooLong) => Incoming::TooLong, + Err(LineError::Io(e)) => Incoming::ReadFailed(e), + }; + let last = !matches!(incoming, Incoming::Message(_)); + if tx.send(incoming).is_err() || last { + return; + } + } + })?; + let (wtx, wrx) = sync_channel::>(WRITE_QUEUE); + start_thread("craft-testkit-mcp-write", move || { + let mut w = writer; + for line in wrx { + if let Err(e) = w.write_all(&line).and_then(|()| w.flush()) { + // Wakes a request waiting for its reply. Ends when the client is dropped. + let _ = write_failed.send(Incoming::WriteFailed(e)); + return; + } + } + })?; + Ok(Self { writer: Some(wtx), rx, next_id: 1, limits, child: None, exit: None, closed: None, notifications: VecDeque::new(), stderr: None }) + } + + /// The message of the failure that closed the connection, or `None` while it is usable. + pub fn closed(&self) -> Option<&str> { + self.closed.as_deref() + } + + /// The last bytes the child wrote on stderr so far (see [`McpLimits::stderr_tail_bytes`]). + pub fn stderr_tail(&self) -> Vec { + self.stderr.as_ref().map(StderrTail::copy).unwrap_or_default() + } + + /// Sends `initialize` with `version` (for example [`PROTOCOL_VERSION`]), empty capabilities and + /// this crate's client info, waits up to [`McpLimits::initialize_timeout`] for the reply, then + /// sends `notifications/initialized`. Returns the reply's result. A reply with another protocol + /// version returns [`McpError::UnsupportedVersion`] and closes the connection. + pub fn initialize(&mut self, version: &str) -> Result { + let params = json!({ + "protocolVersion": version, + "capabilities": {}, + "clientInfo": {"name": env!("CARGO_PKG_NAME"), "version": env!("CARGO_PKG_VERSION")}, + }); + let result = self.request_within("initialize", params, self.limits.initialize_timeout)?; + let returned = match result.get("protocolVersion").and_then(Value::as_str) { + Some(returned) => returned.to_string(), + None => return Err(self.fail(McpError::Protocol("the `initialize` result has no `protocolVersion`".into()))), + }; + if returned != version { + return Err(self.fail(McpError::UnsupportedVersion { requested: version.to_string(), returned })); + } + self.notify("notifications/initialized", Value::Null)?; + Ok(result) + } + + /// Sends a notification: a message without an id, to which the child sends no reply. + /// `Value::Null` params are left out of the message. + pub fn notify(&mut self, method: &str, params: Value) -> Result<(), McpError> { + self.check_open()?; + self.send(&Value::Object(message(method, params))) + } + + /// Sends a request and waits up to [`McpLimits::request_timeout`] for the reply with its id. + /// Returns the reply's `result`. `Value::Null` params are left out of the message. + pub fn request(&mut self, method: &str, params: Value) -> Result { + self.request_within(method, params, self.limits.request_timeout) + } + + /// [`McpChild::request`] with its own deadline, from 1 ns to [`MAX_TIMEOUT`]. + /// + /// While it waits, it answers the child's `ping` requests with an empty result and its other + /// requests with error -32601, keeps notifications for [`McpChild::take_notifications`], and + /// skips replies with another id. None of these extend the deadline. + pub fn request_within(&mut self, method: &str, params: Value, timeout: Duration) -> Result { + self.check_open()?; + check_timeout("the request deadline", timeout)?; + let deadline = Instant::now().checked_add(timeout).ok_or_else(|| McpError::Setup("the request deadline is too far away".into()))?; + let id = self.next_id; + self.next_id = self.next_id.saturating_add(1); + let mut msg = message(method, params); + msg.insert("id".into(), json!(id)); + self.send(&Value::Object(msg))?; + loop { + let left = deadline.checked_duration_since(Instant::now()).filter(|left| !left.is_zero()); + let Some(left) = left else { + return Err(self.fail(McpError::Deadline { method: method.to_string(), after: timeout })); + }; + let incoming = match self.rx.recv_timeout(left) { + Ok(incoming) => incoming, + Err(RecvTimeoutError::Timeout) => return Err(self.fail(McpError::Deadline { method: method.to_string(), after: timeout })), + Err(RecvTimeoutError::Disconnected) => return Err(self.fail(McpError::Ended)), + }; + let v = self.receive(incoming)?; + if let Some(reply) = self.route(v, Some(id))? { + return self.reply(method, reply); + } + } + } + + /// Calls the tool `name` with `arguments` (`tools/call`) and returns its result unchanged, + /// `content` and `isError` included. + pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result { + self.request("tools/call", json!({"name": name, "arguments": arguments})) + } + + /// [`McpChild::call_tool`] with its own deadline. + pub fn call_tool_within(&mut self, name: &str, arguments: Value, timeout: Duration) -> Result { + self.request_within("tools/call", json!({"name": name, "arguments": arguments}), timeout) + } + + /// Every tool the child lists, following `nextCursor` for at most [`McpLimits::max_pages`] + /// pages. The entries are returned as the child sent them. A list that goes on past the + /// limit returns [`McpError::TooManyPages`]. Tools whose JSON text adds up to more than + /// [`McpLimits::max_line_bytes`] return [`McpError::ToolListTooLarge`]. + pub fn list_tools(&mut self) -> Result, McpError> { + let mut tools = Vec::new(); + let mut total = 0usize; + let mut cursor: Option = None; + for _ in 0..self.limits.max_pages { + let params = cursor.take().map_or(Value::Null, |c| json!({"cursor": c})); + let mut page = self.request("tools/list", params)?; + let Some(list) = page.get_mut("tools").and_then(Value::as_array_mut) else { + return Err(self.fail(McpError::Protocol("a `tools/list` result has no `tools` array".into()))); + }; + let mut count = ByteCount(0); + for tool in list.iter() { + // Writing into a counter does not fail. + let _ = serde_json::to_writer(&mut count, tool); + } + total = total.saturating_add(count.0); + if total > self.limits.max_line_bytes { + return Err(McpError::ToolListTooLarge { limit: self.limits.max_line_bytes }); + } + tools.append(list); + cursor = match page.get("nextCursor") { + None | Some(Value::Null) => return Ok(tools), + Some(Value::String(next)) => Some(next.clone()), + Some(_) => return Err(self.fail(McpError::Protocol("a `tools/list` result has a `nextCursor` that is not a string".into()))), + }; + } + Err(McpError::TooManyPages { limit: self.limits.max_pages }) + } + + /// Takes the messages already received without waiting: answers the child's requests as + /// [`McpChild::request_within`] does and returns the notifications kept so far, oldest first. + /// One call handles at most as many messages as the reader thread queues, so a child that + /// keeps writing does not keep it running. A failure found here closes the connection, and + /// [`McpChild::closed`] reports it. + pub fn take_notifications(&mut self) -> Vec { + // The reader's queue and the writer thread's failure message. + for _ in 0..=READ_QUEUE { + if self.closed.is_some() { + break; + } + let incoming = match self.rx.try_recv() { + Ok(incoming) => incoming, + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + self.fail(McpError::Ended); + break; + } + }; + let Ok(v) = self.receive(incoming) else { break }; + if self.route(v, None).is_err() { + break; + } + } + self.notifications.drain(..).collect() + } + + /// Closes the child's stdin, waits up to [`McpLimits::close_grace`] for it to exit, then stops + /// it, and returns its exit status. For a connection made with [`McpChild::connect`], it ends + /// the writer thread, which drops the writer once the lines already queued are written, and + /// returns no status without waiting for that thread. A writer blocked on a server that has + /// stopped reading stays with the thread until the server drops its reading end. + pub fn close(mut self) -> Result { + self.writer = None; + let grace = self.limits.close_grace; + let (status, forced) = match self.child.take() { + Some(mut child) => match reap(&mut child, grace) { + Ok((status, forced)) => (Some(status), forced), + Err(source) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(McpError::Io { what: "waiting for the child", source }); + } + }, + None => self.exit.map_or((None, false), |(status, forced)| (Some(status), forced)), + }; + let stderr = match &self.stderr { + Some(tail) => { + let _ = tail.done.recv_timeout(grace); + tail.copy() + } + None => Vec::new(), + }; + Ok(CloseOutcome { status, forced, stderr }) + } + + fn check_open(&self) -> Result<(), McpError> { + match &self.closed { + Some(why) => Err(McpError::Closed(why.clone())), + None => Ok(()), + } + } + + fn send(&mut self, msg: &Value) -> Result<(), McpError> { + let Some(writer) = &self.writer else { return Err(McpError::Closed(self.closed.clone().unwrap_or_default())) }; + let mut line = serde_json::to_vec(msg).map_err(|e| McpError::Protocol(format!("a message could not be written as JSON: {e}")))?; + line.push(b'\n'); + // Never waits for room: a child that stops reading fills the queue, and the connection is + // closed then. + match writer.try_send(line) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => Err(self.fail(McpError::Io { + what: "writing to the child", + source: io::Error::new(io::ErrorKind::WouldBlock, "the child stopped reading its input"), + })), + Err(TrySendError::Disconnected(_)) => { + Err(self.fail(McpError::Io { what: "writing to the child", source: io::Error::from(io::ErrorKind::BrokenPipe) })) + } + } + } + + /// Turns what the threads handed over into a message, or closes the connection. + fn receive(&mut self, incoming: Incoming) -> Result { + Err(self.fail(match incoming { + Incoming::Message(v) => return Ok(v), + Incoming::TooLong => McpError::LineTooLong { limit: self.limits.max_line_bytes }, + Incoming::Ended => McpError::Ended, + Incoming::Invalid(why) => McpError::Protocol(why), + Incoming::ReadFailed(source) => McpError::Io { what: "reading from the child", source }, + Incoming::WriteFailed(source) => McpError::Io { what: "writing to the child", source }, + })) + } + + /// Handles one message: answers a request from the child, keeps a notification, skips a reply + /// to another id, and returns the reply to `waiting`. + fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { + match (v.get("method"), v.get("id")) { + (Some(Value::String(method)), Some(id)) => { + let reply = if method == "ping" { + json!({"jsonrpc": "2.0", "id": id, "result": {}}) + } else { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": METHOD_NOT_FOUND, "message": "Method not found"}}) + }; + self.send(&reply)?; + Ok(None) + } + (Some(Value::String(_)), None) => { + if self.limits.max_notifications > 0 { + if self.notifications.len() >= self.limits.max_notifications { + self.notifications.pop_front(); + } + self.notifications.push_back(v); + } + Ok(None) + } + (Some(_), _) => Err(self.fail(McpError::Protocol("a message has a `method` that is not a string".into()))), + (None, Some(id)) => Ok((waiting.is_some() && id.as_u64() == waiting).then_some(v)), + (None, None) => Err(self.fail(McpError::Protocol("a message has neither `method` nor `id`".into()))), + } + } + + /// The result of the reply to `method`, or its error. + fn reply(&mut self, method: &str, mut v: Value) -> Result { + let malformed = || McpError::Protocol(format!("the reply to `{method}` does not hold exactly one of `result` and a valid `error`")); + let Some(obj) = v.as_object_mut() else { return Err(self.fail(malformed())) }; + match (obj.remove("result"), obj.remove("error")) { + (Some(result), None) => Ok(result), + (None, Some(Value::Object(mut error))) => { + let code = error.get("code").and_then(Value::as_i64); + let message = error.get("message").and_then(Value::as_str).map(str::to_string); + match (code, message) { + (Some(code), Some(message)) => Err(McpError::Rpc { method: method.to_string(), code, message, data: error.remove("data") }), + _ => Err(self.fail(malformed())), + } + } + _ => Err(self.fail(malformed())), + } + } + + /// Closes the connection with `err`: ends the writer, which closes the child's stdin, and stops + /// and reaps the child. A child that closed its output or input gets + /// [`McpLimits::close_grace`] to exit first. + fn fail(&mut self, err: McpError) -> McpError { + if self.closed.is_none() { + self.closed = Some(err.to_string()); + } + self.writer = None; + if let Some(mut child) = self.child.take() { + let grace = match err { + McpError::Ended | McpError::Io { .. } => self.limits.close_grace, + _ => Duration::ZERO, + }; + match reap(&mut child, grace) { + Ok(exit) => self.exit = Some(exit), + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + } + } + } + err + } +} + +impl Drop for McpChild { + fn drop(&mut self) { + self.writer = None; + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +/// A writer that only counts the bytes written to it. +struct ByteCount(usize); + +impl Write for ByteCount { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0 = self.0.saturating_add(buf.len()); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// A JSON-RPC 2.0 message for `method`; `Value::Null` params are left out. +fn message(method: &str, params: Value) -> Map { + let mut msg = Map::new(); + msg.insert("jsonrpc".into(), json!("2.0")); + msg.insert("method".into(), json!(method)); + if !params.is_null() { + msg.insert("params".into(), params); + } + msg +} + +/// Waits up to `grace` for the child to exit, then stops it. Returns its status and whether it +/// was stopped. +fn reap(child: &mut Child, grace: Duration) -> io::Result<(ExitStatus, bool)> { + let deadline = Instant::now().checked_add(grace); + loop { + if let Some(status) = child.try_wait()? { + return Ok((status, false)); + } + let left = deadline.and_then(|d| d.checked_duration_since(Instant::now())).filter(|left| !left.is_zero()); + let Some(left) = left else { break }; + std::thread::sleep(left.min(EXIT_POLL)); + } + match child.kill() { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::InvalidInput => {} + Err(e) => return Err(e), + } + Ok((child.wait()?, true)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn capped_line_reader() { + let mut r = io::Cursor::new(b"abc\nabcdefgh\nxy".to_vec()); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(Some(b"abc".to_vec()))); + assert!(matches!(read_line_capped(&mut r, 4), Err(LineError::TooLong))); + let mut r = io::Cursor::new(b"xy".to_vec()); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(Some(b"xy".to_vec())), "a last line without a newline"); + assert_eq!(read_line_capped(&mut r, 4).ok(), Some(None)); + } + + #[test] + fn an_over_long_line_is_rejected_before_its_newline_arrives() { + // A reader that fails after the first bytes: a reader that waited for the newline would + // return the error instead. + struct Then(io::Cursor>); + impl Read for Then { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self.0.read(buf)? { + 0 => Err(io::Error::other("no newline yet")), + n => Ok(n), + } + } + } + let mut r = BufReader::new(Then(io::Cursor::new(vec![b'x'; 64]))); + assert!(matches!(read_line_capped(&mut r, 16), Err(LineError::TooLong))); + } + + #[test] + fn timeout_variable_values() { + let parse = |v: &str| parse_timeout_secs(TIMEOUT_VAR, OsStr::new(v)).ok(); + assert_eq!(parse("5"), Some(Duration::from_secs(5))); + assert_eq!(parse("3600"), Some(MAX_TIMEOUT)); + for bad in ["", "0", "3601", "-1", "+5", " 5", "5s", "1.5", "99999999999999999999999"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn a_bad_timeout_variable_name_is_a_setup_error_not_a_panic() { + for name in ["", "A=B", "A\0B"] { + assert!(matches!(McpLimits::default().timeouts_from_var(name), Err(McpError::Setup(_))), "{name:?}"); + } + } +} diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs new file mode 100644 index 0000000000..5d730e85d3 --- /dev/null +++ b/crates/testkit/tests/mcp.rs @@ -0,0 +1,435 @@ +#![cfg(not(target_arch = "wasm32"))] + +use std::io::{BufRead, BufReader, Write}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION}; +use serde_json::{Value, json}; + +/// An in-process MCP server: answers each line it reads with `reply(method, message)`; `None` +/// sends nothing. A reply from the client has the method `""`. Returns the client side. +fn fake_with(limits: McpLimits, reply: F) -> McpChild +where + F: Fn(&str, &Value) -> Option> + Send + 'static, +{ + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + for line in BufReader::new(server_r).lines() { + let Ok(line) = line else { return }; + let Ok(req) = serde_json::from_str::(&line) else { + continue; + }; + let method = req["method"].as_str().unwrap_or("").to_string(); + let Some(out) = reply(&method, &req) else { + continue; + }; + for l in out { + if server_w.write_all(format!("{l}\n").as_bytes()).is_err() { + return; + } + } + } + }); + McpChild::connect(client_r, client_w, limits).unwrap() +} + +fn fake(reply: F) -> McpChild +where + F: Fn(&str, &Value) -> Option> + Send + 'static, +{ + fake_with(McpLimits::default(), reply) +} + +fn result(req: &Value, result: Value) -> String { + json!({"jsonrpc": "2.0", "id": req["id"], "result": result}).to_string() +} + +/// A deadline for replies that never come. +const SHORT: Duration = Duration::from_millis(200); +/// A deadline that a passing test does not reach. +const LONG: Duration = Duration::from_secs(30); + +#[test] +fn handshake_list_and_call() { + let initialized = Arc::new(AtomicBool::new(false)); + let seen = initialized.clone(); + let mut c = fake(move |m, req| match m { + "initialize" => Some(vec![result(req, json!({"protocolVersion": req["params"]["protocolVersion"]}))]), + "notifications/initialized" => { + assert!(req.get("id").is_none(), "a notification has no id"); + seen.store(true, Ordering::SeqCst); + None + } + // The list is sent only after `notifications/initialized`, which the client sends first. + "tools/list" if seen.load(Ordering::SeqCst) => Some(vec![result(req, json!({"tools": [{"name": "doc.new"}, {"no": "name"}]}))]), + "tools/call" => Some(vec![result(req, json!({"content": [{"type": "text", "text": req["params"]["name"]}]}))]), + _ => None, + }); + let init = c.initialize(PROTOCOL_VERSION).unwrap(); + assert_eq!(init["protocolVersion"], PROTOCOL_VERSION); + let tools = c.list_tools().unwrap(); + assert_eq!(tools.len(), 2, "the list is returned as the server sent it"); + assert!(initialized.load(Ordering::SeqCst)); + let r = c.call_tool_within("doc.new", json!({}), Duration::from_secs(5)).unwrap(); + assert_eq!(r["content"][0]["text"], "doc.new"); +} + +#[test] +fn pages_are_followed() { + let mut c = fake(|m, req| match m { + "tools/list" if req["params"]["cursor"].is_null() => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "p2"}))]), + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "b"}]}))]), + _ => None, + }); + let names: Vec = c.list_tools().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect(); + assert_eq!(names, vec!["a", "b"]); +} + +#[test] +fn notifications_log_lines_and_stale_replies_are_skipped() { + // A log line on stdout is a protocol error (`non_json_stdout_is_protocol_error`); a + // notification and a stale reply are skipped. + let mut c = fake(|_, req| { + Some(vec![ + json!({"jsonrpc": "2.0", "method": "notifications/message", "params": {"level": "info", "data": "starting up"}}).to_string(), + json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}).to_string(), + json!({"jsonrpc": "2.0", "id": 999, "result": "stale"}).to_string(), + result(req, json!("mine")), + ]) + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!("mine")); +} + +#[test] +fn a_request_from_the_app_is_refused_and_the_reply_still_arrives() { + let refusal: Arc>> = Arc::default(); + let log = refusal.clone(); + let mut c = fake(move |m, req| match m { + "x" => Some(vec![json!({"jsonrpc": "2.0", "id": "srv-1", "method": "sampling/createMessage"}).to_string()]), + // The reply to `x` follows the client's answer to the server's request. + "" => { + *log.lock().unwrap() = Some(req.clone()); + Some(vec![json!({"jsonrpc": "2.0", "id": 1, "result": 1}).to_string()]) + } + _ => None, + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1)); + let refusal = refusal.lock().unwrap().clone().unwrap(); + assert_eq!(refusal["id"], "srv-1"); + assert_eq!(refusal["error"]["code"], -32601); + assert!(refusal.get("result").is_none()); +} + +#[test] +fn an_error_reply_is_an_err_and_the_connection_stays_usable() { + let mut c = fake(|m, req| match m { + "bad" => { + Some(vec![json!({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -1, "message": "nope", "data": {"why": "test"}}}).to_string()]) + } + _ => Some(vec![result(req, json!(true))]), + }); + match c.request_within("bad", json!({}), Duration::from_secs(5)) { + Err(McpError::Rpc { method, code, message, data }) => { + assert_eq!((method.as_str(), code, message.as_str()), ("bad", -1, "nope")); + assert_eq!(data, Some(json!({"why": "test"}))); + } + other => panic!("{other:?}"), + } + assert!(c.closed().is_none()); + assert_eq!(c.request_within("ok", json!({}), Duration::from_secs(5)).unwrap(), json!(true)); +} + +#[test] +fn a_silent_app_times_out_and_the_connection_is_closed() { + let mut c = fake(|_, _| None); + let err = c.request_within("x", json!({}), Duration::from_millis(100)).unwrap_err(); + assert!(matches!(&err, McpError::Deadline { method, .. } if method == "x"), "{err}"); + assert!(c.closed().is_some()); + assert!(matches!(c.request_within("y", json!({}), Duration::from_secs(5)), Err(McpError::Closed(_)))); +} + +#[test] +fn an_app_that_exits_is_reported() { + let (client_r, server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + drop(server_w); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), Duration::from_secs(5)).unwrap_err(); + assert!(matches!(err, McpError::Ended), "{err}"); + assert!(c.closed().is_some()); +} + +#[test] +fn a_missing_cli_is_an_error_not_a_panic() { + let program = std::env::temp_dir().join("no-such-craft-cli-for-tests"); + let err = McpChild::spawn(&program, ["mcp"], [("CRAFT_TESTKIT_UNUSED", "1")]).unwrap_err(); + assert!(matches!(&err, McpError::Spawn { program: p, .. } if p.as_os_str() == program.as_os_str()), "{err}"); + assert!(err.to_string().contains("could not start"), "{err}"); +} + +#[test] +fn a_tool_list_that_never_ends_is_an_error_not_a_partial_list() { + let mut c = fake(|m, req| match m { + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "a"}], "nextCursor": "more"}))]), + _ => None, + }); + let err = c.list_tools().unwrap_err(); + assert!(matches!(err, McpError::TooManyPages { limit: 64 }), "{err}"); +} + +#[test] +fn a_tool_list_larger_than_the_limit_is_an_error() { + // Each page fits in a line; the pages together do not. + let limits = McpLimits { max_line_bytes: 256, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "tools/list" => Some(vec![result(req, json!({"tools": [{"name": "x".repeat(100)}], "nextCursor": "more"}))]), + _ => None, + }); + let err = c.list_tools().unwrap_err(); + assert!(matches!(err, McpError::ToolListTooLarge { limit: 256 }), "{err}"); +} + +#[test] +fn an_app_that_stops_reading_times_out_instead_of_blocking_the_write() { + // The server side never reads, so the pipe fills and the write blocks the writer thread, not + // the request. + let (client_r, _server_w) = std::io::pipe().unwrap(); + let (server_r, client_w) = std::io::pipe().unwrap(); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let big = "x".repeat(4 << 20); + let err = c.call_tool_within("t", json!({"data": big}), Duration::from_millis(300)).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); + drop(server_r); +} + +#[test] +fn a_tools_changed_notification_is_remembered_once() { + let limits = McpLimits { max_notifications: 8, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "x" => Some(vec![json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}).to_string(), result(req, json!(1))]), + _ => None, + }); + assert!(c.take_notifications().is_empty()); + c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(); + let kept = c.take_notifications(); + assert_eq!(kept.len(), 1, "{kept:?}"); + assert_eq!(kept[0]["method"], "notifications/tools/list_changed"); + assert!(c.take_notifications().is_empty()); +} + +#[test] +fn notifications_are_kept_up_to_the_limit_newest_last() { + let limits = McpLimits { max_notifications: 2, ..McpLimits::default() }; + let mut c = fake_with(limits, |m, req| match m { + "x" => { + let mut out: Vec = + (0..5).map(|n| json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {"n": n}}).to_string()).collect(); + out.push(result(req, json!(1))); + Some(out) + } + _ => None, + }); + c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(); + let kept: Vec = c.take_notifications().iter().map(|n| n["params"]["n"].clone()).collect(); + assert_eq!(kept, vec![json!(3), json!(4)]); +} + +#[test] +fn take_notifications_returns_while_the_server_keeps_writing() { + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + let note = format!("{}\n", json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}})); + while server_w.write_all(note.as_bytes()).is_ok() {} + }); + let limits = McpLimits { max_notifications: 8, ..McpLimits::default() }; + let mut c = McpChild::connect(client_r, client_w, limits).unwrap(); + for _ in 0..3 { + assert!(c.take_notifications().len() <= 8); + } + assert!(c.closed().is_none()); +} + +#[test] +fn a_failed_write_ends_the_waiting_request_at_once() { + struct Broken; + impl std::io::Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("stdin closed")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + // The app keeps stdout open but takes nothing on stdin. The deadline is an hour, so a write + // failure that did not end the request would show as a hung test. + let (client_r, _server_w) = std::io::pipe().unwrap(); + let mut c = McpChild::connect(client_r, Broken, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), Duration::from_secs(3600)).unwrap_err(); + assert!(matches!(&err, McpError::Io { what: "writing to the child", .. }), "{err}"); + assert!(err.to_string().contains("stdin closed"), "{err}"); + assert!(c.closed().is_some()); +} + +#[test] +fn an_app_ping_gets_an_empty_result_during_a_request_and_between_them() { + // `x` brings a ping before its reply and one after it. The second is read while `y` waits; + // the server answers `y` once both pings have their answers, with those answers. + #[derive(Default)] + struct State { + answers: Vec, + y: Option, + } + let state: Arc> = Arc::default(); + let mut c = fake(move |m, req| { + let mut s = state.lock().unwrap(); + match m { + "x" => Some(vec![ + json!({"jsonrpc": "2.0", "id": "p1", "method": "ping"}).to_string(), + result(req, json!(1)), + json!({"jsonrpc": "2.0", "id": "p2", "method": "ping"}).to_string(), + ]), + "y" => { + s.y = Some(req.clone()); + None + } + "" => { + s.answers.push(req.clone()); + None + } + _ => return None, + } + .or_else(|| { + let ready = s.answers.len() == 2; + let y = if ready { s.y.take() } else { None }?; + Some(vec![result(&y, json!(s.answers))]) + }) + }); + assert_eq!(c.request_within("x", json!({}), Duration::from_secs(5)).unwrap(), json!(1)); + let answers = c.request_within("y", json!({}), Duration::from_secs(5)).unwrap(); + for id in ["p1", "p2"] { + let reply = answers.as_array().unwrap().iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {id}: {answers}")); + assert_eq!(reply["result"], json!({}), "{reply}"); + assert!(reply.get("error").is_none()); + } +} + +#[test] +fn over_long_line_returns_error() { + let limits = McpLimits { max_line_bytes: 16, ..McpLimits::default() }; + // The line has no newline yet, and the server keeps its end open. + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + server_w.write_all(&[b'x'; 64]).unwrap(); + let mut c = McpChild::connect(client_r, client_w, limits).unwrap(); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::LineTooLong { limit: 16 }), "{err}"); + assert!(c.closed().is_some()); + drop(server_w); +} + +#[test] +fn wrong_id_does_not_satisfy_request() { + let mut c = fake(|_, req| { + let id = req["id"].as_u64().unwrap(); + Some(vec![ + json!({"jsonrpc": "2.0", "id": id + 1, "result": "other"}).to_string(), + json!({"jsonrpc": "2.0", "id": id.to_string(), "result": "string id"}).to_string(), + json!({"jsonrpc": "2.0", "id": null, "result": "null id"}).to_string(), + ]) + }); + let err = c.request_within("x", json!({}), SHORT).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); +} + +#[test] +fn a_flood_of_stale_replies_does_not_extend_the_deadline() { + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + std::thread::spawn(move || { + let stale = format!("{}\n", json!({"jsonrpc": "2.0", "id": 999, "result": "stale"})); + while server_w.write_all(stale.as_bytes()).is_ok() {} + }); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), SHORT).unwrap_err(); + assert!(matches!(err, McpError::Deadline { .. }), "{err}"); +} + +#[test] +fn non_json_stdout_is_protocol_error() { + for line in ["starting up...", r#"{"id": 1, "result": 1}"#, "[]", "\u{fffd}\u{0}"] { + let line = line.to_string(); + let mut c = fake(move |_, _| Some(vec![line.clone()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } + // Bytes that are not UTF-8. + let (client_r, mut server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + server_w.write_all(b"{\"jsonrpc\": \"2.0\", \"method\": \"\xff\"}\n").unwrap(); + let mut c = McpChild::connect(client_r, client_w, McpLimits::default()).unwrap(); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); +} + +#[test] +fn a_malformed_reply_is_a_protocol_error() { + for reply in [json!({"result": 1, "error": {"code": 1, "message": "both"}}), json!({}), json!({"error": {"code": "x", "message": "m"}})] { + let mut c = fake(move |_, req| { + let mut msg = reply.clone(); + msg["jsonrpc"] = json!("2.0"); + msg["id"] = req["id"].clone(); + Some(vec![msg.to_string()]) + }); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + +#[test] +fn a_tool_error_result_is_returned_unchanged() { + let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); + let r = c.call_tool("doc.save", json!({})).unwrap(); + assert_eq!(r["isError"], true); + assert!(c.closed().is_none()); +} + +#[test] +fn a_different_protocol_version_is_an_error_and_closes() { + let mut c = fake(|m, req| match m { + "initialize" => Some(vec![result(req, json!({"protocolVersion": "2024-11-05"}))]), + _ => None, + }); + let err = c.initialize(PROTOCOL_VERSION).unwrap_err(); + assert!( + matches!(&err, McpError::UnsupportedVersion { requested, returned } if requested == PROTOCOL_VERSION && returned == "2024-11-05"), + "{err}" + ); + assert!(c.closed().is_some()); +} + +#[test] +fn invalid_limits_and_environment_are_setup_errors() { + let zero_line = McpLimits { max_line_bytes: 0, ..McpLimits::default() }; + let zero_deadline = McpLimits { request_timeout: Duration::ZERO, ..McpLimits::default() }; + let long_deadline = McpLimits { initialize_timeout: Duration::from_secs(3601), ..McpLimits::default() }; + let many_notes = McpLimits { max_notifications: 4097, ..McpLimits::default() }; + for limits in [zero_line, zero_deadline, long_deadline, many_notes] { + let (client_r, _server_w) = std::io::pipe().unwrap(); + let (_server_r, client_w) = std::io::pipe().unwrap(); + assert!(matches!(McpChild::connect(client_r, client_w, limits.clone()), Err(McpError::Setup(_))), "{limits:?}"); + } + let program = std::env::temp_dir().join("no-such-craft-cli-for-tests"); + for (key, value) in [("", "1"), ("A=B", "1"), ("A\0B", "1"), ("A", "1\0")] { + let err = McpChild::spawn(&program, ["mcp"], [(key, value)]).unwrap_err(); + assert!(matches!(err, McpError::Setup(_)), "{key:?}={value:?}: {err}"); + } + let mut c = fake(|_, _| None); + assert!(matches!(c.request_within("x", json!({}), Duration::ZERO), Err(McpError::Setup(_)))); + assert!(c.closed().is_none(), "a bad deadline does not close the connection"); +} diff --git a/crates/testkit/tests/mcp_child.rs b/crates/testkit/tests/mcp_child.rs new file mode 100644 index 0000000000..e44029d18a --- /dev/null +++ b/crates/testkit/tests/mcp_child.rs @@ -0,0 +1,17 @@ +//! `McpChild` against a real child process. The child is this test program, started again with +//! `CRAFT_TESTKIT_MCP_CHILD` naming the server it acts as. The target has `harness = false` +//! because the standard test harness writes its own lines on stdout, which an MCP child must not +//! do. `main` runs each test whose name contains every argument that does not start with `-`, and +//! `--list` lists them. On `wasm32`, where the `mcp` module is not built, `main` does nothing. + +#[cfg(not(target_arch = "wasm32"))] +#[path = "mcp_child/child.rs"] +mod child; + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + child::run() +} + +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs new file mode 100644 index 0000000000..f172912acf --- /dev/null +++ b/crates/testkit/tests/mcp_child/child.rs @@ -0,0 +1,160 @@ +use std::io::{BufRead, Write}; +use std::process::ExitCode; +use std::time::Duration; + +use craft_testkit::mcp::{McpChild, McpError, McpLimits, PROTOCOL_VERSION}; +use serde_json::{Value, json}; + +/// The server the child acts as. +const CHILD_VAR: &str = "CRAFT_TESTKIT_MCP_CHILD"; +/// Text the `server` child returns from every tool call. +const ECHO_VAR: &str = "CRAFT_TESTKIT_MCP_ECHO"; +/// Bytes the `flood` child writes on stderr before each reply, more than a pipe holds. +const FLOOD: usize = 1 << 20; + +type Test = fn() -> Result<(), String>; + +const TESTS: &[(&str, Test)] = &[ + ("a_spawned_server_answers_and_closes_cleanly", a_spawned_server_answers_and_closes_cleanly), + ("silent_spawned_child_hits_deadline", silent_spawned_child_hits_deadline), + ("child_exits_before_initialize", child_exits_before_initialize), + ("stderr_flood_does_not_block", stderr_flood_does_not_block), + ("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child), +]; + +pub fn run() -> ExitCode { + if let Some(mode) = std::env::var_os(CHILD_VAR) { + return serve(&mode.to_string_lossy()); + } + let args: Vec = std::env::args().skip(1).collect(); + let filters: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); + let chosen: Vec<&(&str, Test)> = TESTS.iter().filter(|(name, _)| filters.iter().all(|f| name.contains(f.as_str()))).collect(); + if args.iter().any(|a| a == "--list") { + for (name, _) in chosen { + println!("{name}: test"); + } + return ExitCode::SUCCESS; + } + println!("\nrunning {} tests", chosen.len()); + let mut failed = 0; + for (name, test) in &chosen { + match test() { + Ok(()) => println!("test {name} ... ok"), + Err(why) => { + failed += 1; + println!("test {name} ... FAILED\n {why}"); + } + } + } + println!("\ntest result: {}. {} passed; {failed} failed", if failed == 0 { "ok" } else { "FAILED" }, chosen.len() - failed); + if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } +} + +/// Runs as the child: `server` answers `initialize` with the version asked for and every tool call +/// with `ECHO_VAR`, and exits when its stdin closes; `flood` also writes `FLOOD` bytes and `END` on +/// stderr before each reply; `silent` reads and never answers; `stubborn` answers but does not +/// exit when its stdin closes; `exit` exits at once with code 3. +fn serve(mode: &str) -> ExitCode { + if mode == "exit" { + return ExitCode::from(3); + } + let stdin = std::io::stdin(); + let mut out = std::io::stdout(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + let Ok(req) = serde_json::from_str::(&line) else { continue }; + if mode == "silent" || req.get("id").is_none() { + continue; + } + let result = match req["method"].as_str() { + Some("initialize") => { + json!({"protocolVersion": req["params"]["protocolVersion"], "capabilities": {}, "serverInfo": {"name": "child", "version": "0"}}) + } + Some("tools/call") => { + let text = std::env::var(ECHO_VAR).unwrap_or_default(); + json!({"content": [{"type": "text", "text": text}], "isError": false}) + } + _ => json!(null), + }; + if mode == "flood" { + let mut err = std::io::stderr(); + if err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"END")).is_err() { + return ExitCode::FAILURE; + } + } + let reply = json!({"jsonrpc": "2.0", "id": req["id"], "result": result}); + if writeln!(out, "{reply}").and_then(|()| out.flush()).is_err() { + return ExitCode::FAILURE; + } + } + if mode == "stubborn" { + // Waits without a stdin to read until the parent stops it; ends on its own after ten + // minutes so a parent that fails to stop it leaves nothing running. + let (_keep, wait) = std::sync::mpsc::channel::<()>(); + let _ = wait.recv_timeout(Duration::from_secs(600)); + } + ExitCode::SUCCESS +} + +fn start(mode: &str, limits: McpLimits) -> Result { + let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + McpChild::spawn_with_limits(exe, std::iter::empty::<&str>(), [(CHILD_VAR, mode), (ECHO_VAR, "hello from the child")], limits) + .map_err(|e| format!("spawn {mode}: {e}")) +} + +fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { + if ok { Ok(()) } else { Err(what()) } +} + +fn a_spawned_server_answers_and_closes_cleanly() -> Result<(), String> { + let mut c = start("server", McpLimits::default())?; + let init = c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + check(init["serverInfo"]["name"] == "child", || format!("initialize: {init}"))?; + let r = c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; + check(r["content"][0]["text"] == "hello from the child", || format!("the child did not get its variable: {r}"))?; + check(std::env::var_os(ECHO_VAR).is_none(), || "the test process's environment changed".into())?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced && out.status.is_some_and(|s| s.success()), || format!("close: {out:?}")) +} + +fn silent_spawned_child_hits_deadline() -> Result<(), String> { + let limits = McpLimits { initialize_timeout: Duration::from_millis(200), ..McpLimits::default() }; + let mut c = start("silent", limits)?; + let err = c.initialize(PROTOCOL_VERSION).err(); + check(matches!(err, Some(McpError::Deadline { .. })), || format!("initialize: {err:?}"))?; + check(c.closed().is_some(), || "the connection is still open".into())?; + let out = c.close().map_err(|e| e.to_string())?; + check(out.forced && out.status.is_some(), || format!("the silent child was not stopped: {out:?}")) +} + +fn child_exits_before_initialize() -> Result<(), String> { + let mut c = start("exit", McpLimits::default())?; + // The write of `initialize` and the end of stdout race; either one is reported. + let err = c.initialize(PROTOCOL_VERSION).err(); + check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced && out.status.and_then(|s| s.code()) == Some(3), || format!("close: {out:?}")) +} + +fn stderr_flood_does_not_block() -> Result<(), String> { + let limits = McpLimits { + stderr_tail_bytes: 4096, + initialize_timeout: Duration::from_secs(20), + request_timeout: Duration::from_secs(20), + ..McpLimits::default() + }; + let mut c = start("flood", limits)?; + c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; + let out = c.close().map_err(|e| e.to_string())?; + check(!out.forced, || format!("close: {out:?}"))?; + check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeEND"), || format!("kept {} bytes of stderr", out.stderr.len())) +} + +fn close_forces_and_reaps_unresponsive_child() -> Result<(), String> { + let limits = McpLimits { close_grace: Duration::from_millis(200), ..McpLimits::default() }; + let mut c = start("stubborn", limits)?; + c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; + let out = c.close().map_err(|e| e.to_string())?; + check(out.forced && out.status.is_some_and(|s| !s.success()), || format!("close: {out:?}")) +} From 3b0d43204ee9b137d60c9922bb7a9c7e5bbdc537 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:17:14 -0800 Subject: [PATCH 018/490] craft-testkit: blank MCP stdout lines are protocol errors The MCP client no longer skips a blank or whitespace-only stdout line. The line is parsed like any other, so it ends the request with a protocol error and closes the connection instead of waiting for the deadline. --- crates/testkit/src/mcp.rs | 1 - crates/testkit/tests/mcp.rs | 16 ++++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index eedf52c694..400c072718 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -464,7 +464,6 @@ impl McpChild { loop { let incoming = match read_line_capped(&mut r, cap) { Ok(None) => Incoming::Ended, - Ok(Some(line)) if line.iter().all(u8::is_ascii_whitespace) => continue, Ok(Some(line)) => parse_line(&line), Err(LineError::TooLong) => Incoming::TooLong, Err(LineError::Io(e)) => Incoming::ReadFailed(e), diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 5d730e85d3..d56b891cf9 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -376,6 +376,22 @@ fn non_json_stdout_is_protocol_error() { assert!(matches!(err, McpError::Protocol(_)), "{err}"); } +#[test] +fn a_blank_stdout_line_is_protocol_error() { + // The fake ends each line with a newline, so these send "\n" and " \r\n". + for blank in ["", " \r"] { + let mut c = fake(move |_, req| Some(vec![blank.to_string(), result(req, json!(1))])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}"); + assert!(c.closed().is_some()); + // Without a reply after it, the blank line still ends the request before its deadline. + let mut c = fake(move |_, _| Some(vec![blank.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{blank:?}: {err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_malformed_reply_is_a_protocol_error() { for reply in [json!({"result": 1, "error": {"code": 1, "message": "both"}}), json!({}), json!({"error": {"code": "x", "message": "m"}})] { From 3d0bace80f39fdf43e933b45089aa772db0dc0df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:24:01 -0800 Subject: [PATCH 019/490] craft-testkit: the spawn test compares the parent's variable with its value before the child starts --- crates/testkit/tests/mcp_child/child.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/testkit/tests/mcp_child/child.rs b/crates/testkit/tests/mcp_child/child.rs index f172912acf..254488c3e7 100644 --- a/crates/testkit/tests/mcp_child/child.rs +++ b/crates/testkit/tests/mcp_child/child.rs @@ -107,12 +107,13 @@ fn check(ok: bool, what: impl FnOnce() -> String) -> Result<(), String> { } fn a_spawned_server_answers_and_closes_cleanly() -> Result<(), String> { + let before = std::env::var_os(ECHO_VAR); let mut c = start("server", McpLimits::default())?; let init = c.initialize(PROTOCOL_VERSION).map_err(|e| e.to_string())?; check(init["serverInfo"]["name"] == "child", || format!("initialize: {init}"))?; let r = c.call_tool("echo", json!({})).map_err(|e| e.to_string())?; check(r["content"][0]["text"] == "hello from the child", || format!("the child did not get its variable: {r}"))?; - check(std::env::var_os(ECHO_VAR).is_none(), || "the test process's environment changed".into())?; + check(std::env::var_os(ECHO_VAR) == before, || "the test process's environment changed".into())?; let out = c.close().map_err(|e| e.to_string())?; check(!out.forced && out.status.is_some_and(|s| s.success()), || format!("close: {out:?}")) } From 259549fe9330738412fa6aead09d0f1628f95793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:09:26 -0800 Subject: [PATCH 020/490] craft-texture: sRGB tests fail on a difference that is not finite worst() now asserts that each difference is finite and names the code it is at. Before, a NaN difference never replaced the maximum, so a pair that returned NaN at every code passed the tolerance checks. A new test checks that worst() fails on a NaN difference. --- crates/texture/tests/srgb.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/texture/tests/srgb.rs b/crates/texture/tests/srgb.rs index 8884c6e3f3..4edd74086a 100644 --- a/crates/texture/tests/srgb.rs +++ b/crates/texture/tests/srgb.rs @@ -34,8 +34,23 @@ fn codes(max: u32) -> impl Iterator { } /// The largest difference between `f` and `g` over every code of a depth, and the code it is at. +/// A difference that is not finite fails at its code. fn worst(max: u32, f: impl Fn(f32) -> f32, g: impl Fn(f32) -> f32) -> (f32, u32) { - codes(max).map(|(n, v)| ((f(v) - g(v)).abs(), n)).fold((0.0, 0), |a, b| if b.0 > a.0 { b } else { a }) + let mut most = (0.0, 0); + for (n, v) in codes(max) { + let d = (f(v) - g(v)).abs(); + assert!(d.is_finite(), "code {n} of {max} gives a difference of {d}"); + if d > most.0 { + most = (d, n); + } + } + most +} + +#[test] +#[should_panic(expected = "code 0 of 255 gives a difference of NaN")] +fn worst_fails_on_a_difference_that_is_not_finite() { + worst(255, |_| f32::NAN, |v| v); } /// Inputs outside `[0, 1]` that the crates' copies must also agree on. From ba866e1e45aa27a2dad6624c1f534632c3529a05 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Sat, 7 Nov 2026 08:37:23 -0500 Subject: [PATCH 021/490] craft-gpu: add the GPU job traits and the shared providers. This carries over crates/gpu, crates/gpu-wgpu, crates/gpu-null, and crates/gpu-providers from the cut-down #160 branch, with minimal workspace wiring. None of these crates names a vendor or any app. craft-gpu defines GpuJob and ProviderRegistry. craft-gpu-null is an in-memory context for tests. craft-gpu-providers holds the shared craft.* WGSL providers. craft-gpu-wgpu is the wgpu backend, native and WebGPU. --- Cargo.toml | 7 ++ crates/gpu-null/Cargo.toml | 13 +++ crates/gpu-null/src/lib.rs | 46 ++++++++++ crates/gpu-providers/Cargo.toml | 16 ++++ crates/gpu-providers/src/composite.rs | 69 ++++++++++++++ crates/gpu-providers/src/echo.rs | 18 ++++ crates/gpu-providers/src/lib.rs | 33 +++++++ crates/gpu-providers/src/mask.rs | 35 +++++++ crates/gpu-providers/src/noop.rs | 14 +++ crates/gpu-providers/src/params.rs | 13 +++ crates/gpu-providers/src/readback.rs | 38 ++++++++ crates/gpu-providers/src/tests.rs | 127 ++++++++++++++++++++++++++ crates/gpu-wgpu/Cargo.toml | 31 +++++++ crates/gpu-wgpu/src/lib.rs | 89 ++++++++++++++++++ crates/gpu/Cargo.toml | 17 ++++ crates/gpu/src/caps.rs | 23 +++++ crates/gpu/src/chunk.rs | 11 +++ crates/gpu/src/context.rs | 23 +++++ crates/gpu/src/error.rs | 14 +++ crates/gpu/src/job.rs | 28 ++++++ crates/gpu/src/lib.rs | 27 ++++++ crates/gpu/src/provider.rs | 8 ++ crates/gpu/src/readback.rs | 50 ++++++++++ crates/gpu/src/registry.rs | 39 ++++++++ crates/gpu/src/tests.rs | 69 ++++++++++++++ docs/gpu-backends.md | 14 +++ docs/gpu-providers.md | 14 +++ 27 files changed, 886 insertions(+) create mode 100644 crates/gpu-null/Cargo.toml create mode 100644 crates/gpu-null/src/lib.rs create mode 100644 crates/gpu-providers/Cargo.toml create mode 100644 crates/gpu-providers/src/composite.rs create mode 100644 crates/gpu-providers/src/echo.rs create mode 100644 crates/gpu-providers/src/lib.rs create mode 100644 crates/gpu-providers/src/mask.rs create mode 100644 crates/gpu-providers/src/noop.rs create mode 100644 crates/gpu-providers/src/params.rs create mode 100644 crates/gpu-providers/src/readback.rs create mode 100644 crates/gpu-providers/src/tests.rs create mode 100644 crates/gpu-wgpu/Cargo.toml create mode 100644 crates/gpu-wgpu/src/lib.rs create mode 100644 crates/gpu/Cargo.toml create mode 100644 crates/gpu/src/caps.rs create mode 100644 crates/gpu/src/chunk.rs create mode 100644 crates/gpu/src/context.rs create mode 100644 crates/gpu/src/error.rs create mode 100644 crates/gpu/src/job.rs create mode 100644 crates/gpu/src/lib.rs create mode 100644 crates/gpu/src/provider.rs create mode 100644 crates/gpu/src/readback.rs create mode 100644 crates/gpu/src/registry.rs create mode 100644 crates/gpu/src/tests.rs create mode 100644 docs/gpu-backends.md create mode 100644 docs/gpu-providers.md diff --git a/Cargo.toml b/Cargo.toml index bd08fa725e..2a7dcfa648 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -91,6 +91,10 @@ craft-html = { path = "crates/html" } craft-heif = { path = "crates/heif" } craft-fig = { path = "crates/fig" } craft-fonts-build = { path = "crates/fonts-build" } +craft-gpu = { path = "crates/gpu" } +craft-gpu-null = { path = "crates/gpu-null" } +craft-gpu-providers = { path = "crates/gpu-providers" } +craft-gpu-wgpu = { path = "crates/gpu-wgpu" } craft-i18n = { path = "crates/i18n" } craft-idml = { path = "crates/idml" } craft-indd = { path = "crates/indd" } @@ -193,6 +197,9 @@ proptest = "1" encoding_rs = "0.8" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } +# Foundation crates for craft-gpu-wgpu. The versions match the ones the app repos already pin. +pollster = "0.4" +wgpu = { version = "30", default-features = false, features = ["std", "wgsl"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/crates/gpu-null/Cargo.toml b/crates/gpu-null/Cargo.toml new file mode 100644 index 0000000000..adb907597f --- /dev/null +++ b/crates/gpu-null/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-gpu-null" +description = "In-memory GpuContext for CI and headless tests" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs new file mode 100644 index 0000000000..66925b4901 --- /dev/null +++ b/crates/gpu-null/src/lib.rs @@ -0,0 +1,46 @@ +//! CPU-only [`GpuContext`](craft_gpu::GpuContext) for tests and CI. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; + +/// In-memory buffer store; no GPU hardware required. +pub struct NullContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + buffers: Vec>, +} + +impl NullContext { + pub fn new(worker_kind: WorkerKind) -> Self { + Self { + caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() }, + worker_kind, + buffers: Vec::new(), + } + } +} + +impl GpuContext for NullContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} diff --git a/crates/gpu-providers/Cargo.toml b/crates/gpu-providers/Cargo.toml new file mode 100644 index 0000000000..b581b81123 --- /dev/null +++ b/crates/gpu-providers/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-gpu-providers" +description = "Shared GpuProvider implementations (composite, readback, …) — no app deps" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[dev-dependencies] +craft-gpu-null = { workspace = true } diff --git a/crates/gpu-providers/src/composite.rs b/crates/gpu-providers/src/composite.rs new file mode 100644 index 0000000000..aeda3ead04 --- /dev/null +++ b/crates/gpu-providers/src/composite.rs @@ -0,0 +1,69 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft `composite.wgsl` Normal/Dissolve premultiplied "over" until WGSL runs on wgpu. +pub struct PremulCompositeProvider; + +impl GpuProvider for PremulCompositeProvider { + fn id(&self) -> &'static str { + "craft.composite.premul" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (dst_h, src_h) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => { + return Err(GpuFault::InvalidJob("craft.composite.premul expects one or two RGBA8 inputs (backdrop, layer)".into())); + } + }; + let dst_bytes = ctx.read_buffer(*dst_h)?; + let src_bytes = ctx.read_buffer(*src_h)?; + if dst_bytes.len() < len || src_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for px in 0..width.saturating_mul(height) { + let i = px * 4; + let mut dst = straight_to_premul([dst_bytes[i], dst_bytes[i + 1], dst_bytes[i + 2], dst_bytes[i + 3]]); + let src = straight_to_premul([src_bytes[i], src_bytes[i + 1], src_bytes[i + 2], src_bytes[i + 3]]); + premul_over(&mut dst, src); + let straight = premul_to_straight(dst); + out[i..i + 4].copy_from_slice(&straight); + } + let handle = ctx.upload_buffer("craft.composite.premul.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} + +/// Premultiplied `src` over premultiplied `dst` (`filmcraft_render` / `composite.wgsl` Normal path). +fn premul_over(dst: &mut [f32; 4], src: [f32; 4]) { + let k = 1.0 - src[3]; + for c in 0..4 { + dst[c] = src[c] + dst[c] * k; + } +} + +fn straight_to_premul(p: [u8; 4]) -> [f32; 4] { + let a = f32::from(p[3]) / 255.0; + let s = a / 255.0; + [f32::from(p[0]) * s, f32::from(p[1]) * s, f32::from(p[2]) * s, a] +} + +fn premul_to_straight(p: [f32; 4]) -> [u8; 4] { + let a = p[3].clamp(0.0, 1.0); + if a <= f32::EPSILON { + return [0, 0, 0, 0]; + } + let inv = 255.0 / a; + [ + (p[0] * inv).round().clamp(0.0, 255.0) as u8, + (p[1] * inv).round().clamp(0.0, 255.0) as u8, + (p[2] * inv).round().clamp(0.0, 255.0) as u8, + (a * 255.0).round().clamp(0.0, 255.0) as u8, + ] +} diff --git a/crates/gpu-providers/src/echo.rs b/crates/gpu-providers/src/echo.rs new file mode 100644 index 0000000000..2fb356ceb3 --- /dev/null +++ b/crates/gpu-providers/src/echo.rs @@ -0,0 +1,18 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Concatenates job params with bytes from the first input handle (shared test / debug provider). +pub struct EchoProvider; + +impl GpuProvider for EchoProvider { + fn id(&self) -> &'static str { + "craft.test.echo" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let mut data = job.params.0.clone(); + if let Some(&h) = job.inputs.first() { + data.extend_from_slice(&ctx.read_buffer(h)?); + } + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: Some(data) }) + } +} diff --git a/crates/gpu-providers/src/lib.rs b/crates/gpu-providers/src/lib.rs new file mode 100644 index 0000000000..c310a6c4f1 --- /dev/null +++ b/crates/gpu-providers/src/lib.rs @@ -0,0 +1,33 @@ +//! Generic GPU providers extracted from app crates over time (craft-libs#7). + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod composite; +mod echo; +mod mask; +mod noop; +mod params; +mod readback; + +#[cfg(test)] +mod tests; + +use craft_gpu::{GpuProvider, ProviderRegistry}; + +pub use composite::PremulCompositeProvider; +pub use echo::EchoProvider; +pub use mask::MaskProvider; +pub use noop::NoopProvider; +pub use readback::ReadbackProvider; + +/// Default shared providers for worker/runtime init (`craft.*` ids only). +pub fn register_all() -> Vec> { + vec![Box::new(NoopProvider), Box::new(EchoProvider), Box::new(MaskProvider), Box::new(PremulCompositeProvider), Box::new(ReadbackProvider)] +} + +/// Register [`register_all`] providers into an existing registry. +pub fn register_all_into(registry: &mut ProviderRegistry) { + for provider in register_all() { + registry.register(provider); + } +} diff --git a/crates/gpu-providers/src/mask.rs b/crates/gpu-providers/src/mask.rs new file mode 100644 index 0000000000..41957c1f7b --- /dev/null +++ b/crates/gpu-providers/src/mask.rs @@ -0,0 +1,35 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +use crate::params::parse_u32; + +/// CPU stand-in for FilmCraft mask composite until WGSL runs on wgpu. +pub struct MaskProvider; + +impl GpuProvider for MaskProvider { + fn id(&self) -> &'static str { + "craft.mask" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(1).max(1) as usize; + let height = parse_u32(&job.params, b"h:").unwrap_or(1).max(1) as usize; + let len = width.saturating_mul(height).saturating_mul(4); + let (base, mask) = match job.inputs.as_slice() { + [a, b] => (a, b), + [a] => (a, a), + _ => return Err(GpuFault::InvalidJob("craft.mask expects one or two RGBA inputs".into())), + }; + let base_bytes = ctx.read_buffer(*base)?; + let mask_bytes = ctx.read_buffer(*mask)?; + if base_bytes.len() < len || mask_bytes.len() < len { + return Err(GpuFault::InvalidJob("input buffer shorter than w*h*4".into())); + } + let mut out = vec![0u8; len]; + for i in 0..len { + let m = mask_bytes[i]; + out[i] = ((u16::from(base_bytes[i]) * u16::from(m)) / 255) as u8; + } + let handle = ctx.upload_buffer("craft.mask.out", &out)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/noop.rs b/crates/gpu-providers/src/noop.rs new file mode 100644 index 0000000000..4ce8aef91a --- /dev/null +++ b/crates/gpu-providers/src/noop.rs @@ -0,0 +1,14 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// No-op dispatch for wiring tests; shared readback/composite providers live in sibling modules. +pub struct NoopProvider; + +impl GpuProvider for NoopProvider { + fn id(&self) -> &'static str { + "craft.noop" + } + + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(GpuJobOutcome { outputs: job.outputs.clone(), data: None }) + } +} diff --git a/crates/gpu-providers/src/params.rs b/crates/gpu-providers/src/params.rs new file mode 100644 index 0000000000..2327aa3efa --- /dev/null +++ b/crates/gpu-providers/src/params.rs @@ -0,0 +1,13 @@ +use craft_gpu::GpuJobParams; + +pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { + let bytes = params.0.as_slice(); + let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len(); + let rest = &bytes[start..]; + let end = rest.iter().position(|&b| b == b',' || b == b';').unwrap_or(rest.len()); + std::str::from_utf8(&rest[..end]).ok()?.parse().ok() +} + +pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool { + params.0.windows(needle.len()).any(|w| w == needle) +} diff --git a/crates/gpu-providers/src/readback.rs b/crates/gpu-providers/src/readback.rs new file mode 100644 index 0000000000..fb27f798ca --- /dev/null +++ b/crates/gpu-providers/src/readback.rs @@ -0,0 +1,38 @@ +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, chunk_buffer, f16_rgba_to_f32_bytes}; + +use crate::params::{params_contain, parse_u32}; + +/// CPU stand-in for accumulator/output readback (`read_accumulator` / `read_output` in FilmCraft gpu) until wgpu maps buffers. +pub struct ReadbackProvider; + +impl GpuProvider for ReadbackProvider { + fn id(&self) -> &'static str { + "craft.readback" + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let width = parse_u32(&job.params, b"w:").unwrap_or(0); + let height = parse_u32(&job.params, b"h:").unwrap_or(0); + let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?; + let raw = ctx.read_buffer(input)?; + let caps = ctx.caps(); + let _chunks = chunk_buffer(&caps, &raw)?; + + let out_bytes = if params_contain(&job.params, b"fmt:u8") { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("rgba8 readback shorter than w*h*4".into())); + } + raw[..need].to_vec() + } else { + let need = usize::try_from(width.saturating_mul(height).saturating_mul(8)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; + if need == 0 || raw.len() < need { + return Err(GpuFault::InvalidJob("f16 rgba readback shorter than w*h*8".into())); + } + f16_rgba_to_f32_bytes(&raw[..need]).map_err(|len| GpuFault::InvalidJob(format!("f16 rgba length {len} not multiple of 8")))? + }; + + let handle = ctx.upload_buffer("craft.readback.out", &out_bytes)?; + Ok(GpuJobOutcome { outputs: vec![handle], data: None }) + } +} diff --git a/crates/gpu-providers/src/tests.rs b/crates/gpu-providers/src/tests.rs new file mode 100644 index 0000000000..b996ca57b2 --- /dev/null +++ b/crates/gpu-providers/src/tests.rs @@ -0,0 +1,127 @@ +#![allow(clippy::expect_used)] + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, ProviderRegistry, WorkerKind, f16_to_f32, f16_to_f32_fast}; +use craft_gpu_null::NullContext; + +use crate::{EchoProvider, MaskProvider, NoopProvider, PremulCompositeProvider, ReadbackProvider, register_all, register_all_into}; + +#[test] +fn noop_provider_registered_by_id() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(NoopProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("noop dispatch"); + assert!(out.data.is_none()); +} + +#[test] +fn echo_provider_concatenates_params_and_first_input() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(EchoProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = ctx.upload_buffer("in", b"xy").expect("upload_buffer in test"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![h], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("echo dispatch"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); +} + +#[test] +fn register_all_lists_shared_providers() { + let ids: Vec<_> = register_all().iter().map(|p| p.id()).collect(); + assert_eq!(ids, vec!["craft.noop", "craft.test.echo", "craft.mask", "craft.composite.premul", "craft.readback",]); +} + +#[test] +fn gpu_providers_cargo_has_no_app_deps() { + let manifest = include_str!("../Cargo.toml"); + for line in manifest.lines() { + let t = line.trim(); + assert!( + !(t.starts_with("effectcraft") || t.starts_with("filmcraft") || t.contains("effectcraft-") || t.contains("filmcraft-")), + "forbidden app dependency line: {t}" + ); + } +} + +#[test] +fn mask_provider_multiplies_rgba_by_mask_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(MaskProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let base = ctx.upload_buffer("base", &[255u8, 0, 0, 255, 100, 100, 100, 255]).expect("upload base"); + let mask = ctx.upload_buffer("mask", &[128u8, 255, 255, 255, 0, 255, 255, 255]).expect("upload mask"); + let job = + craft_gpu::GpuJob { provider_id: "craft.mask".into(), params: GpuJobParams(b"w:1,h:2".to_vec()), inputs: vec![base, mask], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("mask dispatch"); + let handle = out.outputs[0]; + let bytes = ctx.read_buffer(handle).expect("read mask out"); + assert_eq!(bytes[0], 128); + assert_eq!(bytes[4], 0); +} + +#[test] +fn premul_composite_over_on_cpu() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(PremulCompositeProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + // backdrop: green opaque; layer: half-alpha blue + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("premul composite"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read out"); + assert_eq!(bytes[0], 0); + assert_eq!(bytes[1], 127); + assert_eq!(bytes[2], 128); + assert_eq!(bytes[3], 255); +} + +#[test] +fn readback_decodes_f16_rgba_to_f32() { + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(ReadbackProvider)); + let mut ctx = NullContext::new(WorkerKind::Main); + let h = half_float_one(); + let mut raw = Vec::new(); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&h.to_le_bytes()); + raw.extend_from_slice(&0u16.to_le_bytes()); + let inp = ctx.upload_buffer("accum", &raw).expect("upload f16"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![inp], outputs: vec![] }; + let out = registry.dispatch(&mut ctx, &job).expect("readback"); + let decoded = ctx.read_buffer(out.outputs[0]).expect("read f32 out"); + assert_eq!(decoded.len(), 16); + let r = f32::from_le_bytes(decoded[0..4].try_into().expect("r")); + assert!((r - 1.0).abs() < 1e-3); + assert_eq!(f16_to_f32(h), f16_to_f32_fast(h)); +} + +fn half_float_one() -> u16 { + f32_to_f16(1.0) +} + +fn f32_to_f16(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 31) & 1) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let mant = bits & 0x007f_ffff; + if exp <= 0 { + return sign << 15; + } + if exp >= 0x1f { + return (sign << 15) | 0x7c00; + } + (sign << 15) | ((exp as u16) << 10) | ((mant >> 13) as u16) +} + +#[test] +fn register_all_into_populates_registry() { + let mut registry = ProviderRegistry::new(); + register_all_into(&mut registry); + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let job = GpuJob { provider_id: "craft.noop".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + registry.dispatch(&mut ctx, &job).expect("noop via register_all_into"); +} diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml new file mode 100644 index 0000000000..4f2c9ae5b2 --- /dev/null +++ b/crates/gpu-wgpu/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "craft-gpu-wgpu" +description = "craft-gpu backend using wgpu (WebGPU on wasm32, native APIs on desktop)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-gpu = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true, optional = true } +wgpu = { workspace = true } + +[features] +default = [] +adapter-probe = ["dep:pollster"] +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] + +[dev-dependencies] +pollster = { workspace = true } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs new file mode 100644 index 0000000000..91aa8cc19b --- /dev/null +++ b/crates/gpu-wgpu/src/lib.rs @@ -0,0 +1,89 @@ +//! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). +//! +//! WebGPU on `wasm32`; native APIs when backend features are enabled. Adapter probing is +//! optional on native via the `adapter-probe` feature (pollster). + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; + +fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { + DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn probe_caps_native() -> DeviceCaps { + let instance = wgpu::Instance::default(); + let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { + Ok(adapter) => adapter, + Err(_) => return probe_fallback("wgpu", "no-adapter"), + }; + let info = adapter.get_info(); + let limits = adapter.limits(); + DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + } +} + +/// Report device limits when an adapter is available; otherwise conservative defaults. +pub fn probe_caps() -> DeviceCaps { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + return probe_caps_native(); + } + + #[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))] + { + probe_fallback("wgpu", "probe-not-run") + } + + #[cfg(target_arch = "wasm32")] + { + probe_fallback("webgpu", "browser") + } +} + +/// wgpu-backed context; buffer IO uses staging until full device wiring lands (craft-libs#6). +pub struct WgpuContext { + caps: DeviceCaps, + worker_kind: WorkerKind, + staging: Vec>, +} + +impl WgpuContext { + pub fn new(worker_kind: WorkerKind) -> Self { + Self { caps: probe_caps(), worker_kind, staging: Vec::new() } + } + + pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self { + Self { caps, worker_kind, staging: Vec::new() } + } +} + +impl GpuContext for WgpuContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + self.worker_kind + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.staging.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.staging.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.staging.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.staging.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml new file mode 100644 index 0000000000..3928ad8bee --- /dev/null +++ b/crates/gpu/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-gpu" +description = "Provider-neutral GPU traits, GpuJob envelope, and registry (no vendor IO)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs new file mode 100644 index 0000000000..ae63a43ab2 --- /dev/null +++ b/crates/gpu/src/caps.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; + +/// Limits and labels reported to Settings UI and worker RPC (`GpuCaps`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeviceCaps { + pub backend_name: String, + pub device_name: String, + pub max_storage_buffer_binding_size: u64, + pub max_buffer_size: u64, + pub max_texture_dimension_2d: u32, +} + +impl Default for DeviceCaps { + fn default() -> Self { + Self { + backend_name: "null".into(), + device_name: "null".into(), + max_storage_buffer_binding_size: 128 * 1024 * 1024, + max_buffer_size: 256 * 1024 * 1024, + max_texture_dimension_2d: 8192, + } + } +} diff --git a/crates/gpu/src/chunk.rs b/crates/gpu/src/chunk.rs new file mode 100644 index 0000000000..6246377773 --- /dev/null +++ b/crates/gpu/src/chunk.rs @@ -0,0 +1,11 @@ +use crate::{DeviceCaps, GpuFault}; + +/// Split `data` into contiguous slices no larger than [`DeviceCaps::max_storage_buffer_binding_size`]. +pub fn chunk_buffer<'a>(caps: &DeviceCaps, data: &'a [u8]) -> Result, GpuFault> { + let max = usize::try_from(caps.max_storage_buffer_binding_size) + .map_err(|_| GpuFault::Operation("max_storage_buffer_binding_size exceeds host address space".into()))?; + if max == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } + Ok(data.chunks(max).collect()) +} diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs new file mode 100644 index 0000000000..8d565e3441 --- /dev/null +++ b/crates/gpu/src/context.rs @@ -0,0 +1,23 @@ +use crate::{DeviceCaps, GpuFault, HandleId}; + +/// Where the context was created (main thread vs worker). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WorkerKind { + Main, + DedicatedWorker, + SharedWorker, +} + +/// Device/queue abstraction implemented by `craft-gpu-wgpu` and `craft-gpu-null`. +pub trait GpuContext { + fn caps(&self) -> DeviceCaps; + + fn worker_kind(&self) -> WorkerKind; + + /// Register an opaque buffer blob; returns a handle for job graphs. + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result; + + fn buffer_len(&self, handle: HandleId) -> Result; + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault>; +} diff --git a/crates/gpu/src/error.rs b/crates/gpu/src/error.rs new file mode 100644 index 0000000000..2a44f4b6a0 --- /dev/null +++ b/crates/gpu/src/error.rs @@ -0,0 +1,14 @@ +use thiserror::Error; + +/// Neutral GPU failure (no wgpu/WebGPU types cross this boundary). +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum GpuFault { + #[error("provider not registered: {0}")] + UnknownProvider(String), + #[error("invalid job: {0}")] + InvalidJob(String), + #[error("device unavailable: {0}")] + DeviceUnavailable(String), + #[error("operation failed: {0}")] + Operation(String), +} diff --git a/crates/gpu/src/job.rs b/crates/gpu/src/job.rs new file mode 100644 index 0000000000..5f822b6f6f --- /dev/null +++ b/crates/gpu/src/job.rs @@ -0,0 +1,28 @@ +use serde::{Deserialize, Serialize}; + +/// Opaque resource handle in a job graph (resolved in the active [`GpuContext`](crate::GpuContext)). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HandleId(pub u32); + +/// Stable provider name (`craft.readback`, `effectcraft.compositor.frame`, …). +pub type ProviderId = String; + +/// Versioned parameter blob; schema owned by the provider crate, not craft-gpu. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobParams(pub Vec); + +/// Serializable work unit for generic worker dispatch. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJob { + pub provider_id: ProviderId, + pub params: GpuJobParams, + pub inputs: Vec, + pub outputs: Vec, +} + +/// Result handles or side-channel bytes (provider-defined interpretation). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct GpuJobOutcome { + pub outputs: Vec, + pub data: Option>, +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs new file mode 100644 index 0000000000..bf4993f30e --- /dev/null +++ b/crates/gpu/src/lib.rs @@ -0,0 +1,27 @@ +//! GPU traits, job envelope, and provider registry for Craft apps and the web runtime. +//! +//! Application crates register [`GpuProvider`] implementations; generic hosts dispatch +//! [`GpuJob`] values by [`ProviderId`] without importing app project types. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod caps; +mod chunk; +mod context; +mod error; +mod job; +mod provider; +mod readback; +mod registry; + +#[cfg(test)] +mod tests; + +pub use caps::DeviceCaps; +pub use chunk::chunk_buffer; +pub use context::{GpuContext, WorkerKind}; +pub use error::GpuFault; +pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId}; +pub use provider::GpuProvider; +pub use readback::{f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast}; +pub use registry::ProviderRegistry; diff --git a/crates/gpu/src/provider.rs b/crates/gpu/src/provider.rs new file mode 100644 index 0000000000..677351f579 --- /dev/null +++ b/crates/gpu/src/provider.rs @@ -0,0 +1,8 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome}; + +/// One GPU operation family. App and generic providers implement this trait. +pub trait GpuProvider { + fn id(&self) -> &'static str; + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result; +} diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs new file mode 100644 index 0000000000..ad02afbe88 --- /dev/null +++ b/crates/gpu/src/readback.rs @@ -0,0 +1,50 @@ +/// IEEE half → f32 (FilmCraft `filmcraft_gpu::f16_to_f32`), for decoding `Rgba16Float` readbacks. +pub fn f16_to_f32(h: u16) -> f32 { + let sign = ((h & 0x8000) as u32) << 16; + let exp = ((h >> 10) & 0x1f) as u32; + let mant = (h & 0x03ff) as u32; + let bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let b = 31 - mant.leading_zeros(); + let frac = (mant ^ (1 << b)) << (23 - b); + sign | ((103 + b) << 23) | frac + } + } + 0x1f => sign | 0x7f80_0000 | (mant << 13), + _ => sign | ((exp + 112) << 23) | (mant << 13), + }; + f32::from_bits(bits) +} + +/// [`f16_to_f32`] with a fast path for normal numbers and zeros; subnormals and non-finite values use [`f16_to_f32`]. +#[inline] +pub fn f16_to_f32_fast(h: u16) -> f32 { + let u = u32::from(h); + let sign = (u & 0x8000) << 16; + let abs = u & 0x7fff; + if (0x0400..0x7c00).contains(&abs) { + f32::from_bits(sign | ((abs + (112 << 10)) << 13)) + } else if abs == 0 { + f32::from_bits(sign) + } else { + f16_to_f32(h) + } +} + +/// Expand little-endian RGBA f16 texels to RGBA f32 (row-major, no padding). +pub fn f16_rgba_to_f32_bytes(src: &[u8]) -> Result, usize> { + if !src.len().is_multiple_of(8) { + return Err(src.len()); + } + let mut out = Vec::with_capacity(src.len() * 2); + for chunk in src.as_chunks::<8>().0 { + for pair in chunk.as_chunks::<2>().0 { + let v = f16_to_f32_fast(u16::from_le_bytes(*pair)); + out.extend_from_slice(&v.to_le_bytes()); + } + } + Ok(out) +} diff --git a/crates/gpu/src/registry.rs b/crates/gpu/src/registry.rs new file mode 100644 index 0000000000..9a970da8ba --- /dev/null +++ b/crates/gpu/src/registry.rs @@ -0,0 +1,39 @@ +use crate::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider}; + +/// Lookup table filled at worker/app init. Generic runtime code only talks to this. +pub struct ProviderRegistry { + providers: Vec>, +} + +impl Default for ProviderRegistry { + fn default() -> Self { + Self::new() + } +} + +impl ProviderRegistry { + pub fn new() -> Self { + Self { providers: Vec::new() } + } + + pub fn register(&mut self, provider: Box) { + self.providers.push(provider); + } + + pub fn dispatch(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + for provider in &self.providers { + if provider.id() == job.provider_id { + return provider.run(ctx, job); + } + } + Err(GpuFault::UnknownProvider(job.provider_id.clone())) + } + + pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Result, GpuFault> { + let mut out = Vec::with_capacity(jobs.len()); + for job in jobs { + out.push(self.dispatch(ctx, job)?); + } + Ok(out) + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs new file mode 100644 index 0000000000..411f64311a --- /dev/null +++ b/crates/gpu/src/tests.rs @@ -0,0 +1,69 @@ +#![allow(clippy::expect_used)] + +use crate::{ + DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, WorkerKind, chunk_buffer, f16_rgba_to_f32_bytes, f16_to_f32, + f16_to_f32_fast, +}; + +struct MemContext { + caps: DeviceCaps, + buffers: Vec>, +} + +impl GpuContext for MemContext { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + + fn worker_kind(&self) -> WorkerKind { + WorkerKind::Main + } + + fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { + let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); + self.buffers.push(bytes.to_vec()); + Ok(id) + } + + fn buffer_len(&self, handle: HandleId) -> Result { + self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } + + fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { + self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + } +} + +#[test] +fn unknown_provider_is_fault() { + let registry = ProviderRegistry::new(); + let mut ctx = MemContext { caps: DeviceCaps::default(), buffers: Vec::new() }; + let job = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); +} + +#[test] +fn f16_to_f32_matches_fast_for_one() { + let h = 0x3c00u16; + assert!((f16_to_f32(h) - 1.0).abs() < 1e-6); + assert_eq!(f16_to_f32(h).to_bits(), f16_to_f32_fast(h).to_bits()); +} + +#[test] +fn f16_rgba_to_f32_bytes_expands_texels() { + let src = 0x3c00u16.to_le_bytes(); + let mut raw = Vec::new(); + for _ in 0..4 { + raw.extend_from_slice(&src); + } + let out = f16_rgba_to_f32_bytes(&raw).expect("decode"); + assert_eq!(out.len(), 16); + assert!((f32::from_le_bytes(out[0..4].try_into().expect("le")) - 1.0).abs() < 1e-6); +} + +#[test] +fn chunk_buffer_splits_on_storage_binding_limit() { + let caps = DeviceCaps { max_storage_buffer_binding_size: 4, ..DeviceCaps::default() }; + let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); + assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); +} diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md new file mode 100644 index 0000000000..1e7a383cd0 --- /dev/null +++ b/docs/gpu-backends.md @@ -0,0 +1,14 @@ +# GPU backends + +| Crate | Role | +|-------|------| +| `craft-gpu` | Traits, `GpuJob`, `ProviderRegistry` | +| `craft-gpu-wgpu` | wgpu → WebGPU (wasm) / Vulkan·DX12·Metal (native) | +| `craft-gpu-null` | In-memory context for CI | + +Feature flags on `craft-gpu-wgpu`: + +- `adapter-probe` — native only; uses pollster to `request_adapter` and fill real [`DeviceCaps`](../crates/gpu/src/caps.rs) (falls back when no GPU, e.g. CI). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. + +On `wasm32`, wgpu is built with the `webgpu` feature; caps probing stays browser-default until async init lands in the worker. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md new file mode 100644 index 0000000000..33e5a021e9 --- /dev/null +++ b/docs/gpu-providers.md @@ -0,0 +1,14 @@ +# GPU providers + +Provider ids: + +- `craft.*` — shared ops in **craft-gpu-providers** (no app crate deps) +- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback` — registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init + - `craft.mask` — CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu + - `craft.composite.premul` — CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu + - `craft.readback` — CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `{app}.*` — registered by application wasm at init + +Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. + +Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. From f731e52528090126acb7fa884d64b42b9baa8d3c Mon Sep 17 00:00:00 2001 From: William Dunn Date: Tue, 10 Nov 2026 19:08:19 -0500 Subject: [PATCH 022/490] craft-gpu: real device wiring, device loss and async readback (RFC-0022) Addresses skylartaylor's review gate on #663 at 138f7b2. RFC-0022 has merged since that review. This follows its acceptance requirements. WgpuContext now requests a real device. DeviceCaps comes from that device, reflecting the limits and features actually enabled on it. Buffers are real wgpu::Buffer values when a device exists. The no-adapter case still degrades to the same staging behavior as craft-gpu-null. The RFC defines that case explicitly as the no-adapter path. Device loss is registered via set_device_lost_callback. It surfaces as GpuFault::DeviceLost. It never surfaces as a panic. The recovery is stated on GpuContext's trait docs. GpuContext::read_buffer is no longer a required method. The primitives are request_read and poll_reads. That mirrors craft-worker-host's own HostMessage::GpuJobs to WorkerMessage::GpuBatchDone split one level down. read_buffer stays as a default blocking convenience. It resolves immediately on the null and staging paths. Native wgpu blocks on Device::poll(wait_indefinitely). On wasm32 it returns GpuFault::Operation, since a blocking wait there would freeze the one thread map_async's own callback needs to run on. crates/gpu-wgpu/src/tests.rs adds a real-backend suite, gated on adapter-probe plus non-wasm32. It runs upload, readback and device-loss tests against a real WgpuContext. It also runs three craft-gpu-providers CPU-stand-in providers against that same real WgpuContext. It skips with a clear message when no adapter is present. Verified against lavapipe with mesa-vulkan-drivers, using --features adapter-probe,native-vulkan: every test passes. That run first caught a real wgpu panic on buffer lengths that are not a multiple of 4, COPY_BUFFER_ALIGNMENT. The fix pads real buffers transparently. Every caller still sees exact, unpadded bytes. docs/gpu-backends.md and docs/gpu-providers.md are updated to match, including named consumers (the runtime slice first, then EffectCraft and FilmCraft) and a device-ownership note for when egui's wgpu renderer is also running. --- crates/gpu-null/src/lib.rs | 50 ++++- crates/gpu-wgpu/Cargo.toml | 4 + crates/gpu-wgpu/src/lib.rs | 377 +++++++++++++++++++++++++++++++++-- crates/gpu-wgpu/src/tests.rs | 152 ++++++++++++++ crates/gpu/src/caps.rs | 13 ++ crates/gpu/src/context.rs | 73 ++++++- crates/gpu/src/error.rs | 6 + crates/gpu/src/lib.rs | 2 +- crates/gpu/src/tests.rs | 37 +++- docs/gpu-backends.md | 53 ++++- docs/gpu-providers.md | 4 + 11 files changed, 740 insertions(+), 31 deletions(-) create mode 100644 crates/gpu-wgpu/src/tests.rs diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index 66925b4901..b28fdf80b2 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -2,13 +2,18 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; -/// In-memory buffer store; no GPU hardware required. +/// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is +/// nothing to wait for), so [`request_read`](GpuContext::request_read) and +/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially, and the default +/// [`read_buffer`](GpuContext::read_buffer) never loops more than once. pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, buffers: Vec>, + next_request: u64, + ready: Vec, } impl NullContext { @@ -17,6 +22,8 @@ impl NullContext { caps: DeviceCaps { backend_name: "null".into(), device_name: "null".into(), ..DeviceCaps::default() }, worker_kind, buffers: Vec::new(), + next_request: 0, + ready: Vec::new(), } } } @@ -40,7 +47,42 @@ impl GpuContext for NullContext { self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } +} + +#[cfg(test)] +mod tests { + use craft_gpu::GpuContext; + + use super::NullContext; + use craft_gpu::WorkerKind; + + #[test] + fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("in", b"abc").expect("upload_buffer"); + let request = ctx.request_read(handle).expect("request_read"); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0].request, request); + assert_eq!(outcomes[0].handle, handle); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"abc".as_slice())); + } + + #[test] + fn read_buffer_default_still_works() { + let mut ctx = NullContext::new(WorkerKind::SharedWorker); + let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec()); } } diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml index 4f2c9ae5b2..ecf45c62f0 100644 --- a/crates/gpu-wgpu/Cargo.toml +++ b/crates/gpu-wgpu/Cargo.toml @@ -29,3 +29,7 @@ native-gles = ["wgpu/gles"] [dev-dependencies] pollster = { workspace = true } +# Real-backend test (crates/gpu-wgpu/src/tests.rs): dispatches craft-gpu-providers' CPU-stand-in +# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance +# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu). +craft-gpu-providers = { workspace = true } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 91aa8cc19b..009fd1e4b4 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -1,11 +1,28 @@ //! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). //! -//! WebGPU on `wasm32`; native APIs when backend features are enabled. Adapter probing is -//! optional on native via the `adapter-probe` feature (pollster). +//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe` +//! feature (native only, pollster) and at least one `native-*` backend feature, +//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device +//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's +//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present, +//! or on `wasm32` where real device creation needs the async worker-init path noted in +//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as +//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context); +//! that is RFC-0022's defined no-adapter path, not an error. +//! +//! Readback is asynchronous end to end (`request_read` + `poll_reads`), because WebGPU can only +//! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus +//! `Device::poll`. The blocking `read_buffer` convenience (see +//! [`GpuContext`](craft_gpu::GpuContext)'s trait docs) blocks efficiently on native by polling +//! the device while it waits; on `wasm32` it instead returns a fault, since blocking there would +//! freeze the one thread the map's own completion callback needs to run on. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, WorkerKind}; +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadRequest, WorkerKind}; + +#[cfg(test)] +mod tests; fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { DeviceCaps { backend_name: backend_name.into(), device_name: device_name.into(), ..DeviceCaps::default() } @@ -13,7 +30,7 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] fn probe_caps_native() -> DeviceCaps { - let instance = wgpu::Instance::default(); + let instance = native::instance(); let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { Ok(adapter) => adapter, Err(_) => return probe_fallback("wgpu", "no-adapter"), @@ -26,14 +43,18 @@ fn probe_caps_native() -> DeviceCaps { max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: Vec::new(), } } -/// Report device limits when an adapter is available; otherwise conservative defaults. +/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This +/// is the quick, device-free probe for UI surfaces that want a number before any context exists +/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted +/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists. pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] { - return probe_caps_native(); + probe_caps_native() } #[cfg(all(not(target_arch = "wasm32"), not(feature = "adapter-probe")))] @@ -47,20 +68,201 @@ pub fn probe_caps() -> DeviceCaps { } } -/// wgpu-backed context; buffer IO uses staging until full device wiring lands (craft-libs#6). +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +mod native { + use std::sync::{Arc, Mutex}; + + use craft_gpu::{DeviceCaps, GpuFault}; + + use crate::{Backing, DeviceBacking}; + + /// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu + /// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this + /// as real compute providers land, and it degrades gracefully regardless: see + /// [`create_device`]. + const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty(); + + /// An instance over whichever native backends were compiled in (`native-vulkan`, + /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the + /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in CI. + /// `new_without_display_handle` because this context never has a window (no surface is ever + /// requested); FilmCraft's own off-screen export device uses the same constructor for the + /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). + pub(crate) fn instance() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + if let Some(backends) = wgpu::Backends::from_env() { + desc.backends = backends; + } + wgpu::Instance::new(desc) + } + + /// Request a real device. `None` on the defined no-adapter path (no usable adapter): the + /// caller degrades to the staging backing, identical in shape to `craft-gpu-null`. + /// + /// Never panics: `required_features` is intersected with what the adapter actually + /// advertises, and `required_limits` is set to the adapter's own limits (never more), so + /// `request_device`'s documented panics ("features/limits not supported by this adapter") + /// cannot trigger here. + pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> { + let instance = instance(); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + let features = DESIRED_FEATURES & adapter.features(); + let limits = adapter.limits(); + let desc = + wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + + let lost = Arc::new(Mutex::new(None)); + { + let lost = Arc::clone(&lost); + device.set_device_lost_callback(move |reason, message| { + if let Ok(mut slot) = lost.lock() { + *slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}"))); + } + }); + } + + let info = device.adapter_info(); + let device_limits = device.limits(); + let caps = DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name, + max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size, + max_buffer_size: device_limits.max_buffer_size, + max_texture_dimension_2d: device_limits.max_texture_dimension_2d, + features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + }; + let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); + Some((caps, backing)) + } +} + +/// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined +/// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap). +#[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] +enum Backing { + Staging(Vec>), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +enum Backing { + Staging(Vec>), + /// A real device. `DeviceCaps` was built from it, not from the adapter it came from. + Device(DeviceBacking), +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct DeviceBacking { + device: wgpu::Device, + queue: wgpu::Queue, + /// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer + /// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to + /// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length, + /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. + buffers: Vec<(wgpu::Buffer, u64)>, + /// Set by the device-lost callback registered in [`native::create_device`]; checked before + /// every call that would otherwise touch the (now invalid) device. + lost: std::sync::Arc>>, + pending: Vec, +} + +/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` / +/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back +/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error +/// on native wgpu, surfaced as a panic from inside `wgpu-core`'s own uncaptured-error path unless +/// padded first; `craft-gpu-null`'s plain `Vec` has no such constraint, so this padding is +/// purely an artifact of the real backend, kept invisible to every caller of this crate. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +const COPY_ALIGN: u64 = 4; + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +struct PendingRead { + request: ReadRequest, + handle: HandleId, + staging: wgpu::Buffer, + /// True length to truncate the mapped (padded) bytes back down to. + true_len: u64, + state: std::sync::Arc>>>, +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +fn resolve_pending(pending: PendingRead) -> ReadOutcome { + let PendingRead { request, handle, staging, true_len, state } = pending; + let result = match state.lock() { + Ok(mut guard) => match guard.take() { + Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) { + Ok(view) => { + let mut bytes = view.to_vec(); + drop(view); + staging.unmap(); + bytes.truncate(usize::try_from(true_len).unwrap_or(usize::MAX)); + Ok(bytes) + } + Err(err) => Err(GpuFault::Operation(err.to_string())), + }, + Some(Err(message)) => Err(GpuFault::Operation(message)), + None => Err(GpuFault::Operation("read_buffer: map_async callback has not run yet".into())), + }, + Err(_) => Err(GpuFault::Operation("read_buffer: map state lock poisoned".into())), + }; + ReadOutcome { request, handle, result } +} + +/// wgpu-backed context. See the module docs for the real-device-vs-staging split. pub struct WgpuContext { caps: DeviceCaps, worker_kind: WorkerKind, - staging: Vec>, + backing: Backing, + next_request: u64, + ready: Vec, } impl WgpuContext { pub fn new(worker_kind: WorkerKind) -> Self { - Self { caps: probe_caps(), worker_kind, staging: Vec::new() } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + { + if let Some((caps, backing)) = native::create_device() { + return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }; + } + } + Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } + /// Force the staging (no-device) path with caller-supplied caps. For tests, and for callers + /// that intentionally want the portable path (FilmCraft's `?webgl` / `?nogpuworkers`, per + /// `docs/pilot-filmcraft.md`) rather than a real device's own caps. pub fn with_caps(worker_kind: WorkerKind, caps: DeviceCaps) -> Self { - Self { caps, worker_kind, staging: Vec::new() } + Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } + } + + /// True when this context holds a real device (`request_device` succeeded), false on the + /// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of + /// implying a device that was never created; tests use it to skip rather than fail when the + /// host genuinely has no usable adapter (see `crates/gpu-wgpu/src/tests.rs`). + pub fn has_device(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if matches!(self.backing, Backing::Device(_)) { + return true; + } + false + } + + /// True once the device has reported loss. Every [`DeviceCaps`] read before this point is + /// stale; see [`GpuContext`]'s trait docs for the recovery this context expects. + pub fn is_device_lost(&self) -> bool { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().map(|g| g.is_some()).unwrap_or(false); + } + false + } + + fn take_lost_fault(&self) -> Option { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.lost.lock().ok().and_then(|g| g.clone()); + } + None } } @@ -73,17 +275,158 @@ impl GpuContext for WgpuContext { self.worker_kind } - fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { - let id = HandleId(u32::try_from(self.staging.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.staging.push(bytes.to_vec()); - Ok(id) + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))] + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + if bytes.is_empty() { + return Err(GpuFault::InvalidJob("upload_buffer: bytes must be non-empty".into())); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + buffers.push(bytes.to_vec()); + Ok(HandleId(id)) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let true_len = bytes.len() as u64; + let padded_len = true_len.next_multiple_of(COPY_ALIGN); + let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: padded_len, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + if padded_len == true_len { + d.queue.write_buffer(&buffer, 0, bytes); + } else { + let mut padded = bytes.to_vec(); + padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); + d.queue.write_buffer(&buffer, 0, &padded); + } + let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; + d.buffers.push((buffer, true_len)); + Ok(HandleId(id)) + } + } } fn buffer_len(&self, handle: HandleId) -> Result { - self.staging.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &self.backing { + Backing::Staging(buffers) => buffers.get(handle.0 as usize).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())), + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then(|(_, true_len)| { + usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) + }) + } + } } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.staging.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + match &mut self.backing { + Backing::Staging(buffers) => { + let bytes = buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let true_len = *true_len; + let copy_len = true_len.next_multiple_of(COPY_ALIGN); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft-gpu-wgpu.read-staging"), + size: copy_len, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); + d.queue.submit(Some(encoder.finish())); + let state = std::sync::Arc::new(std::sync::Mutex::new(None)); + { + let state = std::sync::Arc::clone(&state); + staging.map_async(wgpu::MapMode::Read, 0..copy_len, move |result| { + if let Ok(mut slot) = state.lock() { + *slot = Some(result.map_err(|e| e.to_string())); + } + }); + } + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + d.pending.push(PendingRead { request, handle, staging, true_len, state }); + Ok(request) + } + } + } + + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))] + fn poll_reads(&mut self) -> Vec { + let mut outcomes = std::mem::take(&mut self.ready); + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &mut self.backing { + if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) { + outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) })); + return outcomes; + } + let _ = d.device.poll(wgpu::PollType::Poll); + let mut remaining = Vec::with_capacity(d.pending.len()); + for pending in d.pending.drain(..) { + let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false); + if is_ready { + outcomes.push(resolve_pending(pending)); + } else { + remaining.push(pending); + } + } + d.pending = remaining; + } + outcomes + } + + #[cfg(not(target_arch = "wasm32"))] + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + for outcome in self.poll_reads() { + if outcome.request == request { + return outcome.result; + } + } + // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when + // `backing` is `Staging` (nothing to wait for; the request already resolved above) + // or when wgpu is itself WebGPU under the hood, which self-polls. + #[cfg(feature = "adapter-probe")] + if let Backing::Device(d) = &self.backing { + let _ = d.device.poll(wgpu::PollType::wait_indefinitely()); + } + } + } + + /// WebGPU can only map a buffer asynchronously, and `wasm32` is single-threaded: blocking + /// here would stop the only thread the browser needs to run `map_async`'s own completion + /// callback on, hanging the tab instead of returning. Callers on this target drive + /// [`request_read`](GpuContext::request_read) and [`poll_reads`](GpuContext::poll_reads) + /// directly from the worker's message loop; see `docs/gpu-backends.md`. + #[cfg(target_arch = "wasm32")] + fn read_buffer(&mut self, _handle: HandleId) -> Result, GpuFault> { + Err(GpuFault::Operation( + "read_buffer is not supported on wasm32/WebGPU: it can only map asynchronously. Use request_read + poll_reads from the worker's \ + message loop instead." + .into(), + )) } } diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs new file mode 100644 index 0000000000..0ea49d5dfc --- /dev/null +++ b/crates/gpu-wgpu/src/tests.rs @@ -0,0 +1,152 @@ +#![allow(clippy::expect_used)] + +//! RFC-0022 acceptance requirement 2: real backends beside the null one. `craft-gpu-null` stays +//! mandatory for every consumer (it cannot validate shader compilation, resource rules, or +//! numerical results), so these tests run representative jobs on a real wgpu device when one is +//! available, and skip loudly rather than failing the suite when the host genuinely has none +//! (`cargo test` without `--features adapter-probe,native-vulkan` already exercises the masked +//! path: no adapter is ever requested, and every context here falls back to the staging path, +//! same shape as `craft-gpu-null`). +//! +//! Tolerance: every job below is byte/structural equality, not a numeric comparison with slack. +//! That is honest for what runs today: no provider dispatches a real WGSL compute job yet +//! (`craft-gpu-providers` ships CPU stand-ins by design; see `docs/gpu-providers.md`), so the only +//! thing a real device adds over the null one here is the upload → real `wgpu::Buffer` → copy → +//! `map_async` → read round trip itself. A provider that dispatches actual WGSL will need a +//! stated numeric tolerance of its own when it lands; this suite is not that provider. + +use craft_gpu::{GpuContext, GpuJob, GpuJobParams, GpuProvider, WorkerKind}; +use craft_gpu_providers::{EchoProvider, PremulCompositeProvider, ReadbackProvider}; + +use crate::WgpuContext; + +/// A real device if this host has one; otherwise `None` with a loud, honest message instead of a +/// failed assertion. Call at the top of every test in this module. +fn real_context_or_skip(test_name: &str) -> Option { + let ctx = WgpuContext::new(WorkerKind::Main); + if ctx.has_device() { + return Some(ctx); + } + eprintln!( + "SKIP {test_name}: no real wgpu device in this environment (no backend feature compiled \ + in, or `request_adapter` found nothing). This is RFC-0022's defined no-adapter path, not \ + a failure; craft-gpu-null already covers the portable contract. Run with \ + `--features adapter-probe,native-vulkan` against a Vulkan adapter (a software one, such \ + as lavapipe/llvmpipe via mesa-vulkan-drivers, is enough) to exercise this suite for real." + ); + None +} + +#[test] +fn real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested() { + let Some(ctx) = real_context_or_skip("real_device_reports_a_non_null_backend_and_empty_features_it_actually_requested") else { + return; + }; + let caps = ctx.caps(); + assert_ne!(caps.backend_name, "null", "a real device must not report the null backend name"); + assert_ne!(caps.device_name, "no-adapter", "has_device() was true; caps must not be the no-adapter fallback"); + assert_ne!(caps.device_name, "probe-not-run", "has_device() was true; caps must not be the probe-skipped fallback"); + // This context asks the device for no features yet (no provider dispatches real WGSL): the + // device reports exactly what was requested, per `Device::features`' own contract, so this is + // device-truth agreeing with an intentionally empty request, not an unprobed default. + assert!(caps.features.is_empty(), "no feature was requested, so none should be reported enabled: {:?}", caps.features); +} + +#[test] +fn real_device_upload_and_async_readback_round_trips_bytes_exactly() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_async_readback_round_trips_bytes_exactly") else { + return; + }; + let payload: Vec = (0..256u32).map(|b| b as u8).collect(); + let handle = ctx.upload_buffer("round-trip", &payload).expect("upload_buffer on a real device"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), payload.len()); + + // Exercise request_read + poll_reads directly (the primitive every backend implements), + // not just the read_buffer convenience, so the async shape itself is under test. + let request = ctx.request_read(handle).expect("request_read"); + let mut got = None; + // Non-blocking poll_reads() in a bounded loop, exercising the exact primitive a worker's own + // message/poll loop would call; read_buffer_convenience (a separate test) covers the blocking + // path. The bound is generous for a software rasterizer on a 256-byte buffer, never relying + // on wall-clock sleeps. + for _ in 0..1_000_000 { + if let Some(outcome) = ctx.poll_reads().into_iter().find(|o| o.request == request) { + got = Some(outcome.result.expect("map_async + Device::poll round trip")); + break; + } + } + assert_eq!(got.expect("the real device never completed the mapped read within the bounded poll loop"), payload); +} + +#[test] +fn real_device_read_buffer_convenience_blocks_to_completion() { + let Some(mut ctx) = real_context_or_skip("real_device_read_buffer_convenience_blocks_to_completion") else { + return; + }; + let handle = ctx.upload_buffer("blocking-read", b"craft-gpu-wgpu").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"craft-gpu-wgpu".to_vec()); +} + +/// RFC-0022 requirement 2's "representative jobs": the same `craft-gpu-providers` CPU stand-ins +/// `craft-runtime` dispatches against the null context in CI also run, unmodified, against a +/// real device, through the same `&mut dyn GpuContext` seam. +#[test] +fn shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context() { + let Some(mut ctx) = real_context_or_skip("shared_providers_run_against_a_real_device_through_the_same_seam_as_the_null_context") else { + return; + }; + + let echo = EchoProvider; + let input = ctx.upload_buffer("echo-in", b"xy").expect("upload_buffer"); + let job = GpuJob { provider_id: "craft.test.echo".into(), params: GpuJobParams(b"a".to_vec()), inputs: vec![input], outputs: vec![] }; + let out = echo.run(&mut ctx, &job).expect("craft.test.echo on a real device"); + assert_eq!(out.data.as_deref(), Some(b"axy".as_slice())); + + let composite = PremulCompositeProvider; + let dst = ctx.upload_buffer("dst", &[0, 255, 0, 255]).expect("upload dst"); + let src = ctx.upload_buffer("src", &[0, 0, 255, 128]).expect("upload src"); + let job = + GpuJob { provider_id: "craft.composite.premul".into(), params: GpuJobParams(b"w:1,h:1".to_vec()), inputs: vec![dst, src], outputs: vec![] }; + let out = composite.run(&mut ctx, &job).expect("craft.composite.premul on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read composite output off a real device"); + assert_eq!(bytes, vec![0, 127, 128, 255]); + + let readback = ReadbackProvider; + let rgba = ctx.upload_buffer("rgba", &[10, 20, 30, 40]).expect("upload rgba"); + let job = GpuJob { provider_id: "craft.readback".into(), params: GpuJobParams(b"w:1,h:1,fmt:u8".to_vec()), inputs: vec![rgba], outputs: vec![] }; + let out = readback.run(&mut ctx, &job).expect("craft.readback fmt:u8 on a real device"); + let bytes = ctx.read_buffer(out.outputs[0]).expect("read readback output off a real device"); + assert_eq!(bytes, vec![10, 20, 30, 40]); +} + +/// RFC-0022 requirement 1's device-loss half: a stated fault, not a panic, and a documented +/// recovery. `Backing`/`DeviceBacking` are crate-private, so this test reaches `ctx.backing` +/// directly to force the one cause it can trigger deterministically (`device.destroy()`) rather +/// than waiting on a real driver reset. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(mut ctx) = real_context_or_skip("device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls") else { + return; + }; + assert!(!ctx.is_device_lost(), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + // The lost closure can run during destroy() or on the next poll, depending on backend; + // give it the chance either way. + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // poll_reads() is the other place the trait docs promise this surfaces, for a caller that + // polls instead of issuing a buffer call first. + let _ = ctx.poll_reads(); + assert!(ctx.is_device_lost(), "device.destroy() must surface through is_device_lost(), per the GpuContext trait docs"); + + let after = ctx.upload_buffer("after-loss", b"x"); + assert!(matches!(after, Err(GpuFault::DeviceLost(_))), "a call after device loss must return GpuFault::DeviceLost, got {after:?}"); +} diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index ae63a43ab2..75dcf173d0 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -1,6 +1,13 @@ use serde::{Deserialize, Serialize}; /// Limits and labels reported to Settings UI and worker RPC (`GpuCaps`). +/// +/// Per RFC-0022's acceptance requirements, a backend that has a device fills every field here +/// from that created device, never from the adapter it was created on: an adapter advertises more +/// than a device may grant (`required_features`/`required_limits` at `request_device` time narrow +/// both). `craft-gpu-wgpu` reports [`Default`]-shaped conservative values only on the defined +/// no-adapter path (no GPU present, the feature compiled out, or the `wasm32` worker-init gap +/// described in `docs/gpu-backends.md`), never as a stand-in for a real device's own caps. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct DeviceCaps { pub backend_name: String, @@ -8,6 +15,11 @@ pub struct DeviceCaps { pub max_storage_buffer_binding_size: u64, pub max_buffer_size: u64, pub max_texture_dimension_2d: u32, + /// Feature names actually enabled on the created device (`wgpu::Features::iter_names` on + /// native wgpu), empty on backends with no device. A fast path gates on membership here, + /// never on what the adapter merely advertised. + #[serde(default)] + pub features: Vec, } impl Default for DeviceCaps { @@ -18,6 +30,7 @@ impl Default for DeviceCaps { max_storage_buffer_binding_size: 128 * 1024 * 1024, max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, + features: Vec::new(), } } } diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 8d565e3441..df0d5e308a 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -8,7 +8,55 @@ pub enum WorkerKind { SharedWorker, } +/// Opaque in-flight readback request handed out by [`GpuContext::request_read`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ReadRequest(pub u64); + +/// One completed (or failed) readback, delivered by [`GpuContext::poll_reads`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReadOutcome { + pub request: ReadRequest, + pub handle: HandleId, + pub result: Result, GpuFault>, +} + /// Device/queue abstraction implemented by `craft-gpu-wgpu` and `craft-gpu-null`. +/// +/// ## Device loss +/// +/// A context can lose its device at any time: a driver reset, OS-level eviction under memory +/// pressure, or an explicit `device.destroy()`. Device loss is a fault, not a panic. It surfaces +/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device, and +/// also through [`poll_reads`](Self::poll_reads), so a host's event loop can observe it even +/// between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every +/// [`DeviceCaps`] it reported before that point is stale. The consumer's recovery, per RFC-0022, +/// is one of: +/// +/// - fall back to the portable path (a [`DeviceCaps`]-gated path with no fast-path features, or a +/// different, CPU-backed [`GpuContext`]) for the rest of the session, or +/// - re-acquire a device, meaning construct a fresh [`GpuContext`], and re-probe +/// [`caps`](Self::caps) before resuming GPU jobs. +/// +/// No backend here supports continuing to dispatch jobs against a context that has already +/// reported device loss, using caps read before the loss. +/// +/// ## Readback +/// +/// [`read_buffer`](Self::read_buffer) is a blocking convenience built on +/// [`request_read`](Self::request_read) and [`poll_reads`](Self::poll_reads): those two are the +/// primitives every backend implements directly, because WebGPU (and therefore native wgpu's +/// `buffer.map_async`) can only map a buffer asynchronously. The completion is delivered the same +/// way a `GpuJob` batch's outcome is delivered to a worker's host: queued, then collected on a +/// later poll, analogous to `craft-worker-host`'s `HostMessage::GpuJobs` being answered later by +/// `WorkerMessage::GpuBatchDone`. +/// +/// A backend that can honestly block (the null context, which never has anything to wait for; +/// native wgpu driving `Device::poll` itself) uses `read_buffer`'s default body. A backend that +/// cannot honestly block without freezing its single thread (WebGPU on `wasm32`, where a map +/// completes only via the browser's own event loop) overrides `read_buffer` to return +/// [`GpuFault::Operation`] instead of deadlocking; callers there must drive `request_read` and +/// `poll_reads` from the worker's own message loop. See `docs/gpu-backends.md` for which backend +/// does which. pub trait GpuContext { fn caps(&self) -> DeviceCaps; @@ -19,5 +67,28 @@ pub trait GpuContext { fn buffer_len(&self, handle: HandleId) -> Result; - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault>; + /// Queue an asynchronous readback of `handle`. Completion is delivered by + /// [`poll_reads`](Self::poll_reads). + fn request_read(&mut self, handle: HandleId) -> Result; + + /// Drain every read completed (or failed) since the last call. Also where a device-lost + /// fault surfaces for callers that are polling rather than issuing buffer calls. A context + /// that resolves reads synchronously (the null context; native wgpu with no device) may + /// resolve a request on the very next call after [`request_read`](Self::request_read). + fn poll_reads(&mut self) -> Vec; + + /// Blocking convenience for callers that need bytes now, such as the CPU-stand-in providers + /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and + /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly + /// support blocking here and which override this to fail instead of hanging. + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + loop { + for outcome in self.poll_reads() { + if outcome.request == request { + return outcome.result; + } + } + } + } } diff --git a/crates/gpu/src/error.rs b/crates/gpu/src/error.rs index 2a44f4b6a0..794611efb9 100644 --- a/crates/gpu/src/error.rs +++ b/crates/gpu/src/error.rs @@ -9,6 +9,12 @@ pub enum GpuFault { InvalidJob(String), #[error("device unavailable: {0}")] DeviceUnavailable(String), + /// The device was lost (driver reset, OS eviction, explicit `destroy()`) after it was + /// created. Every [`crate::DeviceCaps`] read before this point is stale: per + /// [`crate::GpuContext`]'s trait docs, fall back to the portable path or re-acquire a device + /// and re-probe caps. Never keep dispatching jobs against a context that reported this. + #[error("device lost: {0}")] + DeviceLost(String), #[error("operation failed: {0}")] Operation(String), } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index bf4993f30e..58ba45ebd0 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -19,7 +19,7 @@ mod tests; pub use caps::DeviceCaps; pub use chunk::chunk_buffer; -pub use context::{GpuContext, WorkerKind}; +pub use context::{GpuContext, ReadOutcome, ReadRequest, WorkerKind}; pub use error::GpuFault; pub use job::{GpuJob, GpuJobOutcome, GpuJobParams, HandleId}; pub use provider::GpuProvider; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 411f64311a..56ea34e109 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1,13 +1,15 @@ #![allow(clippy::expect_used)] use crate::{ - DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, WorkerKind, chunk_buffer, f16_rgba_to_f32_bytes, f16_to_f32, - f16_to_f32_fast, + DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind, chunk_buffer, + f16_rgba_to_f32_bytes, f16_to_f32, f16_to_f32_fast, }; struct MemContext { caps: DeviceCaps, buffers: Vec>, + next_request: u64, + ready: Vec, } impl GpuContext for MemContext { @@ -29,19 +31,44 @@ impl GpuContext for MemContext { self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } - fn read_buffer(&self, handle: HandleId) -> Result, GpuFault> { - self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + fn request_read(&mut self, handle: HandleId) -> Result { + let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let request = ReadRequest(self.next_request); + self.next_request = self.next_request.wrapping_add(1); + self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); + Ok(request) } + + fn poll_reads(&mut self) -> Vec { + std::mem::take(&mut self.ready) + } +} + +fn mem_context() -> MemContext { + MemContext { caps: DeviceCaps::default(), buffers: Vec::new(), next_request: 0, ready: Vec::new() } } #[test] fn unknown_provider_is_fault() { let registry = ProviderRegistry::new(); - let mut ctx = MemContext { caps: DeviceCaps::default(), buffers: Vec::new() }; + let mut ctx = mem_context(); let job = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); } +#[test] +fn read_buffer_default_resolves_against_request_read_and_poll_reads() { + let mut ctx = mem_context(); + let handle = ctx.upload_buffer("in", b"hello").expect("upload_buffer"); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"hello".to_vec()); +} + +#[test] +fn request_read_on_bad_handle_is_invalid_job() { + let mut ctx = mem_context(); + assert!(matches!(ctx.request_read(HandleId(99)), Err(GpuFault::InvalidJob(_)))); +} + #[test] fn f16_to_f32_matches_fast_for_one() { let h = 0x3c00u16; diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 1e7a383cd0..35527d5b0b 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,7 +8,54 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe` — native only; uses pollster to `request_adapter` and fill real [`DeviceCaps`](../crates/gpu/src/caps.rs) (falls back when no GPU, e.g. CI). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. +- `adapter-probe` — native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. -On `wasm32`, wgpu is built with the `webgpu` feature; caps probing stays browser-default until async init lands in the worker. +## Real device, device-truth caps (RFC-0022 requirement 1) + +With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device`, not just `request_adapter`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing — no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. + +Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`), not a `Vec>` staged on the host. + +**The no-adapter path is still defined, not an error.** Without a usable adapter — `adapter-probe` off, no backend feature on, no GPU present, or on `wasm32` (see below) — `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. + +**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker" — that landing hasn't happened yet. `request_adapter`/`request_device` are JS promises; driving them synchronously the way `pollster::block_on` does natively isn't available on `wasm32`, and wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. + +## Device loss (RFC-0022 requirement 1) + +`WgpuContext` registers `Device::set_device_lost_callback` when it creates a real device. Loss (a driver reset, OS-level eviction, or an explicit `destroy()`) surfaces as `GpuFault::DeviceLost`, from the next buffer call and from `poll_reads()`, never as a panic. + +Once a context has reported `GpuFault::DeviceLost`, every `DeviceCaps` it reported before that point is stale. The stated recovery, per the trait docs on [`GpuContext`](../crates/gpu/src/context.rs): + +1. fall back to the portable path for the rest of the session, or +2. construct a fresh `GpuContext` and re-probe `caps()` before resuming GPU jobs. + +No backend here supports continuing to dispatch jobs against a context that already reported loss, using caps read before it. + +## Async readback (RFC-0022 requirement 3) + +`GpuContext::read_buffer` used to be synchronous. WebGPU can only map a buffer asynchronously (`map_async`), so the trait's real primitives are now `request_read` (queue a readback, get a `ReadRequest`) and `poll_reads` (drain completions). This mirrors `craft-worker-host`'s own async shape: a `HostMessage::GpuJobs { batch_id, .. }` is answered later by `WorkerMessage::GpuBatchDone { batch_id, outcomes }`, not inline; `request_read`/`poll_reads` is the same split one level down, for one buffer instead of one job batch. + +`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`): + +- `craft-gpu-null`: resolves every request immediately — nothing to wait for. +- `craft-gpu-wgpu`, native, with a real device: blocks by calling `Device::poll(PollType::wait_indefinitely())` between polls, so it waits on the GPU instead of busy-spinning the CPU. +- `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. +- `craft-gpu-wgpu`, `wasm32`: **returns `GpuFault::Operation`, not bytes.** `wasm32` is single-threaded; blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab, not return. A caller there must drive `request_read` + `poll_reads` from the worker's own message loop instead of calling `read_buffer`. + +**Known follow-up on `craft-libs#662`.** That branch's `RuntimeContext` wrapper (`crates/runtime/src/runtime.rs`) implements `GpuContext` by matching on its `Null`/`Wgpu` variants, including an explicit `read_buffer` arm. When #662 rebases past this PR, that block needs two added match arms (`request_read`, `poll_reads`) delegating to each inner context the same way the existing methods do, and its own `read_buffer` arm can simply be deleted in favor of the trait's default (or kept, delegating the same way). No logic in `craft-worker-host` or the runtime facade changes: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, same as before this PR. + +## Named consumers (RFC-0022's "what this RFC decides") + +- **First: the runtime slice**, `craft-libs#662` (`craft-worker-host`, the worker-host executing `GpuJob` batches; `craft-runtime`, the facade `RuntimeBuilder`/`Runtime` build on top of `GpuContext`). +- **Second: the render-path apps**, EffectCraft and FilmCraft. Neither has adopted these crates yet (see `docs/pilot-effectcraft.md`, `docs/pilot-filmcraft.md`); both already carry their own hand-rolled wgpu code today: + - **FilmCraft** (`storytold/filmcraft`, `crates/gpu` = `filmcraft-gpu`): a monitor/preview `GpuCompositor` over `composite.wgsl`, `mask.rs`/`mask.wgsl`, `lut.rs`/`lut.wgsl`, `transition.rs`/`transition.wgsl`, plus its own adapter-selection policy (`adapter.rs`, see device ownership below) and a separate off-screen `ExportRenderer`. The pilot doc orders `craft.mask`, `craft.lut`, `craft.transition`, then `craft.composite`/`craft.readback` as the extraction sequence into `craft-gpu-providers`. + - **EffectCraft** (`storytold/effectcraft`, `apps/effectcraft-web`): its own `store.rs`/`persist.rs`/`diskcache.rs` and dedicated-worker GPU dispatch (`worker.rs`, `frames.rs`); app-specific jobs route through `effectcraft.*` provider ids once it adopts `craft-runtime`, with the shared `craft.*` ids from this slice used alongside them. + +## Device ownership, when egui's wgpu renderer is also running + +The question that decides whether a render-path app can adopt `WgpuContext` as-is: who owns the `Device`/`Queue` when egui (via `eframe`/`egui-wgpu`) is also drawing? + +**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created — one device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. + +`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor — it does not change `GpuContext`'s trait shape — but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index 33e5a021e9..0705b9124f 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -12,3 +12,7 @@ Provider ids: Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. + +## Readback is async underneath; these providers don't see it + +`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that: `craft-gpu-null` still resolves `read_buffer` immediately, and `craft-gpu-wgpu`'s native path now does too, by blocking on the device between polls instead of staging in a plain `Vec>`. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext`, not just the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly, since on `wasm32` `read_buffer` itself returns a fault rather than blocking. From 1ccaafb7ab7564af30341324601ce8071002541a Mon Sep 17 00:00:00 2001 From: William Dunn Date: Tue, 10 Nov 2026 21:20:50 -0500 Subject: [PATCH 023/490] craft-gpu: buffer-size guards, empty-buffer parity, read_buffer keeps other completions Answers the six findings in CodeRabbit review 5852678306 on PR #663. upload_buffer on the device path refuses a padded size past the device's max_buffer_size with GpuFault::InvalidJob before creating the buffer. request_read guards its staging copy the same way. An oversized request used to reach wgpu as a validation error on the device's error scope. Empty buffers are accepted everywhere, matching craft-gpu-null and the documented staging parity. The device path resolves an empty readback immediately (wgpu refuses an empty map range). The blanket InvalidJob on empty upload bytes is gone. read_buffer no longer eats completions that belong to another outstanding request. The wgpu override re-queues them for the next poll_reads. The null context gains an override that takes only its own completion. The trait's default-body contract is documented: with the default body, do not interleave read_buffer with an outstanding request_read. ReadbackProvider validates the storage-binding cap directly. The old chunk_buffer call allocated a Vec of slices only to drop it. parse_u32 and params_contain refuse an empty prefix or needle. windows(0) panics and the crate's rule is never to crash. The manifest guard test now also rejects *-engine dependency lines, per docs/gpu-providers.md. --- crates/gpu-null/src/lib.rs | 35 +++++++++++++++++- crates/gpu-providers/src/params.rs | 6 ++- crates/gpu-providers/src/readback.rs | 10 +++-- crates/gpu-providers/src/tests.rs | 15 +++++++- crates/gpu-wgpu/src/lib.rs | 36 ++++++++++++++++-- crates/gpu-wgpu/src/tests.rs | 55 ++++++++++++++++++++++++++++ crates/gpu/src/context.rs | 6 +++ 7 files changed, 152 insertions(+), 11 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index b28fdf80b2..f5c6dbb188 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -6,8 +6,10 @@ use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadReq /// In-memory buffer store; no GPU hardware required. Reads resolve synchronously (there is /// nothing to wait for), so [`request_read`](GpuContext::request_read) and -/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially, and the default -/// [`read_buffer`](GpuContext::read_buffer) never loops more than once. +/// [`poll_reads`](GpuContext::poll_reads) satisfy the trait trivially. +/// [`read_buffer`](GpuContext::read_buffer) is overridden to take only its own completion, +/// leaving completions for other outstanding requests queued for the next +/// [`poll_reads`](GpuContext::poll_reads). pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, @@ -58,6 +60,14 @@ impl GpuContext for NullContext { fn poll_reads(&mut self) -> Vec { std::mem::take(&mut self.ready) } + + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())), + } + } } #[cfg(test)] @@ -85,4 +95,25 @@ mod tests { let handle = ctx.upload_buffer("in", b"xyz").expect("upload_buffer"); assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), b"xyz".to_vec()); } + + #[test] + fn read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); + } + + #[test] + fn an_empty_buffer_uploads_and_reads_back_empty() { + let mut ctx = NullContext::new(WorkerKind::Main); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); + } } diff --git a/crates/gpu-providers/src/params.rs b/crates/gpu-providers/src/params.rs index 2327aa3efa..7571897dfe 100644 --- a/crates/gpu-providers/src/params.rs +++ b/crates/gpu-providers/src/params.rs @@ -1,6 +1,10 @@ use craft_gpu::GpuJobParams; pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { + // `windows(0)` panics; an empty prefix is a caller bug, answered with None, not a crash. + if prefix.is_empty() { + return None; + } let bytes = params.0.as_slice(); let start = bytes.windows(prefix.len()).position(|w| w == prefix)? + prefix.len(); let rest = &bytes[start..]; @@ -9,5 +13,5 @@ pub(crate) fn parse_u32(params: &GpuJobParams, prefix: &[u8]) -> Option { } pub(crate) fn params_contain(params: &GpuJobParams, needle: &[u8]) -> bool { - params.0.windows(needle.len()).any(|w| w == needle) + !needle.is_empty() && params.0.windows(needle.len()).any(|w| w == needle) } diff --git a/crates/gpu-providers/src/readback.rs b/crates/gpu-providers/src/readback.rs index fb27f798ca..1428fba588 100644 --- a/crates/gpu-providers/src/readback.rs +++ b/crates/gpu-providers/src/readback.rs @@ -1,4 +1,4 @@ -use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, chunk_buffer, f16_rgba_to_f32_bytes}; +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuProvider, f16_rgba_to_f32_bytes}; use crate::params::{params_contain, parse_u32}; @@ -15,8 +15,12 @@ impl GpuProvider for ReadbackProvider { let height = parse_u32(&job.params, b"h:").unwrap_or(0); let input = job.inputs.first().copied().ok_or_else(|| GpuFault::InvalidJob("craft.readback expects one input buffer".into()))?; let raw = ctx.read_buffer(input)?; - let caps = ctx.caps(); - let _chunks = chunk_buffer(&caps, &raw)?; + // A real GPU provider binds the input as a storage buffer. Refuse a caps report no + // device path could satisfy, instead of pretending this stand-in's readback would have + // worked there. + if ctx.caps().max_storage_buffer_binding_size == 0 { + return Err(GpuFault::Operation("max_storage_buffer_binding_size must be non-zero".into())); + } let out_bytes = if params_contain(&job.params, b"fmt:u8") { let need = usize::try_from(width.saturating_mul(height).saturating_mul(4)).map_err(|_| GpuFault::InvalidJob("w*h overflow".into()))?; diff --git a/crates/gpu-providers/src/tests.rs b/crates/gpu-providers/src/tests.rs index b996ca57b2..650ae22e62 100644 --- a/crates/gpu-providers/src/tests.rs +++ b/crates/gpu-providers/src/tests.rs @@ -38,12 +38,25 @@ fn gpu_providers_cargo_has_no_app_deps() { for line in manifest.lines() { let t = line.trim(); assert!( - !(t.starts_with("effectcraft") || t.starts_with("filmcraft") || t.contains("effectcraft-") || t.contains("filmcraft-")), + !(t.starts_with("effectcraft") + || t.starts_with("filmcraft") + || t.contains("effectcraft-") + || t.contains("filmcraft-") + || t.contains("-engine =") + || t.contains("-engine.") + || t.contains("-engine\"")), "forbidden app dependency line: {t}" ); } } +#[test] +fn empty_param_prefix_and_needle_are_refused_not_a_panic() { + let params = GpuJobParams(b"w:3,h:2".to_vec()); + assert_eq!(crate::params::parse_u32(¶ms, b""), None); + assert!(!crate::params::params_contain(¶ms, b"")); +} + #[test] fn mask_provider_multiplies_rgba_by_mask_on_cpu() { let mut registry = ProviderRegistry::new(); diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 009fd1e4b4..cdc1343b75 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -280,9 +280,6 @@ impl GpuContext for WgpuContext { if let Some(fault) = self.take_lost_fault() { return Err(fault); } - if bytes.is_empty() { - return Err(GpuFault::InvalidJob("upload_buffer: bytes must be non-empty".into())); - } match &mut self.backing { Backing::Staging(buffers) => { let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -293,6 +290,12 @@ impl GpuContext for WgpuContext { Backing::Device(d) => { let true_len = bytes.len() as u64; let padded_len = true_len.next_multiple_of(COPY_ALIGN); + if padded_len > self.caps.max_buffer_size { + return Err(GpuFault::InvalidJob(format!( + "upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -345,7 +348,22 @@ impl GpuContext for WgpuContext { Backing::Device(d) => { let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let true_len = *true_len; + if true_len == 0 { + // An empty buffer has nothing to copy or map (wgpu refuses an empty map + // range); resolve it immediately, same as the staging path. + let id = self.next_request; + self.next_request = self.next_request.wrapping_add(1); + let request = ReadRequest(id); + self.ready.push(ReadOutcome { request, handle, result: Ok(Vec::new()) }); + return Ok(request); + } let copy_len = true_len.next_multiple_of(COPY_ALIGN); + if copy_len > self.caps.max_buffer_size { + return Err(GpuFault::Operation(format!( + "request_read: staging copy of {copy_len} bytes exceeds the device's max_buffer_size {}", + self.caps.max_buffer_size + ))); + } let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -401,11 +419,21 @@ impl GpuContext for WgpuContext { fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { let request = self.request_read(handle)?; loop { + let mut matched = None; + let mut others = Vec::new(); for outcome in self.poll_reads() { if outcome.request == request { - return outcome.result; + matched = Some(outcome.result); + } else { + others.push(outcome); } } + // Completions belonging to other outstanding requests go back on the queue for the + // caller's next poll_reads instead of being dropped. + self.ready.extend(others); + if let Some(result) = matched { + return result; + } // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when // `backing` is `Staging` (nothing to wait for; the request already resolved above) // or when wgpu is itself WebGPU under the hood, which self-polls. diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 0ea49d5dfc..0199168e9b 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -150,3 +150,58 @@ fn device_destroy_surfaces_as_device_lost_and_stops_further_buffer_calls() { let after = ctx.upload_buffer("after-loss", b"x"); assert!(matches!(after, Err(GpuFault::DeviceLost(_))), "a call after device loss must return GpuFault::DeviceLost, got {after:?}"); } + +/// The staging path promises "same shape as `craft-gpu-null`": an empty upload is accepted and +/// reads back empty rather than being refused. +#[test] +fn staging_path_accepts_an_empty_buffer_and_reads_it_back_empty() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let handle = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); +} + +/// `read_buffer` must not eat completions that belong to another outstanding `request_read`. +#[test] +fn staging_read_buffer_keeps_another_outstanding_requests_completion_queued() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let outcomes = ctx.poll_reads(); + assert_eq!(outcomes.len(), 1, "a's completion must survive b's read_buffer"); + assert_eq!(outcomes[0].request, request_a); + assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); +} + +/// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without +/// mapping, since wgpu refuses an empty map range) and `read_buffer` re-queues completions that +/// belong to another outstanding request. +#[test] +fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() { + let Some(mut ctx) = real_context_or_skip("real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging") else { + return; + }; + let empty = ctx.upload_buffer("empty", b"").expect("upload empty"); + assert_eq!(ctx.buffer_len(empty).expect("buffer_len"), 0); + assert_eq!(ctx.read_buffer(empty).expect("read_buffer empty"), Vec::::new()); + + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + let request_a = ctx.request_read(a).expect("request_read a"); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec()); + let mut seen_a = false; + for _ in 0..1000 { + for outcome in ctx.poll_reads() { + if outcome.request == request_a { + assert_eq!(outcome.result.as_deref(), Ok(b"aa".as_slice())); + seen_a = true; + } + } + if seen_a { + break; + } + } + assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer"); +} diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index df0d5e308a..3d27a465ae 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -81,6 +81,12 @@ pub trait GpuContext { /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly /// support blocking here and which override this to fail instead of hanging. + /// + /// The default body has nowhere to put completions that belong to other requests, so it + /// drops them: with the default body, never call this while another + /// [`request_read`](Self::request_read) is outstanding. A backend that stores completions + /// overrides this to put the other requests' outcomes back for the next + /// [`poll_reads`](Self::poll_reads); both bundled backends do. fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { let request = self.request_read(handle)?; loop { From 9c25dd40c0001655590a3b72f56ffb221927add6 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 11:27:29 -0500 Subject: [PATCH 024/490] craft-gpu: per-job batch results, wasm staging reads resolve Two findings CodeRabbit raised against the carried copy on PR 662, fixed here where the crates live. dispatch_batch now answers per job in input order. The old first-failure abort discarded outcomes earlier providers had already produced, leaving the caller nothing to reply with and no way to name the jobs worth retrying. A job fed by a failed predecessor fails honestly on its own bad handles. On wasm32 read_buffer now serves the staging backing, whose reads resolve synchronously. The backing on that target is always staging today. The refusal remains for a read that did not resolve synchronously, guarding the future wasm device backing where blocking would hang the tab. --- crates/gpu-wgpu/src/lib.rs | 30 +++++++++++++++++++----------- crates/gpu/src/registry.rs | 12 ++++++------ crates/gpu/src/tests.rs | 24 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 17 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index cdc1343b75..2dfd5e15dc 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -444,17 +444,25 @@ impl GpuContext for WgpuContext { } } - /// WebGPU can only map a buffer asynchronously, and `wasm32` is single-threaded: blocking - /// here would stop the only thread the browser needs to run `map_async`'s own completion - /// callback on, hanging the tab instead of returning. Callers on this target drive - /// [`request_read`](GpuContext::request_read) and [`poll_reads`](GpuContext::poll_reads) - /// directly from the worker's message loop; see `docs/gpu-backends.md`. + /// On `wasm32` the backing is always the in-memory staging store today (real device + /// creation needs the async worker-init path and does not exist on this target yet), and a + /// staging read resolves synchronously, so serving it blocks nothing. The refusal below + /// guards the future wasm device backing: WebGPU can only map a buffer asynchronously, and + /// `wasm32` is single-threaded, so blocking on a real device would stop the only thread the + /// browser needs to run `map_async`'s own completion callback on, hanging the tab. Callers + /// on a device backing drive [`request_read`](GpuContext::request_read) and + /// [`poll_reads`](GpuContext::poll_reads) from the worker's message loop instead; see + /// `docs/gpu-backends.md`. #[cfg(target_arch = "wasm32")] - fn read_buffer(&mut self, _handle: HandleId) -> Result, GpuFault> { - Err(GpuFault::Operation( - "read_buffer is not supported on wasm32/WebGPU: it can only map asynchronously. Use request_read + poll_reads from the worker's \ - message loop instead." - .into(), - )) + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + let request = self.request_read(handle)?; + match self.ready.iter().position(|o| o.request == request) { + Some(i) => self.ready.remove(i).result, + None => Err(GpuFault::Operation( + "read_buffer on wasm32: the read did not resolve synchronously. Use request_read + poll_reads from the worker's message loop \ + instead." + .into(), + )), + } } } diff --git a/crates/gpu/src/registry.rs b/crates/gpu/src/registry.rs index 9a970da8ba..5e9d978dea 100644 --- a/crates/gpu/src/registry.rs +++ b/crates/gpu/src/registry.rs @@ -29,11 +29,11 @@ impl ProviderRegistry { Err(GpuFault::UnknownProvider(job.provider_id.clone())) } - pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Result, GpuFault> { - let mut out = Vec::with_capacity(jobs.len()); - for job in jobs { - out.push(self.dispatch(ctx, job)?); - } - Ok(out) + /// Run every job in order and answer per job, in input order. A later job's failure never + /// discards outcomes earlier providers already produced: the caller replies per job and can + /// retry exactly the failed ones. A job whose inputs came from a failed earlier job fails + /// honestly on its own bad handles. + pub fn dispatch_batch(&self, ctx: &mut dyn GpuContext, jobs: &[GpuJob]) -> Vec> { + jobs.iter().map(|job| self.dispatch(ctx, job)).collect() } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 56ea34e109..0bf86ae1bf 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -56,6 +56,30 @@ fn unknown_provider_is_fault() { assert!(matches!(registry.dispatch(&mut ctx, &job), Err(GpuFault::UnknownProvider(_)))); } +#[test] +fn dispatch_batch_keeps_completed_outcomes_when_a_later_job_fails() { + struct Echo; + impl crate::GpuProvider for Echo { + fn id(&self) -> &'static str { + "test.echo" + } + fn run(&self, _ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + Ok(crate::GpuJobOutcome { outputs: vec![], data: Some(job.params.0.clone()) }) + } + } + let mut registry = ProviderRegistry::new(); + registry.register(Box::new(Echo)); + let mut ctx = mem_context(); + let ok = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"first".to_vec()), inputs: vec![], outputs: vec![] }; + let bad = GpuJob { provider_id: "missing".into(), params: GpuJobParams(Vec::new()), inputs: vec![], outputs: vec![] }; + let ok2 = GpuJob { provider_id: "test.echo".into(), params: GpuJobParams(b"third".to_vec()), inputs: vec![], outputs: vec![] }; + let results = registry.dispatch_batch(&mut ctx, &[ok, bad, ok2]); + assert_eq!(results.len(), 3, "one entry per job, in input order"); + assert_eq!(results[0].as_ref().expect("first job succeeded").data.as_deref(), Some(b"first".as_slice())); + assert!(matches!(results[1], Err(GpuFault::UnknownProvider(_)))); + assert_eq!(results[2].as_ref().expect("job after the failure still ran").data.as_deref(), Some(b"third".as_slice())); +} + #[test] fn read_buffer_default_resolves_against_request_read_and_poll_reads() { let mut ctx = mem_context(); From a0951756a22865b8de325fd06890d3fba8cf9d7a Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:00:20 -0500 Subject: [PATCH 025/490] Add free_buffer and device_status to GpuContext. Two CodeRabbit findings against crates/gpu-wgpu, both answered at the trait level since craft-gpu-null has the exact same gap. free_buffer (lib.rs:313). Every upload_buffer call added an entry to a backend's buffer table. So did every output buffer a provider's job created. Nothing ever removed one. Repeated jobs retained memory for the whole lifetime of a context. The new required method releases a buffer's resources. A freed handle behaves as invalid afterward, the same fault an unknown handle already produces. device_status (lib.rs:401). poll_reads can only attach a device-lost fault to a read it has something to attach it to. A caller whose event loop only polls, with nothing pending when loss happens, could never observe it. The new method, default Ok(()), covers that gap directly; a backend with no concept of device loss needs no override. MemContext in this crate's own tests gets the same free_buffer shape as craft-gpu-null, to keep it compiling under the new required method. --- crates/gpu/src/context.rs | 25 +++++++++++++++++++++++++ crates/gpu/src/tests.rs | 17 +++++++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 3d27a465ae..22ca694e49 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -75,8 +75,33 @@ pub trait GpuContext { /// fault surfaces for callers that are polling rather than issuing buffer calls. A context /// that resolves reads synchronously (the null context; native wgpu with no device) may /// resolve a request on the very next call after [`request_read`](Self::request_read). + /// + /// This can only attach a device-lost fault to a read it has something to attach it to: when + /// nothing is outstanding, there is no [`ReadOutcome`] to fabricate one onto. A caller whose + /// event loop only polls, with no buffer calls and no outstanding read, uses + /// [`device_status`](Self::device_status) for that gap. fn poll_reads(&mut self) -> Vec; + /// Device loss observable independent of any specific read or buffer call, covering the gap + /// [`poll_reads`](Self::poll_reads) has when nothing is outstanding to attach the fault to. + /// The default is `Ok(())`: correct for any backend with no concept of device loss (the null + /// context; the staging/no-device path here). A backend that can lose a device overrides + /// this to report it. + fn device_status(&self) -> Result<(), GpuFault> { + Ok(()) + } + + /// Release a previously uploaded buffer's resources. A no-op, not an error, for a handle + /// that is already invalid or was already freed: callers are never required to track + /// whether they already freed one. A freed handle behaves as invalid afterward (the same + /// fault a never-issued handle would produce) from every other method on this trait. + /// + /// Without this, a backend's buffer table -- and the memory behind it -- can only ever grow + /// for the context's lifetime: every `upload_buffer`, and every output buffer a provider's + /// job creates, adds an entry nothing removes. Repeated jobs then retain GPU (or host, for + /// the null context) memory long after every caller is done with every handle it created. + fn free_buffer(&mut self, handle: HandleId); + /// Blocking convenience for callers that need bytes now, such as the CPU-stand-in providers /// in `craft-gpu-providers`. The default drains [`request_read`](Self::request_read) and /// [`poll_reads`](Self::poll_reads) in a loop; see the trait docs for which backends honestly diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0bf86ae1bf..40ac0583c1 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -7,7 +7,9 @@ use crate::{ struct MemContext { caps: DeviceCaps, - buffers: Vec>, + /// `None` means freed (or never allocated): handles are stable indices, so a freed slot + /// cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, next_request: u64, ready: Vec, } @@ -23,16 +25,17 @@ impl GpuContext for MemContext { fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.buffers.push(bytes.to_vec()); + self.buffers.push(Some(bytes.to_vec())); Ok(id) } fn buffer_len(&self, handle: HandleId) -> Result { - self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); @@ -42,6 +45,12 @@ impl GpuContext for MemContext { fn poll_reads(&mut self) -> Vec { std::mem::take(&mut self.ready) } + + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } } fn mem_context() -> MemContext { From 5b33ccf51353b1df600ddf80166c952dec811a6c Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:00:52 -0500 Subject: [PATCH 026/490] Implement free_buffer for NullContext. buffers moves from Vec> to Vec>>. A handle is a stable index. Freeing a slot replaces it with None. Removing it instead would shift every later handle's index out from under its caller. buffer_len and request_read now reject a freed index the same way they already reject one that never existed. Two new tests. One frees a handle and checks another's index and bytes stay untouched. One frees a handle twice, and a handle that never existed, and confirms both are a harmless no-op. --- crates/gpu-null/src/lib.rs | 50 +++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index f5c6dbb188..8a880a6a55 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -13,7 +13,9 @@ use craft_gpu::{DeviceCaps, GpuContext, GpuFault, HandleId, ReadOutcome, ReadReq pub struct NullContext { caps: DeviceCaps, worker_kind: WorkerKind, - buffers: Vec>, + /// `None` means freed (or never allocated): handles are stable indices into this Vec, so a + /// freed slot cannot simply be removed without shifting every later handle's index. + buffers: Vec>>, next_request: u64, ready: Vec, } @@ -41,16 +43,17 @@ impl GpuContext for NullContext { fn upload_buffer(&mut self, _label: &str, bytes: &[u8]) -> Result { let id = HandleId(u32::try_from(self.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?); - self.buffers.push(bytes.to_vec()); + self.buffers.push(Some(bytes.to_vec())); Ok(id) } fn buffer_len(&self, handle: HandleId) -> Result { - self.buffers.get(handle.0 as usize).map(|b| b.len()).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = self.buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); @@ -68,14 +71,21 @@ impl GpuContext for NullContext { None => Err(GpuFault::Operation("request_read did not resolve synchronously".into())), } } + + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. + fn free_buffer(&mut self, handle: HandleId) { + if let Some(slot) = self.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } } #[cfg(test)] mod tests { - use craft_gpu::GpuContext; + use craft_gpu::{GpuContext, GpuFault, HandleId, WorkerKind}; use super::NullContext; - use craft_gpu::WorkerKind; #[test] fn request_read_then_poll_reads_delivers_the_same_bytes_as_read_buffer() { @@ -116,4 +126,32 @@ mod tests { assert_eq!(ctx.buffer_len(handle).expect("buffer_len"), 0); assert_eq!(ctx.read_buffer(handle).expect("read_buffer"), Vec::::new()); } + + /// CodeRabbit finding on gpu-wgpu/src/lib.rs:313: nothing released an uploaded buffer's + /// resources, so a backend's buffer table could only ever grow. free_buffer must actually + /// reclaim the payload and make the handle behave as invalid afterward, not just forget it + /// exists while still holding its bytes. + #[test] + fn free_buffer_invalidates_the_handle_and_does_not_shift_other_handles() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.buffer_len(b).expect("b must be unaffected by freeing a"), 2); + assert_eq!(ctx.read_buffer(b).expect("read_buffer b"), b"bb".to_vec(), "b's own index must not have shifted"); + } + + /// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not + /// expected to track whether they already freed one. + #[test] + fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = NullContext::new(WorkerKind::Main); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); // already freed + ctx.free_buffer(HandleId(999)); // never existed + } } From 4aefc2dbbac9d606283c7bfa8516a01221dd3e55 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:01:51 -0500 Subject: [PATCH 027/490] Fix the no-device caps fallback, capture allocation failures, free buffers. Four CodeRabbit findings against this crate. The no-device fallback in WgpuContext::new called probe_caps() again on request_device failure (lib.rs:228). A second, successful adapter query would then report the adapter's advertised limits as if they came from a granted device, for a context that holds none. It now falls back to the plain, fixed caps probe_caps's own doc comment already promises for that case. Allocation failures during buffer creation used to reach wgpu's default uncaptured-error handler (lib.rs:299). That handler panics. The size check already in place only catches a request past the device's advertised maximum. It says nothing about whether the device can actually allocate that many bytes right now. An error scope around both the output-buffer and the read-staging-buffer creation converts a failure into a GpuFault instead. free_buffer for WgpuContext (lib.rs:313) matches the Option-wrapped shape just added to craft-gpu-null. Both backings, staging and real device, release a buffer's resources and make the handle behave as invalid afterward, without shifting any other handle's index. device_status for WgpuContext (lib.rs:401) reports device loss through the trait method just added to GpuContext. A caller that only polls can now observe loss even with nothing pending. New tests cover the fixed fallback value and a regression check that the new allocation error scope does not misfire on an ordinary allocation. They also cover free_buffer on both the staging and the real-device path. One more covers device_status observing a destroyed device with nothing outstanding. A genuine out-of-memory condition is not reliably reproducible in CI; the allocation-failure test is the honest half of that fix this can run. --- crates/gpu-wgpu/src/lib.rs | 97 ++++++++++++++++++++++++++++++------ crates/gpu-wgpu/src/tests.rs | 97 ++++++++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 14 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 2dfd5e15dc..efbe432e9a 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -139,14 +139,16 @@ mod native { /// No real device: buffers live on the host, exactly like `craft-gpu-null`. RFC-0022's defined /// degrade path for "no adapter" (feature off, no GPU present, or the `wasm32` async-init gap). +/// Each slot is `None` once freed (or never allocated): handles are stable indices, so a freed +/// slot cannot simply be removed without shifting every later handle's index. #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] enum Backing { - Staging(Vec>), + Staging(Vec>>), } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] enum Backing { - Staging(Vec>), + Staging(Vec>>), /// A real device. `DeviceCaps` was built from it, not from the adapter it came from. Device(DeviceBacking), } @@ -158,8 +160,9 @@ struct DeviceBacking { /// Each buffer paired with its true, caller-given byte length. wgpu requires every buffer /// with copy usage to be sized in multiples of [`COPY_ALIGN`]; the buffer itself is padded to /// that, but callers (`buffer_len`, `request_read`'s returned bytes) see the true length, - /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. - buffers: Vec<(wgpu::Buffer, u64)>, + /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None` + /// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting. + buffers: Vec>, /// Set by the device-lost callback registered in [`native::create_device`]; checked before /// every call that would otherwise touch the (now invalid) device. lost: std::sync::Arc>>, @@ -224,7 +227,20 @@ impl WgpuContext { if let Some((caps, backing)) = native::create_device() { return Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }; } + // request_adapter and/or request_device failed: fall back to the conservative + // fallback, never probe_caps(). probe_caps() would re-query the adapter here, and a + // second, successful adapter query would report the adapter's advertised limits as + // if they came from a granted device -- the exact thing probe_caps's own doc comment + // says caps() must never do for a context with no device. + return Self { + caps: probe_fallback("wgpu", "no-device"), + worker_kind, + backing: Backing::Staging(Vec::new()), + next_request: 0, + ready: Vec::new(), + }; } + #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } @@ -283,7 +299,7 @@ impl GpuContext for WgpuContext { match &mut self.backing { Backing::Staging(buffers) => { let id = u32::try_from(buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; - buffers.push(bytes.to_vec()); + buffers.push(Some(bytes.to_vec())); Ok(HandleId(id)) } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] @@ -296,6 +312,13 @@ impl GpuContext for WgpuContext { self.caps.max_buffer_size ))); } + // The size check above only catches a request past the device's advertised + // maximum; it proves nothing about whether the device can actually allocate + // padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation + // failure to the default uncaptured-error handler, which panics, unless a scope + // captures it first. An error scope converts that into a value this can return + // as a GpuFault instead of taking the worker down with it. + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -309,8 +332,11 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } + if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); + } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; - d.buffers.push((buffer, true_len)); + d.buffers.push(Some((buffer, true_len))); Ok(HandleId(id)) } } @@ -321,13 +347,18 @@ impl GpuContext for WgpuContext { return Err(fault); } match &self.backing { - Backing::Staging(buffers) => buffers.get(handle.0 as usize).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())), - #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] - Backing::Device(d) => { - d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then(|(_, true_len)| { - usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) - }) + Backing::Staging(buffers) => { + buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => d + .buffers + .get(handle.0 as usize) + .and_then(Option::as_ref) + .ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) + .and_then(|(_, true_len)| { + usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) + }), } } @@ -337,7 +368,8 @@ impl GpuContext for WgpuContext { } match &mut self.backing { Backing::Staging(buffers) => { - let bytes = buffers.get(handle.0 as usize).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = + buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let id = self.next_request; self.next_request = self.next_request.wrapping_add(1); let request = ReadRequest(id); @@ -346,7 +378,8 @@ impl GpuContext for WgpuContext { } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] Backing::Device(d) => { - let (buffer, true_len) = d.buffers.get(handle.0 as usize).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let (buffer, true_len) = + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let true_len = *true_len; if true_len == 0 { // An empty buffer has nothing to copy or map (wgpu refuses an empty map @@ -364,6 +397,10 @@ impl GpuContext for WgpuContext { self.caps.max_buffer_size ))); } + // Same reasoning as upload_buffer's error scope: an allocation failure for the + // read-staging buffer must become a GpuFault, not reach the default + // uncaptured-error handler and panic. + d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -373,6 +410,9 @@ impl GpuContext for WgpuContext { let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); + if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); + } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); { let state = std::sync::Arc::clone(&state); @@ -391,6 +431,35 @@ impl GpuContext for WgpuContext { } } + /// Replaces the slot with `None` rather than removing it: handles are stable indices, and + /// removing would shift every later handle's index out from under its caller. Dropping a + /// `Some((wgpu::Buffer, _))` here releases that buffer's GPU-side allocation. + fn free_buffer(&mut self, handle: HandleId) { + match &mut self.backing { + Backing::Staging(buffers) => { + if let Some(slot) = buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + Backing::Device(d) => { + if let Some(slot) = d.buffers.get_mut(handle.0 as usize) { + *slot = None; + } + } + } + } + + /// Covers the gap `poll_reads` has when nothing is pending: that method can only attach a + /// device-lost fault to a read it has something to attach it to, so a caller whose event + /// loop only polls, with no outstanding read, could never observe loss through it alone. + fn device_status(&self) -> Result<(), GpuFault> { + if let Some(fault) = self.take_lost_fault() { + return Err(fault); + } + Ok(()) + } + #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_mut))] fn poll_reads(&mut self) -> Vec { let mut outcomes = std::mem::take(&mut self.ready); diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 0199168e9b..787be45797 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -175,6 +175,103 @@ fn staging_read_buffer_keeps_another_outstanding_requests_completion_queued() { assert_eq!(outcomes[0].result.as_deref(), Ok(b"aa".as_slice())); } +/// CodeRabbit finding on lib.rs:228: if `request_adapter` succeeds but `request_device` fails, +/// the fallback must be the conservative fixed value, never a second, successful `probe_caps()` +/// adapter query -- which would report the adapter's advertised limits as if they came from a +/// granted device, for a context that holds none. Forcing `request_device` itself to fail is +/// hardware-dependent and not reliably reproducible in CI, so this tests the fallback value +/// `WgpuContext::new` falls back to directly: it must be the plain, fixed value, never one that +/// looks like a real probe result. +#[test] +fn the_no_device_fallback_caps_are_the_plain_fixed_value_not_a_probe_result() { + let caps = crate::probe_fallback("wgpu", "no-device"); + assert_eq!(caps.backend_name, "wgpu"); + assert_eq!(caps.device_name, "no-device"); + assert_eq!(caps, craft_gpu::DeviceCaps { backend_name: "wgpu".into(), device_name: "no-device".into(), ..craft_gpu::DeviceCaps::default() }); +} + +/// CodeRabbit finding on lib.rs:299: an allocation failure used to be able to reach wgpu's +/// default uncaptured-error handler, which panics. An error scope around buffer creation now +/// converts that into a `GpuFault` instead. A genuine out-of-memory condition is not reliably +/// reproducible in CI (it depends on how much free VRAM the host actually has), so this is the +/// regression half: the added error scope must not misfire on an entirely ordinary allocation. +#[test] +fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { + let Some(mut ctx) = real_context_or_skip("upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place") else { + return; + }; + let handle = ctx.upload_buffer("scope-regression", b"ok").expect("a normal allocation must not report a false allocation error"); + assert_eq!(ctx.read_buffer(handle).expect("read back"), b"ok".to_vec()); +} + +/// CodeRabbit finding on lib.rs:313: nothing released an uploaded buffer's resources, so the +/// buffer table (and the GPU memory behind it) could only ever grow. free_buffer must actually +/// make the handle behave as invalid afterward, and must not disturb any other handle's index. +#[test] +fn staging_free_buffer_invalidates_the_handle_without_shifting_others() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// The same guarantee on a real device: freeing one handle must not disturb another's index or +/// its own buffer. +#[test] +fn real_device_free_buffer_invalidates_the_handle_without_shifting_others() { + let Some(mut ctx) = real_context_or_skip("real_device_free_buffer_invalidates_the_handle_without_shifting_others") else { + return; + }; + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + let b = ctx.upload_buffer("b", b"bb").expect("upload b"); + + ctx.free_buffer(a); + + assert!(matches!(ctx.buffer_len(a), Err(craft_gpu::GpuFault::InvalidJob(_))), "a freed handle must behave as invalid on a real device too"); + assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); +} + +/// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not expected +/// to track whether they already freed one. +#[test] +fn free_buffer_is_a_harmless_no_op_when_repeated_or_given_an_unknown_handle() { + let mut ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + let a = ctx.upload_buffer("a", b"aa").expect("upload a"); + ctx.free_buffer(a); + ctx.free_buffer(a); + ctx.free_buffer(craft_gpu::HandleId(999)); +} + +/// CodeRabbit finding on lib.rs:401: `poll_reads` can only attach a device-lost fault to a read +/// it has something to attach it to, so a caller whose event loop only polls, with nothing +/// outstanding, could never observe loss through it alone. `device_status` covers exactly that +/// gap: it is checked here with no buffer call and no pending read at all after the device is +/// destroyed. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +#[test] +fn device_status_surfaces_loss_even_with_nothing_pending() { + use craft_gpu::GpuFault; + + use crate::Backing; + + let Some(mut ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { + return; + }; + assert_eq!(ctx.device_status(), Ok(()), "a freshly created device must not already report loss"); + + if let Backing::Device(d) = &ctx.backing { + d.device.destroy(); + let _ = d.device.poll(wgpu::PollType::Poll); + } + + // No upload_buffer, no request_read, no poll_reads: device_status() alone must observe it. + assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_))), "device.destroy() must surface through device_status() alone"); +} + /// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without /// mapping, since wgpu refuses an empty map range) and `read_buffer` re-queues completions that /// belong to another outstanding request. From 8c0a33605bc61a225f66dc4e11d3df733b0a8b0b Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:07:37 -0500 Subject: [PATCH 028/490] Fix the error-scope API call and run cargo fmt. wgpu 30.0.1's Device has no pop_error_scope method. push_error_scope returns an ErrorScopeGuard. pop() lives on that guard. Keep the guard from push_error_scope and call pop() on it. Also drops an unneeded mut on a test binding that never mutates its context. Also runs cargo fmt on the lines the Option-wrapped buffer changes touched. --- crates/gpu-null/src/lib.rs | 3 +-- crates/gpu-wgpu/src/lib.rs | 21 +++++++++------------ crates/gpu-wgpu/src/tests.rs | 2 +- crates/gpu/src/tests.rs | 3 +-- 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/crates/gpu-null/src/lib.rs b/crates/gpu-null/src/lib.rs index 8a880a6a55..a1992e4743 100644 --- a/crates/gpu-null/src/lib.rs +++ b/crates/gpu-null/src/lib.rs @@ -52,8 +52,7 @@ impl GpuContext for NullContext { } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = - self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index efbe432e9a..b7849d7c4d 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -318,7 +318,7 @@ impl GpuContext for WgpuContext { // failure to the default uncaptured-error handler, which panics, unless a scope // captures it first. An error scope converts that into a value this can return // as a GpuFault instead of taking the worker down with it. - d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, @@ -332,7 +332,7 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } - if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + if let Some(err) = pollster::block_on(error_scope.pop()) { return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -351,14 +351,11 @@ impl GpuContext for WgpuContext { buffers.get(handle.0 as usize).and_then(Option::as_ref).map(Vec::len).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) } #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] - Backing::Device(d) => d - .buffers - .get(handle.0 as usize) - .and_then(Option::as_ref) - .ok_or_else(|| GpuFault::InvalidJob("bad handle".into())) - .and_then(|(_, true_len)| { - usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())) - }), + Backing::Device(d) => { + d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into())).and_then( + |(_, true_len)| usize::try_from(*true_len).map_err(|_| GpuFault::Operation("buffer size exceeds host address space".into())), + ) + } } } @@ -400,7 +397,7 @@ impl GpuContext for WgpuContext { // Same reasoning as upload_buffer's error scope: an allocation failure for the // read-staging buffer must become a GpuFault, not reach the default // uncaptured-error handler and panic. - d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, @@ -410,7 +407,7 @@ impl GpuContext for WgpuContext { let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); - if let Some(err) = pollster::block_on(d.device.pop_error_scope()) { + if let Some(err) = pollster::block_on(error_scope.pop()) { return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 787be45797..e681f1fec4 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -258,7 +258,7 @@ fn device_status_surfaces_loss_even_with_nothing_pending() { use crate::Backing; - let Some(mut ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { + let Some(ctx) = real_context_or_skip("device_status_surfaces_loss_even_with_nothing_pending") else { return; }; assert_eq!(ctx.device_status(), Ok(()), "a freshly created device must not already report loss"); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 40ac0583c1..528b2e587d 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -34,8 +34,7 @@ impl GpuContext for MemContext { } fn request_read(&mut self, handle: HandleId) -> Result { - let bytes = - self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; + let bytes = self.buffers.get(handle.0 as usize).and_then(Option::as_ref).cloned().ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?; let request = ReadRequest(self.next_request); self.next_request = self.next_request.wrapping_add(1); self.ready.push(ReadOutcome { request, handle, result: Ok(bytes) }); From 406b20e14e727f21eca526936f301b89049dc448 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:09:25 -0500 Subject: [PATCH 029/490] Drop a needless return clippy flagged in the adapter-probe lane. The fallback branch in WgpuContext::new is the function's own tail expression once the real-device branch above it has already returned early. The explicit return on it was redundant. --- crates/gpu-wgpu/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index b7849d7c4d..6f2df7a0da 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -232,13 +232,13 @@ impl WgpuContext { // second, successful adapter query would report the adapter's advertised limits as // if they came from a granted device -- the exact thing probe_caps's own doc comment // says caps() must never do for a context with no device. - return Self { + Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new(), - }; + } } #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } From c4beee98038e459677466621b148c35e9e2ff287 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 16:10:52 -0500 Subject: [PATCH 030/490] Run cargo fmt on the no-device fallback branch. --- crates/gpu-wgpu/src/lib.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 6f2df7a0da..948f145b6a 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -232,13 +232,7 @@ impl WgpuContext { // second, successful adapter query would report the adapter's advertised limits as // if they came from a granted device -- the exact thing probe_caps's own doc comment // says caps() must never do for a context with no device. - Self { - caps: probe_fallback("wgpu", "no-device"), - worker_kind, - backing: Backing::Staging(Vec::new()), - next_request: 0, - ready: Vec::new(), - } + Self { caps: probe_fallback("wgpu", "no-device"), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } #[cfg(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")))] Self { caps: probe_caps(), worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } From 64b1c2f4aa18861eea89a8d4bfea1c1da36190f4 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 17:16:32 -0500 Subject: [PATCH 031/490] Pop the OOM scope before the call that would misuse a failed buffer. upload_buffer popped its scope only after write_buffer. request_read popped its scope only after the copy and its submission. A buffer that failed to create is invalid. Using an invalid buffer raises a VALIDATION error that an OutOfMemory-only scope never catches. The default uncaptured-error handler still panicked on a failed create even with the scope in place. Pop right after create_buffer in both paths and return before the buffer is used again, with a separate scope around the later write or copy. write_buffer only queues its copy into wgpu's PendingWrites. An upload with no following submission kept the destination and staging buffers alive inside wgpu-core until some other submit happened. upload_buffer now flushes with an empty queue.submit right after its own write_buffer call. A free_buffer right after an upload can now actually release the allocation. --- crates/gpu-wgpu/src/lib.rs | 47 +++++++++++++++++++++----- crates/gpu-wgpu/src/tests.rs | 64 +++++++++++++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 948f145b6a..fb9dd8b7fb 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -310,15 +310,26 @@ impl GpuContext for WgpuContext { // maximum; it proves nothing about whether the device can actually allocate // padded_len bytes right now (free VRAM varies). wgpu 30.0.1 sends an allocation // failure to the default uncaptured-error handler, which panics, unless a scope - // captures it first. An error scope converts that into a value this can return - // as a GpuFault instead of taking the worker down with it. - let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + // captures it first. Pop this scope immediately, before write_buffer below ever + // touches `buffer`: a buffer that failed to create is invalid, and writing to an + // invalid buffer raises its own VALIDATION error, a kind this OutOfMemory-only + // scope does not catch, so it must reach the default handler and panic regardless + // of when this scope is popped. Checking right here is what keeps that from + // happening at all. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let buffer = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: padded_len, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}"))); + } + // write_buffer makes its own staging allocation to carry `bytes` to the device, a + // second allocation that can also run out of memory; it gets its own scope rather + // than reusing the one already closed above. + let write_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); if padded_len == true_len { d.queue.write_buffer(&buffer, 0, bytes); } else { @@ -326,8 +337,16 @@ impl GpuContext for WgpuContext { padded.resize(usize::try_from(padded_len).unwrap_or(bytes.len()), 0); d.queue.write_buffer(&buffer, 0, &padded); } - if let Some(err) = pollster::block_on(error_scope.pop()) { - return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error: {err}"))); + // write_buffer only records the copy into wgpu's PendingWrites; wgpu-core flushes + // that queue at the sooner of the caller's next real command-buffer submission or + // the next map_async on an affected buffer, and keeps the buffer named by the + // write alive internally until then. Without a submission here, a free_buffer + // right after this call could never actually release the GPU allocation behind + // it, since nothing would ever flush PendingWrites to let it go. An empty submit + // is still a submission as far as that flush is concerned, so it is enough. + d.queue.submit(std::iter::empty()); + if let Some(err) = pollster::block_on(write_scope.pop()) { + return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; d.buffers.push(Some((buffer, true_len))); @@ -390,19 +409,29 @@ impl GpuContext for WgpuContext { } // Same reasoning as upload_buffer's error scope: an allocation failure for the // read-staging buffer must become a GpuFault, not reach the default - // uncaptured-error handler and panic. - let error_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + // uncaptured-error handler and panic. Pop immediately, before copy_buffer_to_buffer + // below ever names `staging` as a copy destination: a staging buffer that failed + // to create is invalid, and copying into an invalid buffer raises its own + // VALIDATION error, a kind this OutOfMemory-only scope does not catch, so it must + // reach the default handler and panic regardless of when this scope is popped. + let create_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let staging = d.device.create_buffer(&wgpu::BufferDescriptor { label: Some("craft-gpu-wgpu.read-staging"), size: copy_len, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + if let Some(err) = pollster::block_on(create_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}"))); + } + // The copy and its submission get their own scope rather than reusing the one + // already closed above, same split as upload_buffer's create vs. write. + let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") }); encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); - if let Some(err) = pollster::block_on(error_scope.pop()) { - return Err(GpuFault::Operation(format!("request_read: device reported an allocation error: {err}"))); + if let Some(err) = pollster::block_on(copy_scope.pop()) { + return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); { diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index e681f1fec4..29b4bd0227 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -194,7 +194,9 @@ fn the_no_device_fallback_caps_are_the_plain_fixed_value_not_a_probe_result() { /// default uncaptured-error handler, which panics. An error scope around buffer creation now /// converts that into a `GpuFault` instead. A genuine out-of-memory condition is not reliably /// reproducible in CI (it depends on how much free VRAM the host actually has), so this is the -/// regression half: the added error scope must not misfire on an entirely ordinary allocation. +/// regression half: the added error scope must not misfire on an entirely ordinary allocation, +/// across both the create scope and the write scope that now follows it (see the next doc +/// comment for why those are two separate scopes rather than one spanning both calls). #[test] fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { let Some(mut ctx) = real_context_or_skip("upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place") else { @@ -204,6 +206,44 @@ fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { assert_eq!(ctx.read_buffer(handle).expect("read back"), b"ok".to_vec()); } +/// CodeRabbit finding on lib.rs:329 (upload_buffer) and lib.rs:404 (request_read): the original +/// code popped its single error scope only after write_buffer (respectively, after the copy and +/// its submission), so a failed create_buffer would leave an invalid buffer in play across the +/// later call that used it. write_buffer against an invalid buffer raises a VALIDATION error, a +/// kind the OutOfMemory-only scope never catches, so it would reach wgpu's default +/// uncaptured-error handler and panic there instead of surfacing as a `GpuFault` -- the same +/// crash the scope was added to prevent in the first place. +/// +/// A genuine allocation failure is not reliably reproducible in CI (it depends on how much free +/// VRAM/host memory lavapipe actually has to give), so this cannot be a runtime test that forces +/// `create_buffer` to fail and then observes `write_buffer` never ran. What can be verified +/// honestly, and is verified here, is the ordering itself: `upload_buffer`'s source now pops the +/// create scope and returns on error strictly before it pushes the write scope or calls +/// `write_buffer`, and `request_read`'s source pops the staging-buffer create scope and returns +/// on error strictly before it creates the copy encoder or calls `queue.submit`. Both orderings +/// are asserted directly against the source text below rather than left as an unverified claim in +/// a comment; the success-path test above is the runtime half, proving the added scope split does +/// not misfire on the ordinary case. +#[test] +fn a_failed_allocation_scope_pop_is_ordered_strictly_before_the_call_that_would_use_the_buffer() { + let source = include_str!("lib.rs"); + let upload_create_pop = source.find("create_scope.pop()").expect("upload_buffer must pop a create scope"); + let upload_write_scope_push = + source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); + assert!( + upload_create_pop < upload_write_scope_push, + "upload_buffer must check the create scope's result before it ever pushes the write scope or calls write_buffer" + ); + + let read_create_pop = + source.rfind("device reported an allocation error creating the staging buffer").expect("request_read must pop a create scope"); + let read_copy_scope_push = source.rfind("let copy_scope = d.device.push_error_scope").expect("request_read must push a separate copy scope"); + assert!( + read_create_pop < read_copy_scope_push, + "request_read must check the staging-buffer create scope's result before it ever pushes the copy scope or touches the encoder" + ); +} + /// CodeRabbit finding on lib.rs:313: nothing released an uploaded buffer's resources, so the /// buffer table (and the GPU memory behind it) could only ever grow. free_buffer must actually /// make the handle behave as invalid afterward, and must not disturb any other handle's index. @@ -235,6 +275,28 @@ fn real_device_free_buffer_invalidates_the_handle_without_shifting_others() { assert_eq!(ctx.read_buffer(b).expect("b must be unaffected by freeing a"), b"bb".to_vec()); } +/// CodeRabbit finding on lib.rs:438: `queue.write_buffer` only records its copy in wgpu's +/// PendingWrites; without some submission to flush that queue, wgpu-core keeps the destination +/// buffer (and the staging buffer `write_buffer` made internally) alive on its own, so repeated +/// upload_buffer/free_buffer cycles would retain GPU allocations with nothing ever releasing +/// them. `upload_buffer` now flushes with an empty `queue.submit` right after its own +/// write_buffer call. This cannot assert freed VRAM directly (wgpu exposes no such counter), so +/// it instead proves the behavioral guarantee this fix is actually for: many upload/free cycles +/// in a row complete without panicking and without ever running out of handles, which is exactly +/// what an unbounded, unflushed retention would eventually threaten on a long-lived worker. +#[test] +fn real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table() { + let Some(mut ctx) = real_context_or_skip("real_device_upload_and_free_many_cycles_in_a_row_does_not_panic_or_leak_a_growing_table") else { + return; + }; + for i in 0..256u32 { + let bytes = i.to_le_bytes(); + let handle = ctx.upload_buffer("cycle", &bytes).expect("each upload in the cycle must succeed"); + assert_eq!(ctx.read_buffer(handle).expect("read back this cycle's buffer"), bytes.to_vec()); + ctx.free_buffer(handle); + } +} + /// Freeing a handle twice, or a handle that never existed, is a no-op: callers are not expected /// to track whether they already freed one. #[test] From ca3f6ff1becbcba795717e79be35ef439b394939 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 17:23:19 -0500 Subject: [PATCH 032/490] Run cargo fmt on the new ordering test. --- crates/gpu-wgpu/src/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 29b4bd0227..a4d31c4e39 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -228,8 +228,7 @@ fn upload_buffer_succeeds_normally_with_the_allocation_error_scope_in_place() { fn a_failed_allocation_scope_pop_is_ordered_strictly_before_the_call_that_would_use_the_buffer() { let source = include_str!("lib.rs"); let upload_create_pop = source.find("create_scope.pop()").expect("upload_buffer must pop a create scope"); - let upload_write_scope_push = - source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); + let upload_write_scope_push = source.find("let write_scope = d.device.push_error_scope").expect("upload_buffer must push a separate write scope"); assert!( upload_create_pop < upload_write_scope_push, "upload_buffer must check the create scope's result before it ever pushes the write scope or calls write_buffer" From dd2e729f97e77ecf49af359ab91ae6c507e89759 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Wed, 11 Nov 2026 18:09:06 -0500 Subject: [PATCH 033/490] craft-gpu-wgpu: correct the crate docs on wasm32 read_buffer The staging backing serves wasm32 reads synchronously since the staging-reads fix. Only a read that did not complete synchronously faults. The crate-level summary still described the old unconditional fault. --- Cargo.lock | 34 ++++++++++++++++++++++++++++++++++ crates/gpu-wgpu/src/lib.rs | 6 ++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 60b7f73401..cecd879879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1871,6 +1871,40 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-gpu-null" +version = "0.1.0" +dependencies = [ + "craft-gpu", +] + +[[package]] +name = "craft-gpu-providers" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-null", +] + +[[package]] +name = "craft-gpu-wgpu" +version = "0.1.0" +dependencies = [ + "craft-gpu", + "craft-gpu-providers", + "pollster 0.4.0", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index fb9dd8b7fb..4d0e290354 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -14,8 +14,10 @@ //! map a buffer that way. Native, with a real device, drives it with `Buffer::map_async` plus //! `Device::poll`. The blocking `read_buffer` convenience (see //! [`GpuContext`](craft_gpu::GpuContext)'s trait docs) blocks efficiently on native by polling -//! the device while it waits; on `wasm32` it instead returns a fault, since blocking there would -//! freeze the one thread the map's own completion callback needs to run on. +//! the device while it waits. On `wasm32` the backing is always the in-memory staging store +//! today, whose reads complete synchronously, and `read_buffer` serves them; only a read that +//! did not complete synchronously returns a fault there, since blocking would freeze the one +//! thread a real map's completion callback would need to run on. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] From dbfa4892571ef23175ebce05b30d74be32085588 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Thu, 12 Nov 2026 16:36:29 -0500 Subject: [PATCH 034/490] craft-gpu: sync the docs with the implemented readback behavior Review asked for three corrections. The backends doc, the providers doc and the trait docs now state that both bundled backends override read_buffer's default body and that wasm32 serves the staging read, with a fault only for a read that did not resolve synchronously. The runtime follow-up paragraph now records that #662 consumed it. The software Vulkan container run is described as local testing. Hosted CI coverage and the pilot consumers' browser and hardware validation remain their own requirements. Em dashes swept from both docs per the house writing rules. --- crates/gpu-wgpu/src/lib.rs | 2 +- crates/gpu-wgpu/src/tests.rs | 4 +++- crates/gpu/src/context.rs | 25 ++++++++++++++----------- docs/gpu-backends.md | 26 +++++++++++++------------- docs/gpu-providers.md | 16 ++++++++-------- 5 files changed, 39 insertions(+), 34 deletions(-) diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 4d0e290354..9a6364f4ee 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -86,7 +86,7 @@ mod native { /// An instance over whichever native backends were compiled in (`native-vulkan`, /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the - /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in CI. + /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane. /// `new_without_display_handle` because this context never has a window (no surface is ever /// requested); FilmCraft's own off-screen export device uses the same constructor for the /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index a4d31c4e39..6f0b74f88e 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -3,7 +3,9 @@ //! RFC-0022 acceptance requirement 2: real backends beside the null one. `craft-gpu-null` stays //! mandatory for every consumer (it cannot validate shader compilation, resource rules, or //! numerical results), so these tests run representative jobs on a real wgpu device when one is -//! available, and skip loudly rather than failing the suite when the host genuinely has none +//! available. Runs against a software Vulkan adapter in a local container are local testing, not +//! hosted CI coverage: hosted lanes and the pilot consumers' browser and hardware validation +//! remain their own, separate requirements. The suite skips loudly when the host has no adapter //! (`cargo test` without `--features adapter-probe,native-vulkan` already exercises the masked //! path: no adapter is ever requested, and every context here falls back to the staging path, //! same shape as `craft-gpu-null`). diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 22ca694e49..8d8ccb0a24 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -25,10 +25,10 @@ pub struct ReadOutcome { /// ## Device loss /// /// A context can lose its device at any time: a driver reset, OS-level eviction under memory -/// pressure, or an explicit `device.destroy()`. Device loss is a fault, not a panic. It surfaces -/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device, and -/// also through [`poll_reads`](Self::poll_reads), so a host's event loop can observe it even -/// between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every +/// pressure, or an explicit `device.destroy()`. Device loss surfaces as a fault and never panics. It arrives +/// through [`GpuFault::DeviceLost`] from the next call that would otherwise touch the device. +/// It also arrives through [`poll_reads`](Self::poll_reads), letting a host's event loop observe +/// it even between buffer calls. Once a context has reported [`GpuFault::DeviceLost`], every /// [`DeviceCaps`] it reported before that point is stale. The consumer's recovery, per RFC-0022, /// is one of: /// @@ -50,13 +50,16 @@ pub struct ReadOutcome { /// later poll, analogous to `craft-worker-host`'s `HostMessage::GpuJobs` being answered later by /// `WorkerMessage::GpuBatchDone`. /// -/// A backend that can honestly block (the null context, which never has anything to wait for; -/// native wgpu driving `Device::poll` itself) uses `read_buffer`'s default body. A backend that -/// cannot honestly block without freezing its single thread (WebGPU on `wasm32`, where a map -/// completes only via the browser's own event loop) overrides `read_buffer` to return -/// [`GpuFault::Operation`] instead of deadlocking; callers there must drive `request_read` and -/// `poll_reads` from the worker's own message loop. See `docs/gpu-backends.md` for which backend -/// does which. +/// Both bundled backends override `read_buffer`'s default body, since the default has nowhere +/// to put completions belonging to other outstanding requests: the null context takes only its +/// own completion, and the wgpu context re-queues the others while blocking efficiently on a +/// native device. On `wasm32` the wgpu context's only backing today is the in-memory staging +/// store, whose reads resolve synchronously and are served; only a read that did not resolve +/// synchronously returns [`GpuFault::Operation`] there, the refusal a future real device backing +/// will need, because a map on that target completes only via the browser's own event loop and +/// blocking for it would freeze the one thread that loop runs on. Callers on such a backing +/// drive `request_read` and `poll_reads` from the worker's own message loop. See +/// `docs/gpu-backends.md` for which backend does which. pub trait GpuContext { fn caps(&self) -> DeviceCaps; diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 35527d5b0b..6e2246e918 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,18 +8,18 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe` — native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles` — enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. +- `adapter-probe`: native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. ## Real device, device-truth caps (RFC-0022 requirement 1) -With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device`, not just `request_adapter`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing — no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. +With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device` after `request_adapter`, creating a real device. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. -Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`), not a `Vec>` staged on the host. +Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-staged `Vec>` form survives only on the no-device path. -**The no-adapter path is still defined, not an error.** Without a usable adapter — `adapter-probe` off, no backend feature on, no GPU present, or on `wasm32` (see below) — `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. +**The no-adapter path is still a defined path.** Without a usable adapter (`adapter-probe` off, no backend feature on, no GPU present, or `wasm32`, see below), `WgpuContext` degrades to the same in-memory staging behavior as `craft-gpu-null`. `WgpuContext::has_device()` tells a caller which path it got; `probe_caps()` (no context) stays the quick, adapter-only, advisory estimate it always was. -**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker" — that landing hasn't happened yet. `request_adapter`/`request_device` are JS promises; driving them synchronously the way `pollster::block_on` does natively isn't available on `wasm32`, and wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. +**`wasm32` gap, acknowledged, not hidden.** RFC-0022 itself describes browser capability probing moving "from static defaults to real adapter queries once async initialization lands in the worker". That landing hasn't happened yet. `request_adapter`/`request_device` are JS promises. Driving them synchronously the way `pollster::block_on` does natively is unavailable on `wasm32`. Wiring the async worker-init path is a larger, separate piece of work. Until then, `WgpuContext` on `wasm32` reports the same conservative, adapter-free defaults it always has. This is the RFC's own acknowledged follow-up, not new scope invented for this PR. ## Device loss (RFC-0022 requirement 1) @@ -36,14 +36,14 @@ No backend here supports continuing to dispatch jobs against a context that alre `GpuContext::read_buffer` used to be synchronous. WebGPU can only map a buffer asynchronously (`map_async`), so the trait's real primitives are now `request_read` (queue a readback, get a `ReadRequest`) and `poll_reads` (drain completions). This mirrors `craft-worker-host`'s own async shape: a `HostMessage::GpuJobs { batch_id, .. }` is answered later by `WorkerMessage::GpuBatchDone { batch_id, outcomes }`, not inline; `request_read`/`poll_reads` is the same split one level down, for one buffer instead of one job batch. -`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`): +`read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`). Both bundled backends override that default body. The default has nowhere to put completions belonging to other outstanding requests. The overrides keep those queued for the next `poll_reads`: -- `craft-gpu-null`: resolves every request immediately — nothing to wait for. -- `craft-gpu-wgpu`, native, with a real device: blocks by calling `Device::poll(PollType::wait_indefinitely())` between polls, so it waits on the GPU instead of busy-spinning the CPU. +- `craft-gpu-null`: overrides to take only its own completion; every request resolves immediately, with nothing to wait for. +- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `Device::poll(PollType::wait_indefinitely())` between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. - `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. -- `craft-gpu-wgpu`, `wasm32`: **returns `GpuFault::Operation`, not bytes.** `wasm32` is single-threaded; blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab, not return. A caller there must drive `request_read` + `poll_reads` from the worker's own message loop instead of calling `read_buffer`. +- `craft-gpu-wgpu`, `wasm32`: **serves the staging read.** The only backing on this target today is the in-memory staging store, since real device creation needs the async worker-init path that has not landed. Staging reads resolve synchronously. `read_buffer` returns their bytes. Only a read that did not resolve synchronously returns `GpuFault::Operation`. That refusal will matter once a real device backing exists there: `wasm32` is single-threaded and blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab. A caller on a future device backing must drive `request_read` + `poll_reads` from the worker's own message loop. -**Known follow-up on `craft-libs#662`.** That branch's `RuntimeContext` wrapper (`crates/runtime/src/runtime.rs`) implements `GpuContext` by matching on its `Null`/`Wgpu` variants, including an explicit `read_buffer` arm. When #662 rebases past this PR, that block needs two added match arms (`request_read`, `poll_reads`) delegating to each inner context the same way the existing methods do, and its own `read_buffer` arm can simply be deleted in favor of the trait's default (or kept, delegating the same way). No logic in `craft-worker-host` or the runtime facade changes: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, same as before this PR. +**Consumed on `craft-libs#662`.** That branch's `RuntimeContext` wrapper now forwards `request_read`, `poll_reads`, `free_buffer` and `device_status` to its inner context. It forwards `read_buffer` too, letting the inner backend's completion-preserving override apply. No logic in `craft-worker-host` or the runtime facade changed shape beyond that: `HostMessage::GpuJobs` still dispatches a whole batch synchronously today, answered per job. ## Named consumers (RFC-0022's "what this RFC decides") @@ -56,6 +56,6 @@ No backend here supports continuing to dispatch jobs against a context that alre The question that decides whether a render-path app can adopt `WgpuContext` as-is: who owns the `Device`/`Queue` when egui (via `eframe`/`egui-wgpu`) is also drawing? -**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created — one device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. +**FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created. One device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. -`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor — it does not change `GpuContext`'s trait shape — but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. +`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor that does not change `GpuContext`'s trait shape, but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index 0705b9124f..a1282b8a1e 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -2,17 +2,17 @@ Provider ids: -- `craft.*` — shared ops in **craft-gpu-providers** (no app crate deps) -- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback` — registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init - - `craft.mask` — CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu - - `craft.composite.premul` — CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu - - `craft.readback` — CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** -- `{app}.*` — registered by application wasm at init +- `craft.*`: shared ops in **craft-gpu-providers** (no app crate deps) +- `craft.noop`, `craft.test.echo`, `craft.mask`, `craft.composite.premul`, `craft.readback`: registered by [`register_all()`](../crates/gpu-providers/src/lib.rs) for worker/runtime init + - `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu + - `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu + - `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `{app}.*`: registered by application wasm at init -Generic worker code must only call `ProviderRegistry::dispatch` — never import app gpu crates. +Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates. Dependency lint: **craft-gpu-providers** must not depend on `effectcraft-*`, `filmcraft-*`, or `*-engine`. ## Readback is async underneath; these providers don't see it -`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that: `craft-gpu-null` still resolves `read_buffer` immediately, and `craft-gpu-wgpu`'s native path now does too, by blocking on the device between polls instead of staging in a plain `Vec>`. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext`, not just the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly, since on `wasm32` `read_buffer` itself returns a fault rather than blocking. +`GpuContext::read_buffer`, the method every provider above calls, is a blocking convenience over the trait's real primitives, `request_read` + `poll_reads` (see [gpu-backends.md](./gpu-backends.md)). Nothing in this crate changed for that. `craft-gpu-null` still resolves `read_buffer` immediately. `craft-gpu-wgpu`'s native path now does too, blocking on the device between polls. `crates/gpu-wgpu/src/tests.rs` runs these same providers (`craft.test.echo`, `craft.composite.premul`, `craft.readback`) against a real `WgpuContext` as well as the null one, when a real adapter is available (RFC-0022 requirement 2). A provider dispatching a real WGSL job will be the one that actually needs the non-blocking `request_read`/`poll_reads` shape directly. On `wasm32` today `read_buffer` serves the staging read, the only backing on that target. A read that did not resolve synchronously faults. A future real device backing there will refuse blocking outright, per `gpu-backends.md`. From 87e810f34d64e8cade24b12b6b8138dc362b1e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 19:30:11 -0800 Subject: [PATCH 035/490] craft-scopes: waveform, parade, histogram and vectorscopes of a frame A new crate with the scope math a Craft app's scopes panel draws: the waveform, RGB and YUV parades, histogram (with HDR bins) and the YUV and HLS vectorscopes of a borrowed RGBA8 or NV12 frame, as count grids, with level and vectorscope summaries and painters that turn the grids into RGBA8 trace images. Each *_into form reuses the caller's buffers, so a steady stream of frames does not allocate. Frame strides, plane sizes and hand-built grids are checked against fixed caps. The crate builds on FilmCraft's crates/scopes and LightCraft's HDR histogram bins (NOTICE names the commits). --- Cargo.lock | 9 + Cargo.toml | 1 + crates/scopes/Cargo.toml | 18 + crates/scopes/NOTICE | 9 + crates/scopes/README.md | 72 +++ crates/scopes/src/frame.rs | 93 +++ crates/scopes/src/lib.rs | 1074 ++++++++++++++++++++++++++++++++++ crates/scopes/src/paint.rs | 166 ++++++ crates/scopes/src/summary.rs | 193 ++++++ crates/scopes/src/tests.rs | 661 +++++++++++++++++++++ 10 files changed, 2296 insertions(+) create mode 100644 crates/scopes/Cargo.toml create mode 100644 crates/scopes/NOTICE create mode 100644 crates/scopes/README.md create mode 100644 crates/scopes/src/frame.rs create mode 100644 crates/scopes/src/lib.rs create mode 100644 crates/scopes/src/paint.rs create mode 100644 crates/scopes/src/summary.rs create mode 100644 crates/scopes/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 74732b6d6b..06bb51a477 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2939,6 +2939,15 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-scopes" +version = "0.1.0" +dependencies = [ + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-scraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 72ae0083a2..7b818bf3b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,7 @@ craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } craft-color = { path = "crates/color" } +craft-scopes = { path = "crates/scopes" } craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } diff --git a/crates/scopes/Cargo.toml b/crates/scopes/Cargo.toml new file mode 100644 index 0000000000..dbdd448b29 --- /dev/null +++ b/crates/scopes/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "craft-scopes" +description = "Video scope math: waveform, parade, histogram and vectorscopes from RGBA8 or NV12 frames, with numeric summaries and trace images" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-color = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/scopes/NOTICE b/crates/scopes/NOTICE new file mode 100644 index 0000000000..fe894b8f0f --- /dev/null +++ b/crates/scopes/NOTICE @@ -0,0 +1,9 @@ +craft-scopes +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The scope math, summaries and trace painting come from FilmCraft's `crates/scopes` +(https://github.com/storytold/filmcraft, commit 3f137a7ed420cac79b32145f5243b7f98b31f71c), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. +The HDR histogram bins come from LightCraft's `crates/raster/src/histogram.rs` +(https://github.com/storytold/lightcraft, commit aa08a77060c0cca737dcc29b5db814cbc07ae611), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. diff --git a/crates/scopes/README.md b/crates/scopes/README.md new file mode 100644 index 0000000000..2b32162e82 --- /dev/null +++ b/crates/scopes/README.md @@ -0,0 +1,72 @@ +# craft-scopes + +Video scope math for a Craft app's scopes panel: the waveform, parade, histogram and the YUV and +HLS vectorscopes of a frame, as count grids, with numeric summaries and trace images. The crate +depends only on `craft-color` and `serde`, has no UI, and builds for `wasm32-unknown-unknown`. + +| Item | What | +|---|---| +| `Frame` | a borrowed frame: `Rgba8` with a row stride, or `Nv12` (Y' plane and interleaved Cb Cr plane, each with its own stride, plus the matrix and range) | +| `Signal` | a frame's R'G'B' code values, decimated by nearest-sample picking to at most 480 × 270 (`fill`, `fill_max`, `from_rgba8`, `from_rgba_f32_with` with `linear_to_pq` for HDR, `from_fn`) | +| `waveform`, `waveform_into` | RGB, luma, luma and chroma, or luma and chroma with the chroma hidden: one count grid per trace (columns = signal width, `rows` levels) | +| `parade`, `parade_into` | RGB, YUV, or RGB and luma traces, drawn side by side | +| `histogram`, `histogram_into` | 256 bins of R', G', B', Y'; samples below 0 and above 1 are counted separately | +| `histogram_hdr_into`, `HdrBins` | 256 bins of linear values: black to SDR white sRGB-encoded in the first half, then equal stops above SDR white | +| `vectorscope_yuv`, `vectorscope_yuv_into` | Cb right, Cr up, ±0.6; `targets(matrix, amplitude)` gives the six color-bar targets, `SKIN_TONE_DEG` is 123° | +| `vectorscope_hls`, `vectorscope_hls_into` | hue as the angle (red at the matrix's YUV red angle, then yellow, green, cyan, blue, magenta counter-clockwise), HLS saturation as the radius | +| `compute`, `compute_into` | one scope by `ScopeKind`, with the waveform and parade traces from `Params::waveform` and `Params::parade` | +| `summary` | levels (min, max and mean in percent) per channel and per column range, the densest vectorscope cells with angle and magnitude, a coarse vectorscope | +| `paint` | count grids to premultiplied RGBA8 (log intensity, additive traces, Brightness gain; vectorscope points spread over 3 × 3), with `*_into` forms that take a `Scratch` | + +Settings types (all serde, camelCase): `ScopeKind`, `WaveformType`, `ParadeType`, `ColorSpace` +(Automatic, Rec. 601, Rec. 709 and Rec. 2100 for the BT.601, BT.709 and BT.2020 NCL matrices), +`Scale` (8-bit, Float, HDR), `Brightness` and `Targets` (75 %, 100 %). Their `label` strings are +English; an app translates them before showing them. `ScopeKind`, `Computed`, `Frame` and +`FrameError` are `#[non_exhaustive]`, so a later scope or frame format is not a breaking change. + +## Reusing buffers + +Each `*_into` function writes into a value the caller keeps between frames. After the first frame +of a size, `Signal::fill`, the `*_into` scopes and the `paint::*_into` painters do not allocate. +`summary` allocates its results. + +## Input checks + +`Frame::validate` (called by `Signal::fill`) returns a `FrameError` for a stride shorter than a +row, a plane shorter than its rows, or a size that overflows; the signal is then empty. A signal +holds at most 1920 × 1080 samples whatever size `fill_max` is asked for, and a grid at most 1920 +columns. `Params` clamps `rows` to 2..=4096 and `vector_size` to 3..=1023, rounding an even size up to the next odd one. Grid and vectorscope +lookups outside the grid return 0. `Signal::from_fn` cuts a larger size to 1920 × 1080, and the +painters paint nothing for a hand-built grid wider than 1920 columns or taller than 4096 rows, or a +vectorscope larger than 1023. Summaries leave NaN and infinite samples out. + +## Definitions + +- Y'CbCr from R'G'B' with the matrix's Kr and Kb (ITU-R BT.601-7, BT.709-6, BT.2020-2 NCL), Cb and + Cr in −0.5…0.5. YC chroma amplitude is √(Cb² + Cr²), plotted at Y' ± C. +- NV12 code values are normalized with the frame's range (limited: Y' 16–235, Cb and Cr 16–240; + full: 0–255) and turned into R'G'B' with its matrix. Each Cb Cr pair covers 2 × 2 pixels. +- Waveform rows span 0…1 with clamping (values clamped first) or −0.1…1.1 without (values + outside are dropped). With 256 rows an 8-bit code value `c` lands on row `c`. +- HDR: linear working values (1.0 = 203 cd/m², ITU-R BT.2408) to SMPTE ST 2084 PQ code values; the + axis is 0…10 000 cd/m². SDR frames on the HDR scale use BT.1886 (γ 2.4, 100 cd/m² white). + +## Tests + +`src/tests.rs` uses generated frames with known values: a flat color lands in exact histogram bins; +a 256-step ramp fills every bin and puts column `x` on row `x`; 75 % color bars put each parade +column on its code value and each bar on its vectorscope target cell (BT.601, BT.709, BT.2020); the +8-bit limited-range BT.709 code values of the 100 % color bars in SMPTE RP 219-1 decode from NV12 +to their R'G'B' within 1.5 codes; strided and packed RGBA read the same samples; bad strides, short +planes and overflowing sizes give errors; the `*_into` functions match the allocating ones and keep +their buffers across frames; hostile parameters and inconsistent signals stay bounded; HDR bins +split SDR and stops for any split. + +## Speed + +`cargo test --release -p craft-scopes perf -- --ignored --nocapture` decimates a 1920 × 1080 frame +and times each scope on the 480 × 270 signal. + +## License + +MIT OR Apache-2.0. `NOTICE` names the code this crate started from. diff --git a/crates/scopes/src/frame.rs b/crates/scopes/src/frame.rs new file mode 100644 index 0000000000..4725f18d6e --- /dev/null +++ b/crates/scopes/src/frame.rs @@ -0,0 +1,93 @@ +//! Borrowed frames the scopes read: 8-bit R'G'B'A, or 8-bit NV12 (a Y' plane and an interleaved +//! Cb Cr plane at half width and half height), each with its own row stride. + +use std::fmt; + +use craft_color::{Matrix, Range}; + +/// A frame borrowed from its owner (a readback buffer, a decoder, a capture). Strides are in bytes. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub enum Frame<'a> { + /// R'G'B'A, 4 bytes per pixel, `stride` bytes per row (at least `width * 4`). Alpha is ignored. + Rgba8 { width: usize, height: usize, stride: usize, data: &'a [u8] }, + /// Y' at full size and Cb Cr pairs at half width and half height (rounded up). `matrix` and + /// `range` say how the code values turn back into R'G'B'. + Nv12 { width: usize, height: usize, y: &'a [u8], y_stride: usize, uv: &'a [u8], uv_stride: usize, matrix: Matrix, range: Range }, +} + +/// Why a [`Frame`] cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FrameError { + /// A row stride shorter than one row of samples. + Stride { plane: &'static str, stride: usize, needed: usize }, + /// A plane shorter than its rows. + Short { plane: &'static str, len: usize, needed: usize }, + /// The frame's size in bytes overflows `usize`. + TooLarge, +} + +impl fmt::Display for FrameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrameError::Stride { plane, stride, needed } => write!(f, "{plane} plane stride {stride} is shorter than a row ({needed} bytes)"), + FrameError::Short { plane, len, needed } => write!(f, "{plane} plane holds {len} bytes; the frame needs {needed}"), + FrameError::TooLarge => write!(f, "the frame is too large to address"), + } + } +} + +impl std::error::Error for FrameError {} + +/// Bytes a plane of `rows` rows needs: every row but the last at `stride`, the last one `row_bytes`. +fn plane_len(rows: usize, stride: usize, row_bytes: usize) -> Option { + if rows == 0 { Some(0) } else { stride.checked_mul(rows - 1)?.checked_add(row_bytes) } +} + +fn check_plane(plane: &'static str, len: usize, rows: usize, stride: usize, row_bytes: usize) -> Result<(), FrameError> { + if rows == 0 || row_bytes == 0 { + return Ok(()); + } + if stride < row_bytes { + return Err(FrameError::Stride { plane, stride, needed: row_bytes }); + } + let needed = plane_len(rows, stride, row_bytes).ok_or(FrameError::TooLarge)?; + if len < needed { + return Err(FrameError::Short { plane, len, needed }); + } + Ok(()) +} + +impl Frame<'_> { + pub fn width(&self) -> usize { + match *self { + Frame::Rgba8 { width, .. } | Frame::Nv12 { width, .. } => width, + } + } + + pub fn height(&self) -> usize { + match *self { + Frame::Rgba8 { height, .. } | Frame::Nv12 { height, .. } => height, + } + } + + /// Checks that every row of every plane lies inside its slice. A frame with no width or no + /// height is valid and has no samples. + pub fn validate(&self) -> Result<(), FrameError> { + if self.width() == 0 || self.height() == 0 { + return Ok(()); + } + match *self { + Frame::Rgba8 { width, height, stride, data } => { + let row = width.checked_mul(4).ok_or(FrameError::TooLarge)?; + check_plane("RGBA", data.len(), height, stride, row) + } + Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, .. } => { + check_plane("Y", y.len(), height, y_stride, width)?; + let uv_row = width.div_ceil(2).checked_mul(2).ok_or(FrameError::TooLarge)?; + check_plane("UV", uv.len(), height.div_ceil(2), uv_stride, uv_row) + } + } + } +} diff --git a/crates/scopes/src/lib.rs b/crates/scopes/src/lib.rs new file mode 100644 index 0000000000..0e83ccc9b4 --- /dev/null +++ b/crates/scopes/src/lib.rs @@ -0,0 +1,1074 @@ +//! Video scope math (no UI): the waveform, parade, histogram and the YUV and HLS vectorscopes of +//! a frame, as count grids ("how many samples land on this cell"), plus numeric summaries +//! ([`summary`]) and the density-to-pixels mapping a UI draws ([`paint`]). +//! +//! The input is a [`Signal`]: the frame's R'G'B' code values (display-encoded, 0..1 nominal; +//! values outside it are super-whites and sub-blacks of float or HDR frames), decimated to at most +//! [`MAX_W`] × [`MAX_H`] samples by nearest-sample picking (no averaging, so flat colors and test +//! patterns land on exact cells). [`Signal::fill`] reads a borrowed RGBA8 or NV12 [`Frame`] with +//! any row stride. Y'CbCr comes from the scope's matrix (BT.601, BT.709 or BT.2020 NCL; +//! `craft_color::rgb_to_ycbcr`). +//! +//! | Scope | Grid | Columns × rows | +//! |---|---|---| +//! | Waveform RGB / luma / luma and chroma / luma and chroma with the chroma hidden | per trace: R, G, B / Y / Y and C (Y ± \|CbCr\|) / Y | signal width × `rows` | +//! | Parade RGB / YUV / RGB and luma | per trace: R, G, B / Y, Cb + ½, Cr + ½ / R, G, B, Y | signal width × `rows` (drawn side by side) | +//! | Histogram | 256 bins per channel R, G, B, Y | — | +//! | YUV vectorscope | Cb horizontal, Cr up, ±[`VECTOR_EXTENT`] | `vector_size`² | +//! | HLS vectorscope | hue as the angle (red at the YUV red angle), HLS saturation as the radius (1 = 0.5) | `vector_size`² | +//! +//! [`compute`] picks the waveform and parade traces from [`Params::waveform`] and +//! [`Params::parade`]. +//! +//! Waveform rows cover `[lo, hi]` = `[0, 1]` with clamping on (values clamped first) and +//! `[-0.1, 1.1]` without (values outside are dropped). With 256 rows over `[0, 1]`, an 8-bit code +//! value `c` lands exactly on row `c`. +//! +//! Every `*_into` function writes into a value the caller keeps between frames. Once that value +//! and the [`Signal`] have grown to the frame's size, the call does not allocate. + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +pub mod frame; +pub mod paint; +pub mod summary; +#[cfg(test)] +mod tests; + +pub use craft_color::{Matrix, Range}; +use craft_color::{normalize_c, normalize_y, rgb_to_ycbcr, ycbcr_to_rgb}; +pub use frame::{Frame, FrameError}; +use serde::{Deserialize, Serialize}; + +/// Largest decimated signal (a 1080p frame is sampled every 4th pixel both ways). +pub const MAX_W: usize = 480; +pub const MAX_H: usize = 270; + +/// Largest signal [`Signal::fill_max`] and [`Signal::fill_rgba_f32_with`] make, whatever size they +/// are asked for, and the most columns a [`Grid`] holds. +pub const MAX_SIGNAL_W: usize = 1920; +pub const MAX_SIGNAL_H: usize = 1080; + +/// Most waveform and parade levels a [`Params`] or a [`Grid`] can hold; larger values are clamped. +pub const MAX_ROWS: usize = 4096; +/// Largest vectorscope grid a [`Params`] can ask for; larger values are clamped. +pub const MAX_VECTOR_SIZE: usize = 1023; + +/// Half-width of the vectorscope plane in Cb/Cr units (the 100 % targets of every matrix fit). +pub const VECTOR_EXTENT: f32 = 0.6; + +/// The skin-tone line (the "I" axis of NTSC): 123° counter-clockwise from +Cb. +pub const SKIN_TONE_DEG: f32 = 123.0; + +// ------------------------------------------------------------------------------------ settings + +/// A scope. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum ScopeKind { + VectorscopeYuv, + VectorscopeHls, + Histogram, + Parade, + #[default] + Waveform, +} + +impl ScopeKind { + pub const ALL: [ScopeKind; 5] = + [ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Histogram, ScopeKind::Parade, ScopeKind::Waveform]; + /// Stable id (`"vectorscopeYuv"`…), as in JSON. + pub fn name(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "vectorscopeYuv", + ScopeKind::VectorscopeHls => "vectorscopeHls", + ScopeKind::Histogram => "histogram", + ScopeKind::Parade => "parade", + ScopeKind::Waveform => "waveform", + } + } + /// English label; an app translates it before showing it. + pub fn label(self) -> &'static str { + match self { + ScopeKind::VectorscopeYuv => "YUV vectorscope", + ScopeKind::VectorscopeHls => "HLS vectorscope", + ScopeKind::Histogram => "Histogram", + ScopeKind::Parade => "Parade", + ScopeKind::Waveform => "Waveform", + } + } + /// By id or label, ignoring case, spaces and dashes (`"vectorscope"` = the YUV one). + pub fn from_name(s: &str) -> Option { + let n = norm(s); + if n == "vectorscope" || n == "yuv" { + return Some(ScopeKind::VectorscopeYuv); + } + if n == "hls" { + return Some(ScopeKind::VectorscopeHls); + } + Self::ALL.into_iter().find(|k| norm(k.name()) == n || norm(k.label()) == n) + } +} + +fn norm(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).collect::().to_ascii_lowercase() +} + +/// Waveform type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WaveformType { + #[default] + Rgb, + Luma, + Yc, + YcNoChroma, +} + +impl WaveformType { + pub const ALL: [WaveformType; 4] = [WaveformType::Rgb, WaveformType::Luma, WaveformType::Yc, WaveformType::YcNoChroma]; + pub fn label(self) -> &'static str { + match self { + WaveformType::Rgb => "RGB", + WaveformType::Luma => "Luma", + WaveformType::Yc => "Luma and chroma", + WaveformType::YcNoChroma => "Luma and chroma, chroma hidden", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Parade type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParadeType { + #[default] + Rgb, + Yuv, + RgbWhite, +} + +impl ParadeType { + pub const ALL: [ParadeType; 3] = [ParadeType::Rgb, ParadeType::Yuv, ParadeType::RgbWhite]; + pub fn label(self) -> &'static str { + match self { + ParadeType::Rgb => "RGB", + ParadeType::Yuv => "YUV", + ParadeType::RgbWhite => "RGB and luma", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// The scopes' color space (the Y'CbCr matrix; Rec. 2100 also means an HDR signal). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColorSpace { + /// Follow the source: Rec. 2100 for an HDR working space, else Rec. 709. + #[default] + Auto, + Rec601, + Rec709, + Rec2100, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Auto, ColorSpace::Rec601, ColorSpace::Rec709, ColorSpace::Rec2100]; + pub fn label(self) -> &'static str { + match self { + ColorSpace::Auto => "Automatic", + ColorSpace::Rec601 => "Rec. 601", + ColorSpace::Rec709 => "Rec. 709", + ColorSpace::Rec2100 => "Rec. 2100", + } + } + /// `Auto` resolved for a source (`hdr`: its working space is PQ or HLG). + pub fn resolve(self, hdr: bool) -> ColorSpace { + match self { + ColorSpace::Auto if hdr => ColorSpace::Rec2100, + ColorSpace::Auto => ColorSpace::Rec709, + c => c, + } + } + pub fn matrix(self) -> Matrix { + match self { + ColorSpace::Rec601 => Matrix::Bt601, + ColorSpace::Rec2100 => Matrix::Bt2020Ncl, + _ => Matrix::Bt709, + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n || norm(k.label()).trim_start_matches("rec") == n) + } +} + +/// Signal scale (the bit-depth choice): the labels of the levels axis. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scale { + /// 0–255 code values. + #[default] + Bits8, + /// 0.0–1.0. + Float, + /// cd/m² on a PQ axis (0–10 000). + Hdr, +} + +impl Scale { + pub const ALL: [Scale; 3] = [Scale::Bits8, Scale::Float, Scale::Hdr]; + pub fn label(self) -> &'static str { + match self { + Scale::Bits8 => "8-bit", + Scale::Float => "Float", + Scale::Hdr => "HDR", + } + } + pub fn from_name(s: &str) -> Option { + let n = norm(s); + Self::ALL.into_iter().find(|k| norm(k.label()) == n || norm(&format!("{k:?}")) == n) + } +} + +/// Trace brightness. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Brightness { + Dimmed, + #[default] + Normal, + Bright, +} + +impl Brightness { + pub const ALL: [Brightness; 3] = [Brightness::Dimmed, Brightness::Normal, Brightness::Bright]; + pub fn label(self) -> &'static str { + match self { + Brightness::Dimmed => "Dimmed", + Brightness::Normal => "Normal", + Brightness::Bright => "Bright", + } + } + /// Multiplier of the trace intensity. + pub fn gain(self) -> f32 { + match self { + Brightness::Dimmed => 0.55, + Brightness::Normal => 1.0, + Brightness::Bright => 1.6, + } + } +} + +/// Which color-bar targets the YUV vectorscope draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Targets { + #[default] + #[serde(rename = "75")] + Percent75, + #[serde(rename = "100")] + Percent100, +} + +impl Targets { + pub fn amplitude(self) -> f32 { + match self { + Targets::Percent75 => 0.75, + Targets::Percent100 => 1.0, + } + } + pub fn label(self) -> &'static str { + match self { + Targets::Percent75 => "75%", + Targets::Percent100 => "100%", + } + } +} + +/// How scopes are computed. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Params { + pub matrix: Matrix, + /// Clamping: values are clamped to 0..1 before they are plotted. + pub clamp: bool, + /// Waveform and parade levels (2..=[`MAX_ROWS`]). + pub rows: usize, + /// Vectorscope grid size (square; 3..=[`MAX_VECTOR_SIZE`]). An even size is rounded up to the + /// next odd one, so the center is a cell. + pub vector_size: usize, + /// The traces [`compute`] draws for [`ScopeKind::Waveform`]. + pub waveform: WaveformType, + /// The traces [`compute`] draws for [`ScopeKind::Parade`]. + pub parade: ParadeType, +} + +impl Default for Params { + fn default() -> Self { + Params { matrix: Matrix::Bt709, clamp: true, rows: 256, vector_size: 255, waveform: WaveformType::Rgb, parade: ParadeType::Rgb } + } +} + +impl Params { + /// The plotted value range of waveform rows. + pub fn range(&self) -> (f32, f32) { + if self.clamp { (0.0, 1.0) } else { (-0.1, 1.1) } + } + fn rows(&self) -> usize { + self.rows.clamp(2, MAX_ROWS) + } + fn vector_size(&self) -> usize { + (self.vector_size.clamp(3, MAX_VECTOR_SIZE) | 1).min(MAX_VECTOR_SIZE) + } +} + +// ------------------------------------------------------------------------------------ signal + +/// A frame's R'G'B' samples (decimated), row-major: `rgb[y * w + x]`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Signal { + pub w: usize, + pub h: usize, + pub rgb: Vec<[f32; 3]>, +} + +/// Decimation steps for a `w × h` frame read into at most `max_w × max_h` samples (each capped to +/// [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). +fn steps(w: usize, h: usize, max_w: usize, max_h: usize) -> (usize, usize) { + let (max_w, max_h) = (max_w.clamp(1, MAX_SIGNAL_W), max_h.clamp(1, MAX_SIGNAL_H)); + (w.div_ceil(max_w).max(1), h.div_ceil(max_h).max(1)) +} + +impl Signal { + /// From tightly packed RGBA8 (code / 255), decimated to [`MAX_W`] × [`MAX_H`]. A buffer + /// shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba8(w: usize, h: usize, px: &[u8]) -> Signal { + Self::from_rgba8_max(w, h, px, MAX_W, MAX_H) + } + + pub fn from_rgba8_max(w: usize, h: usize, px: &[u8], max_w: usize, max_h: usize) -> Signal { + let mut s = Signal::default(); + let Some(stride) = w.checked_mul(4) else { return s }; + if s.fill_max(&Frame::Rgba8 { width: w, height: h, stride, data: px }, max_w, max_h).is_err() { + s.clear(); + } + s + } + + /// Reads `frame` into this signal, decimated to [`MAX_W`] × [`MAX_H`], reusing its buffer. + pub fn fill(&mut self, frame: &Frame<'_>) -> Result<(), FrameError> { + self.fill_max(frame, MAX_W, MAX_H) + } + + /// Reads `frame` into this signal, decimated to at most `max_w` × `max_h` samples (never more + /// than [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]). The buffer is reused, so the call does not + /// allocate once it has held a frame this size. On an error the signal is left empty. + pub fn fill_max(&mut self, frame: &Frame<'_>, max_w: usize, max_h: usize) -> Result<(), FrameError> { + self.clear(); + frame.validate()?; + let (w, h) = (frame.width(), frame.height()); + if w == 0 || h == 0 { + return Ok(()); + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + match *frame { + Frame::Rgba8 { stride, data, .. } => { + let lut: [f32; 256] = std::array::from_fn(|i| i as f32 / 255.0); + for y in (0..h).step_by(sy) { + let row = data.get(y * stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match row.get(x * 4..x * 4 + 3) { + Some(&[r, g, b]) => [lut[r as usize], lut[g as usize], lut[b as usize]], + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + Frame::Nv12 { y: yp, y_stride, uv, uv_stride, matrix, range, .. } => { + let ylut: [f32; 256] = std::array::from_fn(|i| normalize_y(i as u32, 8, range).unwrap_or(0.0)); + let clut: [f32; 256] = std::array::from_fn(|i| normalize_c(i as u32, 8, range).unwrap_or(0.0)); + for y in (0..h).step_by(sy) { + let yrow = yp.get(y * y_stride..).unwrap_or(&[]); + let crow = uv.get((y / 2) * uv_stride..).unwrap_or(&[]); + for x in (0..w).step_by(sx) { + let c = match (yrow.get(x), crow.get((x / 2) * 2..(x / 2) * 2 + 2)) { + (Some(&l), Some(&[cb, cr])) => ycbcr_to_rgb(ylut[l as usize], clut[cb as usize], clut[cr as usize], matrix), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + } + } + self.w = ow; + self.h = oh; + Ok(()) + } + + /// From tightly packed RGBA f32 pixels through `map` (for example linear light to PQ code + /// values), decimated. A buffer shorter than `w * h * 4` gives an empty signal. + pub fn from_rgba_f32_with(w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) -> Signal { + let mut s = Signal::default(); + s.fill_rgba_f32_with(w, h, px, max_w, max_h, map); + s + } + + /// [`Signal::from_rgba_f32_with`] into this signal, reusing its buffer. + pub fn fill_rgba_f32_with(&mut self, w: usize, h: usize, px: &[f32], max_w: usize, max_h: usize, map: impl Fn([f32; 4]) -> [f32; 3]) { + self.clear(); + let needed = w.checked_mul(h).and_then(|n| n.checked_mul(4)); + if w == 0 || h == 0 || needed.is_none_or(|n| px.len() < n) { + return; + } + let (sx, sy) = steps(w, h, max_w, max_h); + let (ow, oh) = (w.div_ceil(sx), h.div_ceil(sy)); + self.rgb.reserve(ow.saturating_mul(oh)); + for y in (0..h).step_by(sy) { + for x in (0..w).step_by(sx) { + let i = (y * w + x) * 4; + let c = match px.get(i..i + 4) { + Some(&[r, g, b, a]) => map([r, g, b, a]), + _ => [0.0; 3], + }; + self.rgb.push(c); + } + } + self.w = ow; + self.h = oh; + } + + /// A synthetic signal (tests, generated patterns), at most [`MAX_SIGNAL_W`] × [`MAX_SIGNAL_H`]: + /// a larger size is cut to that. + pub fn from_fn(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 3]) -> Signal { + let (w, h) = (w.min(MAX_SIGNAL_W), h.min(MAX_SIGNAL_H)); + let mut rgb = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + rgb.push(f(x, y)); + } + } + Signal { w, h, rgb } + } + + /// Every sample through `f` (for example SDR code values to PQ for the HDR scale). + pub fn map(&self, f: impl Fn([f32; 3]) -> [f32; 3]) -> Signal { + Signal { w: self.w, h: self.h, rgb: self.rgb.iter().map(|c| f(*c)).collect() } + } + + /// Empties the signal and keeps its buffer. + pub fn clear(&mut self) { + self.w = 0; + self.h = 0; + self.rgb.clear(); + } + + pub fn len(&self) -> usize { + self.rgb.len() + } + pub fn is_empty(&self) -> bool { + self.rgb.is_empty() + } + + /// The rows of samples, each `w` long. A signal whose `w` and `rgb` disagree yields only + /// whole rows. + fn rows(&self) -> std::slice::ChunksExact<'_, [f32; 3]> { + self.rgb.chunks_exact(self.w.max(1)) + } + + /// Columns the grids of this signal have: `w`, or 0 when there are no samples. + fn cols(&self) -> usize { + if self.rgb.is_empty() { 0 } else { self.w.min(self.rgb.len()) } + } +} + +/// Linear light (1.0 = reference white = 203 cd/m², premultiplied RGBA) to PQ code values, for +/// HDR scopes: 0..1 on the axis is 0..10 000 cd/m². +pub fn linear_to_pq([r, g, b, a]: [f32; 4]) -> [f32; 3] { + let a = if a > 1e-6 { a } else { 1.0 }; + let white = craft_color::REFERENCE_WHITE_NITS as f32; + let f = |v: f32| craft_color::pq_inverse_eotf(((v / a).max(0.0) * white / 10_000.0).clamp(0.0, 1.0)); + [f(r), f(g), f(b)] +} + +/// An SDR code value (BT.1886, 100 cd/m² white) on the PQ axis (the HDR scale of an SDR frame). +pub fn sdr_to_pq(v: f32) -> f32 { + craft_color::pq_inverse_eotf((v.clamp(0.0, 1.0).powf(2.4) * 100.0 / 10_000.0).clamp(0.0, 1.0)) +} + +/// cd/m² to height on the PQ axis (0..1). +pub fn nits_to_pq(nits: f32) -> f32 { + craft_color::pq_inverse_eotf((nits / 10_000.0).clamp(0.0, 1.0)) +} + +// ------------------------------------------------------------------------------------ grids + +/// A count grid: `data[row * cols + col]`, row 0 = the lowest level. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Grid { + pub name: &'static str, + pub cols: usize, + pub rows: usize, + pub data: Vec, +} + +impl Grid { + pub fn new(name: &'static str, cols: usize, rows: usize) -> Grid { + let mut g = Grid::default(); + g.reset(name, cols, rows); + g + } + /// Zeroes the grid at a new size (at most [`MAX_SIGNAL_W`] columns and [`MAX_ROWS`] rows), + /// reusing its buffer. + pub fn reset(&mut self, name: &'static str, cols: usize, rows: usize) { + self.name = name; + self.cols = cols.min(MAX_SIGNAL_W); + self.rows = rows.min(MAX_ROWS); + self.data.clear(); + self.data.resize(self.cols * self.rows, 0); + } + /// The count of a cell (0 outside the grid). + pub fn at(&self, col: usize, row: usize) -> u32 { + if col >= self.cols || row >= self.rows { + return 0; + } + row.checked_mul(self.cols).and_then(|i| i.checked_add(col)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn total(&self) -> u64 { + self.data.iter().map(|&c| c as u64).sum() + } + pub fn max(&self) -> u32 { + self.data.iter().copied().max().unwrap_or(0) + } + /// The rows hit in a column, lowest first. + pub fn rows_in(&self, col: usize) -> Vec { + (0..self.rows).filter(|&r| self.at(col, r) > 0).collect() + } + #[inline] + fn hit(&mut self, col: usize, row: usize) { + if col >= self.cols || row >= self.rows { + return; + } + if let Some(c) = self.data.get_mut(row * self.cols + col) { + *c = c.saturating_add(1); + } + } +} + +/// Waveform or parade: one grid per trace, columns = the signal's width. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Waveform { + pub lo: f32, + pub hi: f32, + /// Levels of every trace. + pub rows: usize, + /// Samples per column (the signal's height). + pub per_column: usize, + pub traces: Vec, +} + +impl Waveform { + pub fn trace(&self, name: &str) -> Option<&Grid> { + self.traces.iter().find(|t| t.name == name) + } + /// The value at the center of a row. + pub fn level(&self, row: usize) -> f32 { + self.lo + (self.hi - self.lo) * row as f32 / (self.rows.max(2) - 1) as f32 + } +} + +/// Row of value `v` in `[lo, hi]` over `rows` levels (None outside, for NaN, or with fewer than +/// two rows or an empty range). +#[inline] +pub fn row_of(v: f32, lo: f32, hi: f32, rows: usize) -> Option { + if rows < 2 || hi <= lo { + return None; + } + let t = (v - lo) / (hi - lo); + if !(0.0..=1.0).contains(&t) { + return None; + } + Some(((t * (rows - 1) as f32).round() as usize).min(rows - 1)) +} + +/// Up to 4 (trace, value) pairs per sample. +type Hits = ([(u8, f32); 4], usize); + +fn build_into(s: &Signal, p: &Params, names: &[&'static str], out: &mut Waveform, sample: impl Fn([f32; 3]) -> Hits) { + let (lo, hi) = p.range(); + let rows = p.rows(); + let cols = s.cols(); + out.traces.truncate(names.len()); + while out.traces.len() < names.len() { + out.traces.push(Grid::default()); + } + for (g, &name) in out.traces.iter_mut().zip(names) { + g.reset(name, cols, rows); + } + let mut per_column = 0; + if cols > 0 { + for row in s.rows() { + per_column += 1; + for (x, &c) in row.iter().enumerate() { + let c = if p.clamp { c.map(|v| v.clamp(0.0, 1.0)) } else { c }; + let (hits, n) = sample(c); + for &(t, v) in hits.get(..n).unwrap_or(&[]) { + let v = if p.clamp { v.clamp(0.0, 1.0) } else { v }; + if let (Some(r), Some(g)) = (row_of(v, lo, hi, rows), out.traces.get_mut(t as usize)) { + g.hit(x, r); + } + } + } + } + } + out.lo = lo; + out.hi = hi; + out.rows = rows; + out.per_column = per_column; +} + +/// The waveform of a signal. +pub fn waveform(s: &Signal, kind: WaveformType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + waveform_into(s, kind, p, &mut w); + w +} + +/// [`waveform`] into `out`, reusing its grids. +pub fn waveform_into(s: &Signal, kind: WaveformType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + WaveformType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + WaveformType::Luma | WaveformType::YcNoChroma => build_into(s, p, &["Y"], out, |[r, g, b]| ([(0, rgb_to_ycbcr(r, g, b, m)[0]), z, z, z], 1)), + WaveformType::Yc => build_into(s, p, &["Y", "C"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + let c = (cb * cb + cr * cr).sqrt(); + ([(0, y), (1, y + c), (1, y - c), z], if c > 1e-6 { 3 } else { 2 }) + }), + } +} + +/// The parade of a signal (the traces are drawn side by side). +pub fn parade(s: &Signal, kind: ParadeType, p: &Params) -> Waveform { + let mut w = Waveform::default(); + parade_into(s, kind, p, &mut w); + w +} + +/// [`parade`] into `out`, reusing its grids. +pub fn parade_into(s: &Signal, kind: ParadeType, p: &Params, out: &mut Waveform) { + let m = p.matrix; + let z = (0u8, 0.0f32); + match kind { + ParadeType::Rgb => build_into(s, p, &["R", "G", "B"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), z], 3)), + ParadeType::RgbWhite => { + build_into(s, p, &["R", "G", "B", "Y"], out, |[r, g, b]| ([(0, r), (1, g), (2, b), (3, rgb_to_ycbcr(r, g, b, m)[0])], 4)) + } + ParadeType::Yuv => build_into(s, p, &["Y", "Cb", "Cr"], out, |[r, g, b]| { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + ([(0, y), (1, cb + 0.5), (2, cr + 0.5), z], 3) + }), + } +} + +// ------------------------------------------------------------------------------------ histogram + +/// 256-bin histograms of R', G', B' and Y'. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Histogram { + pub r: Vec, + pub g: Vec, + pub b: Vec, + pub y: Vec, + pub samples: u32, + /// Samples below 0 or above the top bin per channel (R, G, B, Y). With clamping they are + /// also counted in the first or last bin of an SDR histogram. + pub below: [u32; 4], + pub above: [u32; 4], + /// How an HDR histogram splits its bins; `None` for an SDR histogram. + #[serde(skip_serializing_if = "Option::is_none")] + pub hdr: Option, + /// HDR histograms: samples with any of R, G and B above SDR white (0 for SDR histograms). + pub above_sdr_samples: u32, +} + +pub const BINS: usize = 256; + +impl Histogram { + fn reset(&mut self, hdr: Option) { + for v in [&mut self.r, &mut self.g, &mut self.b, &mut self.y] { + v.clear(); + v.resize(BINS, 0); + } + self.samples = 0; + self.below = [0; 4]; + self.above = [0; 4]; + self.hdr = hdr; + self.above_sdr_samples = 0; + } + fn channel(&mut self, i: usize) -> &mut Vec { + match i { + 0 => &mut self.r, + 1 => &mut self.g, + 2 => &mut self.b, + _ => &mut self.y, + } + } + fn count(&mut self, i: usize, bin: usize) { + if let Some(c) = self.channel(i).get_mut(bin) { + *c = c.saturating_add(1); + } + } +} + +/// Bin of a value (None when outside 0..1). +#[inline] +pub fn bin_of(v: f32) -> Option { + if (0.0..=1.0 + 1e-6).contains(&v) { Some(((v * 255.0).round() as usize).min(BINS - 1)) } else { None } +} + +pub fn histogram(s: &Signal, p: &Params) -> Histogram { + let mut h = Histogram::default(); + histogram_into(s, p, &mut h); + h +} + +/// [`histogram`] into `out`, reusing its bins. +pub fn histogram_into(s: &Signal, p: &Params, out: &mut Histogram) { + out.reset(None); + out.samples = u32::try_from(s.len()).unwrap_or(u32::MAX); + for &[r, g, b] in &s.rgb { + let y = rgb_to_ycbcr(r, g, b, p.matrix)[0]; + // With clamping, the luma bin comes from the clamped R'G'B', as on the waveform; `below` + // and `above` count the luma of the sample as it is. + let y_bin = if p.clamp { + let [cr, cg, cb] = [r, g, b].map(|v| v.clamp(0.0, 1.0)); + rgb_to_ycbcr(cr, cg, cb, p.matrix)[0] + } else { + y + }; + for (i, (v, at)) in [(r, r), (g, g), (b, b), (y, y_bin)].into_iter().enumerate() { + if !v.is_nan() && bin_of(v).is_none() { + let side = if v < 0.0 { &mut out.below[i] } else { &mut out.above[i] }; + *side = side.saturating_add(1); + } + match bin_of(at) { + Some(k) => out.count(i, k), + None if at.is_nan() || !p.clamp => {} + None => out.count(i, if at < 0.0 { 0 } else { BINS - 1 }), + } + } + } +} + +/// The split of an HDR histogram: bins below `from` cover black to SDR white (sRGB-encoded, as an +/// SDR histogram), and bins `from..256` cover `0..stops` stops above SDR white in equal steps. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrBins { + pub from: usize, + pub stops: f32, +} + +impl HdrBins { + /// SDR takes the left half of the bins. + pub const DEFAULT_FROM: usize = BINS / 2; + + /// The default split reaching `stops` stops above SDR white. + pub fn new(stops: f32) -> HdrBins { + HdrBins { from: Self::DEFAULT_FROM, stops } + } + + /// The bin of a linear value (1 = SDR white; NaN and negatives count as black). Any `from` + /// and any `stops` give a bin inside the histogram. + pub fn bin(self, v: f32) -> usize { + let last = BINS - 1; + let from = self.from.clamp(2, last); + if v.is_nan() || v <= 0.0 { + return 0; + } + if v <= 1.0 { + let e = craft_color::linear_to_srgb(v); + return ((e * (from - 1) as f32 + 0.5) as usize).min(from - 1); + } + let t = (v.log2() / self.stops()).clamp(0.0, 1.0); + (from + (t * (last - from) as f32 + 0.5) as usize).min(last) + } + + fn stops(self) -> f32 { + if self.stops.is_finite() { self.stops.max(1e-3) } else { 1e-3 } + } + + /// The linear value the last bin reaches. + pub fn top(self) -> f32 { + self.stops().exp2() + } +} + +/// The HDR histogram of a signal of linear values (1 = SDR white): R, G, B and the luma of +/// `matrix`, split by `bins`. Negative values count in `below`, values past [`HdrBins::top`] in +/// `above`; both also land in the first or last bin. +pub fn histogram_hdr_into(linear: &Signal, matrix: Matrix, bins: HdrBins, out: &mut Histogram) { + out.reset(Some(bins)); + out.samples = u32::try_from(linear.len()).unwrap_or(u32::MAX); + let (kr, kb) = matrix.kr_kb(); + let top = bins.top(); + for &[r, g, b] in &linear.rgb { + if r > 1.0 || g > 1.0 || b > 1.0 { + out.above_sdr_samples = out.above_sdr_samples.saturating_add(1); + } + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + for (i, v) in [r, g, b, y].into_iter().enumerate() { + out.count(i, bins.bin(v)); + if v < 0.0 { + out.below[i] = out.below[i].saturating_add(1); + } else if v > top { + out.above[i] = out.above[i].saturating_add(1); + } + } + } +} + +/// Fraction of samples with any of R, G and B above SDR white (0 for SDR histograms). +pub fn above_sdr(h: &Histogram) -> f32 { + if h.hdr.is_none() || h.samples == 0 { + return 0.0; + } + (h.above_sdr_samples as f32 / h.samples as f32).min(1.0) +} + +// ------------------------------------------------------------------------------------ vectorscopes + +/// A vectorscope: `data[y * size + x]`, x = Cb (right = +), y = Cr (row 0 = top = +Cr). +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Vectorscope { + pub size: usize, + pub extent: f32, + pub data: Vec, + pub samples: u32, + /// Mean (Cb, Cr) of the plotted points. + pub mean: [f32; 2], + /// The matrix the points were plotted with; [`paint::vectorscope`] colors them with it. + pub matrix: Matrix, + /// Whether the points are HLS (hue as the angle from the matrix's red, saturation as the + /// radius) instead of (Cb, Cr). + pub hls: bool, +} + +/// Cell of a (Cb, Cr) point on a `size`² plane spanning ±`extent` (None outside, for NaN, or for a +/// plane under 2 cells or with no extent). +#[inline] +pub fn cell_of(cb: f32, cr: f32, size: usize, extent: f32) -> Option<(usize, usize)> { + if size < 2 || extent.is_nan() || extent <= 0.0 { + return None; + } + let n = (size - 1) as f32; + let fx = (cb / extent * 0.5 + 0.5) * n; + let fy = (0.5 - cr / extent * 0.5) * n; + if !(0.0..=n).contains(&fx) || !(0.0..=n).contains(&fy) { + return None; + } + Some((fx.round() as usize, fy.round() as usize)) +} + +impl Vectorscope { + fn reset(&mut self, size: usize, matrix: Matrix, hls: bool) { + self.size = size; + self.matrix = matrix; + self.hls = hls; + self.extent = VECTOR_EXTENT; + self.data.clear(); + self.data.resize(size.saturating_mul(size), 0); + self.samples = 0; + self.mean = [0.0; 2]; + } + /// The count of a cell (0 outside the plane). + pub fn at(&self, x: usize, y: usize) -> u32 { + if x >= self.size || y >= self.size { + return 0; + } + y.checked_mul(self.size).and_then(|i| i.checked_add(x)).and_then(|i| self.data.get(i)).copied().unwrap_or(0) + } + pub fn cell(&self, cb: f32, cr: f32) -> Option<(usize, usize)> { + cell_of(cb, cr, self.size, self.extent) + } + /// (Cb, Cr) at the center of a cell. + pub fn point(&self, x: usize, y: usize) -> [f32; 2] { + let n = self.size.saturating_sub(1).max(1) as f32; + [(x as f32 / n - 0.5) * 2.0 * self.extent, (0.5 - y as f32 / n) * 2.0 * self.extent] + } + #[inline] + fn plot(&mut self, cb: f32, cr: f32, sum: &mut [f64; 2]) { + if let Some((x, y)) = self.cell(cb, cr) + && let Some(c) = self.data.get_mut(y * self.size + x) + { + *c = c.saturating_add(1); + self.samples = self.samples.saturating_add(1); + sum[0] += cb as f64; + sum[1] += cr as f64; + } + } + fn finish(&mut self, sum: [f64; 2]) { + if self.samples > 0 { + self.mean = [(sum[0] / self.samples as f64) as f32, (sum[1] / self.samples as f64) as f32]; + } + } +} + +/// The YUV vectorscope (Cb, Cr of each sample). +pub fn vectorscope_yuv(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_yuv_into(s, p, &mut v); + v +} + +/// [`vectorscope_yuv`] into `out`, reusing its plane. +pub fn vectorscope_yuv_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, false); + let mut sum = [0f64; 2]; + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [_, cb, cr] = rgb_to_ycbcr(r, g, b, p.matrix); + out.plot(cb, cr, &mut sum); + } + out.finish(sum); +} + +/// Angle (degrees, counter-clockwise from +Cb, 0..360) of a chroma point. +pub fn angle_deg(cb: f32, cr: f32) -> f32 { + cr.atan2(cb).to_degrees().rem_euclid(360.0) +} + +/// The angle of pure red on a matrix's vectorscope (BT.709 ≈ 103°): the HLS scope puts hue 0 there. +pub fn red_angle(m: Matrix) -> f32 { + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, m); + angle_deg(cb, cr) +} + +/// A sample's point on the HLS vectorscope: hue as the angle from red (counter-clockwise, red, +/// yellow, green, cyan, blue, magenta), HLS saturation as the radius (1 = 0.5). +pub fn hls_point([r, g, b]: [f32; 3], m: Matrix) -> [f32; 2] { + let [h, s, _] = craft_color::rgb_to_hsl(r, g, b); + let a = (red_angle(m) + h * 360.0).to_radians(); + let rad = s.clamp(0.0, 1.0) * 0.5; + [rad * a.cos(), rad * a.sin()] +} + +/// Hue steps of the HLS vectorscope's direction table (0.1°). +const HUE_STEPS: usize = 3600; + +/// The HLS vectorscope. +pub fn vectorscope_hls(s: &Signal, p: &Params) -> Vectorscope { + let mut v = Vectorscope::default(); + vectorscope_hls_into(s, p, &mut v); + v +} + +/// [`vectorscope_hls`] into `out`, reusing its plane. +pub fn vectorscope_hls_into(s: &Signal, p: &Params, out: &mut Vectorscope) { + out.reset(p.vector_size(), p.matrix, true); + let mut sum = [0f64; 2]; + // hue to unit direction, tabulated at 0.1° on the stack (trigonometry per sample is the slow part) + let red = red_angle(p.matrix); + let dirs: [[f32; 2]; HUE_STEPS + 1] = std::array::from_fn(|i| { + let a = (red + i as f32 / 10.0).to_radians(); + [a.cos(), a.sin()] + }); + for &c in &s.rgb { + let [r, g, b] = if p.clamp { c.map(|x| x.clamp(0.0, 1.0)) } else { c }; + let [h, sat, _] = craft_color::rgb_to_hsl(r, g, b); + let [dx, dy] = dirs.get(((h * HUE_STEPS as f32).round() as usize).min(HUE_STEPS)).copied().unwrap_or([1.0, 0.0]); + let rad = sat.clamp(0.0, 1.0) * 0.5; + out.plot(rad * dx, rad * dy, &mut sum); + } + out.finish(sum); +} + +/// A color-bar target of the YUV vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Target { + pub name: &'static str, + pub rgb: [f32; 3], + pub cb: f32, + pub cr: f32, +} + +/// The six color-bar targets (R, Mg, B, Cy, G, Yl) at `amplitude` (0.75 or 1.0). +pub fn targets(m: Matrix, amplitude: f32) -> [Target; 6] { + let a = amplitude; + let t = |name, rgb: [f32; 3]| { + let [_, cb, cr] = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m); + Target { name, rgb, cb, cr } + }; + [t("R", [a, 0.0, 0.0]), t("Mg", [a, 0.0, a]), t("B", [0.0, 0.0, a]), t("Cy", [0.0, a, a]), t("G", [0.0, a, 0.0]), t("Yl", [a, a, 0.0])] +} + +/// Hue labels of the HLS vectorscope at radius 0.5: (name, Cb, Cr). +pub fn hls_targets(m: Matrix) -> [(&'static str, f32, f32); 6] { + let red = red_angle(m); + let at = |name, h: f32| { + let a = (red + h).to_radians(); + (name, 0.5 * a.cos(), 0.5 * a.sin()) + }; + [at("R", 0.0), at("Yl", 60.0), at("G", 120.0), at("Cy", 180.0), at("B", 240.0), at("Mg", 300.0)] +} + +// ------------------------------------------------------------------------------------ all scopes + +/// One computed scope. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum Computed { + Waveform(Waveform), + Parade(Waveform), + Histogram(Histogram), + Vectorscope(Vectorscope), +} + +impl Default for Computed { + fn default() -> Self { + Computed::Waveform(Waveform::default()) + } +} + +/// Compute one scope. +pub fn compute(kind: ScopeKind, s: &Signal, p: &Params) -> Computed { + let mut c = Computed::default(); + compute_into(kind, s, p, &mut c); + c +} + +/// [`compute`] into `out`. While `kind` stays the same, the buffers of the previous result are +/// reused. +pub fn compute_into(kind: ScopeKind, s: &Signal, p: &Params, out: &mut Computed) { + match (kind, &mut *out) { + (ScopeKind::Waveform, Computed::Waveform(w)) => waveform_into(s, p.waveform, p, w), + (ScopeKind::Parade, Computed::Parade(w)) => parade_into(s, p.parade, p, w), + (ScopeKind::Histogram, Computed::Histogram(h)) => histogram_into(s, p, h), + (ScopeKind::VectorscopeYuv, Computed::Vectorscope(v)) => vectorscope_yuv_into(s, p, v), + (ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => vectorscope_hls_into(s, p, v), + _ => { + // a different kind: move the old grids over where the shapes match + let old = std::mem::take(out); + *out = match (kind, old) { + (ScopeKind::Waveform, Computed::Parade(w)) => Computed::Waveform(w), + (ScopeKind::Parade, Computed::Waveform(w)) => Computed::Parade(w), + (ScopeKind::Waveform, _) => Computed::Waveform(Waveform::default()), + (ScopeKind::Parade, _) => Computed::Parade(Waveform::default()), + (ScopeKind::Histogram, _) => Computed::Histogram(Histogram::default()), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, Computed::Vectorscope(v)) => Computed::Vectorscope(v), + (ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls, _) => Computed::Vectorscope(Vectorscope::default()), + }; + compute_into(kind, s, p, out); + } + } +} diff --git a/crates/scopes/src/paint.rs b/crates/scopes/src/paint.rs new file mode 100644 index 0000000000..fff26ea9a2 --- /dev/null +++ b/crates/scopes/src/paint.rs @@ -0,0 +1,166 @@ +//! Count grids to pixels: the trace images a UI uploads as textures. +//! +//! A cell's intensity grows with the logarithm of its count relative to a reference count (a +//! "full" cell: a flat color puts a whole column of samples on one waveform cell), so sparse +//! detail stays visible next to flat areas, like a phosphor trace. Traces of several grids add +//! up (R + G + B traces that coincide read white). +//! +//! The `*_into` functions write into buffers the caller keeps ([`Scratch`] and the output `Vec`), +//! so painting the same size again does not allocate. + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Vectorscope}; + +/// Intensity 0..1 of a cell holding `count` samples (`reference` = a full cell, `gain` = the +/// Brightness setting). +#[inline] +pub fn intensity(count: u32, reference: f32, gain: f32) -> f32 { + if count == 0 { + return 0.0; + } + let r = (1.0 + reference.max(1.0)).ln(); + (gain * (0.12 + 0.88 * (1.0 + count as f32).ln() / r)).clamp(0.0, 1.0) +} + +/// Working buffers of the painters, kept between frames. +#[derive(Clone, Debug, Default)] +pub struct Scratch { + acc: Vec<[f32; 3]>, + level: Vec, + tint: Vec<[f32; 3]>, +} + +fn reset(v: &mut Vec, n: usize, value: T) { + v.clear(); + v.resize(n, value); +} + +/// Paint grids of equal size with colors (0..1 RGB), additively, into premultiplied RGBA8 with the +/// highest row at the top. Empty cells are transparent. Grids of another size than the first are +/// skipped. +pub fn grids(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = grids_into(layers, reference, gain, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`grids`] into `out` (resized to `w * h * 4`), returning `(w, h)`. A first grid wider than +/// [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] paints nothing and gives `(0, 0)`. +pub fn grids_into(layers: &[(&Grid, [f32; 3])], reference: f32, gain: f32, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + let Some((first, _)) = layers.first().filter(|(g, _)| g.cols <= MAX_SIGNAL_W && g.rows <= MAX_ROWS) else { + out.clear(); + return (0, 0); + }; + let (w, h) = (first.cols, first.rows); + let n = w.saturating_mul(h); + reset(out, n.saturating_mul(4), 0u8); + reset(&mut scratch.acc, n, [0f32; 3]); + for (g, col) in layers { + if g.cols != w || g.rows != h || g.data.len() < n { + continue; + } + for (row, counts) in g.data.chunks_exact(w.max(1)).take(h).enumerate() { + let dst = (h - 1 - row) * w; + let Some(acc) = scratch.acc.get_mut(dst..dst + w) else { continue }; + for (a, &c) in acc.iter_mut().zip(counts) { + if c > 0 { + let i = intensity(c, reference, gain); + for k in 0..3 { + a[k] += col[k] * i; + } + } + } + } + } + for (o, a) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.acc) { + let m = a[0].max(a[1]).max(a[2]); + if m <= 0.0 { + continue; + } + o[0] = (a[0].min(1.0) * 255.0).round() as u8; + o[1] = (a[1].min(1.0) * 255.0).round() as u8; + o[2] = (a[2].min(1.0) * 255.0).round() as u8; + o[3] = (m.min(1.0) * 255.0).round() as u8; + } + (w, h) +} + +/// The reference count of a waveform cell: half a column. +pub fn waveform_reference(per_column: usize) -> f32 { + (per_column as f32 / 2.0).max(1.0) +} + +/// The 3 × 3 spread of a vectorscope point: (dy, dx, weight). +const SPREAD: [(i64, i64, f32); 9] = + [(0, 0, 1.0), (-1, 0, 0.6), (1, 0, 0.6), (0, -1, 0.6), (0, 1, 0.6), (-1, -1, 0.35), (-1, 1, 0.35), (1, -1, 0.35), (1, 1, 0.35)]; + +/// Paint a vectorscope: each point takes the color of its own position (hue = angle) when +/// `colorize`, else `col`, and spreads over its 3 × 3 neighborhood (falling off), so isolated +/// points stay visible when the scope is drawn smaller than its grid. Premultiplied RGBA8, row +/// 0 = +Cr. +pub fn vectorscope(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool) -> (usize, usize, Vec) { + let mut out = Vec::new(); + let (w, h) = vectorscope_into(v, col, gain, colorize, &mut Scratch::default(), &mut out); + (w, h, out) +} + +/// [`vectorscope`] into `out` (resized to `size² * 4`), returning `(size, size)`. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] paints nothing and gives `(0, 0)`. +pub fn vectorscope_into(v: &Vectorscope, col: [f32; 3], gain: f32, colorize: bool, scratch: &mut Scratch, out: &mut Vec) -> (usize, usize) { + if v.size > MAX_VECTOR_SIZE { + out.clear(); + return (0, 0); + } + let n = v.size; + let cells = n.saturating_mul(n); + let reference = (v.samples as f32 / 64.0).max(1.0); + reset(&mut scratch.level, cells, 0f32); + reset(&mut scratch.tint, cells, [0f32; 3]); + for y in 0..n { + for x in 0..n { + let c = v.at(x, y); + if c == 0 { + continue; + } + let i = intensity(c, reference, gain); + let t = if colorize { + let [px, py] = v.point(x, y); + // the color at this point with mid lightness, desaturated towards white + let [r, g, b] = if v.hls { + let hue = ((crate::angle_deg(px, py) - crate::red_angle(v.matrix)) / 360.0).rem_euclid(1.0); + let sat = (px.hypot(py) / 0.5).clamp(0.0, 1.0); + craft_color::hsl_to_rgb(hue, sat * 0.8, 0.5) + } else { + craft_color::ycbcr_to_rgb(0.6, px * 0.8, py * 0.8, v.matrix) + }; + [0.55 + 0.45 * r.clamp(0.0, 1.0), 0.55 + 0.45 * g.clamp(0.0, 1.0), 0.55 + 0.45 * b.clamp(0.0, 1.0)] + } else { + col + }; + for (dy, dx, w) in SPREAD { + let (yy, xx) = (y as i64 + dy, x as i64 + dx); + if yy < 0 || xx < 0 || yy >= n as i64 || xx >= n as i64 { + continue; + } + let k = yy as usize * n + xx as usize; + if let (Some(l), Some(tk)) = (scratch.level.get_mut(k), scratch.tint.get_mut(k)) + && i * w > *l + { + *l = i * w; + *tk = t; + } + } + } + } + reset(out, cells.saturating_mul(4), 0u8); + for ((o, l), t) in out.as_chunks_mut::<4>().0.iter_mut().zip(&scratch.level).zip(&scratch.tint) { + if *l > 0.0 { + o.copy_from_slice(&[ + (t[0] * l * 255.0).round() as u8, + (t[1] * l * 255.0).round() as u8, + (t[2] * l * 255.0).round() as u8, + (l * 255.0).round() as u8, + ]); + } + } + (n, n) +} diff --git a/crates/scopes/src/summary.rs b/crates/scopes/src/summary.rs new file mode 100644 index 0000000000..8d6f8efa12 --- /dev/null +++ b/crates/scopes/src/summary.rs @@ -0,0 +1,193 @@ +//! Numeric summaries of scopes, for agents and control clients checking color without looking. +//! Levels are in percent of full scale (IRE-like: code value / 255 × 100 for 8-bit signals). + +use craft_color::rgb_to_ycbcr; +use serde::Serialize; + +use crate::{Grid, MAX_ROWS, MAX_SIGNAL_W, MAX_VECTOR_SIZE, Matrix, Signal, Vectorscope, Waveform, angle_deg, red_angle}; + +/// Minimum, maximum and mean of a set of levels (percent). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +pub struct Level { + pub min: f64, + pub max: f64, + pub mean: f64, +} + +#[derive(Default)] +struct Acc { + min: f32, + max: f32, + sum: f64, + n: u64, +} + +impl Acc { + /// Adds `count` samples at `v`; NaN and infinite values are left out. + fn add(&mut self, v: f32, count: u64) { + if !v.is_finite() { + return; + } + if self.n == 0 { + self.min = v; + self.max = v; + } else { + self.min = self.min.min(v); + self.max = self.max.max(v); + } + self.sum += v as f64 * count as f64; + self.n += count; + } + fn level(&self) -> Option { + (self.n > 0).then(|| Level { min: round2(self.min), max: round2(self.max), mean: round2(self.sum / self.n as f64) }) + } +} + +/// Rounded to 0.01 (as f64, so JSON shows `78.43`, not the f32's `78.43000030517578`). +fn round2(v: impl Into) -> f64 { + (v.into() * 100.0).round() / 100.0 +} + +/// Per-channel levels of the signal itself (R', G', B', Y'), exact (not from grid cells). NaN and +/// infinite values are left out of every level and of the chroma mean. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelStats { + pub r: Level, + pub g: Level, + pub b: Level, + pub y: Level, + /// Mean chroma (Cb, Cr) in −50..50 and its angle and magnitude (percent of 0.5). + pub chroma_mean: [f64; 2], + pub hue_deg: f64, + pub saturation: f64, +} + +pub fn channel_stats(s: &Signal, m: Matrix) -> Option { + if s.is_empty() { + return None; + } + let mut acc: [Acc; 4] = Default::default(); + let (mut cb_sum, mut cr_sum, mut chroma_n) = (0f64, 0f64, 0u64); + for &[r, g, b] in &s.rgb { + let [y, cb, cr] = rgb_to_ycbcr(r, g, b, m); + for (a, v) in acc.iter_mut().zip([r, g, b, y]) { + a.add(v * 100.0, 1); + } + if cb.is_finite() && cr.is_finite() { + cb_sum += cb as f64; + cr_sum += cr as f64; + chroma_n += 1; + } + } + let n = chroma_n.max(1) as f64; + let (cb, cr) = ((cb_sum / n) as f32, (cr_sum / n) as f32); + let [r, g, b, y] = &acc; + Some(ChannelStats { + r: r.level()?, + g: g.level()?, + b: b.level()?, + y: y.level()?, + chroma_mean: [round2(cb * 100.0), round2(cr * 100.0)], + hue_deg: round2(angle_deg(cb, cr)), + saturation: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + }) +} + +/// A trace split into `buckets` column ranges, each with the levels its cells hold (None when a +/// range holds no samples). A grid wider than [`MAX_SIGNAL_W`] or taller than [`MAX_ROWS`] gives +/// no ranges. +pub fn trace_columns(w: &Waveform, g: &Grid, buckets: usize) -> Vec> { + if g.cols > MAX_SIGNAL_W || g.rows > MAX_ROWS { + return Vec::new(); + } + let buckets = buckets.clamp(1, g.cols.max(1)); + (0..buckets) + .map(|b| { + let (c0, c1) = (b * g.cols / buckets, ((b + 1) * g.cols / buckets).max(b * g.cols / buckets + 1).min(g.cols)); + let mut a = Acc::default(); + for col in c0..c1 { + for row in 0..g.rows { + let n = g.at(col, row); + if n > 0 { + a.add(w.level(row) * 100.0, n as u64); + } + } + } + a.level() + }) + .collect() +} + +/// A dense spot of a vectorscope. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Peak { + /// Cell coordinates on the scope's grid. + pub x: usize, + pub y: usize, + /// Cb, Cr at the cell center (percent: −50..50 is the nominal range). + pub cb: f64, + pub cr: f64, + /// Degrees counter-clockwise from +Cb; on an HLS scope, the hue (0 = red, 120 = green). + pub angle_deg: f64, + /// Distance from the center in percent of 0.5 (100 % red in BT.709 ≈ 102.6). + pub magnitude: f64, + /// Share of the plotted samples in this cell (0..1). + pub share: f64, +} + +/// The `n` densest cells holding at least `min_share` of the samples, densest first. +pub fn peaks(v: &Vectorscope, n: usize, min_share: f32) -> Vec { + let total = v.samples.max(1) as f32; + let size = v.size.max(1); + let mut cells: Vec<(u32, usize)> = v.data.iter().enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| (*c, i)).collect(); + cells.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + cells + .into_iter() + .filter(|(c, _)| *c as f32 / total >= min_share) + .take(n) + .map(|(c, i)| { + let (x, y) = (i % size, i / size); + let [cb, cr] = v.point(x, y); + // the center cell has no hue + let angle = if v.hls && (cb, cr) != (0.0, 0.0) { + (angle_deg(cb, cr) - red_angle(v.matrix)).rem_euclid(360.0) + } else if v.hls { + 0.0 + } else { + angle_deg(cb, cr) + }; + Peak { + x, + y, + cb: round2(cb * 100.0), + cr: round2(cr * 100.0), + angle_deg: round2(angle), + magnitude: round2((cb * cb + cr * cr).sqrt() / 0.5 * 100.0), + share: (c as f64 / total as f64 * 10_000.0).round() / 10_000.0, + } + }) + .collect() +} + +/// Sparse cells of a vectorscope re-binned to `size`² (for a coarse numeric picture): `[x, y, count]`. +/// A vectorscope larger than [`MAX_VECTOR_SIZE`] gives no cells. +pub fn coarse(v: &Vectorscope, size: usize) -> Vec<[u32; 3]> { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } + let size = size.clamp(1, v.size.max(1)); + let mut out = vec![0u32; size * size]; + for y in 0..v.size { + for x in 0..v.size { + let c = v.at(x, y); + if c > 0 + && let Some(cell) = out.get_mut((y * size / v.size) * size + x * size / v.size) + { + *cell = cell.saturating_add(c); + } + } + } + out.iter().enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| [(i % size) as u32, (i / size) as u32, *c]).collect() +} diff --git a/crates/scopes/src/tests.rs b/crates/scopes/src/tests.rs new file mode 100644 index 0000000000..8abebb8d02 --- /dev/null +++ b/crates/scopes/src/tests.rs @@ -0,0 +1,661 @@ +//! Scope math on generated frames with known values. + +use crate::*; +use craft_color::rgb_to_ycbcr; + +fn rgba8(w: usize, h: usize, mut f: impl FnMut(usize, usize) -> [u8; 3]) -> Vec { + let mut px = Vec::with_capacity(w * h * 4); + for y in 0..h { + for x in 0..w { + let [r, g, b] = f(x, y); + px.extend_from_slice(&[r, g, b, 255]); + } + } + px +} + +fn solid(w: usize, h: usize, c: [u8; 3]) -> Signal { + Signal::from_rgba8(w, h, &rgba8(w, h, |_, _| c)) +} + +/// 75 % color bars (code 191): white, yellow, cyan, green, magenta, red, blue, black; 32 px each. +const BAR: u8 = 191; +const BARS: [[u8; 3]; 8] = [[BAR, BAR, BAR], [BAR, BAR, 0], [0, BAR, BAR], [0, BAR, 0], [BAR, 0, BAR], [BAR, 0, 0], [0, 0, BAR], [0, 0, 0]]; + +fn bars() -> Signal { + Signal::from_rgba8(256, 16, &rgba8(256, 16, |x, _| BARS[x / 32])) +} + +fn code(v: u8) -> f32 { + v as f32 / 255.0 +} + +#[test] +fn single_color_lands_in_exact_histogram_bins() { + let s = solid(64, 36, [200, 100, 50]); + let n = 64 * 36; + let h = histogram(&s, &Params::default()); + assert_eq!(h.samples, n); + assert_eq!((h.r[200], h.g[100], h.b[50]), (n, n, n)); + assert_eq!(h.r.iter().sum::(), n); + let y = rgb_to_ycbcr(code(200), code(100), code(50), Matrix::Bt709)[0]; + assert_eq!(h.y[(y * 255.0).round() as usize], n); + assert_eq!((h.below, h.above, h.hdr), ([0; 4], [0; 4], None)); +} + +#[test] +fn ramp_fills_every_bin_and_waveform_row_equals_code_value() { + let s = Signal::from_rgba8(256, 10, &rgba8(256, 10, |x, _| [x as u8; 3])); + let p = Params::default(); + let h = histogram(&s, &p); + for k in 0..256 { + assert_eq!((h.r[k], h.g[k], h.b[k], h.y[k]), (10, 10, 10, 10), "bin {k}"); + } + for kind in [WaveformType::Luma, WaveformType::YcNoChroma] { + let w = waveform(&s, kind, &p); + let y = w.trace("Y").unwrap(); + for x in 0..256 { + assert_eq!(y.rows_in(x), vec![x], "{kind:?} column {x}"); + assert_eq!(y.at(x, x), 10); + } + } + let w = waveform(&s, WaveformType::Rgb, &p); + assert_eq!(w.traces.len(), 3); + for t in &w.traces { + assert!((0..256).all(|x| t.rows_in(x) == vec![x]), "{}", t.name); + } +} + +#[test] +fn color_bars_parade_levels_and_vectorscope_targets() { + let s = bars(); + let p = Params::default(); + // RGB parade: every bar column holds its channel's code value exactly + let par = parade(&s, ParadeType::Rgb, &p); + for (ch, name) in ["R", "G", "B"].iter().enumerate() { + let t = par.trace(name).unwrap(); + for (i, bar) in BARS.iter().enumerate() { + for x in i * 32..(i + 1) * 32 { + assert_eq!(t.rows_in(x), vec![bar[ch] as usize], "{name} bar {i}"); + assert_eq!(t.at(x, bar[ch] as usize), 16); + } + } + } + // RGB-White adds the luma trace; YUV has Y, Cb, Cr + assert_eq!(parade(&s, ParadeType::RgbWhite, &p).traces.iter().map(|t| t.name).collect::>(), ["R", "G", "B", "Y"]); + assert_eq!(parade(&s, ParadeType::Yuv, &p).traces.iter().map(|t| t.name).collect::>(), ["Y", "Cb", "Cr"]); + // Vectorscope: each colored bar on its 75 % target cell, white and black in the center + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let p = Params { matrix: m, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.samples, 256 * 16); + let bar_samples = 32 * 16; + for t in targets(m, code(BAR)) { + let (x, y) = v.cell(t.cb, t.cr).unwrap(); + assert_eq!(v.at(x, y), bar_samples, "{m:?} {}", t.name); + } + let (cx, cy) = v.cell(0.0, 0.0).unwrap(); + assert_eq!(v.at(cx, cy), 2 * bar_samples); + // the densest spots: the center (two bars), then the six targets + let pk = summary::peaks(&v, 10, 0.01); + assert_eq!(pk.len(), 7); + assert_eq!((pk[0].x, pk[0].y, pk[0].share), (cx, cy, 0.25)); + assert!(pk[1..].iter().all(|k| k.share == 0.125)); + } +} + +#[test] +fn vectorscope_positions_of_primaries_are_known() { + let p = Params::default(); + // BT.709 red: Cb = −0.2126 / 1.8556 = −0.11457, Cr = 0.5 + let v = vectorscope_yuv(&solid(8, 8, [255, 0, 0]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), (103, 21)); + assert_eq!((pk.share, v.samples), (1.0, 64)); + assert!((red_angle(Matrix::Bt709) - 102.906).abs() < 0.01, "{}", red_angle(Matrix::Bt709)); + assert!((red_angle(Matrix::Bt601) - 108.645).abs() < 0.01, "{}", red_angle(Matrix::Bt601)); + // the mean chroma of a flat color is its own + let [_, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + assert!((v.mean[0] - cb).abs() < 1e-6 && (v.mean[1] - cr).abs() < 1e-6); + // greys sit in the center for every matrix + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let v = vectorscope_yuv(&solid(4, 4, [77, 77, 77]), &Params { matrix: m, ..p }); + assert_eq!(v.at(127, 127), 16, "{m:?}"); + } + // the skin-tone line sits between red and yellow + let yl = targets(Matrix::Bt709, 1.0)[5]; + assert!(red_angle(Matrix::Bt709) < SKIN_TONE_DEG && SKIN_TONE_DEG < angle_deg(yl.cb, yl.cr)); +} + +#[test] +fn hls_vectorscope_puts_hue_on_the_angle_and_saturation_on_the_radius() { + let p = Params::default(); + let red = red_angle(p.matrix); + for (rgb, hue) in + [([255, 0, 0], 0.0f32), ([255, 255, 0], 60.0), ([0, 255, 0], 120.0), ([0, 255, 255], 180.0), ([0, 0, 255], 240.0), ([255, 0, 255], 300.0)] + { + let v = vectorscope_hls(&solid(4, 4, rgb), &p); + let a = (red + hue).to_radians(); + let want = cell_of(0.5 * a.cos(), 0.5 * a.sin(), p.vector_size, VECTOR_EXTENT).unwrap(); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.x, pk.y), want, "{rgb:?}"); + assert!((pk.magnitude - 100.0).abs() < 0.6, "{rgb:?} {}", pk.magnitude); + // the per-sample helper agrees with the tabulated scope + let [cb, cr] = hls_point(rgb.map(code), p.matrix); + assert_eq!(cell_of(cb, cr, p.vector_size, VECTOR_EXTENT), Some(want), "{rgb:?}"); + } + // half-saturated red (HSL s = 0.5) at half the radius; grey in the center + let v = vectorscope_hls(&solid(4, 4, [191, 64, 64]), &p); + let pk = summary::peaks(&v, 1, 0.0)[0]; + let hue_off = pk.angle_deg.min(360.0 - pk.angle_deg); + assert!((pk.magnitude - 50.0).abs() < 1.0 && hue_off < 0.5, "{pk:?}"); + let v = vectorscope_hls(&solid(4, 4, [90, 90, 90]), &p); + assert_eq!(v.at(127, 127), 16); + let pk = summary::peaks(&v, 1, 0.0)[0]; + assert_eq!((pk.angle_deg, pk.magnitude), (0.0, 0.0), "{pk:?}"); + // Clamp Signal off: an over-range sample keeps its own hue + let over = Signal::from_fn(1, 1, |_, _| [1.2, 0.5, 0.0]); + let inside = Signal::from_fn(1, 1, |_, _| [1.0, 0.5, 0.0]); + let off = Params { clamp: false, ..p }; + let peak = |s: &Signal, p: &Params| summary::peaks(&vectorscope_hls(s, p), 1, 0.0)[0]; + assert_ne!((peak(&over, &off).x, peak(&over, &off).y), (peak(&inside, &off).x, peak(&inside, &off).y)); + assert_eq!((peak(&over, &p).x, peak(&over, &p).y), (peak(&inside, &p).x, peak(&inside, &p).y)); +} + +#[test] +fn yc_waveform_draws_chroma_around_luma() { + let p = Params::default(); + let w = waveform(&solid(4, 4, [128, 128, 128]), WaveformType::Yc, &p); + assert_eq!((w.trace("Y").unwrap().rows_in(0), w.trace("C").unwrap().rows_in(0)), (vec![128], vec![128])); + let w = waveform(&solid(4, 4, [255, 0, 0]), WaveformType::Yc, &p); + let [y, cb, cr] = rgb_to_ycbcr(1.0, 0.0, 0.0, Matrix::Bt709); + let c = (cb * cb + cr * cr).sqrt(); + let row = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize; + assert_eq!(w.trace("Y").unwrap().rows_in(2), vec![row(y)]); + assert_eq!(w.trace("C").unwrap().rows_in(2), vec![row(y - c), row(y + c)]); +} + +#[test] +fn yuv_parade_offsets_chroma_to_mid_scale() { + let w = parade(&solid(4, 4, [128, 128, 128]), ParadeType::Yuv, &Params::default()); + assert_eq!(w.trace("Y").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cb").unwrap().rows_in(0), vec![128]); + assert_eq!(w.trace("Cr").unwrap().rows_in(0), vec![128]); +} + +#[test] +fn decimation_keeps_whole_samples() { + let px = rgba8(1920, 1080, |x, y| [(x % 256) as u8, (y % 256) as u8, 7]); + let s = Signal::from_rgba8(1920, 1080, &px); + assert_eq!((s.w, s.h), (480, 270)); + assert_eq!(s.rgb[1], [code(4), 0.0, code(7)]); + assert_eq!(s.rgb[480], [0.0, code(4), code(7)]); + let s = Signal::from_rgba8(1921, 9, &rgba8(1921, 9, |_, _| [1, 2, 3])); + assert_eq!((s.w, s.h), (385, 9)); + assert!(Signal::from_rgba8(10, 10, &[0; 12]).is_empty()); +} + +#[test] +fn clamp_signal_controls_out_of_range_values() { + let s = Signal::from_fn(4, 4, |x, _| if x < 2 { [1.2, 0.5, -0.05] } else { [0.5, 0.5, 0.5] }); + let on = Params::default(); + let off = Params { clamp: false, ..on }; + let h = histogram(&s, &on); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (8, 8, 8, 8)); + let h = histogram(&s, &off); + assert_eq!((h.r[255], h.above[0], h.b[0], h.below[2]), (0, 8, 0, 8)); + // with clamping, the histogram's luma comes from the clamped R'G'B', as the waveform's does + let hot = Signal::from_fn(1, 1, |_, _| [2.0, -1.0, 0.0]); + let rows = waveform(&hot, WaveformType::Luma, &on).trace("Y").unwrap().rows_in(0); + let hh = histogram(&hot, &on); + assert_eq!(hh.y.iter().position(|&c| c > 0), rows.first().copied()); + // and the luma of the sample as it is still counts as out of range + assert_eq!((hh.below[3], hh.above[3]), (1, 0)); + let white = histogram(&Signal::from_fn(1, 1, |_, _| [2.0; 3]), &on); + assert_eq!((white.y[255], white.above[3]), (1, 1)); + // waveform: clamped onto the top row, or plotted above 100 % within −10..110 + let w = waveform(&s, WaveformType::Rgb, &on); + assert_eq!(w.trace("R").unwrap().rows_in(0), vec![255]); + let w = waveform(&s, WaveformType::Rgb, &off); + assert_eq!((w.lo, w.hi), (-0.1, 1.1)); + assert!(w.trace("R").unwrap().rows_in(0).is_empty(), "1.2 is outside −10..110"); + let r = w.trace("B").unwrap().rows_in(0); + assert_eq!(r, vec![row_of(-0.05, -0.1, 1.1, 256).unwrap()]); +} + +#[test] +fn hdr_axis_helpers() { + assert!(nits_to_pq(0.0) < 1e-5); + assert!((nits_to_pq(10_000.0) - 1.0).abs() < 1e-6); + // reference white (203 cd/m²) ≈ 58 % of the PQ range (BT.2408) + let w = linear_to_pq([1.0, 1.0, 1.0, 1.0])[0]; + assert!((w - nits_to_pq(203.0)).abs() < 1e-6 && (w - 0.58).abs() < 0.01, "{w}"); + // premultiplied: half-covered white is still white + assert!((linear_to_pq([0.5, 0.5, 0.5, 0.5])[0] - w).abs() < 1e-6); + assert!((sdr_to_pq(1.0) - nits_to_pq(100.0)).abs() < 1e-6); +} + +#[test] +fn nan_and_empty_signals_do_not_panic() { + let s = Signal::from_fn(3, 3, |x, _| if x == 1 { [f32::NAN; 3] } else { [0.5; 3] }); + for clamp in [true, false] { + let p = Params { clamp, ..Params::default() }; + for k in ScopeKind::ALL { + let _ = compute(k, &s, &Params { waveform: WaveformType::Yc, parade: ParadeType::RgbWhite, ..p }); + let _ = compute(k, &Signal::default(), &p); + } + } + assert!(summary::channel_stats(&Signal::default(), Matrix::Bt709).is_none()); + // NaN and infinite samples are left out of the levels, so every number stays finite + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.min, st.r.max, st.r.mean, st.y.mean), (50.0, 50.0, 50.0, 50.0)); + assert!(st.chroma_mean.iter().all(|v| v.is_finite()) && st.saturation.is_finite()); + let inf = Signal::from_fn(2, 1, |x, _| if x == 0 { [f32::INFINITY, 0.25, 0.25] } else { [0.25; 3] }); + let st = summary::channel_stats(&inf, Matrix::Bt709).unwrap(); + assert_eq!((st.r.max, st.g.mean), (25.0, 25.0)); + assert!(summary::channel_stats(&Signal::from_fn(1, 1, |_, _| [f32::NAN; 3]), Matrix::Bt709).is_none()); +} + +#[test] +fn summaries_report_levels_in_percent() { + let s = solid(8, 8, [200, 100, 50]); + let st = summary::channel_stats(&s, Matrix::Bt709).unwrap(); + assert_eq!((st.r.mean, st.g.mean, st.b.mean), (78.43, 39.22, 19.61)); + assert_eq!((st.r.min, st.r.max), (78.43, 78.43)); + // a two-level frame: left half black, right half white + let s = Signal::from_rgba8(100, 4, &rgba8(100, 4, |x, _| if x < 50 { [0; 3] } else { [255; 3] })); + let w = waveform(&s, WaveformType::Luma, &Params::default()); + let cols = summary::trace_columns(&w, w.trace("Y").unwrap(), 4); + assert_eq!(cols.len(), 4); + assert_eq!(cols[0].unwrap(), summary::Level { min: 0.0, max: 0.0, mean: 0.0 }); + assert_eq!(cols[3].unwrap(), summary::Level { min: 100.0, max: 100.0, mean: 100.0 }); + assert_eq!((cols[1].unwrap().max, cols[2].unwrap().min), (0.0, 100.0)); + let c = summary::coarse(&vectorscope_yuv(&bars(), &Params::default()), 16); + assert_eq!(c.iter().map(|e| e[2]).sum::(), 256 * 16); +} + +#[test] +fn paint_adds_traces_and_leaves_empty_cells_transparent() { + let s = solid(4, 8, [128, 128, 128]); + let w = waveform(&s, WaveformType::Rgb, &Params::default()); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().zip([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]).collect(); + let (pw, ph, px) = paint::grids(&layers, paint::waveform_reference(w.per_column), 1.0); + assert_eq!((pw, ph, px.len()), (4, 256, 4 * 256 * 4)); + // row 128 from the bottom = image row 127; R+G+B coincide → white + let i = (127 * 4) * 4; + assert_eq!(&px[i..i + 4], &[255, 255, 255, 255]); + assert_eq!(&px[0..4], &[0, 0, 0, 0]); + // dimmed is darker than bright + assert!(paint::intensity(3, 100.0, Brightness::Dimmed.gain()) < paint::intensity(3, 100.0, Brightness::Bright.gain())); + let v = vectorscope_yuv(&bars(), &Params::default()); + let (n, _, vp) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + assert_eq!(vp.len(), n * n * 4); + // seven spots of 3 × 3 texels each (none touch) + assert_eq!(vp.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count(), 7 * 9); +} + +#[test] +fn names_round_trip() { + for k in ScopeKind::ALL { + assert_eq!(ScopeKind::from_name(k.name()), Some(k)); + assert_eq!(ScopeKind::from_name(k.label()), Some(k)); + assert_eq!(serde_json::to_value(k).unwrap(), serde_json::Value::from(k.name())); + } + assert_eq!(ScopeKind::from_name("vectorscope"), Some(ScopeKind::VectorscopeYuv)); + assert_eq!(WaveformType::from_name("Luma and chroma, chroma hidden"), Some(WaveformType::YcNoChroma)); + assert_eq!(WaveformType::from_name("ycNoChroma"), Some(WaveformType::YcNoChroma)); + assert_eq!(ParadeType::from_name("rgb and luma"), Some(ParadeType::RgbWhite)); + assert_eq!(ColorSpace::from_name("709"), Some(ColorSpace::Rec709)); + assert_eq!(ColorSpace::from_name("Rec. 2100"), Some(ColorSpace::Rec2100)); + assert_eq!(Scale::from_name("8 bit"), Some(Scale::Bits8)); + assert_eq!(serde_json::to_value(Targets::Percent100).unwrap(), serde_json::Value::from("100")); + assert_eq!(ColorSpace::Auto.resolve(true), ColorSpace::Rec2100); + assert_eq!(ColorSpace::Auto.resolve(false).matrix(), Matrix::Bt709); +} + +// ------------------------------------------------------------------------------------ frames + +/// An NV12 frame of `w × h` with every pixel at one (Y', Cb, Cr) code value, `pad` spare bytes at +/// the end of each row of both planes. +fn nv12(w: usize, h: usize, pad: usize, [y, cb, cr]: [u8; 3]) -> (Vec, usize, Vec, usize) { + let ys = w + pad; + let cs = w.div_ceil(2) * 2 + pad; + let mut yp = vec![0xEE; ys * h]; + let mut uv = vec![0xEE; cs * h.div_ceil(2)]; + for row in yp.chunks_mut(ys) { + row[..w].fill(y); + } + for row in uv.chunks_mut(cs) { + for pair in row[..w.div_ceil(2) * 2].chunks_mut(2) { + pair.copy_from_slice(&[cb, cr]); + } + } + (yp, ys, uv, cs) +} + +fn read_nv12(w: usize, h: usize, pad: usize, ycc: [u8; 3], matrix: Matrix, range: Range) -> Signal { + let (y, y_stride, uv, uv_stride) = nv12(w, h, pad, ycc); + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width: w, height: h, y: &y, y_stride, uv: &uv, uv_stride, matrix, range }).unwrap(); + s +} + +/// 8-bit limited-range BT.709 code values of the 100 % color bars (SMPTE RP 219-1, table 1; +/// the Y'CbCr equations of ITU-R BT.709-6 item 3), decoded back to R'G'B'. +#[test] +fn nv12_bt709_limited_bars_decode_to_their_rgb() { + let bars: [([u8; 3], [f32; 3]); 8] = [ + ([235, 128, 128], [1.0, 1.0, 1.0]), + ([219, 16, 138], [1.0, 1.0, 0.0]), + ([188, 154, 16], [0.0, 1.0, 1.0]), + ([173, 42, 26], [0.0, 1.0, 0.0]), + ([78, 214, 230], [1.0, 0.0, 1.0]), + ([63, 102, 240], [1.0, 0.0, 0.0]), + ([32, 240, 118], [0.0, 0.0, 1.0]), + ([16, 128, 128], [0.0, 0.0, 0.0]), + ]; + for (ycc, want) in bars { + let s = read_nv12(6, 4, 0, ycc, Matrix::Bt709, Range::Limited); + assert_eq!((s.w, s.h, s.len()), (6, 4, 24)); + for got in &s.rgb { + for k in 0..3 { + // the published code values are rounded to whole codes: within 1.5 codes of 255 + assert!((got[k] - want[k]).abs() < 1.5 / 255.0, "{ycc:?}: {got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn nv12_full_range_and_odd_sizes() { + // full range: Y' 255 with neutral chroma is white, Y' 0 is black + let s = read_nv12(5, 3, 3, [255, 128, 128], Matrix::Bt601, Range::Full); + assert_eq!((s.w, s.h), (5, 3)); + assert!(s.rgb.iter().all(|c| c.iter().all(|v| (v - 1.0).abs() < 0.01)), "{:?}", s.rgb[0]); + let s = read_nv12(1, 1, 0, [0, 128, 128], Matrix::Bt601, Range::Full); + assert!(s.rgb[0].iter().all(|v| v.abs() < 0.01), "{:?}", s.rgb[0]); + // a grey NV12 frame and the same grey as RGBA8 give the same histogram luma bin + let s = read_nv12(7, 5, 1, [126, 128, 128], Matrix::Bt709, Range::Limited); + let h = histogram(&s, &Params::default()); + let grey = ((126.0 - 16.0) / 219.0 * 255.0f32).round() as usize; + assert_eq!(h.y[grey], 35); +} + +#[test] +fn rgba_with_a_stride_reads_the_same_samples_as_packed_rgba() { + let (w, h) = (9, 5); + let packed = rgba8(w, h, |x, y| [x as u8 * 20, y as u8 * 40, 3]); + let stride = w * 4 + 12; + let mut strided = vec![0xAB; stride * h]; + for y in 0..h { + strided[y * stride..y * stride + w * 4].copy_from_slice(&packed[y * w * 4..(y + 1) * w * 4]); + } + let mut s = Signal::default(); + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided }).unwrap(); + assert_eq!(s, Signal::from_rgba8(w, h, &packed)); + // the last row needs only its own pixels, not a whole stride + s.fill(&Frame::Rgba8 { width: w, height: h, stride, data: &strided[..stride * (h - 1) + w * 4] }).unwrap(); + assert_eq!(s.len(), w * h); +} + +#[test] +fn bad_frames_give_errors_and_an_empty_signal() { + let px = [0u8; 64]; + let mut s = solid(2, 2, [1, 2, 3]); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 4, stride: 8, data: &px }), Err(FrameError::Stride { plane: "RGBA", stride: 8, needed: 16 })); + assert!(s.is_empty()); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: 5, stride: 16, data: &px }), Err(FrameError::Short { plane: "RGBA", len: 64, needed: 80 })); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 2, stride: 16, data: &px }), Err(FrameError::TooLarge)); + assert_eq!(s.fill(&Frame::Rgba8 { width: 4, height: usize::MAX, stride: usize::MAX / 2, data: &px }), Err(FrameError::TooLarge)); + let nv = |width, height, y: &[u8], y_stride, uv: &[u8], uv_stride| { + let mut s = Signal::default(); + s.fill(&Frame::Nv12 { width, height, y, y_stride, uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }) + }; + assert_eq!(nv(4, 4, &px[..16], 4, &px[..7], 4), Err(FrameError::Short { plane: "UV", len: 7, needed: 8 })); + assert_eq!(nv(5, 2, &px[..10], 5, &px[..6], 5), Err(FrameError::Stride { plane: "UV", stride: 5, needed: 6 })); + assert_eq!(nv(4, 4, &px[..15], 4, &px[..8], 4), Err(FrameError::Short { plane: "Y", len: 15, needed: 16 })); + // a frame with no area is valid and empty + assert_eq!(nv(0, 4, &[], 0, &[], 0), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: 3, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(s.fill(&Frame::Rgba8 { width: usize::MAX, height: 0, stride: 0, data: &[] }), Ok(())); + assert_eq!(nv(usize::MAX, 0, &[], 0, &[], 0), Ok(())); + assert!(s.is_empty()); + assert!(FrameError::TooLarge.to_string().contains("too large")); +} + +#[test] +fn colorized_vectorscope_points_use_the_scope_matrix() { + let s = Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]); + let p = Params { matrix: Matrix::Bt2020Ncl, ..Params::default() }; + let v = vectorscope_yuv(&s, &p); + assert_eq!(v.matrix, Matrix::Bt2020Ncl); + let [_, cb, cr] = rgb_to_ycbcr(0.0, 1.0, 0.0, Matrix::Bt2020Ncl); + let (x, y) = v.cell(cb, cr).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 4]; + let [ccb, ccr] = v.point(x, y); + let tint = |m| craft_color::ycbcr_to_rgb(0.6, ccb * 0.8, ccr * 0.8, m).map(|c: f32| 0.55 + 0.45 * c.clamp(0.0, 1.0)); + let l = f32::from(px[3]) / 255.0; + let got = [0, 1, 2].map(|i| f32::from(px[i]) / 255.0 / l); + let (want, other) = (tint(Matrix::Bt2020Ncl), tint(Matrix::Bt709)); + let err = |t: [f32; 3]| (0..3).map(|i| (got[i] - t[i]).abs()).fold(0.0f32, f32::max); + assert!(err(want) < 0.005, "{got:?} vs {want:?}"); + assert!(err(other) > 0.01, "the BT.709 tint {other:?} is not told apart from {want:?}"); + // HLS points are colored by their hue: saturated yellow paints yellow, not orange + let yellow = Signal::from_fn(1, 1, |_, _| [1.0, 1.0, 0.0]); + let v = vectorscope_hls(&yellow, &Params::default()); + assert!(v.hls); + let [hx, hy] = hls_point([1.0, 1.0, 0.0], Matrix::Bt709); + let (x, y) = v.cell(hx, hy).unwrap(); + let (n, _, img) = paint::vectorscope(&v, [1.0; 3], 1.0, true); + let px = &img[(y * n + x) * 4..(y * n + x) * 4 + 3]; + assert!(px[0].abs_diff(px[1]) <= 6 && px[2] + 40 < px[1], "{px:?}"); + // HLS peaks report the hue: yellow at 60°, green at 120° + assert!((summary::peaks(&v, 1, 0.0)[0].angle_deg - 60.0).abs() < 1.0, "{:?}", summary::peaks(&v, 1, 0.0)); + let green = vectorscope_hls(&Signal::from_fn(1, 1, |_, _| [0.0, 1.0, 0.0]), &Params { matrix: Matrix::Bt601, ..Params::default() }); + assert!((summary::peaks(&green, 1, 0.0)[0].angle_deg - 120.0).abs() < 1.0, "{:?}", summary::peaks(&green, 1, 0.0)); +} + +// ------------------------------------------------------------------------------------ reuse + +#[test] +fn into_functions_match_the_allocating_ones_and_keep_their_buffers() { + let frame_px = rgba8(1920, 1080, |x, y| [(x % 251) as u8, (y % 241) as u8, ((x + y) % 239) as u8]); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &frame_px }; + let p = Params::default(); + let mut s = Signal::default(); + let mut w = Waveform::default(); + let mut h = Histogram::default(); + let mut v = Vectorscope::default(); + let mut scratch = paint::Scratch::default(); + let mut img = Vec::new(); + let mut c = Computed::default(); + let mut run = |s: &mut Signal| { + s.fill(&frame).unwrap(); + waveform_into(s, WaveformType::Yc, &p, &mut w); + histogram_into(s, &p, &mut h); + vectorscope_hls_into(s, &p, &mut v); + let layers: Vec<(&Grid, [f32; 3])> = w.traces.iter().map(|t| (t, [1.0; 3])).collect(); + paint::grids_into(&layers, 10.0, 1.0, &mut scratch, &mut img); + compute_into(ScopeKind::Parade, s, &Params { parade: ParadeType::RgbWhite, ..p }, &mut c); + (s.rgb.as_ptr(), w.traces[1].data.as_ptr(), h.y.as_ptr(), v.data.as_ptr(), img.as_ptr(), w.clone(), h.clone(), v.clone(), c.clone()) + }; + let first = run(&mut s); + let second = run(&mut s); + assert_eq!((first.0, first.1, first.2, first.3, first.4), (second.0, second.1, second.2, second.3, second.4), "buffers were reallocated"); + assert_eq!(second.5, waveform(&s, WaveformType::Yc, &p)); + assert_eq!(second.6, histogram(&s, &p)); + assert_eq!(second.7, vectorscope_hls(&s, &p)); + assert_eq!(second.8, compute(ScopeKind::Parade, &s, &Params { parade: ParadeType::RgbWhite, ..p })); + // switching kinds keeps working and gives the same result as a fresh compute + let mut c = Computed::default(); + let lp = Params { waveform: WaveformType::Luma, parade: ParadeType::Yuv, ..p }; + for k in [ScopeKind::Parade, ScopeKind::Histogram, ScopeKind::VectorscopeYuv, ScopeKind::VectorscopeHls, ScopeKind::Waveform, ScopeKind::Parade] { + compute_into(k, &s, &lp, &mut c); + assert_eq!(c, compute(k, &s, &lp), "{k:?}"); + } +} + +// ------------------------------------------------------------------------------------ hostile input + +#[test] +fn hostile_params_and_signals_stay_bounded() { + let s = bars(); + // rows and grid sizes are clamped + let w = waveform(&s, WaveformType::Rgb, &Params { rows: usize::MAX, ..Params::default() }); + assert_eq!(w.traces[0].rows, MAX_ROWS); + let w = waveform(&s, WaveformType::Rgb, &Params { rows: 0, ..Params::default() }); + assert_eq!(w.traces[0].rows, 2); + let v = vectorscope_yuv(&s, &Params { vector_size: usize::MAX, ..Params::default() }); + assert_eq!(v.size, MAX_VECTOR_SIZE); + let v = vectorscope_hls(&s, &Params { vector_size: 0, ..Params::default() }); + assert_eq!((v.size, v.samples), (3, 256 * 16)); + // an even size becomes odd, so a gray sample lands on the center cell with no magnitude + let gray = Signal::from_fn(1, 1, |_, _| [0.5; 3]); + let v = vectorscope_yuv(&gray, &Params { vector_size: 256, ..Params::default() }); + assert_eq!(v.size, 257); + assert_eq!(v.cell(0.0, 0.0), Some((128, 128))); + assert_eq!(v.point(128, 128), [0.0, 0.0]); + // a signal whose public fields disagree reads only whole rows and never indexes past them + let odd = Signal { w: 1000, h: 1000, rgb: vec![[0.5; 3]; 10] }; + let w = waveform(&odd, WaveformType::Rgb, &Params::default()); + assert_eq!((w.traces[0].cols, w.per_column, w.traces[0].total()), (10, 0, 0)); + // sizes asked for past the caps are clamped, and samples past a clamped grid are dropped + let px = rgba8(2000, 4, |_, _| [9, 9, 9]); + let mut big = Signal::default(); + big.fill_max(&Frame::Rgba8 { width: 2000, height: 4, stride: 8000, data: &px }, usize::MAX, usize::MAX).unwrap(); + assert_eq!((big.w, big.h), (1000, 4), "2000 columns decimated by 2 to fit 1920"); + let f = Signal::from_rgba_f32_with(4000, 1, &vec![0.5; 16_000], usize::MAX, usize::MAX, |p| [p[0], p[1], p[2]]); + assert_eq!(f.w, 1334, "4000 columns decimated by 3"); + let g = Grid::new("Y", usize::MAX, usize::MAX); + assert_eq!((g.cols, g.rows, g.data.len()), (MAX_SIGNAL_W, MAX_ROWS, MAX_SIGNAL_W * MAX_ROWS)); + let wide = Signal::from_fn(3000, 2, |_, _| [0.5; 3]); + let w = waveform(&wide, WaveformType::Luma, &Params::default()); + assert_eq!((w.traces[0].cols, w.traces[0].total()), (MAX_SIGNAL_W, 2 * MAX_SIGNAL_W as u64)); + let wide = Signal { w: usize::MAX, h: 0, rgb: Vec::new() }; + assert_eq!(waveform(&wide, WaveformType::Luma, &Params::default()).traces[0].data.len(), 0); + // helpers outside their range answer None or 0 instead of panicking + assert_eq!(row_of(0.5, 0.0, 1.0, 1), None); + assert_eq!(row_of(0.5, 1.0, 1.0, 256), None); + assert_eq!(cell_of(0.0, 0.0, 1, VECTOR_EXTENT), None); + assert_eq!(cell_of(0.0, 0.0, 255, f32::NAN), None); + let g = Grid::new("Y", 3, 3); + assert_eq!((g.at(3, 0), g.at(0, 3), g.at(0, usize::MAX), g.at(usize::MAX, usize::MAX)), (0, 0, 0, 0)); + let v = vectorscope_yuv(&s, &Params::default()); + assert_eq!((v.at(0, usize::MAX), v.at(usize::MAX, 0)), (0, 0)); + let empty = Vectorscope::default(); + assert!(summary::coarse(&empty, 0).is_empty()); + assert!(summary::peaks(&empty, 5, 0.0).is_empty()); + assert_eq!(empty.at(0, 0), 0); +} + +#[test] +fn hand_built_values_past_the_caps_paint_nothing() { + let huge = Signal::from_fn(usize::MAX, 2, |_, _| [0.5; 3]); + assert_eq!((huge.w, huge.h, huge.len()), (MAX_SIGNAL_W, 2, 2 * MAX_SIGNAL_W)); + let mut scratch = paint::Scratch::default(); + let mut out = vec![1u8; 4]; + let v = Vectorscope { size: usize::MAX, ..Vectorscope::default() }; + assert_eq!(paint::vectorscope_into(&v, [1.0; 3], 1.0, true, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::coarse(&v, usize::MAX).is_empty()); + let g = Grid { name: "Y", cols: usize::MAX, rows: usize::MAX, data: Vec::new() }; + out.push(1); + assert_eq!(paint::grids_into(&[(&g, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); + assert!(out.is_empty()); + assert!(summary::trace_columns(&Waveform::default(), &g, usize::MAX).is_empty()); + let tall = Grid { name: "Y", cols: 4, rows: MAX_ROWS + 1, data: Vec::new() }; + assert_eq!(paint::grids_into(&[(&tall, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); +} + +// ------------------------------------------------------------------------------------ HDR + +#[test] +fn hdr_bins_split_sdr_and_stops() { + let px = Signal { w: 5, h: 1, rgb: vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 4.0, 4.0], [16.0, 16.0, 16.0], [f32::NAN, -1.0, f32::INFINITY]] }; + let mut h = Histogram::default(); + histogram_hdr_into(&px, Matrix::Bt709, HdrBins::new(4.0), &mut h); + let b = h.hdr.unwrap(); + assert_eq!(h.samples, 5); + assert_eq!(b.bin(1.0), b.from - 1, "SDR white is the last SDR bin"); + assert_eq!(b.bin(16.0), 255); + assert_eq!(b.bin(1e9), 255); + let two = b.bin(4.0); + assert!(two > b.from && two < 255, "{two}"); + assert_eq!(h.r[0], 2, "black and NaN"); + assert_eq!(h.b[255], 2, "16 and +inf"); + assert_eq!((h.below[1], h.above[2]), (1, 1), "-1 below, +inf above 2^4"); + assert!((above_sdr(&h) - 0.6).abs() < 1e-6, "{}", above_sdr(&h)); + // over-white samples in different channels each count once + let split = Signal { w: 2, h: 1, rgb: vec![[2.0, 0.5, 0.5], [0.5, 0.5, 2.0]] }; + histogram_hdr_into(&split, Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!((h.above_sdr_samples, above_sdr(&h)), (2, 1.0)); + histogram_hdr_into(&Signal::default(), Matrix::Bt709, HdrBins::new(4.0), &mut h); + assert_eq!(above_sdr(&h), 0.0); + assert_eq!(above_sdr(&histogram(&bars(), &Params::default())), 0.0); + // the SDR half follows the sRGB curve: linear 0.5 is about 73.5 % of the way to SDR white + let half = b.bin(0.5); + assert_eq!(half, (craft_color::linear_to_srgb(0.5) * 127.0 + 0.5) as usize); +} + +/// A hand-built split outside the bins (any `from`, any `stops`) never panics and stays in range. +#[test] +fn hdr_bins_with_any_split_stay_in_range() { + for from in [0, 1, 2, 128, 255, 256, usize::MAX] { + for stops in [0.0, 3.0, f32::NAN, f32::INFINITY] { + let b = HdrBins { from, stops }; + for v in [f32::NAN, -1.0, 0.0, 0.5, 1.0, 2.0, 1e9] { + assert!(b.bin(v) < BINS, "{from} {stops} {v}"); + } + let mut h = Histogram::default(); + histogram_hdr_into(&Signal { w: 1, h: 1, rgb: vec![[2.0; 3]] }, Matrix::Bt2020Ncl, b, &mut h); + assert!((0.0..=1.0).contains(&above_sdr(&h))); + } + } +} + +/// `cargo test --release -p craft-scopes perf -- --ignored --nocapture` +#[test] +#[ignore] +fn perf_scopes_at_1080p() { + let mut seed = 0x1234_5678u32; + let px = rgba8(1920, 1080, |_, _| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + [seed as u8, (seed >> 8) as u8, (seed >> 16) as u8] + }); + let reps = 20; + let mut s = Signal::default(); + let frame = Frame::Rgba8 { width: 1920, height: 1080, stride: 1920 * 4, data: &px }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&frame).unwrap(); + } + println!("decimate RGBA 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + let (y, y_stride, uv, uv_stride) = nv12(1920, 1080, 0, [100, 120, 140]); + let nv = Frame::Nv12 { width: 1920, height: 1080, y: &y, y_stride, uv: &uv, uv_stride, matrix: Matrix::Bt709, range: Range::Limited }; + let t = std::time::Instant::now(); + for _ in 0..reps { + s.fill(&nv).unwrap(); + } + println!("decimate NV12 1920x1080: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + s.fill(&frame).unwrap(); + let p = Params::default(); + let mut c = Computed::default(); + for (k, wt, pt) in [ + (ScopeKind::Waveform, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::Waveform, WaveformType::Yc, ParadeType::Rgb), + (ScopeKind::Parade, WaveformType::Rgb, ParadeType::RgbWhite), + (ScopeKind::Histogram, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeYuv, WaveformType::Rgb, ParadeType::Rgb), + (ScopeKind::VectorscopeHls, WaveformType::Rgb, ParadeType::Rgb), + ] { + let t = std::time::Instant::now(); + for _ in 0..reps { + compute_into(k, &s, &Params { waveform: wt, parade: pt, ..p }, &mut c); + std::hint::black_box(&c); + } + println!("{k:?} {wt:?}/{pt:?}: {:.3} ms", t.elapsed().as_secs_f64() * 1000.0 / reps as f64); + } +} From 958ced53eb355e9236c7af292a7b306f8a0199c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 20:13:36 -0800 Subject: [PATCH 036/490] craft-testkit: an MCP message whose id is not a string, number or null is a protocol error A reply or request from the server with an id such as true, an array or an object was skipped as an unrelated reply, so the request waited for its deadline. It now returns a protocol error and closes the connection. --- crates/testkit/src/mcp.rs | 3 +++ crates/testkit/tests/mcp.rs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 400c072718..32b9d7bbf3 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -704,6 +704,9 @@ impl McpChild { /// Handles one message: answers a request from the child, keeps a notification, skips a reply /// to another id, and returns the reply to `waiting`. fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { + if v.get("id").is_some_and(|id| !matches!(id, Value::String(_) | Value::Number(_) | Value::Null)) { + return Err(self.fail(McpError::Protocol("a message has an `id` that is not a string, a number or null".into()))); + } match (v.get("method"), v.get("id")) { (Some(Value::String(method)), Some(id)) => { let reply = if method == "ping" { diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index d56b891cf9..7fae87f1fc 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -407,6 +407,22 @@ fn a_malformed_reply_is_a_protocol_error() { } } +#[test] +fn a_message_with_an_invalid_id_is_a_protocol_error() { + let replies = [ + json!({"jsonrpc": "2.0", "id": true, "result": 1}), + json!({"jsonrpc": "2.0", "id": [1], "result": 1}), + json!({"jsonrpc": "2.0", "id": {"n": 1}, "error": {"code": 1, "message": "m"}}), + json!({"jsonrpc": "2.0", "id": false, "method": "ping"}), + ]; + for msg in replies { + let mut c = fake(move |_, _| Some(vec![msg.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_tool_error_result_is_returned_unchanged() { let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); From 5f47a0abeac436803b2521a4c59a14d5e0921eb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 20:17:44 -0800 Subject: [PATCH 037/490] craft-testkit: a malformed MCP reply to another id is a protocol error A reply to an id the client is not waiting for was skipped without a look at its shape, so a reply with both or neither of `result` and `error`, or an error without an integer code and a string message, left the waiting request to run into its deadline. It is now a protocol error that closes the connection; a well-formed reply to another id is still skipped. --- crates/testkit/README.md | 2 +- crates/testkit/src/mcp.rs | 22 ++++++++++++++++++---- crates/testkit/tests/mcp.rs | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index ddce7e0a89..56bc12d7b2 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -215,7 +215,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The | Call | What it does | |---|---| | `initialize(version)` | Sends `initialize` with `version` (`mcp::PROTOCOL_VERSION` is `2025-06-18`), waits for the reply, then sends `notifications/initialized`. A reply with another version returns `UnsupportedVersion` and closes the connection. | -| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | +| `request(method, params)`, `request_within(.., timeout)` | Sends a request with a new numeric id and returns the `result` of the reply with that id. Well-formed replies with other ids are skipped. An error reply returns `Rpc` with its code, message and data, and the connection stays usable. | | `call_tool(name, args)`, `call_tool_within(.., timeout)` | Sends `tools/call` and returns the tool result unchanged, `content` and `isError` included. | | `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. | | `notify(method, params)` | Sends a notification, which has no id and gets no reply. | diff --git a/crates/testkit/src/mcp.rs b/crates/testkit/src/mcp.rs index 32b9d7bbf3..de13650cdc 100644 --- a/crates/testkit/src/mcp.rs +++ b/crates/testkit/src/mcp.rs @@ -298,6 +298,16 @@ fn read_line_capped(r: &mut impl BufRead, cap: usize) -> Result>, } } +/// Whether `v` holds exactly one of `result` and an `error` object with an integer `code` and a +/// string `message`. +fn is_reply(v: &Value) -> bool { + match (v.get("result"), v.get("error")) { + (Some(_), None) => true, + (None, Some(error)) => error.get("code").and_then(Value::as_i64).is_some() && error.get("message").is_some_and(Value::is_string), + _ => false, + } +} + /// Parses one stdout line as a JSON-RPC 2.0 message object. fn parse_line(line: &[u8]) -> Incoming { let preview = || String::from_utf8_lossy(&line[..line.len().min(PREVIEW)]).into_owned(); @@ -537,7 +547,7 @@ impl McpChild { /// /// While it waits, it answers the child's `ping` requests with an empty result and its other /// requests with error -32601, keeps notifications for [`McpChild::take_notifications`], and - /// skips replies with another id. None of these extend the deadline. + /// skips well-formed replies with another id. None of these extend the deadline. pub fn request_within(&mut self, method: &str, params: Value, timeout: Duration) -> Result { self.check_open()?; check_timeout("the request deadline", timeout)?; @@ -701,8 +711,8 @@ impl McpChild { })) } - /// Handles one message: answers a request from the child, keeps a notification, skips a reply - /// to another id, and returns the reply to `waiting`. + /// Handles one message: answers a request from the child, keeps a notification, skips a + /// well-formed reply to another id, and returns the reply to `waiting`. fn route(&mut self, v: Value, waiting: Option) -> Result, McpError> { if v.get("id").is_some_and(|id| !matches!(id, Value::String(_) | Value::Number(_) | Value::Null)) { return Err(self.fail(McpError::Protocol("a message has an `id` that is not a string, a number or null".into()))); @@ -727,7 +737,11 @@ impl McpChild { Ok(None) } (Some(_), _) => Err(self.fail(McpError::Protocol("a message has a `method` that is not a string".into()))), - (None, Some(id)) => Ok((waiting.is_some() && id.as_u64() == waiting).then_some(v)), + (None, Some(id)) if waiting.is_some() && id.as_u64() == waiting => Ok(Some(v)), + (None, Some(_)) if is_reply(&v) => Ok(None), + (None, Some(_)) => { + Err(self.fail(McpError::Protocol("a reply to another id does not hold exactly one of `result` and a valid `error`".into()))) + } (None, None) => Err(self.fail(McpError::Protocol("a message has neither `method` nor `id`".into()))), } } diff --git a/crates/testkit/tests/mcp.rs b/crates/testkit/tests/mcp.rs index 7fae87f1fc..408f9ece55 100644 --- a/crates/testkit/tests/mcp.rs +++ b/crates/testkit/tests/mcp.rs @@ -423,6 +423,21 @@ fn a_message_with_an_invalid_id_is_a_protocol_error() { } } +#[test] +fn a_malformed_reply_to_another_id_is_a_protocol_error() { + let replies = [ + json!({"jsonrpc": "2.0", "id": 9999, "result": 1, "error": {"code": 1, "message": "both"}}), + json!({"jsonrpc": "2.0", "id": "other"}), + json!({"jsonrpc": "2.0", "id": null, "error": {"code": "x", "message": "m"}}), + ]; + for msg in replies { + let mut c = fake(move |_, _| Some(vec![msg.to_string()])); + let err = c.request_within("x", json!({}), LONG).unwrap_err(); + assert!(matches!(err, McpError::Protocol(_)), "{err}"); + assert!(c.closed().is_some()); + } +} + #[test] fn a_tool_error_result_is_returned_unchanged() { let mut c = fake(|_, req| Some(vec![result(req, json!({"content": [{"type": "text", "text": "no document"}], "isError": true}))])); From c0845ba8d32436d6eed4ae8d41ac43ae56397214 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:38:39 -0800 Subject: [PATCH 038/490] craft-testkit: open corpus files without waiting on a named pipe Manifest::read and verify checked a path's type and then opened it. A path replaced by a named pipe between the two blocked the open until a writer appeared. On Unix both now open with O_NONBLOCK and check the opened file's type again. --- Cargo.lock | 1 + crates/testkit/Cargo.toml | 5 ++++- crates/testkit/README.md | 1 + crates/testkit/src/corpus.rs | 33 +++++++++++++++++++++++++++++++-- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 22e6ee881e..2b49aeac33 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3124,6 +3124,7 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ + "libc", "sha2 0.10.9", ] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 33bf1c9d9d..275e178e29 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,10 +10,13 @@ publish = false [features] # Pinned-corpus manifests and the `corpus::pinned` test gate (native only). -corpus = ["dep:sha2"] +corpus = ["dep:sha2", "dep:libc"] [dependencies] sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } +[target.'cfg(unix)'.dependencies] +libc = { version = "0.2", optional = true } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 107ed212d4..5aa907a7c0 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -215,6 +215,7 @@ A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 h - `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. - `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. - `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. - `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. `Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index fb0a4e4d91..85929938a2 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -158,7 +158,7 @@ impl Manifest { if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { return Err(ManifestError::NotAFile); } - let file = File::open(path).map_err(ManifestError::Io)?; + let file = open_for_reading(path).map_err(ManifestError::Io)?; if !file.metadata().map_err(ManifestError::Io)?.is_file() { return Err(ManifestError::NotAFile); } @@ -422,7 +422,7 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> if !kind.is_file() { return Err(VerifyError::NotAFile { path: path() }); } - let file = File::open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let file = open_for_reading(&target).map_err(|error| VerifyError::Read { path: path(), error })?; let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; if !meta.is_file() { return Err(VerifyError::NotAFile { path: path() }); @@ -452,6 +452,20 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Ok(()) } +/// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was +/// replaced by a named pipe after its type was checked opens at once instead of waiting for a +/// writer; the caller checks the opened file's type. Reads from a regular file are not affected. +fn open_for_reading(path: &Path) -> io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + options.open(path) +} + /// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file /// `manifest` lists has been checked with [`verify`]. /// @@ -749,6 +763,21 @@ mod tests { assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); } + /// Files are opened with `O_NONBLOCK`, read back from the open file's status flags in + /// `/proc/self/fdinfo`, so a path replaced by a named pipe after its type was checked opens at + /// once instead of waiting for a writer. + #[cfg(target_os = "linux")] + #[test] + fn files_are_opened_with_o_nonblock() { + use std::os::fd::AsRawFd; + let (scratch, _) = hello_corpus(); + let file = open_for_reading(&scratch.0.join("hello.txt")).expect("open"); + let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", file.as_raw_fd())).expect("read fdinfo"); + let flags = info.lines().find_map(|line| line.strip_prefix("flags:")).map(str::trim).expect("flags line"); + let flags = i32::from_str_radix(flags, 8).expect("octal flags"); + assert_ne!(flags & libc::O_NONBLOCK, 0, "flags {flags:o}"); + } + #[test] fn file_size_limit_is_error() { let (scratch, manifest) = hello_corpus(); From aea1ee6860149b23f1b3adb81d7d8e04c6a88921 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:50:31 -0800 Subject: [PATCH 039/490] craft-testkit: refuse corpus files opened outside the folder and control characters in paths On Unix, verify checks after the open that the opened file is inside the corpus folder: by the path the kernel reports for the open file on Linux, Android and Apple platforms, otherwise by resolving the path again and comparing device and inode. Manifest paths that hold a control character are refused. --- Cargo.lock | 1 + crates/testkit/Cargo.toml | 5 +- crates/testkit/README.md | 4 +- crates/testkit/src/corpus.rs | 113 +++++++++++++++++++++++++++++++++-- 4 files changed, 114 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2b49aeac33..a6e198f5ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3125,6 +3125,7 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "rustix 1.1.5", "sha2 0.10.9", ] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 275e178e29..32085ff235 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,7 +10,7 @@ publish = false [features] # Pinned-corpus manifests and the `corpus::pinned` test gate (native only). -corpus = ["dep:sha2", "dep:libc"] +corpus = ["dep:sha2", "dep:libc", "dep:rustix"] [dependencies] sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } @@ -18,5 +18,8 @@ sha2 = { version = "0.10", default-features = false, features = ["std"], optiona [target.'cfg(unix)'.dependencies] libc = { version = "0.2", optional = true } +[target.'cfg(target_vendor = "apple")'.dependencies] +rustix = { version = "1.1", default-features = false, features = ["std", "fs"], optional = true } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 5aa907a7c0..aa72b1daec 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -212,10 +212,10 @@ Changes from `craft-media-testkit`'s `hammer`: A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. -- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. - `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. - `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. -- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or when that path cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again. - `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. `Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index 85929938a2..f40c6dc4f7 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -200,13 +200,13 @@ fn parse_digest(text: &str) -> Option<[u8; 32]> { } /// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none -/// empty, `.` or `..`, and no `\`, `:` or NUL anywhere, so the same row means the same file on -/// every platform. +/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so the same +/// row means the same file on every platform. fn check_path(path: &str) -> Result<(), PathError> { if path.is_empty() { return Err(PathError::Empty); } - if path.contains(['\\', ':', '\0']) { + if path.contains(['\\', ':']) || path.chars().any(char::is_control) { return Err(PathError::Character); } for part in path.split('/') { @@ -230,7 +230,7 @@ pub enum PathError { EmptyPart, /// The path has a `.` or `..` part. DotPart, - /// The path holds a `\`, a `:` or a NUL character. + /// The path holds a `\`, a `:` or a control character. Character, } @@ -241,7 +241,7 @@ impl fmt::Display for PathError { Self::Absolute => "the path is absolute", Self::EmptyPart => "the path has an empty part", Self::DotPart => "the path has a . or .. part", - Self::Character => "the path holds a \\, a : or a NUL character", + Self::Character => "the path holds a \\, a : or a control character", }) } } @@ -413,6 +413,17 @@ pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> R } fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + verify_entry_with(root, entry, limits, buf, open_for_reading) +} + +/// [`verify_entry`] with the function that opens the resolved path; tests change the path in it. +fn verify_entry_with( + root: &Path, + entry: &Entry, + limits: &Limits, + buf: &mut [u8], + open: impl FnOnce(&Path) -> io::Result, +) -> Result<(), VerifyError> { let path = || entry.path.clone(); let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; if !target.starts_with(root) { @@ -422,11 +433,13 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> if !kind.is_file() { return Err(VerifyError::NotAFile { path: path() }); } - let file = open_for_reading(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let file = open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; if !meta.is_file() { return Err(VerifyError::NotAFile { path: path() }); } + #[cfg(unix)] + opened_file_is_inside(root, entry, &file, &meta)?; if meta.len() > limits.max_file_bytes { return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); } @@ -452,6 +465,49 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Ok(()) } +/// Checks, after the open, that the opened file is inside `root`, so a path changed into a link out +/// of the folder between the first check and the open is refused. On Linux, Android and Apple +/// platforms the kernel reports the open file's path, which must start with `root`. On other Unix +/// systems, and where that path cannot be read, the entry's path is resolved again and must lead, without a link in its last part, to the +/// opened file (the same device and inode). +#[cfg(unix)] +fn opened_file_is_inside(root: &Path, entry: &Entry, file: &File, opened: &std::fs::Metadata) -> Result<(), VerifyError> { + use std::os::unix::fs::MetadataExt; + let path = || entry.path.clone(); + if let Some(actual) = opened_path(file).map_err(|error| VerifyError::Read { path: path(), error })? { + return if actual.starts_with(root) { Ok(()) } else { Err(VerifyError::Escapes { path: path() }) }; + } + let again = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + let now = std::fs::symlink_metadata(&again).map_err(|error| VerifyError::Read { path: path(), error })?; + if !again.starts_with(root) || (now.dev(), now.ino()) != (opened.dev(), opened.ino()) { + return Err(VerifyError::Escapes { path: path() }); + } + Ok(()) +} + +/// The path of the file `file` has open, as the kernel reports it in `/proc/self/fd`, or `None` +/// when that cannot be read (for example without a mounted `/proc`). +#[cfg(any(target_os = "linux", target_os = "android"))] +#[allow(clippy::unnecessary_wraps)] +fn opened_path(file: &File) -> io::Result> { + use std::os::fd::AsRawFd; + Ok(std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()) +} + +/// The path of the file `file` has open, as the kernel reports it. +#[cfg(target_vendor = "apple")] +fn opened_path(file: &File) -> io::Result> { + use std::os::unix::ffi::OsStringExt; + let path = rustix::fs::getpath(file)?; + Ok(Some(PathBuf::from(OsString::from_vec(path.into_bytes())))) +} + +/// `None`: the platform does not report the path of an open file. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +fn opened_path(_file: &File) -> io::Result> { + Ok(None) +} + /// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was /// replaced by a named pipe after its type was checked opens at once instead of waiting for a /// writer; the caller checks the opened file's type. Reads from a regular file are not affected. @@ -661,6 +717,9 @@ mod tests { ("C:a", PathError::Character), ("\\\\server\\share\\a", PathError::Character), ("a\\..\\..\\b", PathError::Character), + ("a\u{1}b", PathError::Character), + ("a\u{7f}b", PathError::Character), + ("a\u{85}b", PathError::Character), ]; for (path, expected) in cases { match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { @@ -819,6 +878,48 @@ mod tests { assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); } + /// A file opened outside the folder, as after the listed path was changed into a link between + /// the first check and the open, is refused even when its contents match. + #[cfg(unix)] + #[test] + fn a_file_opened_outside_the_folder_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let entry = &manifest.entries[0]; + let opened = File::open(&other).expect("open the outside file"); + let meta = opened.metadata().expect("metadata"); + match opened_file_is_inside(&root, entry, &opened, &meta) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + let listed = File::open(root.join("hello.txt")).expect("open the listed file"); + let meta = listed.metadata().expect("metadata"); + opened_file_is_inside(&root, entry, &listed, &meta).expect("the listed file passes"); + } + + /// `verify` refuses a listed file that is changed into a link out of the folder after it was + /// resolved and before it is opened, even when the outside file's contents match. + #[cfg(unix)] + #[test] + fn a_file_changed_into_an_outside_link_before_the_open_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let mut buf = vec![0u8; CHUNK]; + let swap = |path: &Path| { + std::fs::remove_file(path)?; + std::os::unix::fs::symlink(&other, path)?; + open_for_reading(path) + }; + match verify_entry_with(&root, &manifest.entries[0], &Limits::default(), &mut buf, swap) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + #[test] fn the_gate_skips_only_an_optional_unset_corpus() { let (scratch, _) = hello_corpus(); From ee98081611f957ef59fd8d647344611c0892475f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 23:39:28 -0800 Subject: [PATCH 040/490] craft-scopes: peaks skip oversized scopes and data past the plane summary::peaks now returns no peaks for a vectorscope larger than MAX_VECTOR_SIZE, as summary::coarse does, and reads only the first size * size entries of the data, so a trailing entry is not reported as a cell outside the grid. --- crates/scopes/src/summary.rs | 10 ++++++++-- crates/scopes/src/tests.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/scopes/src/summary.rs b/crates/scopes/src/summary.rs index 8d6f8efa12..a8c73d00a4 100644 --- a/crates/scopes/src/summary.rs +++ b/crates/scopes/src/summary.rs @@ -137,11 +137,17 @@ pub struct Peak { pub share: f64, } -/// The `n` densest cells holding at least `min_share` of the samples, densest first. +/// The `n` densest cells holding at least `min_share` of the samples, densest first. A vectorscope +/// larger than [`MAX_VECTOR_SIZE`] gives no peaks. pub fn peaks(v: &Vectorscope, n: usize, min_share: f32) -> Vec { + if v.size > MAX_VECTOR_SIZE { + return Vec::new(); + } let total = v.samples.max(1) as f32; let size = v.size.max(1); - let mut cells: Vec<(u32, usize)> = v.data.iter().enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| (*c, i)).collect(); + // entries past the size² plane are not cells + let plane = v.size * v.size; + let mut cells: Vec<(u32, usize)> = v.data.iter().take(plane).enumerate().filter(|(_, c)| **c > 0).map(|(i, c)| (*c, i)).collect(); cells.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); cells .into_iter() diff --git a/crates/scopes/src/tests.rs b/crates/scopes/src/tests.rs index 8abebb8d02..747ceaa5e8 100644 --- a/crates/scopes/src/tests.rs +++ b/crates/scopes/src/tests.rs @@ -559,6 +559,15 @@ fn hand_built_values_past_the_caps_paint_nothing() { assert_eq!(paint::vectorscope_into(&v, [1.0; 3], 1.0, true, &mut scratch, &mut out), (0, 0)); assert!(out.is_empty()); assert!(summary::coarse(&v, usize::MAX).is_empty()); + let big = Vectorscope { size: MAX_VECTOR_SIZE + 1, data: vec![1; 4], samples: 4, ..Vectorscope::default() }; + assert!(summary::peaks(&big, 5, 0.0).is_empty()); + assert!(summary::coarse(&big, 4).is_empty()); + // entries past the size² plane are not cells + let mut data = vec![0; 10]; + data[9] = 5; + let trailing = Vectorscope { size: 3, extent: VECTOR_EXTENT, data, samples: 5, ..Vectorscope::default() }; + assert!(summary::peaks(&trailing, 5, 0.0).is_empty()); + assert!(summary::coarse(&trailing, 3).is_empty()); let g = Grid { name: "Y", cols: usize::MAX, rows: usize::MAX, data: Vec::new() }; out.push(1); assert_eq!(paint::grids_into(&[(&g, [1.0; 3])], 1.0, 1.0, &mut scratch, &mut out), (0, 0)); From a7d402ff95e79d08ec499834bd054c4e57cb3c66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:34:35 -0800 Subject: [PATCH 041/490] craft-gpu-device: choose and open a wgpu device Adds the adapter preference (Auto, low power, a named adapter, software) with a key that survives a reordered adapter list and a driver update, wgpu's adapter rule with corrections for drivers that crash, a ranked fallback order ending in a software adapter, a capability report, and device health that records a loss or an uncaptured error without a lock. --- ATTRIBUTION.md | 4 + Cargo.lock | 11 + Cargo.toml | 1 + README.md | 5 + crates/gpu-device/Cargo.toml | 29 ++ crates/gpu-device/NOTICE | 10 + crates/gpu-device/README.md | 55 +++ crates/gpu-device/src/adapter.rs | 581 ++++++++++++++++++++++++++++ crates/gpu-device/src/caps.rs | 203 ++++++++++ crates/gpu-device/src/health.rs | 488 +++++++++++++++++++++++ crates/gpu-device/src/lib.rs | 35 ++ crates/gpu-device/src/open.rs | 304 +++++++++++++++ crates/gpu-device/src/preference.rs | 404 +++++++++++++++++++ crates/gpu-device/src/recovery.rs | 153 ++++++++ 14 files changed, 2283 insertions(+) create mode 100644 crates/gpu-device/Cargo.toml create mode 100644 crates/gpu-device/NOTICE create mode 100644 crates/gpu-device/README.md create mode 100644 crates/gpu-device/src/adapter.rs create mode 100644 crates/gpu-device/src/caps.rs create mode 100644 crates/gpu-device/src/health.rs create mode 100644 crates/gpu-device/src/lib.rs create mode 100644 crates/gpu-device/src/open.rs create mode 100644 crates/gpu-device/src/preference.rs create mode 100644 crates/gpu-device/src/recovery.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f772eede22..f2c076c222 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -141,3 +141,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `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` comes from StudioCraft `crates/craft-gpu-device` at `17e2120f7d79bb677e2871a4192ba1ced1dab57a` (MIT OR Apache-2.0). Its 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. diff --git a/Cargo.lock b/Cargo.lock index da06541564..652fbd1743 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2106,6 +2106,17 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8cd94409b..48cc474b46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } diff --git a/README.md b/README.md index e21de2e1a3..f6d3e55763 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,11 @@ 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-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. diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml new file mode 100644 index 0000000000..a2561dc3a8 --- /dev/null +++ b/crates/gpu-device/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "craft-gpu-device" +description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing `Preference` and `AdapterKey` with serde. +serde = ["dep:serde"] + +[dependencies] +wgpu = "30" +log = { workspace = true } +serde = { workspace = true, optional = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = "0.4" + +[dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { version = "30", features = ["noop"] } +serde_json = { workspace = true } diff --git a/crates/gpu-device/NOTICE b/crates/gpu-device/NOTICE new file mode 100644 index 0000000000..e7ca2f2c92 --- /dev/null +++ b/crates/gpu-device/NOTICE @@ -0,0 +1,10 @@ +craft-gpu-device +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's +`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit +93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and +the FilmCraft contributors. +Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs` +(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md new file mode 100644 index 0000000000..ee05ec009b --- /dev/null +++ b/crates/gpu-device/README.md @@ -0,0 +1,55 @@ +# craft-gpu-device + +Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for +drivers that crash, a software fallback, a capability report, and device health with recovery +after a device loss. The crate depends on `wgpu` 30, `pollster` and `log`, with `serde` as an +optional feature (on by default). It depends on no app crate. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface | +| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s | +| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply | +| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) | +| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` | +| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids | +| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | +| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | +| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector` | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | +| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | +| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | + +## Failure cases + +- With no usable adapter, `select` returns `None` and `open` returns `OpenError::NoAdapter`. +- An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a + `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists + each failure. +- A named adapter that is no longer listed, or can no longer draw to the surface, gives the + automatic choice and `Notice::AdapterMissing`. +- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older + version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 + GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's + fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their + names. When a + driver reports no bus id, a second GPU of the same model on the same driver looks like an + older version, and is used through its other backend (DirectX 12 on Windows, OpenGL + elsewhere). +- Only an error that says the device is lost counts as a loss. An error about a destroyed buffer + or texture is recorded as an error. +- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that + `Device::poll` raises on a lost device and record the loss. + +## Tests + +The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop +backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares +`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter +is listed. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs new file mode 100644 index 0000000000..c0d1b5c8ff --- /dev/null +++ b/crates/gpu-device/src/adapter.rs @@ -0,0 +1,581 @@ +//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash. +//! +//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC +//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated +//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current +//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu +//! takes the first entry of the device type it prefers, which is whichever version the loader +//! listed first; a window drawn through the stale one ends the process inside the driver +//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs. +//! +//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the +//! surface, by device type for the power preference, then as enumerated) with one addition: when +//! the adapter that rule picks is listed again by the same driver, the entry exposing the most +//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own. +//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are +//! left alone, and wgpu's order between them stays. +//! +//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan +//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with +//! 0xc0000005 when the device is created, after the adapters are listed. + +use std::cmp::Reverse; +use std::fmt; + +use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface}; + +/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure +/// functions that tests run without a GPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + /// PCI vendor and device ids; both zero when the backend reports none (OpenGL). + pub vendor: u32, + pub device: u32, + /// PCI bus id such as `0000:03:00.0`; empty when the driver reports none. + pub pci_bus_id: String, + /// The driver's name (Vulkan) or version (DirectX 12). + pub driver: String, + /// More about the driver, for the log. + pub driver_info: String, + /// How many wgpu features the driver exposes; a newer version of one driver exposes more. + pub features: u32, + /// Whether the surface can be drawn through this adapter (true without a surface). + pub usable: bool, +} + +impl Candidate { + pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self { + let info = adapter.get_info(); + Candidate { + name: info.name, + backend: info.backend, + device_type: info.device_type, + vendor: info.vendor, + device: info.device, + pci_bus_id: info.device_pci_bus_id, + driver: info.driver, + driver_info: info.driver_info, + features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(), + usable: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader). + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + } +} + +impl fmt::Display for Candidate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.device_type { + DeviceType::DiscreteGpu => "discrete GPU", + DeviceType::IntegratedGpu => "integrated GPU", + DeviceType::VirtualGpu => "virtual GPU", + DeviceType::Cpu => "software", + DeviceType::Other => "unknown type", + }; + let driver = format!("{} {}", self.driver, self.driver_info); + write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?; + if !self.pci_bus_id.is_empty() { + write!(f, ", bus {}", self.pci_bus_id)?; + } + if !self.usable { + write!(f, ", cannot draw to the window")?; + } + write!(f, ")") + } +} + +/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of +/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id +/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two +/// of them cannot be told apart. +pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool { + let identified = a.vendor != 0 || a.device != 0; + let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id; + identified + && a.backend == b.backend + && a.device_type == b.device_type + && a.vendor == b.vendor + && a.device == b.device + && a.driver == b.driver + && same_bus +} + +/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first. +/// Without a preference the adapters stay as enumerated. +pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 { + let prefer_integrated = match power { + PowerPreference::LowPower => true, + PowerPreference::HighPerformance => false, + PowerPreference::None => return 0, + }; + match device_type { + DeviceType::DiscreteGpu if prefer_integrated => 2, + DeviceType::IntegratedGpu if prefer_integrated => 1, + DeviceType::DiscreteGpu => 1, + DeviceType::IntegratedGpu => 2, + DeviceType::Other => 3, + DeviceType::VirtualGpu => 4, + DeviceType::Cpu => 5, + } +} + +/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best +/// device type for `power`. `None` without a usable adapter. +pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option { + let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable); + usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index) +} + +/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on +/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's +/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices +/// dropped at the same time can then deadlock in that driver. +pub fn native_instance() -> wgpu::Instance { + wgpu::Instance::new(native_descriptor()) +} + +/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend +/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no +/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`, +/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever +/// `WGPU_BACKEND` says. +/// +/// The descriptor has no display handle, which a headless instance does not need. OpenGL on +/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`, +/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe +/// fills in the window's display handle. +pub fn native_descriptor() -> wgpu::InstanceDescriptor { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + desc.flags = desc.flags.with_env(); + desc.backend_options = desc.backend_options.with_env(); + desc +} + +/// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the +/// most features among those that are the same GPU listed by the same driver (the first of them +/// when several expose as many). For an Intel Gen 9 to Gen 11 GPU on Intel's Windows Vulkan +/// driver it is the same GPU's DirectX 12 entry, or without one the best other usable adapter. +/// `None` without a usable adapter, and when that Intel Vulkan entry is the only one. +pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { + let first = wgpu_choice(candidates, power)?; + let preferred = candidates.get(first)?; + let index = corrected(candidates, first, preferred); + if candidates.get(index).is_some_and(intel_vulkan_crashes) { + // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. + let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); + let (other, c) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(corrected(candidates, other, c)); + } + Some(index) +} + +/// `index` (the entry `preferred`), or the entry to draw with instead of it. +pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { + if let Some(dx12) = dx12_instead(candidates, preferred) { + return dx12; + } + let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c)); + versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index) +} + +/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one +/// GPU twice. Creating a device or drawing through either can end the process, so it is never +/// tried as a fallback either. A second GPU of the same model on the same driver, when the +/// driver reports no bus id for either, looks like an older version; it is still listed through +/// the other backends (DirectX 12 on Windows, OpenGL elsewhere). +pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool { + let Some(c) = candidates.get(index) else { + return true; + }; + intel_vulkan_crashes(c) || corrected(candidates, index, c) != index +} + +/// PCI vendor id of Intel. +pub(crate) const INTEL: u32 = 0x8086; + +/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and +/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby +/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake), +/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those +/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares. +/// +/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is +/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy +/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs. +pub fn intel_gen9_to_gen11(device: u32) -> bool { + matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84 +} + +/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan +/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a +/// driver name with "Mesa" in it and is not included. +pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool { + c.backend == Backend::Vulkan + && c.device_type == DeviceType::IntegratedGpu + && c.vendor == INTEL + && intel_gen9_to_gen11(c.device) + && !c.driver.to_ascii_lowercase().contains("mesa") +} + +/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the +/// index of the same GPU's usable DirectX 12 entry, if there is one. +fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option { + if !intel_vulkan_crashes(preferred) { + return None; + } + candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device) +} + +/// Write the adapters and the choice to the log, with a warning when a correction applied. +pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) { + for candidate in candidates { + log::info!("graphics adapter available: {candidate}"); + } + let Some(chosen) = candidates.get(index) else { + return; + }; + let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count(); + if others > 0 { + log::warn!( + "{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.", + chosen.backend, + chosen.name, + others.saturating_add(1) + ); + } + if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i)) + && wgpu_own.backend == Backend::Vulkan + && chosen.backend == Backend::Dx12 + && wgpu_own.vendor == INTEL + && wgpu_own.device == chosen.device + { + log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name); + } + log::info!("graphics adapter chosen: {chosen}"); +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use wgpu::Backend::{Dx12, Gl, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other}; + use wgpu::PowerPreference::{HighPerformance, LowPower}; + + pub(crate) const AMD: u32 = 0x1002; + pub(crate) const RX_6800M: u32 = 0x73df; + pub(crate) const RADEON_IGPU: u32 = 0x1638; + const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance]; + + #[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")] + pub(crate) fn gpu( + name: &str, + backend: Backend, + device_type: DeviceType, + vendor: u32, + device: u32, + bus: &str, + driver: &str, + driver_info: &str, + features: u32, + ) -> Candidate { + Candidate { + name: name.into(), + backend, + device_type, + vendor, + device, + pci_bus_id: bus.into(), + driver: driver.into(), + driver_info: driver_info.into(), + features, + usable: true, + } + } + + /// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one, + /// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one + /// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll` + /// (0xc0000005) on every launch. + pub(crate) fn two_amd_drivers() -> Vec { + let amd = "AMD proprietary driver"; + vec![ + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60), + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68), + gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56), + gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36), + gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36), + ] + } + + #[test] + fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() { + let adapters = two_amd_drivers(); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed"); + assert_eq!(choose(&adapters, power), Some(1)); + } + // whichever version the loader lists first + let mut newer_first = adapters.clone(); + newer_first.swap(0, 1); + assert_eq!(choose(&newer_first, HighPerformance), Some(0)); + // two entries exposing as much: wgpu's, the first + let mut equal = adapters.clone(); + if let Some(c) = equal.get_mut(1) { + c.features = 60; + } + assert_eq!(choose(&equal, HighPerformance), Some(0)); + // three versions: the one exposing the most + let mut three = adapters.clone(); + three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64)); + assert_eq!(choose(&three, HighPerformance), Some(2)); + // the stale entries are avoided, the newest is not + assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); + } + + #[test] + fn a_newer_version_never_overtakes_another_gpu_or_backend() { + assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); + let mut dx12_first = two_amd_drivers(); + dx12_first.rotate_left(3); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(choose(&dx12_first, power), Some(0)); + } + assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower)); + } + + #[test] + fn without_two_versions_of_one_driver_the_choice_is_wgpus() { + let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features); + let intel = + |backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features); + let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features); + let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features); + let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::>(); + let listings: Vec> = vec![ + vec![], + vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // a laptop with two GPUs, through Vulkan and DirectX 12 + vec![ + intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60), + nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70), + nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36), + intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36), + ], + // one GPU through two different drivers: Linux with AMDVLK and RADV + vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)], + // a vendor's driver and Dozen (Vulkan on DirectX 12) + vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // two cards of one model, on their own buses + vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)], + // OpenGL reports no ids: two adapters cannot be told apart + vec![gl("ANGLE", 20), gl("ANGLE", 30)], + vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)], + without(0), + without(1), + ]; + for adapters in &listings { + for power in POWERS { + assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}"); + } + } + assert_eq!(choose(&[], HighPerformance), None); + } + + /// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A + /// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created. + pub(crate) fn uhd_630() -> Vec { + vec![ + gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44), + gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36), + ] + } + + fn uhd_630_as(name: &str, device: u32) -> Vec { + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect() + } + + #[test] + fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() { + for power in POWERS { + assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed"); + assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}"); + } + for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] { + assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}"); + } + let mut dx12_first = uhd_630(); + dx12_first.swap(0, 1); + assert_eq!(choose(&dx12_first, HighPerformance), Some(0)); + // without a usable DirectX 12 entry, the Vulkan entry is still never drawn with + let vulkan_only: Vec = uhd_630().into_iter().take(1).collect(); + assert_eq!(choose(&vulkan_only, HighPerformance), None); + assert!(avoided(&vulkan_only, 0)); + let mut dx12_unusable = uhd_630(); + if let Some(c) = dx12_unusable.get_mut(1) { + c.usable = false; + } + assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter"); + // Mesa's Vulkan driver for the same GPU on Linux is drawn with + let mesa = vec![gpu( + "Intel(R) UHD Graphics 630 (CFL GT2)", + Vulkan, + IntegratedGpu, + INTEL, + 0x3e91, + "0000:00:02.0", + "Intel open-source Mesa driver", + "Mesa 25.2.4", + 44, + )]; + assert_eq!(choose(&mesa, HighPerformance), Some(0)); + assert!(!avoided(&mesa, 0)); + // beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry + let mut laptop = uhd_630(); + laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70)); + assert_eq!(choose(&laptop, HighPerformance), Some(1)); + assert_eq!(choose(&laptop, LowPower), Some(2)); + assert!(avoided(&laptop, 0)); + } + + #[test] + fn later_intel_gpus_keep_wgpus_choice() { + for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)] + { + let adapters = uhd_630_as(name, device); + for power in POWERS { + assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}"); + } + } + let discrete: Vec = + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect(); + assert_eq!(choose(&discrete, HighPerformance), Some(0)); + } + + #[test] + fn gen9_to_gen11_ids() { + for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] { + assert!(intel_gen9_to_gen11(id), "{id:#06x}"); + } + for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] { + assert!(!intel_gen9_to_gen11(id), "{id:#06x}"); + } + } + + #[test] + fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() { + let stale = two_amd_drivers().swap_remove(0); + let newer = two_amd_drivers().swap_remove(1); + assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale)); + let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() }; + assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0"))); + assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0"))); + assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0"))); + for other in [ + Candidate { backend: Dx12, ..newer.clone() }, + Candidate { device_type: IntegratedGpu, ..newer.clone() }, + Candidate { vendor: 0x10de, ..newer.clone() }, + Candidate { device: RADEON_IGPU, ..newer.clone() }, + Candidate { driver: "radv".into(), ..newer.clone() }, + ] { + assert!(!same_gpu_and_driver(&stale, &other), "{other}"); + } + let unidentified = Candidate { vendor: 0, device: 0, ..newer }; + assert!(!same_gpu_and_driver(&unidentified, &unidentified)); + } + + #[test] + fn adapters_that_cannot_draw_to_the_window_are_left_out() { + let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| { + let mut adapters = two_amd_drivers(); + for (i, c) in adapters.iter_mut().enumerate() { + c.usable = !which(i, c); + } + adapters + }; + assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0)); + assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1)); + assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3)); + assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None); + } + + #[test] + fn candidates_describe_themselves_for_the_log() { + let adapters = two_amd_drivers(); + let text = adapters.get(1).map(ToString::to_string).unwrap_or_default(); + assert_eq!( + text, + "\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)" + ); + let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default(); + assert_eq!( + offscreen, + "\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)" + ); + assert!(adapters.get(5).is_some_and(Candidate::is_software)); + assert!(!adapters.first().is_some_and(Candidate::is_software)); + } + + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` + /// says. Runs in a child process, which has them set. + #[test] + fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() { + const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "gl") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = native_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + assert_eq!(desc.backends, backends); + } + + /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's + /// `request_adapter` returns, and [`choose`] returns that adapter too, a version of it exposing + /// more features, or for an Intel Gen 9 to Gen 11 GPU its DirectX 12 entry. Passes without + /// adapters. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { + let backends = wgpu::Backends::PRIMARY; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() }); + let adapters = pollster::block_on(instance.enumerate_adapters(backends)); + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, None)).collect(); + for power in POWERS { + let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; + let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); + assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); + let picked = choose(&candidates, power).and_then(|i| candidates.get(i)); + match (&wgpu_own, picked) { + (Some(wgpu_own), Some(picked)) if wgpu_own != picked => { + let newer_version = same_gpu_and_driver(wgpu_own, picked) && picked.features > wgpu_own.features; + let intel_dx12 = wgpu_own.vendor == INTEL + && intel_gen9_to_gen11(wgpu_own.device) + && picked.backend == Backend::Dx12 + && picked.device == wgpu_own.device; + assert!(newer_version || intel_dx12, "{power:?}: {picked} instead of {wgpu_own}"); + } + _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), + } + } + } +} diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs new file mode 100644 index 0000000000..e0841a0293 --- /dev/null +++ b/crates/gpu-device/src/caps.rs @@ -0,0 +1,203 @@ +//! What an adapter can do, for choosing a pipeline and for the settings and the log. + +use std::fmt; + +use wgpu::{AdapterInfo, Backend, DeviceType, Features, Limits}; + +/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers +/// report instead). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Vendor { + Nvidia, + Amd, + Intel, + Apple, + Qualcomm, + Arm, + ImgTec, + /// Microsoft's software adapter (WARP) and its virtual GPUs. + Microsoft, + /// Mesa's software drivers (llvmpipe, lavapipe). + Mesa, + /// Another id, or none (0). + Other(u32), +} + +impl Vendor { + pub fn from_id(id: u32) -> Vendor { + match id { + 0x10de => Vendor::Nvidia, + 0x1002 | 0x1022 => Vendor::Amd, + 0x8086 => Vendor::Intel, + 0x106b => Vendor::Apple, + 0x5143 => Vendor::Qualcomm, + 0x13b5 => Vendor::Arm, + 0x1010 => Vendor::ImgTec, + 0x1414 => Vendor::Microsoft, + 0x10005 => Vendor::Mesa, + other => Vendor::Other(other), + } + } +} + +impl fmt::Display for Vendor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Vendor::Nvidia => "NVIDIA", + Vendor::Amd => "AMD", + Vendor::Intel => "Intel", + Vendor::Apple => "Apple", + Vendor::Qualcomm => "Qualcomm", + Vendor::Arm => "Arm", + Vendor::ImgTec => "Imagination", + Vendor::Microsoft => "Microsoft", + Vendor::Mesa => "Mesa", + Vendor::Other(0) => return f.write_str("unknown vendor"), + Vendor::Other(id) => return write!(f, "vendor {id:#06x}"), + }; + f.write_str(name) + } +} + +/// What an adapter reports it can do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + pub vendor: Vendor, + /// The adapter draws on the CPU. + pub software: bool, + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub nv12: bool, + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub p010: bool, + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub norm16: bool, + /// `f16` in shaders. + pub shader_f16: bool, + /// Timestamp queries, for measuring GPU time per pass. + pub timestamps: bool, + /// The widest and tallest 2D texture. + pub max_texture_2d: u32, + /// The largest buffer, in bytes. + pub max_buffer_size: u64, +} + +impl Capabilities { + /// From an adapter's (or a device's) info, features and limits. + pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { + Capabilities { + name: info.name.clone(), + backend: info.backend, + device_type: info.device_type, + vendor: Vendor::from_id(info.vendor), + software: info.device_type == DeviceType::Cpu, + nv12: features.contains(Features::TEXTURE_FORMAT_NV12), + p010: features.contains(Features::TEXTURE_FORMAT_P010), + norm16: features.contains(Features::TEXTURE_FORMAT_16BIT_NORM), + shader_f16: features.contains(Features::SHADER_F16), + timestamps: features.contains(Features::TIMESTAMP_QUERY), + max_texture_2d: limits.max_texture_dimension_2d, + max_buffer_size: limits.max_buffer_size, + } + } + + /// What `adapter` can do. + pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { + Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) + } + + /// What a device opened on `adapter` can do: the features and limits it was opened with. + pub fn of_device(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Self { + Self::from_parts(&adapter.get_info(), device.features(), &device.limits()) + } + + /// Whether a `width` × `height` texture fits. + pub fn fits(&self, width: u32, height: u32) -> bool { + width > 0 && height > 0 && width <= self.max_texture_2d && height <= self.max_texture_2d + } + + /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be + /// sampled. + pub fn ten_bit(&self) -> bool { + self.norm16 + } + + /// The features from `wanted` this adapter has, to ask for when opening a device. + pub fn available(adapter_features: Features, wanted: Features) -> Features { + adapter_features & wanted + } +} + +impl fmt::Display for Capabilities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({}, {:?}", self.name, self.vendor, self.backend)?; + if self.software { + f.write_str(", software")?; + } + let flags = + [(self.nv12, "NV12"), (self.p010, "P010"), (self.norm16, "16-bit norm"), (self.shader_f16, "f16"), (self.timestamps, "timestamps")]; + for (on, name) in flags { + if on { + write!(f, ", {name}")?; + } + } + write!(f, ", textures up to {} px)", self.max_texture_2d) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { + AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) } + } + + #[test] + fn vendors_from_pci_and_khronos_ids() { + assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia); + assert_eq!(Vendor::from_id(0x1002), Vendor::Amd); + assert_eq!(Vendor::from_id(0x8086), Vendor::Intel); + assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa); + assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft); + assert_eq!(Vendor::from_id(0), Vendor::Other(0)); + assert_eq!(Vendor::Other(0).to_string(), "unknown vendor"); + assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234"); + } + + #[test] + fn features_and_limits_become_capabilities() { + let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; + let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; + let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert!(c.nv12 && !c.p010 && c.norm16 && c.timestamps && !c.shader_f16 && !c.software); + assert!(c.ten_bit()); + assert_eq!(c.vendor, Vendor::Nvidia); + assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); + assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); + assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); + } + + #[test] + fn a_software_adapter_without_extras() { + let limits = Limits::downlevel_defaults(); + let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); + assert!(c.software && !c.ten_bit() && !c.nv12); + // P010 alone is sampled, not drawn to + let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); + assert!(p010.p010 && !p010.ten_bit()); + assert_eq!(c.max_texture_2d, 2048); + assert!(!c.fits(3840, 2160)); + assert!(c.to_string().contains("software")); + let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; + assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); + } +} diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs new file mode 100644 index 0000000000..a113ee783c --- /dev/null +++ b/crates/gpu-device/src/health.rs @@ -0,0 +1,488 @@ +//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing +//! GPU work and reopen a device or fall back, instead of panicking. +//! +//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device +//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the +//! fault and registers the device-lost callback, and the polls here run only while the device is +//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks +//! [`DeviceHealth::fault`] first. +//! +//! Builds for the web too: the callbacks only touch atomics and a mutex. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +/// Outcome of a bounded wait for submitted GPU work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaitOutcome { + /// The submitted work finished before the deadline. + Finished, + /// The deadline passed (or the device faulted) before the work finished. + TimedOut, + /// The caller canceled the wait before the work finished. + Canceled, +} + +/// Why the GPU cannot be used any more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// The device was lost (driver reset, the OS ended a submission, `Device::destroy`). + Lost(String), + /// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be + /// trusted, and on most drivers the device is about to be lost anyway. + Error(String), +} + +impl Fault { + /// Whether the device itself was lost (rather than an error reported). + pub fn is_lost(&self) -> bool { + matches!(self, Fault::Lost(_)) + } + + /// An out-of-memory error on a device that still works: freeing memory and trying again can + /// succeed, unlike after a loss or a validation error. Only wgpu's own out-of-memory error is + /// recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory is not + /// one. + pub fn is_out_of_memory(&self) -> bool { + matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) + } + + /// The driver's or wgpu's message. + pub fn detail(&self) -> &str { + match self { + Fault::Lost(s) | Fault::Error(s) => s, + } + } +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"), + Fault::Lost(s) => write!(f, "GPU device lost: {s}"), + Fault::Error(s) => write!(f, "GPU error: {s}"), + } + } +} + +/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). +pub const OUT_OF_MEMORY: &str = "Out of Memory"; + +/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each +/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set` +/// of the same slot waits only for that one store. +#[derive(Default)] +struct Inner { + faulted: AtomicBool, + /// The first device loss. + lost: OnceLock, + /// An out-of-memory error was seen. + out_of_memory: AtomicBool, + /// The first other error. + error: OnceLock, + errors: AtomicU64, + /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]). + device_lost: AtomicBool, +} + +/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state. +#[derive(Clone, Default)] +pub struct DeviceHealth(Arc); + +impl fmt::Debug for DeviceHealth { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish() + } +} + +impl DeviceHealth { + /// A healthy flag not attached to a device (tests, CPU-only callers). + pub fn new() -> Self { + Self::default() + } + + /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). + pub fn watch(device: &wgpu::Device) -> Self { + let health = Self::new(); + let lost = health.clone(); + // Called by wgpu with its own locks held: only record, never call back into wgpu. + device.set_device_lost_callback(move |reason, message| { + let detail = match (reason, message.is_empty()) { + (wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(), + (_, true) => "lost by the driver".to_string(), + (_, false) => message, + }; + log::error!("wgpu device lost ({reason:?}): {detail}"); + lost.0.device_lost.store(true, Ordering::Release); + lost.mark(Fault::Lost(detail)); + }); + let errors = health.clone(); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); + health + } + + /// Record an uncaptured wgpu error. + fn uncaptured(&self, e: &wgpu::Error) { + self.0.errors.fetch_add(1, Ordering::Relaxed); + log::error!("uncaptured wgpu error: {e}"); + self.mark(fault_of(e)); + } + + /// Record an error an error scope caught. + /// + /// The uncaptured-error handler never sees a scoped error, so without this a watched device + /// would keep being handed work after it failed. Polls first: a lost device is a + /// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does + /// not block. + pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) { + if self.lost() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + self.poll(device); + #[cfg(target_arch = "wasm32")] + let _ = device; + if self.lost() { + return; + } + self.mark(fault_of(error)); + } + + fn lost(&self) -> bool { + self.fault().is_some_and(|f| f.is_lost()) + } + + /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, + /// and a later out-of-memory error replaces another error, so a caller can still free memory + /// and recover after a validation error in the same frame. + pub fn mark(&self, fault: Fault) { + if fault.is_out_of_memory() { + self.0.out_of_memory.store(true, Ordering::Release); + } else { + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; + } + self.0.faulted.store(true, Ordering::Release); + } + + /// Whether the device may still be used. + pub fn is_ok(&self) -> bool { + !self.0.faulted.load(Ordering::Acquire) + } + + /// Why the device cannot be used, if it cannot. + pub fn fault(&self) -> Option { + if self.is_ok() { + return None; + } + if let Some(text) = self.0.lost.get() { + return Some(Fault::Lost(text.clone())); + } + if self.0.out_of_memory.load(Ordering::Acquire) { + return Some(Fault::Error(OUT_OF_MEMORY.into())); + } + self.0.error.get().map(|text| Fault::Error(text.clone())) + } + + /// Uncaptured wgpu errors seen so far. + pub fn errors(&self) -> u64 { + self.0.errors.load(Ordering::Relaxed) + } + + /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it + /// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing + /// drawn with the device reaches the screen, the window's own frames included. + pub fn device_lost(&self) -> bool { + self.0.device_lost.load(Ordering::Acquire) + } + + /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost + /// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next + /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost). + pub fn probe(&self, device: &wgpu::Device) { + if self.device_lost() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// `Device::poll` panicked: wgpu found the device lost. + fn lost_by_poll(&self) { + self.0.device_lost.store(true, Ordering::Release); + self.mark(Fault::Lost("the device stopped responding".into())); + } + + /// Block until `index` (or all submitted work) finished, unless the device is unusable. + /// Returns whether the work finished with the device still healthy: `false` when the device + /// was unusable, when it faulted, and when the poll itself failed, so the work may still be + /// running. A panic in `Device::poll` is caught and recorded as a loss. Native only: the web + /// has no blocking wait. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait(&self, device: &wgpu::Device, index: Option) -> bool { + if !self.is_ok() { + return false; + } + let poll = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Wait { submission_index: index, timeout: None }))); + match poll { + Ok(Ok(_)) => self.is_ok(), + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + false + } + Err(_) => { + self.lost_by_poll(); + false + } + } + } + + /// Non-blocking poll (reclaims staging memory), skipped once the device is unusable. + pub fn poll(&self, device: &wgpu::Device) { + if !self.is_ok() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// Like [`Self::wait`], but bounded: returns whether the submitted work finished within + /// `timeout`. A timeout marks the device faulted, so later work stops going to a GPU that no + /// longer answers. A submission index the device never issued returns `false` and leaves the + /// device healthy. A zero `timeout`, or + /// one that passes before the first poll, returns `false` and leaves the device healthy. A + /// device that was already faulted returns `false` unchanged. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, device: &wgpu::Device, index: Option, timeout: Duration) -> bool { + self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished + } + + /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between + /// them, keeping the same overall deadline. A slice that times out means the work has not + /// finished yet; only the overall deadline (or a poll that panics) marks the device faulted. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout_cancelable( + &self, + device: &wgpu::Device, + index: Option, + timeout: Duration, + canceled: &(dyn Fn() -> bool + Sync), + ) -> WaitOutcome { + if !self.is_ok() { + return WaitOutcome::TimedOut; + } + let mut wrong_index = false; + let mut polled = false; + let outcome = wait_slices(timeout, canceled, |slice| { + polled = true; + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: index.clone(), timeout: Some(slice) }) + })); + match poll { + Ok(Ok(_)) => { + if self.is_ok() { + SlicePoll::Done + } else { + SlicePoll::Failed + } + } + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + // A submission index the device never issued: the caller's mistake, not the GPU's. + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + wrong_index = true; + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }); + // A deadline that passed before the first poll says nothing about the device. + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.is_ok() { + self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); + } + outcome + } +} + +/// What one bounded poll reported. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SlicePoll { + Done, + Pending, + Failed, +} + +/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between +/// them. A slice that times out is pending, not a failure; only the overall deadline or a failed +/// poll ends the wait early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: impl FnMut(Duration) -> SlicePoll) -> WaitOutcome { + const SLICE: Duration = Duration::from_millis(100); + let start = Instant::now(); + loop { + if canceled() { + return WaitOutcome::Canceled; + } + let remaining = total.saturating_sub(start.elapsed()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + match poll(remaining.min(SLICE)) { + SlicePoll::Done => return WaitOutcome::Finished, + SlicePoll::Pending => {} + SlicePoll::Failed => return WaitOutcome::TimedOut, + } + } +} + +/// The fault a wgpu error stands for. An error that names a lost device follows a device loss +/// whose callback may not have run yet (it runs on the next poll), so it counts as a loss rather +/// than as an error. An error about a destroyed buffer or texture is an error. Only wgpu's own +/// out-of-memory error is [`OUT_OF_MEMORY`]. +fn fault_of(e: &wgpu::Error) -> Fault { + let text = e.to_string(); + let lower = text.to_ascii_lowercase(); + if matches!(e, wgpu::Error::OutOfMemory { .. }) { + Fault::Error(OUT_OF_MEMORY.into()) + } else if lower.contains("device is lost") { + Fault::Lost(first_line(&text)) + } else { + Fault::Error(first_line(&text)) + } +} + +fn first_line(s: &str) -> String { + let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let mut out: String = line.chars().take(200).collect(); + if line.chars().count() > 200 { + out.push('…'); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_fault_wins_but_loss_replaces_an_error() { + let h = DeviceHealth::new(); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + h.mark(Fault::Error("out of memory".into())); + assert!(!h.is_ok()); + let c = h.clone(); + c.mark(Fault::Error("second".into())); + assert_eq!(h.fault(), Some(Fault::Error("out of memory".into()))); + c.mark(Fault::Lost("reset".into())); + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + c.mark(Fault::Lost("later".into())); + assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset")); + // a recorded loss is not wgpu reporting the device lost + assert!(!h.device_lost()); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_cancel_timeout_and_completion() { + let never = || false; + assert_eq!(wait_slices(Duration::ZERO, &never, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &never, |_| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + }); + assert_eq!(outcome, WaitOutcome::Finished); + assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure"); + + let canceled = || true; + let mut called = false; + assert_eq!( + wait_slices(Duration::from_secs(1), &canceled, |_| { + called = true; + SlicePoll::Done + }), + WaitOutcome::Canceled + ); + assert!(!called, "cancellation is checked before polling"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_observes_cancel_while_pending() { + let flag = AtomicBool::new(false); + let canceled = || flag.load(Ordering::SeqCst); + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &canceled, |_| { + polls += 1; + flag.store(true, Ordering::SeqCst); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::Canceled); + assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); + } + + #[test] + fn fault_text() { + assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); + assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); + assert_eq!(first_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid"); + assert_eq!(first_line(&"a".repeat(300)).chars().count(), 201); + assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); + let h = DeviceHealth::new(); + h.mark(Fault::Error("Validation Error".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.mark(Fault::Lost("reset".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_lost())); + assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); + } + + #[test] + fn marks_from_several_threads_keep_the_loss() { + let h = DeviceHealth::new(); + let threads: Vec<_> = (0..8) + .map(|i| { + let h = h.clone(); + std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) })) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + } + + #[test] + fn only_a_lost_device_counts_as_a_loss() { + let validation = + |description: &str| wgpu::Error::Validation { source: Box::new(std::io::Error::other("x")), description: description.into() }; + let lost = validation("Validation Error\n\nCaused by:\n In Device::create_buffer\n Parent device is lost\n"); + assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); + let destroyed = validation("Validation Error\n\nCaused by:\n In Queue::submit\n Buffer 'pc' has been destroyed\n"); + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into())); + let texture = validation("Validation Error\n\nCaused by:\n Texture with 'frame' label has been destroyed\n"); + assert!(!fault_of(&texture).is_lost()); + } +} diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs new file mode 100644 index 0000000000..72c2ba2acf --- /dev/null +++ b/crates/gpu-device/src/lib.rs @@ -0,0 +1,35 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Choosing and opening a wgpu device for a Craft app. +//! +//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and +//! [`AdapterKey`] identifies one across runs. +//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named +//! adapter, software) with wgpu's own rule and two corrections for drivers that crash +//! ([`choose`]); [`Notice`] says when the choice was not the one asked for. +//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device +//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` +//! block on wgpu's futures and are native only; a browser build picks with [`pick`]. +//! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm +//! formats, `f16`, timestamps, sizes). +//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and +//! [`Recovery`] says what to open after a loss. +//! +//! The selection functions are pure, so tests run without a GPU. + +mod adapter; +mod caps; +mod health; +mod open; +mod preference; +mod recovery; + +pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; +pub use caps::{Capabilities, Vendor}; +pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; +pub use open::{OpenError, Opened, Request, pick}; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{list, open}; +pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; +pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs new file mode 100644 index 0000000000..5156e09c20 --- /dev/null +++ b/crates/gpu-device/src/open.rs @@ -0,0 +1,304 @@ +//! Listing adapters and opening a device, trying the next adapter when one fails. + +use std::fmt; + +#[cfg(not(target_arch = "wasm32"))] +use wgpu::Instance; +use wgpu::{Adapter, Features, Limits, Surface}; + +use crate::adapter::{Candidate, avoided, log_choice}; +use crate::caps::Capabilities; +use crate::health::DeviceHealth; +use crate::preference::{Notice, Preference, Selection, select}; +#[cfg(not(target_arch = "wasm32"))] +use crate::preference::{asked_for, ranked}; + +/// What the device is opened with. +#[derive(Clone, Debug, Default)] +pub struct Request<'a> { + pub label: Option<&'a str>, + /// Features the device must have. An adapter without them is skipped. + pub required_features: Features, + /// Features asked for when the adapter has them. + pub optional_features: Features, + /// The limits to ask for; `None` asks for the adapter's own limits. + pub limits: Option, +} + +/// An opened device. +#[derive(Debug)] +pub struct Opened { + pub adapter: Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// The adapter as plain data. + pub candidate: Candidate, + /// What the device was opened with. + pub caps: Capabilities, + /// Watches the device for a loss and for uncaptured errors. + pub health: DeviceHealth, + /// What to tell the user about the choice. + pub notices: Vec, +} + +/// Why no device could be opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenError { + /// No adapter is listed that can draw (to the surface, when there is one). + NoAdapter, + /// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`]. + NoDevice(Vec), + /// The only adapters that can draw are ones [`choose`](crate::choose) never draws with, + /// because their driver can end the process; these are their names. + UnsafeDriver(Vec), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoAdapter => f.write_str("no graphics adapter is available"), + OpenError::NoDevice(notices) => { + f.write_str("no graphics adapter could be opened")?; + for n in notices { + if let Notice::DeviceFailed { adapter, error } = n { + write!(f, "; \"{adapter}\": {error}")?; + } + } + Ok(()) + } + OpenError::UnsafeDriver(names) => { + let names = names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", "); + write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver") + } + } + } +} + +impl std::error::Error for OpenError {} + +/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` +/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's +/// future, which on the web would wait on the thread that must resolve it. +#[cfg(not(target_arch = "wasm32"))] +pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) +} + +/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the +/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device +/// itself. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), String> { + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + let Some(selection) = select(&candidates, preference) else { + let left_out = left_out(&candidates); + if !left_out.is_empty() { + return Err(OpenError::UnsafeDriver(left_out).to_string()); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + return Err(format!("no usable graphics adapter among {}: {listed}", candidates.len())); + }; + log_choice(&candidates, selection.index, preference.power()); + for notice in &selection.notices { + log::warn!("{notice}"); + } + let adapter = + adapters.get(selection.index).cloned().ok_or_else(|| format!("graphics adapter {} of {} is missing", selection.index, adapters.len()))?; + Ok((adapter, selection)) +} + +/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] +/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter +/// without `request.required_features`, or whose device fails to open, adds a +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { + let (adapters, candidates) = list(instance, surface); + // Whether drawing is in software depends on the adapter that opens, which `finish` knows. + let mut notices: Vec = + select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); + let order = ranked(&candidates, preference); + if let Some(first) = order.first() { + log_choice(&candidates, *first, preference.power()); + } + let mut tried_software = false; + for index in order { + let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { + continue; + }; + tried_software |= candidate.is_software(); + match open_on(adapter, request) { + Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), + Err(error) => { + log::warn!("graphics adapter {candidate} could not be opened: {error}"); + notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }); + } + } + } + if !tried_software { + let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; + if let Ok(adapter) = pollster::block_on(instance.request_adapter(&options)) { + let candidate = Candidate::of(&adapter, surface); + match open_on(&adapter, request) { + Ok((device, queue)) => { + log::info!("graphics adapter chosen: {candidate}"); + return Ok(finish(adapter, device, queue, candidate, preference, notices)); + } + Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }), + } + } + } + if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) { + return Err(OpenError::NoDevice(notices)); + } + let left_out = left_out(&candidates); + if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) } +} + +/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with. +fn left_out(candidates: &[Candidate]) -> Vec { + candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish( + adapter: Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + candidate: Candidate, + preference: &Preference, + mut notices: Vec, +) -> Opened { + let caps = Capabilities::of_device(&adapter, &device); + if candidate.is_software() && !asked_for(preference, &candidate) { + notices.push(Notice::SoftwareOnly); + } + for notice in ¬ices { + log::warn!("{notice}"); + } + log::info!("graphics device opened: {caps}"); + let health = DeviceHealth::watch(&device); + Opened { adapter, device, queue, candidate, caps, health, notices } +} + +/// Open a device on `adapter`, or say why it cannot be. +#[cfg(not(target_arch = "wasm32"))] +fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { + let has = adapter.features(); + if !has.contains(request.required_features) { + return Err(format!("it lacks the features {:?}", request.required_features - has)); + } + let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); + let desc = wgpu::DeviceDescriptor { + label: request.label, + required_features: request.required_features | (request.optional_features & has), + required_limits, + ..Default::default() + }; + pollster::block_on(adapter.request_device(&desc)).map_err(|e| e.to_string()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::preference::AdapterKey; + + /// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu + /// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says. + fn noop(features: Option) -> Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() }; + Instance::new(desc) + } + + #[test] + fn a_device_opens_with_the_optional_features_the_adapter_has() { + let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12, "{}", opened.caps); + assert!(!opened.caps.shader_f16 && !opened.caps.timestamps, "only the features asked for: {}", opened.caps); + assert!(opened.notices.is_empty(), "{:?}", opened.notices); + assert!(opened.health.is_ok()); + } + + #[test] + fn an_adapter_without_a_required_feature_is_reported() { + let instance = noop(Some(Features::empty())); + let request = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = open(&instance, None, &Preference::Auto, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}"); + assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); + } + + #[test] + fn a_software_adapter_is_reported_unless_it_was_asked_for() { + let cpu = noop(None); + let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); + assert!(opened.caps.software); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); + assert!(asked.notices.is_empty(), "{:?}", asked.notices); + // the software adapter picked by name is what was asked for + let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap(); + assert!(named.notices.is_empty(), "{:?}", named.notices); + // a named adapter that is gone: the automatic choice, with both notices + let gone = + AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() }; + let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap(); + assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]); + } + + #[test] + fn no_adapter_is_an_error() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let instance = Instance::new(desc); + assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter); + assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available"); + assert_eq!( + OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), + "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" + ); + assert!(pick(&[], None, &Preference::Auto).is_err()); + } + + #[test] + fn a_zero_timeout_leaves_a_healthy_device_healthy() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + assert!(!opened.health.wait_timeout(&opened.device, None, std::time::Duration::ZERO)); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + assert!(opened.health.wait_timeout(&opened.device, None, std::time::Duration::from_secs(5))); + // an index from another device's queue is one this device never issued + let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + other.queue.submit([]); + let index = other.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, Some(index), std::time::Duration::from_secs(5))); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + } + + #[test] + fn a_lost_device_is_seen_by_its_health() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + opened.device.destroy(); + health.probe(&opened.device); + assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); + assert!(!health.is_ok()); + // a later wait does not touch the lost device + assert!(!health.wait(&opened.device, None)); + } + + #[test] + fn pick_returns_the_selected_adapter() { + let instance = noop(None); + let (adapters, candidates) = list(&instance, None); + assert_eq!(candidates.len(), 1); + let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap(); + assert_eq!(selection.index, 0); + assert_eq!(Candidate::of(&adapter, None), candidates[0]); + } +} diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs new file mode 100644 index 0000000000..7a60529c70 --- /dev/null +++ b/crates/gpu-device/src/preference.rs @@ -0,0 +1,404 @@ +//! The adapter the user asked for, and what was drawn with instead when it is not there. + +use std::fmt; + +use wgpu::{Backend, PowerPreference}; + +use crate::adapter::{Candidate, avoided, choose, corrected, intel_vulkan_crashes, type_order}; + +/// Which adapter to draw with. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))] +pub enum Preference { + /// The fastest adapter: a discrete GPU before an integrated one, hardware before software. + #[default] + Auto, + /// An integrated GPU before a discrete one, for battery life. + LowPower, + /// One adapter the user picked from [`crate::list`]. + Adapter(AdapterKey), + /// A software adapter that draws on the CPU. + Software, +} + +impl Preference { + /// The power preference that orders the adapters for this preference: low power for + /// [`Preference::LowPower`], high performance otherwise. + pub fn power(&self) -> PowerPreference { + match self { + Preference::LowPower => PowerPreference::LowPower, + _ => PowerPreference::HighPerformance, + } + } +} + +/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and +/// the name. The order in which the system lists adapters can change between runs, so an index +/// cannot be kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))] +pub struct AdapterKey { + pub name: String, + /// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`). + pub backend: String, + pub vendor: u32, + pub device: u32, + /// Empty when the driver reports none. + pub pci_bus_id: String, + /// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on + /// Linux) and stays the same across versions of a driver. Empty on the other backends, and + /// when the driver reports none. + pub driver: String, +} + +impl AdapterKey { + pub fn of(candidate: &Candidate) -> Self { + AdapterKey { + name: candidate.name.clone(), + backend: backend_name(candidate.backend).to_string(), + vendor: candidate.vendor, + device: candidate.device, + pci_bus_id: candidate.pci_bus_id.clone(), + // DirectX 12 reports the driver's version here, which changes with every update. + driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() }, + } + } + + /// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the + /// same driver when both report one, and the same name when the backend reports no PCI ids. + pub fn matches(&self, candidate: &Candidate) -> bool { + let identified = self.vendor != 0 || self.device != 0; + let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + self.backend == backend_name(candidate.backend) + && self.vendor == candidate.vendor + && self.device == candidate.device + && same(&self.pci_bus_id, &candidate.pci_bus_id) + && same(&self.driver, &candidate.driver) + && (identified || self.name == candidate.name) + } +} + +impl fmt::Display for AdapterKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({})", self.name, self.backend) + } +} + +/// wgpu's lowercase name of `backend`. +pub fn backend_name(backend: Backend) -> &'static str { + backend.to_str() +} + +/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is +/// English, for the log; an app shows its own translated text for each variant. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Notice { + /// The adapter the user picked is not listed (unplugged, disabled, or its driver removed). + /// The automatic choice draws instead. + AdapterMissing(AdapterKey), + /// Software was asked for and no software adapter is listed. The automatic choice draws + /// instead. + NoSoftwareAdapter, + /// The only adapter that can draw is a software one: drawing is slower and uses the CPU. + SoftwareOnly, + /// An adapter could not open a device, and the next one was tried. + DeviceFailed { adapter: String, error: String }, + /// The device was lost this many times in a short time, so drawing moved to software. + SoftwareAfterLosses(u32), +} + +impl fmt::Display for Notice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"), + Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"), + Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"), + Notice::DeviceFailed { adapter, error } => { + write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one") + } + Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"), + } + } +} + +/// The adapter chosen for a preference, and what the user should be told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + /// Index into the candidates. + pub index: usize, + pub notices: Vec, +} + +/// The adapter to draw with for `preference`, or `None` when no adapter is usable. +/// +/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`]. +/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most +/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when +/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and +/// [`Notice::AdapterMissing`]. +/// - [`Preference::Software`] uses the first usable software adapter; without one, the automatic +/// choice and [`Notice::NoSoftwareAdapter`]. +/// +/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. +pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { + let mut notices = Vec::new(); + let wanted = match preference { + Preference::Auto | Preference::LowPower => None, + Preference::Adapter(key) => { + // An entry that reports no bus id matches any saved bus. When it is the same model on + // the same driver it cannot be told apart from an older version of that driver, and + // the correction draws with the entry exposing the most features. + let found = + candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i))); + match found.map(|(index, c)| corrected(candidates, index, c)) { + Some(index) if !candidates.get(index).is_some_and(intel_vulkan_crashes) => Some(index), + _ => { + notices.push(Notice::AdapterMissing(key.clone())); + None + } + } + } + Preference::Software => { + let found = candidates.iter().position(|c| c.usable && c.is_software()); + if found.is_none() { + notices.push(Notice::NoSoftwareAdapter); + } + found + } + }; + let index = match wanted { + Some(index) => index, + None => { + let index = choose(candidates, preference.power())?; + if candidates.get(index).is_some_and(Candidate::is_software) { + notices.push(Notice::SoftwareOnly); + } + index + } + }; + Some(Selection { index, notices }) +} + +/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key +/// of this adapter. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { + match preference { + Preference::Software => candidate.is_software(), + Preference::Adapter(key) => key.matches(candidate), + Preference::Auto | Preference::LowPower => false, + } +} + +/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then +/// every other usable adapter by device type for the preference's power (software after +/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver +/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver. +/// Empty when no adapter is usable. +pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec { + let Some(first) = select(candidates, preference).map(|s| s.index) else { + return Vec::new(); + }; + let power = preference.power(); + let mut rest: Vec = + (0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect(); + rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i)); + let mut order = vec![first]; + order.extend(rest); + order +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630}; + use wgpu::Backend::{Dx12, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + + fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey { + candidates.get(index).map(AdapterKey::of).unwrap_or_default() + } + + #[test] + fn auto_and_low_power_are_the_corrected_wgpu_choice() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] })); + assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2)); + assert_eq!(select(&[], &Preference::Auto), None); + assert_eq!(Preference::default(), Preference::Auto); + } + + #[test] + fn a_named_adapter_is_found_wherever_it_is_listed() { + let adapters = two_amd_drivers(); + // the integrated Radeon through DirectX 12, picked by the user + let key = key_of(&adapters, 4); + assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4)); + // listed in another order on the next run + let mut reordered = adapters.clone(); + reordered.reverse(); + assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1)); + // the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws + let stale = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1)); + } + + #[test] + fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() { + let adapters = uhd_630(); + let vulkan = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1)); + // without the DirectX 12 entry, the named Vulkan entry is not available + let mut dx12_unusable = adapters.clone(); + dx12_unusable[1].usable = false; + let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly]))); + } + + #[test] + fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() { + let adapters = two_amd_drivers(); + let gone = AdapterKey { + name: "NVIDIA GeForce RTX 4090".into(), + backend: "vulkan".into(), + vendor: 0x10de, + device: 0x2684, + pci_bus_id: String::new(), + driver: "NVIDIA".into(), + }; + let s = select(&adapters, &Preference::Adapter(gone.clone())); + assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] })); + // listed but unable to draw to the window counts as missing + let mut unusable = adapters.clone(); + for c in &mut unusable { + c.usable = c.backend != Vulkan; + } + let vulkan_key = key_of(&adapters, 1); + let s = select(&unusable, &Preference::Adapter(vulkan_key.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)]))); + // nothing usable at all + assert_eq!(select(&[], &Preference::Adapter(gone)), None); + } + + #[test] + fn keys_tell_apart_backends_buses_and_unidentified_names() { + let adapters = two_amd_drivers(); + let dx12 = key_of(&adapters, 3); + assert!(dx12.matches(&adapters[3])); + assert!(!dx12.matches(&adapters[1]), "same GPU, other backend"); + let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() }; + assert!(!dx12.matches(&other_bus)); + // a key stored without a bus id still matches an entry that reports one + let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() }; + assert!(no_bus.matches(&adapters[3])); + // two Vulkan drivers for one GPU are told apart by the driver name; a key saved without + // one matches either + let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70); + let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72); + let two = vec![radv.clone(), amdvlk.clone()]; + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0)); + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1)); + let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) }; + assert!(old.matches(&radv) && old.matches(&amdvlk)); + // a DirectX 12 key keeps matching after a driver update changes the reported version + assert!(dx12.driver.is_empty()); + let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() }; + assert!(dx12.matches(&updated)); + // OpenGL reports no ids: the name decides + let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let key = AdapterKey::of(&angle); + assert!(key.matches(&angle) && !key.matches(&swiftshader)); + assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)"); + } + + #[test] + fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] })); + let hardware_only: Vec = adapters.iter().filter(|c| !c.is_software()).cloned().collect(); + assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] })); + let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)]; + assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] })); + assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] })); + // picked by name, it is what was asked for + let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0])); + assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] })); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0])); + assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1])); + } + } + + #[test] + fn the_fallback_order_never_tries_entries_that_can_crash() { + let adapters = two_amd_drivers(); + // the newer RX 6800M, then the other hardware by type for high performance, then software; + // the stale RX 6800M entry is never tried + assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]); + assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]); + assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]); + // two cards of one model on one driver, one without a Vulkan bus id: the second card's + // Vulkan entry looks like an older version, and the card is tried through DirectX 12 + let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68); + let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36); + let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")]; + assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]); + // the same bus id on both entries: one GPU, and the older version is never tried + let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")]; + versions[1].features = 70; + assert_eq!(ranked(&versions, &Preference::Auto), vec![1]); + // a third entry without a bus id and with more features: both older entries are left out + versions.push(card("")); + versions[2].features = 80; + assert_eq!(ranked(&versions, &Preference::Auto), vec![2]); + // two GPUs on different buses are both tried + let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")]; + assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]); + // the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry + assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]); + let mut dx12_unusable = uhd_630(); + dx12_unusable[1].usable = false; + assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]); + assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty()); + assert!(ranked(&[], &Preference::Auto).is_empty()); + let unusable: Vec = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect(); + assert!(ranked(&unusable, &Preference::Auto).is_empty()); + } + + #[test] + fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() { + let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36); + let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36); + let a = vec![intel.clone(), nvidia.clone()]; + let b = vec![nvidia, intel]; + let picked = Preference::Adapter(key_of(&a, 0)); + assert_eq!(select(&a, &picked).map(|s| s.index), Some(0)); + assert_eq!(select(&b, &picked).map(|s| s.index), Some(1)); + assert_eq!(ranked(&b, &picked), vec![1, 0]); + } + + #[cfg(feature = "serde")] + #[test] + fn preferences_read_back_what_they_write() { + let key = AdapterKey { + name: "AMD Radeon RX 6800M".into(), + backend: "dx12".into(), + vendor: 0x1002, + device: 0x73df, + pci_bus_id: "0000:03:00.0".into(), + driver: String::new(), + }; + for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] { + let text = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), p, "{text}"); + } + assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#); + // a key written by an older version without some fields + let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap(); + assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() })); + assert!(serde_json::from_str::(r#"{"kind":"fastest"}"#).is_err()); + } +} diff --git a/crates/gpu-device/src/recovery.rs b/crates/gpu-device/src/recovery.rs new file mode 100644 index 0000000000..2732d8c986 --- /dev/null +++ b/crates/gpu-device/src/recovery.rs @@ -0,0 +1,153 @@ +//! What to open after a device loss. +//! +//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps, +//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one. +//! [`Recovery`] decides with what preference: the user's own, until the device has been lost +//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that, +//! so a GPU that keeps failing does not stop the app from drawing. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::preference::{Notice, Preference}; + +/// When repeated losses move drawing to software. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecoveryPolicy { + /// Losses within [`window`](Self::window) after which the next device is a software one. + /// 0 never moves to software. + pub max_losses: u32, + pub window: Duration, +} + +impl Default for RecoveryPolicy { + fn default() -> Self { + RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) } + } +} + +/// The preference to open the next device with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecoveryStep { + pub preference: Preference, + /// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software. + pub notice: Option, +} + +/// Device losses seen so far, against the user's preference. +#[derive(Clone, Debug)] +pub struct Recovery { + preference: Preference, + policy: RecoveryPolicy, + /// When each loss inside the window happened, oldest first. + losses: VecDeque, + software: bool, +} + +impl Recovery { + pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self { + Recovery { preference, policy, losses: VecDeque::new(), software: false } + } + + /// The preference to open a device with now. + pub fn preference(&self) -> &Preference { + if self.software { &Preference::Software } else { &self.preference } + } + + /// The user changed the preference: losses counted so far no longer apply. + pub fn set_preference(&mut self, preference: Preference) { + self.preference = preference; + self.losses.clear(); + self.software = false; + } + + /// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and + /// return what to open next. A time earlier than the last loss counts as the same time. + pub fn lost(&mut self, at: Duration) -> RecoveryStep { + let at = self.losses.back().map_or(at, |last| at.max(*last)); + self.losses.push_back(at); + // Only the last `max_losses` losses decide anything, so no more are kept. + let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX); + while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) { + self.losses.pop_front(); + } + let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX); + let mut notice = None; + if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software { + self.software = true; + notice = Some(Notice::SoftwareAfterLosses(count)); + } + RecoveryStep { preference: self.preference().clone(), notice } + } + + /// Losses inside the window, as of the last one, counting at most + /// [`RecoveryPolicy::max_losses`] (at least 1). + pub fn recent_losses(&self) -> usize { + self.losses.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(secs: u64) -> Duration { + Duration::from_secs(secs) + } + + #[test] + fn the_third_loss_in_ten_minutes_moves_to_software() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default()); + assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) }); + // it stays on software, and says so once + assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None }); + assert_eq!(r.preference(), &Preference::Software); + } + + #[test] + fn losses_outside_the_window_are_forgotten() { + let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default()); + r.lost(s(0)); + r.lost(s(500)); + // the first loss is more than 600 s before this one + assert_eq!(r.lost(s(601)).preference, Preference::LowPower); + assert_eq!(r.recent_losses(), 2); + // a clock that goes back counts as the last loss's time + assert_eq!(r.lost(s(1)).preference, Preference::Software); + } + + #[test] + fn changing_the_preference_starts_over() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) }); + r.lost(s(1)); + assert_eq!(r.lost(s(2)).preference, Preference::Software); + r.set_preference(Preference::LowPower); + assert_eq!(r.preference(), &Preference::LowPower); + assert_eq!(r.recent_losses(), 0); + assert_eq!(r.lost(s(3)).preference, Preference::LowPower); + } + + #[test] + fn software_and_a_zero_limit_never_add_a_notice() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default()); + for t in 0..5 { + assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None }); + } + let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) }); + for t in 0..10 { + assert_eq!(never.lost(s(t)).preference, Preference::Auto); + } + assert_eq!(never.recent_losses(), 1); + } + + #[test] + fn the_loss_history_stays_bounded() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX }); + for _ in 0..10_000 { + r.lost(s(5)); + } + assert_eq!(r.recent_losses(), 3); + } +} From 5c4c73f4a96ef13aae4118aa1b63e4bad9d01b33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:01:11 -0800 Subject: [PATCH 042/490] craft-gpu-device: bounded waits keep one target, and a label cannot mark a loss - wait_timeout and wait_timeout_cancelable take a submission index instead of an Option. Every 100 ms slice waits for that index, so work submitted during the wait no longer moves the target and can no longer make a healthy device time out. Pass queue.submit([]) to wait for everything submitted so far. - An uncaptured error counts as a device loss only when an error in its source chain is wgpu's "Parent device is lost". A resource label that contains those words, on its own line or not, is recorded as an error. --- crates/gpu-device/README.md | 8 ++- crates/gpu-device/src/health.rs | 90 +++++++++++++++++++++++++-------- crates/gpu-device/src/open.rs | 7 +-- 3 files changed, 78 insertions(+), 27 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index ee05ec009b..32b4750f91 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -42,8 +42,12 @@ Licensed under MIT OR Apache-2.0. driver reports no bus id, a second GPU of the same model on the same driver looks like an older version, and is used through its other backend (DirectX 12 on Windows, OpenGL elsewhere). -- Only an error that says the device is lost counts as a loss. An error about a destroyed buffer - or texture is recorded as an error. +- Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in + a resource's label do not count. An error about a destroyed buffer or texture is recorded as an + error. +- `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for + everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the + wait. - `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that `Device::poll` raises on a lost device and record the loss. diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index a113ee783c..c2254ee4e9 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -257,25 +257,27 @@ impl DeviceHealth { } } - /// Like [`Self::wait`], but bounded: returns whether the submitted work finished within - /// `timeout`. A timeout marks the device faulted, so later work stops going to a GPU that no - /// longer answers. A submission index the device never issued returns `false` and leaves the - /// device healthy. A zero `timeout`, or - /// one that passes before the first poll, returns `false` and leaves the device healthy. A - /// device that was already faulted returns `false` unchanged. + /// Like [`Self::wait`], but bounded: returns whether the work up to `index` finished within + /// `timeout`. To wait for everything submitted so far, pass the index of an empty submission + /// (`queue.submit([])`); work submitted after it does not extend the wait. A timeout marks the + /// device faulted, so later work stops going to a GPU that no longer answers. A submission + /// index the device never issued returns `false` and leaves the device healthy. A zero + /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device + /// healthy. A device that was already faulted returns `false` unchanged. #[cfg(not(target_arch = "wasm32"))] - pub fn wait_timeout(&self, device: &wgpu::Device, index: Option, timeout: Duration) -> bool { + pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished } /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between - /// them, keeping the same overall deadline. A slice that times out means the work has not - /// finished yet; only the overall deadline (or a poll that panics) marks the device faulted. + /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice + /// that times out means the work has not finished yet; only the overall deadline (or a poll + /// that panics) marks the device faulted. #[cfg(not(target_arch = "wasm32"))] pub fn wait_timeout_cancelable( &self, device: &wgpu::Device, - index: Option, + index: wgpu::SubmissionIndex, timeout: Duration, canceled: &(dyn Fn() -> bool + Sync), ) -> WaitOutcome { @@ -287,7 +289,7 @@ impl DeviceHealth { let outcome = wait_slices(timeout, canceled, |slice| { polled = true; let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - device.poll(wgpu::PollType::Wait { submission_index: index.clone(), timeout: Some(slice) }) + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) })); match poll { Ok(Ok(_)) => { @@ -350,16 +352,29 @@ fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: } } -/// The fault a wgpu error stands for. An error that names a lost device follows a device loss -/// whose callback may not have run yet (it runs on the next poll), so it counts as a loss rather -/// than as an error. An error about a destroyed buffer or texture is an error. Only wgpu's own -/// out-of-memory error is [`OUT_OF_MEMORY`]. +/// The whole message of wgpu's `DeviceError::Lost`. +const LOST_CAUSE: &str = "Parent device is lost"; + +/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`: +/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's +/// message, so a label never matches. +fn caused_by_loss(e: &wgpu::Error) -> bool { + let source: &(dyn std::error::Error + 'static) = match e { + wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(), + _ => return false, + }; + std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE)) +} + +/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) +/// follows a device loss whose callback may not have run yet (it runs on the next poll), so it +/// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. fn fault_of(e: &wgpu::Error) -> Fault { let text = e.to_string(); - let lower = text.to_ascii_lowercase(); if matches!(e, wgpu::Error::OutOfMemory { .. }) { Fault::Error(OUT_OF_MEMORY.into()) - } else if lower.contains("device is lost") { + } else if caused_by_loss(e) { Fault::Lost(first_line(&text)) } else { Fault::Error(first_line(&text)) @@ -474,15 +489,46 @@ mod tests { assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); } + /// An error and the errors that caused it, outermost first, as wgpu-core chains them. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|c| c as _) + } + } + + /// A validation error with the causes `chain` and wgpu's description of them. + fn validation(chain: &[&'static str]) -> wgpu::Error { + let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner)))); + let mut description = String::from("Validation Error\n\nCaused by:\n"); + for c in chain { + description.push_str(&format!(" {c}\n")); + } + wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description } + } + #[test] fn only_a_lost_device_counts_as_a_loss() { - let validation = - |description: &str| wgpu::Error::Validation { source: Box::new(std::io::Error::other("x")), description: description.into() }; - let lost = validation("Validation Error\n\nCaused by:\n In Device::create_buffer\n Parent device is lost\n"); + let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); - let destroyed = validation("Validation Error\n\nCaused by:\n In Queue::submit\n Buffer 'pc' has been destroyed\n"); + let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into())); - let texture = validation("Validation Error\n\nCaused by:\n Texture with 'frame' label has been destroyed\n"); + let texture = validation(&["Texture with 'frame' label has been destroyed"]); assert!(!fault_of(&texture).is_lost()); + // a label is the caller's text, not the cause, even on a line of its own + let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error".into())); + for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { + let labeled = validation(&["In Queue::submit", label]); + assert!(!fault_of(&labeled).is_lost(), "{label:?}"); + } } } diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 5156e09c20..388d8bdd20 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -269,14 +269,15 @@ mod tests { #[test] fn a_zero_timeout_leaves_a_healthy_device_healthy() { let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); - assert!(!opened.health.wait_timeout(&opened.device, None, std::time::Duration::ZERO)); + let everything = opened.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO)); assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); - assert!(opened.health.wait_timeout(&opened.device, None, std::time::Duration::from_secs(5))); + assert!(opened.health.wait_timeout(&opened.device, everything, std::time::Duration::from_secs(5))); // an index from another device's queue is one this device never issued let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); other.queue.submit([]); let index = other.queue.submit([]); - assert!(!opened.health.wait_timeout(&opened.device, Some(index), std::time::Duration::from_secs(5))); + assert!(!opened.health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5))); assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); } From 61aaf23e7287d9f3c5a78dd4a8d231cfdf42f541 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:15:12 -0800 Subject: [PATCH 043/490] Cloud: signing out closes the share sheet and stops offering Share sign_out cleared the account, its files and its busy state, but left the share dialog as it was. Share stayed available on the signed-out account's capabilities, and a sheet open on one of its documents stayed open and could still send. Signing out now closes the sheet and offers Share to nobody until the next sign-in asks the provider again. The provider is not asked during the sign-out itself, and a capabilities answer to a question asked before a refresh or a sign-out is ignored when it arrives. --- crates/ui/src/cloud/mod.rs | 5 +++++ crates/ui/src/cloud/tests.rs | 43 ++++++++++++++++++++++++++++++++++++ crates/ui/src/share/mod.rs | 25 ++++++++++++++++++++- crates/ui/src/share/tests.rs | 18 +++++++++++++++ 4 files changed, 90 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/cloud/mod.rs b/crates/ui/src/cloud/mod.rs index 3844c4f8f1..3e091a7d4c 100644 --- a/crates/ui/src/cloud/mod.rs +++ b/crates/ui/src/cloud/mod.rs @@ -400,7 +400,12 @@ pub fn sign_out(app: &mut A) { // that never heard back does not refuse every one after it forever. cloud.account_generation.fetch_add(1, Ordering::Relaxed); cloud.busy = None; + cloud.sharing_save = false; cloud.save_as_target = None; + // Sharing went with the account: Share is not offered on the old + // account's answer, and a sheet open on one of its documents closes. The + // next sign-in asks the provider again. + app.sharing().signed_out(); submit(app, Job::SignOut); } diff --git a/crates/ui/src/cloud/tests.rs b/crates/ui/src/cloud/tests.rs index 875612144f..4a411389ff 100644 --- a/crates/ui/src/cloud/tests.rs +++ b/crates/ui/src/cloud/tests.rs @@ -430,6 +430,49 @@ fn signing_out_forgets_everything_this_window_knew() { assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too"); } +/// A sharing service that says it can share and answers nothing else. +struct Shares; + +impl crate::share::ShareBackend for Shares { + fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) { + if request == crate::share::Request::Capabilities { + reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true }); + } + } +} + +#[test] +fn signing_out_takes_sharing_with_it() { + let (mut app, _jobs, ctx) = wired(); + app.share.connect(Shares); + // Enough frames for an account answer to land, the provider to be asked, + // and its answer to be read. + let frames = |app: &mut Notebook| { + for _ in 0..3 { + ctx.begin_pass(Default::default()); + app.share.show(&ctx); + pump(app, &ctx); + ctx.end_pass().textures_delta.clear(); + } + }; + frames(&mut app); + assert!(app.share.available()); + app.share.open("/Minutes.note", "Minutes"); + assert!(app.share.is_open()); + + sign_out(&mut app); + assert!(!app.share.is_open(), "a sheet open on the old account's document closes"); + assert!(!app.share.available(), "Share is not offered on the old account's answer"); + // The provider is not asked again while the sign-out may still be on its + // way, so a service that still has the old account cannot offer it back. + frames(&mut app); + assert!(!app.share.available(), "nobody is signed in"); + + sign_in(&mut app); + frames(&mut app); + assert!(app.share.available(), "the next sign-in asks again"); +} + #[test] fn bytes_are_said_the_way_a_person_reads_them() { assert_eq!(size_text(None), ""); diff --git a/crates/ui/src/share/mod.rs b/crates/ui/src/share/mod.rs index e380674119..5512bea6b8 100644 --- a/crates/ui/src/share/mod.rs +++ b/crates/ui/src/share/mod.rs @@ -338,6 +338,10 @@ pub struct ShareDialog { provider: Option, /// When the capability question was last asked. asked: Option, + /// The last request number issued before the latest [`ShareDialog::refresh`] + /// or [`ShareDialog::connect`]. A capabilities answer to that request or an + /// earlier one describes the account as it was, and is ignored. + capabilities_after: u64, open: Option, /// Keyed by the URL the contact carried, so reopening the dialog does not /// fetch the same faces again. @@ -370,6 +374,7 @@ impl ShareDialog { seq: 0, provider: None, asked: None, + capabilities_after: 0, open: None, avatars: HashMap::new(), wants_save: None, @@ -387,6 +392,7 @@ impl ShareDialog { self.backend = Some(Box::new(backend)); self.provider = None; self.asked = None; + self.capabilities_after = self.seq; } pub fn connected(&self) -> bool { @@ -413,10 +419,25 @@ impl ShareDialog { /// The answer is kept once it arrives, so a host that signs somebody /// in after the first answer has to say so. Without this the dialog /// keeps the answer it got while nobody was signed in, and Share - /// stays unavailable for the rest of the run. + /// stays unavailable for the rest of the run. An answer to a question + /// asked before the refresh is ignored when it arrives. pub fn refresh(&mut self) { self.provider = None; self.asked = None; + self.capabilities_after = self.seq; + } + + /// Forget sharing for an account that signed out. + /// + /// Closes the sheet and offers nothing until [`ShareDialog::refresh`], + /// which the next sign-in calls. The provider is not asked again here: a + /// question asked before the sign-out reaches the service would describe + /// the account that is leaving. Answers to earlier questions are ignored. + pub fn signed_out(&mut self) { + self.close(); + self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false }); + self.asked = None; + self.capabilities_after = self.seq; } pub fn available(&self) -> bool { @@ -639,6 +660,8 @@ impl ShareDialog { // once the open sheet is no longer borrowed. let mut reload = None; match answer { + // Asked before the account changed: it describes the old one. + Answer::Capabilities { .. } if seq <= self.capabilities_after => {} Answer::Capabilities { capabilities, linked } => { self.provider = Some(Provider { sharing: linked && capabilities.contains(&Capability::Sharing), diff --git a/crates/ui/src/share/tests.rs b/crates/ui/src/share/tests.rs index dfdb3eb1e3..92d202c1c4 100644 --- a/crates/ui/src/share/tests.rs +++ b/crates/ui/src/share/tests.rs @@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() { assert!(dialog.is_open()); } +#[test] +fn a_capabilities_answer_asked_before_a_refresh_is_ignored() { + let ctx = Context::default(); + let backend = Silent::default(); + let mut dialog = ShareDialog::new(); + dialog.connect(backend.clone()); + dialog.collect(&ctx); + dialog.refresh(); + dialog.collect(&ctx); + assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again"); + + // The first question was about the account before the refresh. + dialog.receive(&ctx, 1, Ok(everything())); + assert!(!dialog.available(), "the old account's answer must not offer Share"); + dialog.receive(&ctx, 2, Ok(everything())); + assert!(dialog.available()); +} + #[test] fn an_unlinked_account_cannot_share_even_where_the_provider_can() { let ctx = Context::default(); From ef6df591b4b88080a95d18cd61016fde4e8a1be6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:14:33 -0800 Subject: [PATCH 044/490] craft-gpu-yuv: RGBA to NV12, P010 and I420 on the GPU --- ATTRIBUTION.md | 4 + Cargo.lock | 8 + Cargo.toml | 1 + README.md | 4 + crates/gpu-yuv/Cargo.toml | 17 ++ crates/gpu-yuv/README.md | 61 ++++++ crates/gpu-yuv/src/cpu.rs | 129 +++++++++++++ crates/gpu-yuv/src/gpu.rs | 356 +++++++++++++++++++++++++++++++++++ crates/gpu-yuv/src/layout.rs | 101 ++++++++++ crates/gpu-yuv/src/lib.rs | 27 +++ crates/gpu-yuv/src/spec.rs | 180 ++++++++++++++++++ crates/gpu-yuv/src/tests.rs | 344 +++++++++++++++++++++++++++++++++ 12 files changed, 1232 insertions(+) create mode 100644 crates/gpu-yuv/Cargo.toml create mode 100644 crates/gpu-yuv/README.md create mode 100644 crates/gpu-yuv/src/cpu.rs create mode 100644 crates/gpu-yuv/src/gpu.rs create mode 100644 crates/gpu-yuv/src/layout.rs create mode 100644 crates/gpu-yuv/src/lib.rs create mode 100644 crates/gpu-yuv/src/spec.rs create mode 100644 crates/gpu-yuv/src/tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ae72ae8515..edff4ec38f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -157,3 +157,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `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 color conversion + +`crates/gpu-yuv` comes from StudioCraft `crates/craft-gpu-yuv` at `8d8b6929e37217e0a3095cfc015b79c0e1e8e510` (MIT OR Apache-2.0). diff --git a/Cargo.lock b/Cargo.lock index cc0965d177..1e6c02533e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2137,6 +2137,14 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu-yuv" +version = "0.1.0" +dependencies = [ + "pollster 0.4.0", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index fd9ccf7a62..ab4bd99df3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } craft-wasm = { path = "crates/wasm" } +craft-gpu-yuv = { path = "crates/gpu-yuv" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } diff --git a/README.md b/README.md index e21de2e1a3..602deac549 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,10 @@ 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): RGBA to NV12, P010 and I420 on the GPU, scaled to + the output size, in BT.601, BT.709 and BT.2020 at limited or full range; each output texel + averages the part of the source it covers; read-back layouts and unpacking to a packed frame; + and the same conversion on the CPU. Encoders and scopes 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. diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml new file mode 100644 index 0000000000..4d37856c86 --- /dev/null +++ b/crates/gpu-yuv/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-gpu-yuv" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, with a CPU reference of the same conversion" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +wgpu = "30" + +[dev-dependencies] +pollster = "0.4" diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md new file mode 100644 index 0000000000..76cc76881d --- /dev/null +++ b/crates/gpu-yuv/README.md @@ -0,0 +1,61 @@ +# craft-gpu-yuv + +RGBA to 4:2:0 Y'CbCr on the GPU for the Craft apps' encoders and scopes: NV12, P010 and I420, +scaled to the output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. +`cpu::convert` is the same conversion on the CPU. The crate depends only on `wgpu` 30. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | +| `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | +| `Conversion` | one format, matrix and range | +| `Converter::new(device, conversion)` | the two render pipelines of one conversion; no per-frame state | +| `Converter::bind(device, view)` | a source texture view bound once, as a `Source` | +| `Converter::planes(device, width, height)` | the plane textures of one output size, as `Planes` | +| `Converter::draw(encoder, source, planes)` | records a luma pass and a chroma pass | +| `Planes::copy_to_buffer(encoder, buffer, offset)` | records the copies of every plane into a read-back buffer | +| `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | +| `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | + +## Sampling + +The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel +(luma at the output size, chroma at half the output size in both directions) takes the average +of up to 4 × 4 bilinear taps spread over the part of the source it covers: 1 tap per axis while +the source is at most twice the plane's size, and one more for each further 2:1 of reduction. +At the same size, each chroma sample is the average of the 2 × 2 pixels it covers, and its +position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of +the source between taps. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`). The shader rounds +each value half to even. P010 does not need wgpu's 16-bit norm feature. + +## Limits + +- The matrix applies to the stored values: the source must already be in the output's primaries + and transfer function. An sRGB view of the source gives linear values, which the matrix does + not expect; bind a non-sRGB view. Alpha is ignored, so premultiplied pixels convert as if they + were over black. +- Output sides must be even and not zero (`Error::OutputSize`), and no larger than the device's + largest 2D texture (`Error::TooLarge`). A layout whose byte sizes do not fit in `u32` rows, `u64` + offsets or a `usize` frame is `Error::Overflow`. `Converter::planes` refuses a read-back layout + larger than the device's largest buffer (`Error::BufferLimit`), and `cpu::convert` refuses an + output side over `cpu::MAX_SIDE` (16384). +- The source view must be a 2D view of a filterable float format, such as `Rgba8Unorm`, + `Bgra8Unorm` or `Rgba16Float`. +- `copy_to_buffer` needs an offset that is a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` + (`Error::Offset`) and a buffer of at least `buffer_size` bytes from it (`Error::BufferSize`). + `draw` refuses planes made for another format (`Error::Mismatch`). + +## Tests + +The CPU tests check standard code values (BT.709 limited-range red is 63, 102, 240), each +format's plane order, the area average of a reduction and the read-back layout. The GPU tests +convert pictures with hard edges at the same size, and smooth pictures at five scales, in every +format, and compare each sample with `cpu::convert`. The tolerance is 2 code values at 8 bits and +6 at 10 bits. A machine without a graphics +adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs new file mode 100644 index 0000000000..c268677091 --- /dev/null +++ b/crates/gpu-yuv/src/cpu.rs @@ -0,0 +1,129 @@ +//! The conversion on the CPU, sample for sample the rule the GPU passes follow. Tests compare the +//! two, and a caller without a GPU can use it directly. +//! +//! Each output texel (luma at the output size, chroma at half of it) takes the area of the source +//! under it: up to 4 × 4 bilinear taps spread over the texel's footprint, 1 per axis while the +//! source is at most twice the plane's size, one more for each further 2:1 of reduction. The +//! average of the taps goes through the matrix. At the same size the chroma tap lands between +//! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error}; + +/// The largest output side [`convert`] takes. +pub const MAX_SIDE: u32 = 16384; + +/// The taps along one axis for a reduction of `r` (source size over plane size). +pub(crate) fn taps(r: f32) -> u32 { + ((r * 0.5 - 0.001).ceil() as i32).clamp(1, 4) as u32 +} + +struct Image<'a> { + rgba: &'a [u8], + width: usize, + height: usize, +} + +impl Image<'_> { + fn pixel(&self, x: i64, y: i64) -> [f32; 3] { + let x = x.clamp(0, self.width as i64 - 1) as usize; + let y = y.clamp(0, self.height as i64 - 1) as usize; + let i = (y * self.width + x) * 4; + match self.rgba.get(i..i + 3) { + Some(p) => [f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0], + None => [0.0; 3], + } + } + + /// The linear filter at `(x, y)` in pixels (pixel centers at .5), clamped to the edges. + fn bilinear(&self, x: f32, y: f32) -> [f32; 3] { + let (x, y) = (x - 0.5, y - 0.5); + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let (xi, yi) = (x0 as i64, y0 as i64); + let [a, b, c, d] = [self.pixel(xi, yi), self.pixel(xi + 1, yi), self.pixel(xi, yi + 1), self.pixel(xi + 1, yi + 1)]; + let mut out = [0.0; 3]; + for k in 0..3 { + let top = a[k] + (b[k] - a[k]) * fx; + let bottom = c[k] + (d[k] - c[k]) * fx; + out[k] = top + (bottom - top) * fy; + } + out + } + + /// The average color under the texel centered at `pos` of a plane of `size` texels. + fn area(&self, pos: [f32; 2], size: [f32; 2]) -> [f32; 3] { + let s = [self.width as f32, self.height as f32]; + let r = [s[0] / size[0], s[1] / size[1]]; + let n = [taps(r[0]), taps(r[1])]; + let nf = [n[0] as f32, n[1] as f32]; + let step = [r[0] / nf[0], r[1] / nf[1]]; + let center = [pos[0] / size[0] * s[0], pos[1] / size[1] * s[1]]; + let mut sum = [0.0f32; 3]; + for j in 0..n[1] { + for i in 0..n[0] { + let px = center[0] + (i as f32 + 0.5 - nf[0] * 0.5) * step[0]; + let py = center[1] + (j as f32 + 0.5 - nf[1] * 0.5) * step[1]; + let c = self.bilinear(px, py); + for k in 0..3 { + sum[k] += c[k]; + } + } + } + let count = nf[0] * nf[1]; + [sum[0] / count, sum[1] / count, sum[2] / count] + } +} + +/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied +/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly +/// packed frame in [`FrameLayout`] order. +pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Conversion, width: u32, height: u32) -> Result, Error> { + let bytes = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || bytes != Some(rgba.len()) { + return Err(Error::Source { width: src_width, height: src_height, bytes: rgba.len() }); + } + if width > MAX_SIDE || height > MAX_SIDE { + return Err(Error::TooLarge { width, height, limit: MAX_SIDE }); + } + let layout = FrameLayout::new(conversion.format, width, height)?; + let image = Image { rgba, width: src_width as usize, height: src_height as usize }; + let c = Coefficients::of(conversion); + let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2); + let mut out = Vec::with_capacity(layout.frame_bytes()); + let mut put = |v: u16| { + let v = v << shift; + if wide { + out.extend_from_slice(&v.to_le_bytes()); + } else { + out.push(v as u8); + } + }; + let plane = |pw: u32, ph: u32, pick: &mut dyn FnMut([u16; 3])| { + let size = [pw as f32, ph as f32]; + for j in 0..ph { + for i in 0..pw { + pick(c.codes(image.area([i as f32 + 0.5, j as f32 + 0.5], size))); + } + } + }; + let (cw, ch) = (width / 2, height / 2); + plane(width, height, &mut |v| put(v[0])); + match conversion.format { + crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| { + put(v[1]); + put(v[2]); + }), + crate::Format::I420 => { + let mut cr = Vec::with_capacity(cw as usize * ch as usize); + plane(cw, ch, &mut |v| { + put(v[1]); + cr.push(v[2]); + }); + for v in cr { + put(v); + } + } + } + Ok(out) +} diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs new file mode 100644 index 0000000000..eb413e3c25 --- /dev/null +++ b/crates/gpu-yuv/src/gpu.rs @@ -0,0 +1,356 @@ +//! The conversion as render passes: one pass draws the luma plane, one draws the chroma plane or +//! planes, each into unsigned-integer textures that hold the exact stored words. + +use wgpu::util::DeviceExt; + +use crate::layout::FrameLayout; +use crate::spec::{Coefficients, Conversion, Error, Format}; + +/// The render pipelines of one [`Conversion`]. Make it once per device and conversion; it holds +/// no per-frame state. +pub struct Converter { + conversion: Conversion, + plane_layout: wgpu::BindGroupLayout, + source_layout: wgpu::BindGroupLayout, + luma: wgpu::RenderPipeline, + chroma: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +/// A source texture view bound for a [`Converter`]. Keep one per texture that is converted more +/// than once. +pub struct Source { + bind: wgpu::BindGroup, +} + +/// The plane textures of one output size, and their read-back layout. +pub struct Planes { + layout: FrameLayout, + textures: Vec, + views: Vec, + luma_bind: wgpu::BindGroup, + chroma_bind: wgpu::BindGroup, +} + +fn plane_formats(format: Format) -> &'static [wgpu::TextureFormat] { + use wgpu::TextureFormat as T; + match format { + Format::Nv12 => &[T::R8Uint, T::Rg8Uint], + Format::P010 => &[T::R16Uint, T::Rg16Uint], + Format::I420 => &[T::R8Uint, T::R8Uint, T::R8Uint], + } +} + +fn attachment(view: &wgpu::TextureView) -> Option> { + Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + }) +} + +fn vec3(w: [f32; 3]) -> String { + format!("vec3({:?}, {:?}, {:?})", w[0], w[1], w[2]) +} + +/// The WGSL of `conversion`, with its weights and scale written in as constants. +pub(crate) fn shader(conversion: Conversion) -> String { + let k = Coefficients::of(conversion); + let chroma = match conversion.format { + Format::Nv12 | Format::P010 => { + "@fragment fn fs_chroma(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = area(pos.xy); + return vec4(code(dot(c, CB) * CS + CO), code(dot(c, CR) * CS + CO), 0u, 0u); +}" + } + Format::I420 => { + "struct Chroma { @location(0) cb: vec4, @location(1) cr: vec4 } +@fragment fn fs_chroma(@builtin(position) pos: vec4) -> Chroma { + let c = area(pos.xy); + var o: Chroma; + o.cb = vec4(code(dot(c, CB) * CS + CO), 0u, 0u, 0u); + o.cr = vec4(code(dot(c, CR) * CS + CO), 0u, 0u, 0u); + return o; +}" + } + }; + format!( + "const KY = {ky}; +const CB = {cb}; +const CR = {cr}; +const YS = {ys:?}; +const YO = {yo:?}; +const CS = {cs:?}; +const CO = {co:?}; +const MAX = {max:?}; +const SHIFT = {shift}u; + +struct Plane {{ size: vec2, pad: vec2 }} +@group(0) @binding(0) var plane: Plane; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var samp: sampler; + +@vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 {{ + let x = f32((vi << 1u) & 2u); + let y = f32(vi & 2u); + return vec4(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0); +}} + +fn taps(r: f32) -> i32 {{ + return clamp(i32(ceil(r * 0.5 - 0.001)), 1, 4); +}} + +// The average color under the texel centered at `pos`: up to 4 x 4 bilinear taps over its +// footprint in the source. +fn area(pos: vec2) -> vec3 {{ + let src = vec2(textureDimensions(tex)); + let r = src / plane.size; + let n = vec2(taps(r.x), taps(r.y)); + let nf = vec2(n); + let step = r / nf; + let center = pos / plane.size * src; + var sum = vec3(0.0); + for (var j = 0; j < n.y; j++) {{ + for (var i = 0; i < n.x; i++) {{ + let p = center + (vec2(f32(i), f32(j)) + 0.5 - nf * 0.5) * step; + sum += textureSampleLevel(tex, samp, p / src, 0.0).rgb; + }} + }} + return sum / (nf.x * nf.y); +}} + +fn code(v: f32) -> u32 {{ + return u32(clamp(round(v), 0.0, MAX)) << SHIFT; +}} + +@fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ + return vec4(code(dot(area(pos.xy), KY) * YS + YO), 0u, 0u, 0u); +}} + +{chroma} +", + ky = vec3(k.y), + cb = vec3(k.cb), + cr = vec3(k.cr), + ys = k.y_scale, + yo = k.y_offset, + cs = k.c_scale, + co = k.c_offset, + max = k.max, + shift = conversion.format.shift(), + ) +} + +impl Converter { + /// The pipelines of `conversion` on `device`. + pub fn new(device: &wgpu::Device, conversion: Conversion) -> Converter { + let plane_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv plane"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(16), + }, + count: None, + }], + }); + let source_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("yuv source"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("yuv"), + bind_group_layouts: &[Some(&plane_layout), Some(&source_layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(conversion.format.name()), + source: wgpu::ShaderSource::Wgsl(shader(conversion).into()), + }); + let target = |format| Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL }); + let formats = plane_formats(conversion.format); + let pipeline = |label: &str, fs: &str, targets: &[Option]| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(fs), targets, compilation_options: Default::default() }), + multiview_mask: None, + cache: None, + }) + }; + let luma = pipeline("yuv luma", "fs_luma", &[target(formats[0])]); + let chroma_targets: Vec<_> = formats[1..].iter().map(|f| target(*f)).collect(); + let chroma = pipeline("yuv chroma", "fs_chroma", &chroma_targets); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("yuv linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Converter { conversion, plane_layout, source_layout, luma, chroma, sampler } + } + + pub fn conversion(&self) -> Conversion { + self.conversion + } + + /// Bind `view` as a source. The view must be a 2D view of a filterable float format, such as + /// `Rgba8Unorm` or `Bgra8Unorm`; an sRGB view gives linear values, which the matrix does not + /// expect. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> Source { + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv source"), + layout: &self.source_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + Source { bind } + } + + /// Plane textures for frames of `width × height`. Both sides must be even, not zero, and no + /// larger than the device's largest 2D texture. + pub fn planes(&self, device: &wgpu::Device, width: u32, height: u32) -> Result { + let limit = device.limits().max_texture_dimension_2d; + if width > limit || height > limit { + return Err(Error::TooLarge { width, height, limit }); + } + let layout = FrameLayout::new(self.conversion.format, width, height)?; + let max = device.limits().max_buffer_size; + if layout.buffer_size > max { + return Err(Error::BufferLimit { needed: layout.buffer_size, limit: max }); + } + let formats = plane_formats(self.conversion.format); + let textures: Vec = layout + .planes + .iter() + .zip(formats) + .map(|(p, format)| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("yuv plane"), + size: wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: *format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }) + .collect(); + let views = textures.iter().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())).collect(); + let uniform = |w: u32, h: u32| { + let mut bytes = [0u8; 16]; + bytes[..4].copy_from_slice(&(w as f32).to_le_bytes()); + bytes[4..8].copy_from_slice(&(h as f32).to_le_bytes()); + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("yuv plane size"), + contents: &bytes, + usage: wgpu::BufferUsages::UNIFORM, + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("yuv plane"), + layout: &self.plane_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }], + }) + }; + let luma_bind = uniform(width, height); + let chroma_bind = uniform(width / 2, height / 2); + Ok(Planes { layout, textures, views, luma_bind, chroma_bind }) + } + + /// Record the passes that convert `source` into `planes`. + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, source: &Source, planes: &Planes) -> Result<(), Error> { + if planes.layout.format != self.conversion.format { + return Err(Error::Mismatch { converter: self.conversion.format, planes: planes.layout.format }); + } + // No allocation per frame: one luma view, then one or two chroma views. + let chroma_count = planes.views.len().saturating_sub(1).min(2); + let luma = [planes.views.first().and_then(attachment)]; + let chroma = [planes.views.get(1).and_then(attachment), planes.views.get(2).and_then(attachment)]; + let passes: [(&wgpu::RenderPipeline, &wgpu::BindGroup, &[Option>]); 2] = + [(&self.luma, &planes.luma_bind, &luma), (&self.chroma, &planes.chroma_bind, &chroma[..chroma_count])]; + for (pipeline, plane, attachments) in passes { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("yuv"), + color_attachments: attachments, + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, plane, &[]); + pass.set_bind_group(1, &source.bind, &[]); + pass.draw(0..3, 0..1); + } + Ok(()) + } +} + +impl Planes { + pub fn layout(&self) -> &FrameLayout { + &self.layout + } + + /// The plane textures, luma first. + pub fn textures(&self) -> &[wgpu::Texture] { + &self.textures + } + + /// Record copies of every plane into `buffer` from `offset`, in the [`FrameLayout`]'s + /// places. `offset` must be a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`, and the + /// buffer must hold `layout().buffer_size` bytes from it. + pub fn copy_to_buffer(&self, encoder: &mut wgpu::CommandEncoder, buffer: &wgpu::Buffer, offset: u64) -> Result<(), Error> { + if !offset.is_multiple_of(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) { + return Err(Error::Offset(offset)); + } + let needed = offset.saturating_add(self.layout.buffer_size); + if buffer.size() < needed { + return Err(Error::BufferSize { needed, actual: buffer.size() }); + } + for (texture, p) in self.textures.iter().zip(&self.layout.planes) { + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: offset + p.offset, + bytes_per_row: Some(p.bytes_per_row), + rows_per_image: Some(p.height), + }, + }, + wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + ); + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs new file mode 100644 index 0000000000..b5d4bbf170 --- /dev/null +++ b/crates/gpu-yuv/src/layout.rs @@ -0,0 +1,101 @@ +//! Where each plane sits in a read-back buffer and in a tightly packed frame. + +use crate::spec::{Error, Format}; + +/// One plane: its size in texels, the bytes of one texel, and where its rows start in a +/// read-back buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub width: u32, + pub height: u32, + /// Bytes per texel: 1 or 2 for one sample, 2 or 4 for an interleaved Cb and Cr pair. + pub texel_bytes: u32, + /// The plane's first byte in the read-back buffer. + pub offset: u64, + /// Bytes from one row to the next in the read-back buffer, a multiple of + /// `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + pub bytes_per_row: u32, +} + +impl PlaneLayout { + /// Bytes of one row in a packed frame. + pub fn row_bytes(&self) -> u32 { + self.width * self.texel_bytes + } +} + +/// The planes of one frame of `format` at `width × height`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FrameLayout { + pub format: Format, + pub width: u32, + pub height: u32, + pub planes: Vec, + /// Bytes a read-back buffer needs from its offset. + pub buffer_size: u64, +} + +fn aligned(n: u32) -> Option { + let a = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + n.div_ceil(a).checked_mul(a) +} + +impl FrameLayout { + /// The layout of `format` at `width × height`; both sides must be even and not zero. + pub fn new(format: Format, width: u32, height: u32) -> Result { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let sizes: Vec<(u32, u32, u32)> = match format { + Format::Nv12 | Format::P010 => vec![(width, height, s), (cw, ch, 2 * s)], + Format::I420 => vec![(width, height, s), (cw, ch, s), (cw, ch, s)], + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = Vec::with_capacity(sizes.len()); + for (w, h, texel_bytes) in sizes { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + planes.push(PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }); + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok(FrameLayout { format, width, height, planes, buffer_size: offset }) + } + + /// Bytes of one tightly packed frame: the planes one after another, each row without padding. + pub fn frame_bytes(&self) -> usize { + self.planes.iter().map(|p| p.row_bytes() as usize * p.height as usize).sum() + } + + /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) + /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if (padded.len() as u64) < self.buffer_size { + return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); + } + let tight = self.frame_bytes(); + if frame.len() != tight { + return Err(Error::BufferSize { needed: tight as u64, actual: frame.len() as u64 }); + } + let mut out = frame; + for p in &self.planes { + let (row, padded_row) = (p.row_bytes() as usize, p.bytes_per_row as usize); + let (dst, rest) = out.split_at_mut(row * p.height as usize); + let src = padded.get(p.offset as usize..).unwrap_or_default(); + for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { + // The size check above leaves every row whole. + if let Some(s) = s.get(..row) { + d.copy_from_slice(s); + } + } + out = rest; + } + Ok(()) + } +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs new file mode 100644 index 0000000000..220fa5b3d0 --- /dev/null +++ b/crates/gpu-yuv/src/lib.rs @@ -0,0 +1,27 @@ +//! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. +//! +//! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full). +//! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane +//! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled +//! to the output size. +//! - [`Planes::copy_to_buffer`] records the copies into a read-back buffer, and +//! [`FrameLayout::unpack`] turns the mapped buffer into one tightly packed frame. +//! - [`cpu::convert`] is the same conversion on the CPU. +//! +//! The matrix applies to the stored values as they are: the input must already be in the +//! output's primaries and transfer, and alpha is ignored. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod cpu; +mod gpu; +mod layout; +mod spec; + +pub use gpu::{Converter, Planes, Source}; +pub use layout::{FrameLayout, PlaneLayout}; +pub use spec::{Conversion, Error, Format, Matrix, Range}; + +#[cfg(test)] +mod tests; diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs new file mode 100644 index 0000000000..e11be59098 --- /dev/null +++ b/crates/gpu-yuv/src/spec.rs @@ -0,0 +1,180 @@ +//! What a conversion produces: the plane format, the matrix and the range, and the code values +//! they give. + +use std::fmt; + +/// The 4:2:0 layout a conversion writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Format { + /// 8 bits: the luma plane, then one plane of interleaved Cb and Cr samples. + Nv12, + /// 10 bits in the high bits of little-endian 16-bit words: the luma plane, then one plane of + /// interleaved Cb and Cr samples. + P010, + /// 8 bits: the luma plane, then the Cb plane, then the Cr plane. + I420, +} + +impl Format { + /// Bits per sample value. + pub fn bits(self) -> u32 { + match self { + Format::P010 => 10, + Format::Nv12 | Format::I420 => 8, + } + } + + /// Bytes each sample takes in memory. + pub fn sample_bytes(self) -> u32 { + match self { + Format::P010 => 2, + Format::Nv12 | Format::I420 => 1, + } + } + + /// The left shift from a sample value to the stored word: 6 for P010, else 0. + pub fn shift(self) -> u32 { + match self { + Format::P010 => 6, + Format::Nv12 | Format::I420 => 0, + } + } + + /// The format's usual name: `NV12`, `P010` or `I420`. + pub fn name(self) -> &'static str { + match self { + Format::Nv12 => "NV12", + Format::P010 => "P010", + Format::I420 => "I420", + } + } +} + +impl fmt::Display for Format { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The RGB to Y'CbCr matrix (ITU-R BT.601, BT.709 and BT.2020 non-constant luminance). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Matrix { + Bt601, + Bt709, + Bt2020, +} + +impl Matrix { + /// The red and blue luma weights, Kr and Kb. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } + } +} + +/// The code values the signal spans. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Range { + /// Luma from 16 to 235 and chroma from 16 to 240, scaled by 4 at 10 bits. + Limited, + /// Every code value, from 0 to 255 (1023 at 10 bits); chroma is centered on 128 (512). + Full, +} + +/// One conversion: the plane format, the matrix and the range. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Conversion { + pub format: Format, + pub matrix: Matrix, + pub range: Range, +} + +impl Conversion { + pub fn new(format: Format, matrix: Matrix, range: Range) -> Conversion { + Conversion { format, matrix, range } + } +} + +/// The weights and the scale of one conversion. The code value of luma is +/// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr +/// `dot(cr, rgb) * c_scale + c_offset`, rounded half to even and clamped to `0..=max`, for `rgb` +/// from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Coefficients { + pub y: [f32; 3], + pub cb: [f32; 3], + pub cr: [f32; 3], + pub y_scale: f32, + pub y_offset: f32, + pub c_scale: f32, + pub c_offset: f32, + pub max: f32, +} + +impl Coefficients { + pub fn of(c: Conversion) -> Coefficients { + let (kr, kb) = c.matrix.kr_kb(); + let kg = 1.0 - kr - kb; + let (db, dr) = (2.0 * (1.0 - kb), 2.0 * (1.0 - kr)); + let bits = c.format.bits(); + let max = ((1u32 << bits) - 1) as f32; + let step = (1u32 << (bits - 8)) as f32; + let (y_scale, y_offset, c_scale, c_offset) = match c.range { + Range::Limited => (219.0 * step, 16.0 * step, 224.0 * step, 128.0 * step), + Range::Full => (max, 0.0, max, (1u32 << (bits - 1)) as f32), + }; + Coefficients { y: [kr, kg, kb], cb: [-kr / db, -kg / db, 0.5], cr: [0.5, -kg / dr, -kb / dr], y_scale, y_offset, c_scale, c_offset, max } + } + + /// The code values of luma, Cb and Cr for `rgb`. + pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { + let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; + let code = |v: f32| v.round_ties_even().clamp(0.0, self.max) as u16; + [ + code(dot(self.y) * self.y_scale + self.y_offset), + code(dot(self.cb) * self.c_scale + self.c_offset), + code(dot(self.cr) * self.c_scale + self.c_offset), + ] + } +} + +/// What a conversion cannot do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// An output side is zero or odd; 4:2:0 needs both sides even. + OutputSize { width: u32, height: u32 }, + /// A side is larger than the device's largest 2D texture. + TooLarge { width: u32, height: u32, limit: u32 }, + /// The frame's byte sizes do not fit in the integer types that hold them. + Overflow { width: u32, height: u32 }, + /// A read-back buffer for the frame would be larger than the device's largest buffer. + BufferLimit { needed: u64, limit: u64 }, + /// A source side is zero, or the pixels are not `width × height × 4` bytes. + Source { width: u32, height: u32, bytes: usize }, + /// A buffer or a frame does not have the size the layout needs. + BufferSize { needed: u64, actual: u64 }, + /// A buffer offset is not a multiple of `wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`. + Offset(u64), + /// The planes were made for another format than the converter's. + Mismatch { converter: Format, planes: Format }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::OutputSize { width, height } => write!(f, "a 4:2:0 picture of {width}×{height} needs both sides even and not zero"), + Error::TooLarge { width, height, limit } => write!(f, "{width}×{height} is larger than the largest texture side, {limit}"), + Error::Overflow { width, height } => write!(f, "a frame of {width}×{height} is too large to hold"), + Error::BufferLimit { needed, limit } => write!(f, "a read-back buffer of {needed} bytes is larger than the largest buffer, {limit}"), + Error::Source { width, height, bytes } => write!(f, "{bytes} bytes are not an RGBA picture of {width}×{height}"), + Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), + Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs new file mode 100644 index 0000000000..ad0476effd --- /dev/null +++ b/crates/gpu-yuv/src/tests.rs @@ -0,0 +1,344 @@ +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +fn solid(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect() +} + +/// The first luma sample and the first Cb and Cr samples of a converted frame, as values. +fn first(frame: &[u8], format: Format, w: u32, h: u32) -> [u16; 3] { + let s = samples(frame, format); + let luma = (w * h) as usize; + let quarter = luma / 4; + match format { + Format::Nv12 | Format::P010 => [s[0], s[luma], s[luma + 1]], + Format::I420 => [s[0], s[luma], s[luma + quarter]], + } +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +fn cpu(rgb: [u8; 3], c: Conversion) -> [u16; 3] { + let frame = cpu::convert(&solid(2, 2, rgb), 2, 2, c, 2, 2).unwrap(); + first(&frame, c.format, 2, 2) +} + +#[test] +fn bt709_limited_colors_have_their_standard_codes() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + assert_eq!(cpu([255, 255, 255], c), [235, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [16, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [63, 102, 240]); + assert_eq!(cpu([0, 0, 255], c), [32, 240, 118]); +} + +#[test] +fn each_matrix_weights_red_by_its_kr() { + let red = |m| cpu([255, 0, 0], Conversion::new(Format::Nv12, m, Range::Limited)); + assert_eq!(red(Matrix::Bt601), [81, 90, 240]); + assert_eq!(red(Matrix::Bt2020), [74, 97, 240]); +} + +#[test] +fn full_range_spans_every_code() { + let c = Conversion::new(Format::I420, Matrix::Bt709, Range::Full); + assert_eq!(cpu([255, 255, 255], c), [255, 128, 128]); + assert_eq!(cpu([0, 0, 0], c), [0, 128, 128]); + assert_eq!(cpu([255, 0, 0], c), [54, 99, 255]); +} + +#[test] +fn p010_holds_ten_bit_codes_in_the_high_bits() { + let limited = Conversion::new(Format::P010, Matrix::Bt2020, Range::Limited); + assert_eq!(cpu([255, 255, 255], limited), [940, 512, 512]); + assert_eq!(cpu([0, 0, 0], limited), [64, 512, 512]); + let full = Conversion::new(Format::P010, Matrix::Bt2020, Range::Full); + assert_eq!(cpu([255, 255, 255], full), [1023, 512, 512]); + let frame = cpu::convert(&solid(2, 2, [255, 255, 255]), 2, 2, limited, 2, 2).unwrap(); + assert_eq!(&frame[..2], &(940u16 << 6).to_le_bytes()); + assert_eq!(frame.len(), 12); +} + +#[test] +fn planes_follow_each_format_s_order() { + let red = solid(4, 2, [255, 0, 0]); + let nv12 = cpu::convert(&red, 4, 2, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(nv12, [63, 63, 63, 63, 63, 63, 63, 63, 102, 240, 102, 240]); + let i420 = cpu::convert(&red, 4, 2, Conversion::new(Format::I420, Matrix::Bt709, Range::Limited), 4, 2).unwrap(); + assert_eq!(i420, [63, 63, 63, 63, 63, 63, 63, 63, 102, 102, 240, 240]); +} + +#[test] +fn chroma_at_the_same_size_averages_the_four_pixels_it_covers() { + // Red over blue: chroma is the code of their average, magenta at half strength. + let mut px = solid(2, 1, [255, 0, 0]); + px.extend(solid(2, 1, [0, 0, 255])); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 2, 2, c, 2, 2).unwrap(); + let half = cpu([128, 0, 128], c); + assert!(frame[4].abs_diff(half[1] as u8) <= 1 && frame[5].abs_diff(half[2] as u8) <= 1, "{frame:?} {half:?}"); +} + +#[test] +fn a_reduction_averages_the_area_under_each_texel() { + // One white column in four: a 4:1 reduction gives a quarter of white, where one bilinear tap + // at the texel's center would land between two black columns. + let px: Vec = (0..16).flat_map(|i| if i % 4 == 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Full); + let frame = cpu::convert(&px, 8, 2, c, 2, 2).unwrap(); + assert_eq!(&frame[..4], &[64, 64, 64, 64]); +} + +#[test] +fn the_tap_count_grows_with_the_reduction_up_to_four() { + assert_eq!([0.5, 1.0, 2.0, 2.01, 4.0, 4.5, 8.0, 100.0].map(cpu::taps), [1, 1, 1, 2, 2, 3, 4, 4]); +} + +#[test] +fn bad_sizes_are_errors() { + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let px = solid(2, 2, [0, 0, 0]); + assert_eq!(cpu::convert(&px, 2, 2, c, 3, 2).unwrap_err(), Error::OutputSize { width: 3, height: 2 }); + assert_eq!(cpu::convert(&px, 2, 2, c, 0, 0).unwrap_err(), Error::OutputSize { width: 0, height: 0 }); + assert_eq!(cpu::convert(&px, 2, 3, c, 2, 2).unwrap_err(), Error::Source { width: 2, height: 3, bytes: 16 }); + assert_eq!(cpu::convert(&[], 0, 0, c, 2, 2).unwrap_err(), Error::Source { width: 0, height: 0, bytes: 0 }); + assert_eq!(FrameLayout::new(Format::P010, 4, 5).unwrap_err(), Error::OutputSize { width: 4, height: 5 }); + let big = cpu::MAX_SIDE + 2; + assert_eq!(cpu::convert(&px, 2, 2, c, big, 2).unwrap_err(), Error::TooLarge { width: big, height: 2, limit: cpu::MAX_SIDE }); + // Byte sizes past the integer types are an error, not an overflow. + let huge = u32::MAX - 1; + assert_eq!(FrameLayout::new(Format::P010, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(FrameLayout::new(Format::Nv12, huge, 2).unwrap_err(), Error::Overflow { width: huge, height: 2 }); + assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero"); +} + +#[test] +fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { + let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap(); + assert_eq!( + l.planes.iter().map(|p| (p.width, p.height, p.offset, p.bytes_per_row)).collect::>(), + [(1920, 1080, 0, 2048), (960, 540, 2048 * 1080, 2048)] + ); + assert_eq!((l.buffer_size, l.frame_bytes()), (2048 * 1620, 1920 * 1620)); + let p = FrameLayout::new(Format::P010, 640, 360).unwrap(); + assert_eq!((p.planes[0].bytes_per_row, p.planes[1].texel_bytes, p.frame_bytes()), (1280, 4, 640 * 360 * 3)); + let i = FrameLayout::new(Format::I420, 4, 2).unwrap(); + assert_eq!(i.planes.iter().map(|p| p.offset).collect::>(), [0, 512, 768]); + let mut padded = vec![0u8; i.buffer_size as usize]; + padded[..4].copy_from_slice(&[1, 2, 3, 4]); + padded[256..260].copy_from_slice(&[5, 6, 7, 8]); + padded[512..514].copy_from_slice(&[9, 10]); + padded[768..770].copy_from_slice(&[11, 12]); + let mut frame = vec![0u8; i.frame_bytes()]; + i.unpack(&padded, &mut frame).unwrap(); + assert_eq!(frame, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert_eq!(i.unpack(&padded[..100], &mut frame).unwrap_err(), Error::BufferSize { needed: 1024, actual: 100 }); + assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); +} + +#[test] +fn an_enlarged_solid_color_keeps_its_codes() { + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&solid(3, 1, [10, 200, 90]), 3, 1, c, 8, 6).unwrap(); + let expect = cpu([10, 200, 90], c); + let s = samples(&frame, format); + assert_eq!(s.len(), 8 * 6 * 3 / 2); + assert!(s[..48].iter().all(|&v| v == expect[0]), "{format}"); + } +} + +#[test] +fn shaders_write_no_value_wgsl_cannot_read() { + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let s = gpu::shader(Conversion::new(format, matrix, range)); + assert!(!s.contains("NaN") && !s.contains("inf"), "{s}"); + assert!(s.contains("fn fs_chroma") && s.contains("fn fs_luma")); + } + } + } +} + +// The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips +// these comparisons and says so on stderr. + +fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(|l| l) +} + +/// A device with the adapter's limits as `limits` changes them. +fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("no graphics adapter: the GPU half of this test is skipped"); + return None; + }; + let desc = wgpu::DeviceDescriptor { required_limits: limits(adapter.limits()), ..Default::default() }; + match pollster::block_on(adapter.request_device(&desc)) { + Ok(d) => Some(d), + Err(e) => { + eprintln!("the graphics adapter did not open ({e}): the GPU half of this test is skipped"); + None + } + } +} + +/// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). +fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { + let ((rgba, sw, sh), (w, h)) = (src, out); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + texture.as_image_copy(), + rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }, + wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + ); + let converter = Converter::new(device, c); + let source = converter.bind(device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(device, w, h).unwrap(); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 256 + planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + converter.draw(&mut enc, &source, &planes).unwrap(); + planes.copy_to_buffer(&mut enc, &buffer, 256).unwrap(); + queue.submit([enc.finish()]); + buffer.map_async(wgpu::MapMode::Read, 256.., |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let view = buffer.get_mapped_range(256..).unwrap(); + let mut frame = vec![0; planes.layout().frame_bytes()]; + planes.layout().unpack(&view, &mut frame).unwrap(); + frame +} + +/// The tolerance in code values: 2 at 8 bits and 6 at 10 bits. GPUs filter with fewer bits of +/// weight than `f32` and may round a half the other way. +fn tolerance(format: Format) -> u16 { + if format.bits() == 10 { 6 } else { 2 } +} + +fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { + assert_eq!(gpu.len(), cpu.len(), "{what}"); + let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); + let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); + if let Some((i, (a, b))) = worst { + assert!(a.abs_diff(*b) <= tolerance(c.format), "{what} {c:?}: sample {i} is {a} on the GPU and {b} on the CPU"); + } +} + +/// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. +fn noise(w: u32, h: u32) -> Vec { + let mut x = 0x2545_f491_u32; + (0..w * h * 4) + .map(|i| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + if i % 4 == 3 { 255 } else { (x >> 24) as u8 } + }) + .collect() +} + +/// A smooth picture: three ramps at different angles. +fn ramps(w: u32, h: u32) -> Vec { + (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + [(u * 255.0) as u8, (v * 255.0) as u8, ((1.0 - (u + v) * 0.5) * 255.0) as u8, 255] + }) + }) + .collect() +} + +#[test] +fn the_gpu_matches_the_cpu_at_the_same_size() { + let Some((device, queue)) = device() else { return }; + let px = noise(64, 36); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let g = gpu_convert(&device, &queue, (&px, 64, 36), c, (64, 36)); + assert_close(&g, &cpu::convert(&px, 64, 36, c, 64, 36).unwrap(), c, "64×36 at the same size"); + } + } + } +} + +#[test] +fn the_gpu_matches_the_cpu_when_scaling() { + let Some((device, queue)) = device() else { return }; + let px = ramps(160, 90); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (32, 18), (16, 10), (240, 136)] { + let g = gpu_convert(&device, &queue, (&px, 160, 90), c, (w, h)); + assert_close(&g, &cpu::convert(&px, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h}")); + } + let odd = ramps(37, 23); + let g = gpu_convert(&device, &queue, (&odd, 37, 23), c, (20, 12)); + assert_close(&g, &cpu::convert(&odd, 37, 23, c, 20, 12).unwrap(), c, "37×23 to 20×12"); + } +} + +#[test] +fn planes_larger_than_the_device_allows_are_errors() { + // The queue stays alive: a device whose queue was dropped cannot make an encoder. + let Some((device, _queue)) = device() else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + let limit = device.limits().max_texture_dimension_2d; + let too_big = (limit + 2) & !1; + assert_eq!(converter.planes(&device, too_big, 2).err(), Some(Error::TooLarge { width: too_big, height: 2, limit })); + let planes = converter.planes(&device, 4, 2).unwrap(); + let other = Converter::new(&device, Conversion::new(Format::P010, Matrix::Bt709, Range::Limited)); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 4, height: 2, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let source = other.bind(&device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + assert_eq!(other.draw(&mut enc, &source, &planes).unwrap_err(), Error::Mismatch { converter: Format::P010, planes: Format::Nv12 }); + let small = + device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 256, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 0).unwrap_err(), Error::BufferSize { needed: 768, actual: 256 }); + assert_eq!(planes.copy_to_buffer(&mut enc, &small, 4).unwrap_err(), Error::Offset(4)); +} + +#[test] +fn planes_whose_read_back_is_larger_than_the_largest_buffer_are_errors() { + let Some((device, _queue)) = device_with(|l| wgpu::Limits { max_buffer_size: 1 << 20, ..l }) else { return }; + let converter = Converter::new(&device, Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited)); + // 1024 × 1024 NV12 reads back 1.5 MiB. + assert_eq!(converter.planes(&device, 1024, 1024).err(), Some(Error::BufferLimit { needed: 1024 * 1536, limit: 1 << 20 })); + assert!(converter.planes(&device, 512, 512).is_ok()); +} From 228e53c90422e40fccb15142796dded4b2afa272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:25:36 -0800 Subject: [PATCH 045/490] craft-gpu-yuv: drop the source line from ATTRIBUTION.md --- ATTRIBUTION.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index edff4ec38f..ae72ae8515 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -157,7 +157,3 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `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 color conversion - -`crates/gpu-yuv` comes from StudioCraft `crates/craft-gpu-yuv` at `8d8b6929e37217e0a3095cfc015b79c0e1e8e510` (MIT OR Apache-2.0). From 30a5407a74f6245fe820ebad7f53e5e99873b85c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:25:37 -0800 Subject: [PATCH 046/490] craft-gpu-device: keep only third-party sources in ATTRIBUTION.md --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f2c076c222..96091a1b5a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -144,4 +144,4 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## GPU device selection -`crates/gpu-device` comes from StudioCraft `crates/craft-gpu-device` at `17e2120f7d79bb677e2871a4192ba1ced1dab57a` (MIT OR Apache-2.0). Its 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. +`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. From 50b82932cadb25ac99d9ab6ad8ff1227ca337394 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:33:20 -0800 Subject: [PATCH 047/490] craft-gpu-device: Software draws with the newest version of a driver listed twice Preference::Software took the first usable software entry without the correction Auto, LowPower and Adapter apply. When one driver listed a software adapter twice, a stale version could be chosen, and the fallback order then left the newer one out. Every preference now goes through the same correction. --- crates/gpu-device/src/preference.rs | 36 +++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs index 7a60529c70..a9a107e9a8 100644 --- a/crates/gpu-device/src/preference.rs +++ b/crates/gpu-device/src/preference.rs @@ -137,8 +137,8 @@ pub struct Selection { /// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when /// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and /// [`Notice::AdapterMissing`]. -/// - [`Preference::Software`] uses the first usable software adapter; without one, the automatic -/// choice and [`Notice::NoSoftwareAdapter`]. +/// - [`Preference::Software`] uses the first usable software adapter, with [`choose`]'s +/// corrections; without one, the automatic choice and [`Notice::NoSoftwareAdapter`]. /// /// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { @@ -151,16 +151,14 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Some(index), - _ => { - notices.push(Notice::AdapterMissing(key.clone())); - None - } + let found = found.and_then(|(index, _)| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::AdapterMissing(key.clone())); } + found } Preference::Software => { - let found = candidates.iter().position(|c| c.usable && c.is_software()); + let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index)); if found.is_none() { notices.push(Notice::NoSoftwareAdapter); } @@ -180,6 +178,15 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Option { + let index = corrected(candidates, index, candidates.get(index)?); + (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) +} + /// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key /// of this adapter. #[cfg(not(target_arch = "wasm32"))] @@ -332,6 +339,17 @@ mod tests { } } + #[test] + fn software_draws_with_the_newer_version_of_a_driver_listed_twice() { + let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40); + let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50); + let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36); + let adapters = vec![stale, newer, hardware]; + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] })); + // the stale entry is never tried, and the newer one is not left out + assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]); + } + #[test] fn the_fallback_order_never_tries_entries_that_can_crash() { let adapters = two_amd_drivers(); From e66c13b9bf139d44cd4e3c76c9e836aabe135dd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:23:21 -0800 Subject: [PATCH 048/490] craft-gpu-yuv: unpack refuses a layout whose fields were changed FrameLayout's fields are public, so a caller can change a layout after FrameLayout::new made it. unpack now compares the layout with the one FrameLayout::new gives for its format and size and returns Error::Layout when they differ, instead of panicking on a zero row length or returning Ok with rows left out. --- crates/gpu-yuv/src/layout.rs | 6 +++++- crates/gpu-yuv/src/spec.rs | 4 ++++ crates/gpu-yuv/src/tests.rs | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs index b5d4bbf170..4d3db5321e 100644 --- a/crates/gpu-yuv/src/layout.rs +++ b/crates/gpu-yuv/src/layout.rs @@ -75,7 +75,11 @@ impl FrameLayout { /// Copy the planes from `padded` (a mapped read-back buffer, from the offset it was copied to) /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. + /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { + if FrameLayout::new(self.format, self.width, self.height).as_ref() != Ok(self) { + return Err(Error::Layout); + } if (padded.len() as u64) < self.buffer_size { return Err(Error::BufferSize { needed: self.buffer_size, actual: padded.len() as u64 }); } @@ -89,7 +93,7 @@ impl FrameLayout { let (dst, rest) = out.split_at_mut(row * p.height as usize); let src = padded.get(p.offset as usize..).unwrap_or_default(); for (d, s) in dst.chunks_exact_mut(row).zip(src.chunks(padded_row)) { - // The size check above leaves every row whole. + // The layout and size checks above leave every row whole. if let Some(s) = s.get(..row) { d.copy_from_slice(s); } diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index e11be59098..cb852b8761 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -160,6 +160,9 @@ pub enum Error { Offset(u64), /// The planes were made for another format than the converter's. Mismatch { converter: Format, planes: Format }, + /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and + /// size. + Layout, } impl fmt::Display for Error { @@ -173,6 +176,7 @@ impl fmt::Display for Error { Error::BufferSize { needed, actual } => write!(f, "{actual} bytes where {needed} are needed"), Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), + Error::Layout => f.write_str("the frame layout does not match its format and size"), } } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index ad0476effd..1db1ef20d8 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -145,6 +145,27 @@ fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() { assert_eq!(i.unpack(&padded, &mut [0; 3]).unwrap_err(), Error::BufferSize { needed: 12, actual: 3 }); } +#[test] +fn unpack_refuses_a_layout_that_was_changed_after_it_was_made() { + let l = FrameLayout::new(Format::I420, 4, 2).unwrap(); + let padded = vec![0u8; l.buffer_size as usize]; + let changes: [fn(&mut FrameLayout); 6] = [ + |l| l.planes[0].bytes_per_row = 0, + |l| l.planes[0].width = 0, + |l| l.planes[0].texel_bytes = 0, + |l| l.planes[0].offset = 768, + |l| l.planes[0].bytes_per_row = 2, + |l| l.planes.truncate(1), + ]; + for (n, change) in changes.iter().enumerate() { + let mut bad = l.clone(); + change(&mut bad); + let mut frame = vec![0u8; bad.frame_bytes()]; + assert_eq!(bad.unpack(&padded, &mut frame), Err(Error::Layout), "change {n}"); + } + assert_eq!(Error::Layout.to_string(), "the frame layout does not match its format and size"); +} + #[test] fn an_enlarged_solid_color_keeps_its_codes() { for format in ALL { From ffd6453e34bc6485d2c7f8f3d9f17aa0b2d21a9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:26:32 -0800 Subject: [PATCH 049/490] craft-gpu-yuv: the layout check in unpack does not allocate unpack runs once per frame. The check now builds the expected planes in a stack array instead of a FrameLayout with its own Vec. --- crates/gpu-yuv/src/layout.rs | 62 ++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/gpu-yuv/src/layout.rs b/crates/gpu-yuv/src/layout.rs index 4d3db5321e..7898aa76d9 100644 --- a/crates/gpu-yuv/src/layout.rs +++ b/crates/gpu-yuv/src/layout.rs @@ -40,32 +40,46 @@ fn aligned(n: u32) -> Option { n.div_ceil(a).checked_mul(a) } +/// The planes of `format` at `width × height` (the first `count` of the array) and the read-back +/// buffer size. +fn planes_of(format: Format, width: u32, height: u32) -> Result<([PlaneLayout; 3], usize, u64), Error> { + if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { + return Err(Error::OutputSize { width, height }); + } + let s = format.sample_bytes(); + let (cw, ch) = (width / 2, height / 2); + let (sizes, count) = match format { + Format::Nv12 | Format::P010 => ([(width, height, s), (cw, ch, 2 * s), (0, 0, 0)], 2), + Format::I420 => ([(width, height, s), (cw, ch, s), (cw, ch, s)], 3), + }; + let overflow = Error::Overflow { width, height }; + let mut offset = 0u64; + let mut tight = 0u64; + let mut planes = [PlaneLayout { width: 0, height: 0, texel_bytes: 0, offset: 0, bytes_per_row: 0 }; 3]; + for (plane, (w, h, texel_bytes)) in planes.iter_mut().zip(sizes).take(count) { + let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; + let bytes_per_row = aligned(row).ok_or(overflow.clone())?; + *plane = PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }; + offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; + tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; + } + // A packed frame must also fit in memory on this target. + usize::try_from(tight).map_err(|_| overflow)?; + Ok((planes, count, offset)) +} + impl FrameLayout { /// The layout of `format` at `width × height`; both sides must be even and not zero. pub fn new(format: Format, width: u32, height: u32) -> Result { - if width == 0 || height == 0 || width % 2 == 1 || height % 2 == 1 { - return Err(Error::OutputSize { width, height }); - } - let s = format.sample_bytes(); - let (cw, ch) = (width / 2, height / 2); - let sizes: Vec<(u32, u32, u32)> = match format { - Format::Nv12 | Format::P010 => vec![(width, height, s), (cw, ch, 2 * s)], - Format::I420 => vec![(width, height, s), (cw, ch, s), (cw, ch, s)], - }; - let overflow = Error::Overflow { width, height }; - let mut offset = 0u64; - let mut tight = 0u64; - let mut planes = Vec::with_capacity(sizes.len()); - for (w, h, texel_bytes) in sizes { - let row = w.checked_mul(texel_bytes).ok_or(overflow.clone())?; - let bytes_per_row = aligned(row).ok_or(overflow.clone())?; - planes.push(PlaneLayout { width: w, height: h, texel_bytes, offset, bytes_per_row }); - offset = offset.checked_add(u64::from(bytes_per_row) * u64::from(h)).ok_or(overflow.clone())?; - tight = tight.checked_add(u64::from(row) * u64::from(h)).ok_or(overflow.clone())?; - } - // A packed frame must also fit in memory on this target. - usize::try_from(tight).map_err(|_| overflow)?; - Ok(FrameLayout { format, width, height, planes, buffer_size: offset }) + let (planes, count, buffer_size) = planes_of(format, width, height)?; + Ok(FrameLayout { format, width, height, planes: planes[..count].to_vec(), buffer_size }) + } + + /// Whether the fields are what [`FrameLayout::new`] gives for the format and size. It does not + /// allocate, so a frame loop can call it. + fn is_valid(&self) -> bool { + matches!(planes_of(self.format, self.width, self.height), + Ok((planes, count, size)) if planes[..count] == self.planes[..] && size == self.buffer_size) } /// Bytes of one tightly packed frame: the planes one after another, each row without padding. @@ -77,7 +91,7 @@ impl FrameLayout { /// into `frame` without the row padding. `frame` must be [`FrameLayout::frame_bytes`] long. /// A layout whose fields differ from what [`FrameLayout::new`] gives is [`Error::Layout`]. pub fn unpack(&self, padded: &[u8], frame: &mut [u8]) -> Result<(), Error> { - if FrameLayout::new(self.format, self.width, self.height).as_ref() != Ok(self) { + if !self.is_valid() { return Err(Error::Layout); } if (padded.len() as u64) < self.buffer_size { From 383ae5d15b656b04c54ee79896772f7176ddaf29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:47:09 -0800 Subject: [PATCH 050/490] craft-gpu-device: pick returns OpenError, and the docs describe the web path pick now returns OpenError instead of a String, so a caller can tell UnsafeDriver from NoAdapter. With no usable adapter it logs the listed adapters and returns NoAdapter. egui-wgpu's selector takes a String, so that caller converts with map_err(|e| e.to_string()). The crate docs and README now say what applies in a browser: WebGPU lists only the adapter the browser offers, a web build requests it with Preference::power(), and Capabilities, Recovery and DeviceHealth (apart from its blocking waits) work there. --- crates/gpu-device/README.md | 11 ++++++++-- crates/gpu-device/src/lib.rs | 6 +++++- crates/gpu-device/src/open.rs | 39 +++++++++++++++++++++++++---------- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 32b4750f91..fe8037fcae 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -20,7 +20,7 @@ Licensed under MIT OR Apache-2.0. | `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | | `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | | `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | -| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector` | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | | `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | | `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | | `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | @@ -28,7 +28,14 @@ Licensed under MIT OR Apache-2.0. ## Failure cases -- With no usable adapter, `select` returns `None` and `open` returns `OpenError::NoAdapter`. +- With no usable adapter, `select` returns `None`, and `open` and `pick` return + `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the + process can draw. +- In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be + chosen. A web build requests the adapter with `Preference::power()` as the power preference + and opens the device itself. `Capabilities` and `Recovery` work there as they do on native, + and so does `DeviceHealth` apart from `wait`, `wait_timeout` and `wait_timeout_cancelable`, + which are native only. - An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists each failure. diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs index 72c2ba2acf..c41f041f5f 100644 --- a/crates/gpu-device/src/lib.rs +++ b/crates/gpu-device/src/lib.rs @@ -10,7 +10,11 @@ //! ([`choose`]); [`Notice`] says when the choice was not the one asked for. //! - [`open`] opens a device, moving to the next adapter and last to a software one when a device //! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` -//! block on wgpu's futures and are native only; a browser build picks with [`pick`]. +//! block on wgpu's futures and are native only. +//! - In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be +//! chosen. A web build requests the adapter with [`Preference::power`] as the power preference +//! and opens the device itself. [`Capabilities`] and [`Recovery`] work there as they do on +//! native, and so does [`DeviceHealth`] apart from its blocking waits, which are native only. //! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm //! formats, `f16`, timestamps, sizes). //! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 388d8bdd20..8f31a851ee 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -88,26 +88,35 @@ pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec /// The adapter to draw with for `preference`, from adapters already listed, with the choice in the /// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device -/// itself. -pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), String> { +/// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. +/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that +/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise, +/// with the listed adapters in the log. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> { let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); let Some(selection) = select(&candidates, preference) else { - let left_out = left_out(&candidates); - if !left_out.is_empty() { - return Err(OpenError::UnsafeDriver(left_out).to_string()); - } - let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); - return Err(format!("no usable graphics adapter among {}: {listed}", candidates.len())); + return Err(unselected(&candidates)); }; log_choice(&candidates, selection.index, preference.power()); for notice in &selection.notices { log::warn!("{notice}"); } - let adapter = - adapters.get(selection.index).cloned().ok_or_else(|| format!("graphics adapter {} of {} is missing", selection.index, adapters.len()))?; + let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?; Ok((adapter, selection)) } +/// The error for `candidates` among which `select` found no adapter, with the list in the log +/// when it is not [`OpenError::UnsafeDriver`]. +fn unselected(candidates: &[Candidate]) -> OpenError { + let left_out = left_out(candidates); + if !left_out.is_empty() { + return OpenError::UnsafeDriver(left_out); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + log::warn!("no usable graphics adapter among {}: {listed}", candidates.len()); + OpenError::NoAdapter +} + /// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] /// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter /// without `request.required_features`, or whose device fails to open, adds a @@ -263,7 +272,15 @@ mod tests { OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" ); - assert!(pick(&[], None, &Preference::Auto).is_err()); + assert_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn pick_says_when_only_a_driver_that_can_crash_can_draw() { + let vulkan_only: Vec = crate::adapter::tests::uhd_630().into_iter().take(1).collect(); + assert_eq!(select(&vulkan_only, &Preference::Auto), None); + assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()])); + assert_eq!(unselected(&[]), OpenError::NoAdapter); } #[test] From d9473fcefb265b8f0f9843f19579e62fc2e81edb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:08:53 -0800 Subject: [PATCH 051/490] craft-gpu-yuv: run as the craft.yuv provider on craft-gpu YuvProvider implements craft-gpu's GpuProvider under the id craft.yuv. YuvJob writes and strictly parses the job's key:value parameters. The provider checks the source and output sides and the padded read-back size against the context's DeviceCaps and the input's length before reading it, so a job is refused the same way on craft-gpu-null and on a device. YuvProvider::new() converts on the CPU on any context; with_device runs the render passes on a device the host holds, inside validation and out-of-memory error scopes. Code values now round halves away from zero on the CPU and in WGSL, as INT in BT.709 and BT.2020 and Round in BT.2100 do. Round-half-even gave full-range cyan a Cr of 0 instead of 1. oracle_tests.rs checks the conversion against sources outside the crate: code values computed in f64 from each recommendation's Kr, Kb and quantization, the nominal levels the recommendations state, the yuv crate's conversion (a dev-dependency) for every format, matrix and range, and a 4x4 frame against the byte offsets of the WebCodecs and Linux media API format definitions. The README documents the job parameters, the plane layout with its sources, the rounding rule, and why the CPU scaler takes the shader's taps. docs/gpu-providers.md lists craft.yuv. --- Cargo.lock | 12 + README.md | 10 +- crates/gpu-yuv/Cargo.toml | 11 +- crates/gpu-yuv/README.md | 108 ++++++++- crates/gpu-yuv/src/cpu.rs | 5 + crates/gpu-yuv/src/gpu.rs | 4 +- crates/gpu-yuv/src/job.rs | 351 +++++++++++++++++++++++++++++ crates/gpu-yuv/src/job_tests.rs | 233 +++++++++++++++++++ crates/gpu-yuv/src/lib.rs | 11 +- crates/gpu-yuv/src/oracle_tests.rs | 335 +++++++++++++++++++++++++++ crates/gpu-yuv/src/spec.rs | 11 +- crates/gpu-yuv/src/tests.rs | 12 +- docs/gpu-providers.md | 1 + 13 files changed, 1076 insertions(+), 28 deletions(-) create mode 100644 crates/gpu-yuv/src/job.rs create mode 100644 crates/gpu-yuv/src/job_tests.rs create mode 100644 crates/gpu-yuv/src/oracle_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 4a7c14296c..dea6be59cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2175,8 +2175,11 @@ dependencies = [ name = "craft-gpu-yuv" version = "0.1.0" dependencies = [ + "craft-gpu", + "craft-gpu-null", "pollster 0.4.0", "wgpu", + "yuv", ] [[package]] @@ -13078,6 +13081,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" diff --git a/README.md b/README.md index 602deac549..9f915aeddd 100644 --- a/README.md +++ b/README.md @@ -184,10 +184,12 @@ 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): RGBA to NV12, P010 and I420 on the GPU, scaled to - the output size, in BT.601, BT.709 and BT.2020 at limited or full range; each output texel - averages the part of the source it covers; read-back layouts and unpacking to a packed frame; - and the same conversion on the CPU. Encoders and scopes stay in each app. +- [`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-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. diff --git a/crates/gpu-yuv/Cargo.toml b/crates/gpu-yuv/Cargo.toml index 4d37856c86..ddf2fa6cc2 100644 --- a/crates/gpu-yuv/Cargo.toml +++ b/crates/gpu-yuv/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-gpu-yuv" -description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, with a CPU reference of the same conversion" +description = "RGBA to NV12, P010 and I420 on the GPU with scaling, in BT.601, BT.709 and BT.2020 at limited or full range, as a craft-gpu provider, with a CPU reference of the same conversion" version.workspace = true edition.workspace = true license.workspace = true @@ -11,7 +11,14 @@ repository.workspace = true workspace = true [dependencies] +craft-gpu = { workspace = true } wgpu = "30" +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = { workspace = true } + [dev-dependencies] -pollster = "0.4" +craft-gpu-null = { workspace = true } +pollster = { workspace = true } +# The independent reference the oracle tests compare with (BSD-3-Clause OR Apache-2.0). +yuv = { version = "0.8.20", default-features = false, features = ["professional_mode"] } diff --git a/crates/gpu-yuv/README.md b/crates/gpu-yuv/README.md index 76cc76881d..4869219866 100644 --- a/crates/gpu-yuv/README.md +++ b/crates/gpu-yuv/README.md @@ -1,8 +1,9 @@ # craft-gpu-yuv -RGBA to 4:2:0 Y'CbCr on the GPU for the Craft apps' encoders and scopes: NV12, P010 and I420, -scaled to the output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. -`cpu::convert` is the same conversion on the CPU. The crate depends only on `wgpu` 30. +RGBA to 4:2:0 Y'CbCr for the Craft apps' encoders and scopes: NV12, P010 and I420, scaled to the +output size, in the BT.601, BT.709 and BT.2020 matrices at limited or full range. `YuvProvider` is +the `craft.yuv` provider of the `craft-gpu` job layer. `Converter` records the same conversion as +render passes into a caller's own encoder, and `cpu::convert` is the same conversion on the CPU. Licensed under MIT OR Apache-2.0. @@ -10,6 +11,9 @@ Licensed under MIT OR Apache-2.0. | Item | What | |---|---| +| `YuvProvider` | the `craft.yuv` `GpuProvider`; `new()` converts on the CPU on any `GpuContext`, `with_device(device, queue)` converts with the render passes on that device (not on `wasm32`) | +| `YuvJob` | one job's conversion, source size and output size; `params()` writes them, `parse` reads them, `job(input)` makes the `GpuJob` | +| `PROVIDER_ID` | `"craft.yuv"` | | `Format` | `Nv12` (8-bit luma, then interleaved Cb and Cr), `P010` (10-bit values in the high bits of little-endian 16-bit words, same planes as NV12) and `I420` (8-bit luma, Cb, then Cr) | | `Matrix`, `Range` | BT.601, BT.709 and BT.2020 non-constant luminance; limited range (luma 16 to 235, chroma 16 to 240, times 4 at 10 bits) or full range (every code, chroma centered on 128 or 512) | | `Conversion` | one format, matrix and range | @@ -21,6 +25,72 @@ Licensed under MIT OR Apache-2.0. | `FrameLayout` | each plane's size, its offset and row pitch in a read-back buffer (`buffer_size`), and the size of a packed frame (`frame_bytes`); `unpack` copies a mapped buffer into a packed frame | | `cpu::convert(rgba, src_width, src_height, conversion, width, height)` | the conversion of an RGBA8 picture on the CPU, as one packed frame | +## Jobs + +A host registers `YuvProvider` in a `ProviderRegistry` and dispatches jobs made by `YuvJob::job`: + +```rust +let mut registry = craft_gpu::ProviderRegistry::new(); +registry.register(Box::new(craft_gpu_yuv::YuvProvider::new())); +let input = ctx.upload_buffer("rgba", &rgba)?; +let job = craft_gpu_yuv::YuvJob::new(conversion, 1920, 1080, 1280, 720).job(input); +let outcome = registry.dispatch(&mut ctx, &job)?; +let frame = ctx.read_buffer(outcome.outputs[0])?; +``` + +A job has one input, an RGBA8 buffer of exactly `src_width × src_height × 4` bytes, and no +outputs; its outcome has one output, a new buffer that holds the packed frame. The parameters are +ASCII `key:value` fields separated by `;`: +`fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +`i420`, `matrix` is `bt601`, `bt709` or `bt2020`, `range` is `limited` or `full`, and the four sides +are decimal digits. + +The provider checks the job against the context's `DeviceCaps` on every context, the null one +included: each source and output side must be at most `max_texture_dimension_2d`, and the +read-back layout with its padded rows (`FrameLayout::buffer_size`) at most `max_buffer_size` +bytes. It checks the input's length before reading it. A +malformed, missing, repeated or unknown parameter, a wrong input count or length, and a size the +caps or the conversion do not allow are `GpuFault::InvalidJob`. With a device, the provider also +checks the device's own limits, and an error the device reports during the job is +`GpuFault::Operation`. Each conversion's pipelines are made once per provider. + +`YuvProvider::new()` runs `cpu::convert`, so a consumer's tests and CI run on `craft-gpu-null` +without a graphics adapter. `YuvProvider::with_device` runs the render passes on the given device +and waits for each job to finish; the input and the output still move through the context's +buffers. + +## Plane layout + +A packed frame of `w × h` (both even) holds its planes one after another, each row without +padding: + +| Format | Plane | Offset | Row bytes | Rows | +|---|---|---|---|---| +| NV12 | Y' | 0 | `w` | `h` | +| NV12 | Cb, Cr interleaved | `w·h` | `w` | `h/2` | +| P010 | Y' | 0 | `2w` | `h` | +| P010 | Cb, Cr interleaved | `2w·h` | `2w` | `h/2` | +| I420 | Y' | 0 | `w` | `h` | +| I420 | Cb | `w·h` | `w/2` | `h/2` | +| I420 | Cr | `w·h + w·h/4` | `w/2` | `h/2` | + +A frame is `1.5·w·h` bytes in NV12 and I420 and `3·w·h` bytes in P010. Each P010 word holds the +10-bit value in its high bits, with the 6 low bits zero. NV12 and I420 follow the W3C WebCodecs +definitions (), and NV12 and P010 follow +the Linux media API's sample images +(). + +In a read-back buffer, `FrameLayout` pads each row to a multiple of +`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT` (256) bytes, as a texture-to-buffer copy needs, and puts each +plane right after the previous plane's padded rows. `FrameLayout::unpack` removes the padding. + +## Code values + +Luma and chroma follow BT.601-7 section 2.5, BT.709-6 items 3.2 to 3.5 and BT.2020-2 tables 4 and +5 at limited range, and BT.2100-3 table 9 at full range. A half rounds away from zero, as `INT` in +BT.709 and BT.2020 and `Round` in BT.2100 do, so a full-range Cb or Cr that computes to 0.5 is +code 1. + ## Sampling The source is scaled to the output size; the caller keeps the aspect ratio. Each output texel @@ -31,8 +101,13 @@ At the same size, each chroma sample is the average of the 2 × 2 pixels it cove position is the center of those pixels. A reduction of more than 8:1 along an axis skips part of the source between taps. -The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`). The shader rounds -each value half to even. P010 does not need wgpu's 16-bit norm feature. +`cpu::convert` scales with these same taps rather than with a resampling crate such as +`fast_image_resize`, because it is the reference the shader is tested against, and a different +kernel would differ from the shader at every edge. A caller that wants another filter on the CPU +can resize first with such a crate and convert at the same size. + +The passes write unsigned-integer textures (`R8Uint`, `Rg8Uint`, `R16Uint`, `Rg16Uint`), so P010 +does not need wgpu's 16-bit norm feature. ## Limits @@ -53,9 +128,20 @@ each value half to even. P010 does not need wgpu's 16-bit norm feature. ## Tests -The CPU tests check standard code values (BT.709 limited-range red is 63, 102, 240), each -format's plane order, the area average of a reduction and the read-back layout. The GPU tests -convert pictures with hard edges at the same size, and smooth pictures at five scales, in every -format, and compare each sample with `cpu::convert`. The tolerance is 2 code values at 8 bits and -6 at 10 bits. A machine without a graphics -adapter skips the GPU tests and prints that it did so. +- `oracle_tests.rs` checks the conversion against sources outside the crate. It computes the + code values of 729 colors in `f64` from each recommendation's Kr, Kb and quantization, and + checks the nominal levels the recommendations state (white, black, neutral chroma and the + chroma extremes). It compares every format, matrix and range with the `yuv` crate's conversion + of the same pictures (`yuv` 0.8, a dev-dependency), within 1 code value at 8 bits and 2 at + 10 bits. It checks the packed plane sizes against the planes `yuv` allocates, and a 4 × 4 frame + against the byte offsets of the public format definitions. The GPU passes are checked against + the same equations, within 1 code value. +- `job_tests.rs` runs `craft.yuv` through a `ProviderRegistry` on `craft-gpu-null`, and with a + device. It checks the parameters, the inputs and outputs, the caps limits, and a device whose + limits are smaller than the context's. +- `tests.rs` checks standard code values, each format's plane order, the area average of a + reduction and the read-back layout. It also compares the GPU passes with `cpu::convert` on + pictures with hard edges at the same size and on smooth pictures at five scales, within 2 code + values at 8 bits and 6 at 10 bits. + +A machine without a graphics adapter skips the GPU tests and prints that it did so. diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs index c268677091..c7afe643f2 100644 --- a/crates/gpu-yuv/src/cpu.rs +++ b/crates/gpu-yuv/src/cpu.rs @@ -6,6 +6,11 @@ //! source is at most twice the plane's size, one more for each further 2:1 of reduction. The //! average of the taps goes through the matrix. At the same size the chroma tap lands between //! four source pixels, so each chroma sample is the average of the 2 × 2 pixels it covers. +//! +//! The scaler here takes the shader's taps at the shader's positions instead of using a +//! resampling crate such as `fast_image_resize`: this function is the reference the shader is +//! tested against, and another kernel would differ from the shader at every edge. For another +//! filter, resize with such a crate first and convert at the same size. use crate::layout::FrameLayout; use crate::spec::{Coefficients, Conversion, Error}; diff --git a/crates/gpu-yuv/src/gpu.rs b/crates/gpu-yuv/src/gpu.rs index eb413e3c25..350c6adb66 100644 --- a/crates/gpu-yuv/src/gpu.rs +++ b/crates/gpu-yuv/src/gpu.rs @@ -120,8 +120,10 @@ fn area(pos: vec2) -> vec3 {{ return sum / (nf.x * nf.y); }} +// A half rounds up, as INT and Round do in the recommendations; WGSL's round() takes it to the +// even neighbor. Values below 0 clamp to 0 either way. fn code(v: f32) -> u32 {{ - return u32(clamp(round(v), 0.0, MAX)) << SHIFT; + return u32(clamp(floor(v + 0.5), 0.0, MAX)) << SHIFT; }} @fragment fn fs_luma(@builtin(position) pos: vec4) -> @location(0) vec4 {{ diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs new file mode 100644 index 0000000000..3534816000 --- /dev/null +++ b/crates/gpu-yuv/src/job.rs @@ -0,0 +1,351 @@ +//! The conversion as a `craft-gpu` job: [`YuvProvider`] answers [`GpuJob`]s whose provider id is +//! [`PROVIDER_ID`], dispatched through a [`craft_gpu::ProviderRegistry`]. +//! +//! A job has one input, an RGBA8 buffer of `src_width × src_height × 4` bytes in the context, and +//! [`YuvJob::params`] as its parameters. Its outcome has one output: a new buffer that holds the +//! packed frame in [`FrameLayout`] order. Every side must be no larger than the context's +//! [`DeviceCaps::max_texture_dimension_2d`](craft_gpu::DeviceCaps), and the frame no larger than its +//! `max_buffer_size`, on every context, so that a job that runs on the null context also runs on a +//! device with the same caps. + +use craft_gpu::{GpuContext, GpuFault, GpuJob, GpuJobOutcome, GpuJobParams, GpuProvider, HandleId}; + +use crate::cpu; +use crate::layout::FrameLayout; +use crate::spec::{Conversion, Error, Format, Matrix, Range}; + +/// The provider id of [`YuvProvider`]. +pub const PROVIDER_ID: &str = "craft.yuv"; + +/// The parameter keys, in the order [`YuvJob::params`] writes them. +const KEYS: [&str; 7] = ["fmt", "matrix", "range", "sw", "sh", "w", "h"]; + +/// The parameters of one `craft.yuv` job: the conversion, the source size and the output size. +/// +/// They are written as ASCII `key:value` fields separated by `;`, for example +/// `fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720`. `fmt` is `nv12`, `p010` or +/// `i420`; `matrix` is `bt601`, `bt709` or `bt2020`; `range` is `limited` or `full`; the sides are +/// decimal digits. A missing, repeated or unknown key, or a value outside these, is +/// [`GpuFault::InvalidJob`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct YuvJob { + pub conversion: Conversion, + pub src_width: u32, + pub src_height: u32, + pub width: u32, + pub height: u32, +} + +fn invalid(message: impl std::fmt::Display) -> GpuFault { + GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}")) +} + +/// A conversion error as a fault: device errors are [`GpuFault::Operation`], the rest describe a +/// job that cannot run and are [`GpuFault::InvalidJob`]. +fn fault(e: Error) -> GpuFault { + match e { + Error::Device(_) => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")), + _ => invalid(e), + } +} + +fn format_token(f: Format) -> &'static str { + match f { + Format::Nv12 => "nv12", + Format::P010 => "p010", + Format::I420 => "i420", + } +} + +fn matrix_token(m: Matrix) -> &'static str { + match m { + Matrix::Bt601 => "bt601", + Matrix::Bt709 => "bt709", + Matrix::Bt2020 => "bt2020", + } +} + +fn range_token(r: Range) -> &'static str { + match r { + Range::Limited => "limited", + Range::Full => "full", + } +} + +impl YuvJob { + pub fn new(conversion: Conversion, src_width: u32, src_height: u32, width: u32, height: u32) -> YuvJob { + YuvJob { conversion, src_width, src_height, width, height } + } + + /// The job's parameters. + pub fn params(&self) -> GpuJobParams { + let c = self.conversion; + let text = format!( + "fmt:{};matrix:{};range:{};sw:{};sh:{};w:{};h:{}", + format_token(c.format), + matrix_token(c.matrix), + range_token(c.range), + self.src_width, + self.src_height, + self.width, + self.height + ); + GpuJobParams(text.into_bytes()) + } + + /// A `craft.yuv` job that converts the RGBA8 buffer `input`. + pub fn job(&self, input: HandleId) -> GpuJob { + GpuJob { provider_id: PROVIDER_ID.into(), params: self.params(), inputs: vec![input], outputs: Vec::new() } + } + + /// Read parameters written by [`YuvJob::params`]. + pub fn parse(params: &GpuJobParams) -> Result { + let text = std::str::from_utf8(¶ms.0).map_err(|_| invalid("the parameters are not UTF-8"))?; + let mut values: [Option<&str>; KEYS.len()] = [None; KEYS.len()]; + for field in text.split(';') { + let (key, value) = field.split_once(':').ok_or_else(|| invalid(format!("`{field}` is not a key:value field")))?; + let i = KEYS.iter().position(|k| *k == key).ok_or_else(|| invalid(format!("unknown key `{key}`")))?; + if values[i].replace(value).is_some() { + return Err(invalid(format!("`{key}` is given twice"))); + } + } + let get = |i: usize| values[i].ok_or_else(|| invalid(format!("`{}` is missing", KEYS[i]))); + let token = |i: usize, value: &str| invalid(format!("`{value}` is not a value of `{}`", KEYS[i])); + let format = match get(0)? { + "nv12" => Format::Nv12, + "p010" => Format::P010, + "i420" => Format::I420, + v => return Err(token(0, v)), + }; + let matrix = match get(1)? { + "bt601" => Matrix::Bt601, + "bt709" => Matrix::Bt709, + "bt2020" => Matrix::Bt2020, + v => return Err(token(1, v)), + }; + let range = match get(2)? { + "limited" => Range::Limited, + "full" => Range::Full, + v => return Err(token(2, v)), + }; + let side = |i: usize| -> Result { + let v = get(i)?; + if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) { + return Err(token(i, v)); + } + v.parse().map_err(|_| token(i, v)) + }; + Ok(YuvJob { + conversion: Conversion::new(format, matrix, range), + src_width: side(3)?, + src_height: side(4)?, + width: side(5)?, + height: side(6)?, + }) + } +} + +/// The `craft.yuv` provider. +/// +/// [`YuvProvider::new`] converts with [`cpu::convert`], on any context: the null context in tests +/// and CI, or a context whose device a provider cannot reach. [`YuvProvider::with_device`] +/// converts with the render passes on a device the caller holds, such as the one it already draws +/// with; the RGBA8 input and the output frame still move through the context's buffers. Both give +/// the same frame within the tolerance the crate's tests state. +pub struct YuvProvider { + device: Option, +} + +impl Default for YuvProvider { + fn default() -> Self { + Self::new() + } +} + +impl YuvProvider { + /// A provider that converts on the CPU. + pub fn new() -> YuvProvider { + YuvProvider { device: None } + } + + /// A provider that converts with the render passes on `device`. Each job waits for the device + /// to finish, so this is not available on `wasm32`, where a buffer map completes only from the + /// browser's event loop. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue) -> YuvProvider { + YuvProvider { device: Some(device::DeviceRunner::new(device, queue)) } + } + + /// Whether jobs run on a device. + pub fn has_device(&self) -> bool { + self.device.is_some() + } + + fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + match &self.device { + Some(d) => d.convert(rgba, job), + None => cpu::convert(rgba, job.src_width, job.src_height, job.conversion, job.width, job.height), + } + } +} + +impl GpuProvider for YuvProvider { + fn id(&self) -> &'static str { + PROVIDER_ID + } + + fn run(&self, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result { + let spec = YuvJob::parse(&job.params)?; + let [input] = job.inputs.as_slice() else { + return Err(invalid(format!("expects one RGBA8 input, not {}", job.inputs.len()))); + }; + if !job.outputs.is_empty() { + return Err(invalid("makes its own output buffer, so the job names no outputs")); + } + let YuvJob { conversion, src_width, src_height, width, height } = spec; + let layout = FrameLayout::new(conversion.format, width, height).map_err(fault)?; + let caps = ctx.caps(); + let limit = caps.max_texture_dimension_2d; + for (w, h) in [(src_width, src_height), (width, height)] { + if w > limit || h > limit { + return Err(fault(Error::TooLarge { width: w, height: h, limit })); + } + } + // The read-back buffer with its padded rows is the largest buffer a device run makes, so + // the null context refuses the same jobs a device with these caps does. + let needed = layout.buffer_size.max(layout.frame_bytes() as u64); + if needed > caps.max_buffer_size { + return Err(fault(Error::BufferLimit { needed, limit: caps.max_buffer_size })); + } + // The input's size is checked before its bytes are read. + let bytes = ctx.buffer_len(*input)?; + let expected = (src_width as usize).checked_mul(src_height as usize).and_then(|n| n.checked_mul(4)); + if src_width == 0 || src_height == 0 || expected != Some(bytes) { + return Err(fault(Error::Source { width: src_width, height: src_height, bytes })); + } + let rgba = ctx.read_buffer(*input)?; + let frame = self.convert(&rgba, &spec).map_err(fault)?; + let output = ctx.upload_buffer("craft.yuv.frame", &frame)?; + Ok(GpuJobOutcome { outputs: vec![output], data: None }) + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod device { + use std::sync::Mutex; + + use crate::gpu::{Converter, Planes}; + use crate::spec::{Conversion, Error}; + + use super::YuvJob; + + /// A device, its queue, and the converters made on it so far, one per conversion. + pub(super) struct DeviceRunner { + device: wgpu::Device, + queue: wgpu::Queue, + converters: Mutex>, + } + + fn device_error(e: impl std::fmt::Display) -> Error { + Error::Device(e.to_string()) + } + + impl DeviceRunner { + pub(super) fn new(device: wgpu::Device, queue: wgpu::Queue) -> DeviceRunner { + DeviceRunner { device, queue, converters: Mutex::new(Vec::new()) } + } + + /// `rgba` converted on the device, as one packed frame. Errors the device reports go to + /// error scopes and come back as [`Error::Device`]. + pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result, Error> { + let (sw, sh) = (job.src_width, job.src_height); + let limit = self.device.limits().max_texture_dimension_2d; + if sw > limit || sh > limit { + return Err(Error::TooLarge { width: sw, height: sh, limit }); + } + // A converter leaves the cache while a job uses it, and goes back only when the device + // reported no error, so a converter whose pipelines failed is not used again. + let mut converters = self.converters.lock().map_err(|_| device_error("the converter cache lock is poisoned"))?; + let cached = take(&mut converters, job.conversion); + drop(converters); + let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation); + let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion)); + let recorded = self.record(&converter, rgba, job); + // Both scopes are popped on every path, so that none stays open on the device. + let errors = [pollster::block_on(validation.pop()), pollster::block_on(oom.pop())]; + if let Some(e) = errors.into_iter().flatten().next() { + return Err(device_error(e)); + } + if let Ok(mut converters) = self.converters.lock() { + converters.push(converter); + } + let (planes, buffer) = recorded?; + let (tx, rx) = std::sync::mpsc::channel(); + buffer.map_async(wgpu::MapMode::Read, .., move |result| { + let _ = tx.send(result); + }); + self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?; + rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?; + let mapped = buffer.get_mapped_range(..).map_err(device_error)?; + let mut frame = vec![0u8; planes.layout().frame_bytes()]; + let unpacked = planes.layout().unpack(&mapped, &mut frame); + drop(mapped); + buffer.unmap(); + unpacked.map(|()| frame) + } + + /// Upload `rgba` and record and submit the passes and the copy into a read-back buffer. + fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> { + let (sw, sh) = (job.src_width, job.src_height); + let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("craft.yuv source"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) }; + self.queue.write_texture(texture.as_image_copy(), rgba, layout, size); + let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default())); + let planes = converter.planes(&self.device, job.width, job.height)?; + let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("craft.yuv read-back"), + size: planes.layout().buffer_size, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft.yuv") }); + converter.draw(&mut encoder, &source, &planes)?; + planes.copy_to_buffer(&mut encoder, &buffer, 0)?; + self.queue.submit([encoder.finish()]); + Ok((planes, buffer)) + } + } + + /// Remove and return the converter of `conversion` from `converters`, if there is one. + fn take(converters: &mut Vec, conversion: Conversion) -> Option { + let i = converters.iter().position(|c| c.conversion() == conversion)?; + Some(converters.swap_remove(i)) + } +} + +#[cfg(target_arch = "wasm32")] +mod device { + use crate::spec::Error; + + use super::YuvJob; + + /// No device runs jobs on `wasm32`: [`super::YuvProvider::with_device`] is native only. + pub(super) enum DeviceRunner {} + + impl DeviceRunner { + pub(super) fn convert(&self, _rgba: &[u8], _job: &YuvJob) -> Result, Error> { + match *self {} + } + } +} diff --git a/crates/gpu-yuv/src/job_tests.rs b/crates/gpu-yuv/src/job_tests.rs new file mode 100644 index 0000000000..eb77b63e53 --- /dev/null +++ b/crates/gpu-yuv/src/job_tests.rs @@ -0,0 +1,233 @@ +//! `craft.yuv` through the job contract: on `craft-gpu-null`, which needs no hardware, and with a +//! device when the machine has a graphics adapter. + +use craft_gpu::{DeviceCaps, GpuContext, GpuFault, GpuJob, GpuJobParams, HandleId, ProviderRegistry, ReadOutcome, ReadRequest, WorkerKind}; +use craft_gpu_null::NullContext; + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// A null context with caps of the test's choosing, which counts the buffers read. +struct Capped { + inner: NullContext, + caps: DeviceCaps, + reads: usize, +} + +impl Capped { + fn new(caps: DeviceCaps) -> Capped { + Capped { inner: NullContext::new(WorkerKind::Main), caps, reads: 0 } + } +} + +impl GpuContext for Capped { + fn caps(&self) -> DeviceCaps { + self.caps.clone() + } + fn worker_kind(&self) -> WorkerKind { + self.inner.worker_kind() + } + fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { + self.inner.upload_buffer(label, bytes) + } + fn buffer_len(&self, handle: HandleId) -> Result { + self.inner.buffer_len(handle) + } + fn request_read(&mut self, handle: HandleId) -> Result { + self.reads += 1; + self.inner.request_read(handle) + } + fn poll_reads(&mut self) -> Vec { + self.inner.poll_reads() + } + fn free_buffer(&mut self, handle: HandleId) { + self.inner.free_buffer(handle); + } + fn read_buffer(&mut self, handle: HandleId) -> Result, GpuFault> { + self.reads += 1; + self.inner.read_buffer(handle) + } +} + +fn registry(provider: YuvProvider) -> ProviderRegistry { + let mut r = ProviderRegistry::new(); + r.register(Box::new(provider)); + r +} + +/// Run `job` on `ctx` and read its one output back. +fn dispatch(r: &ProviderRegistry, ctx: &mut dyn GpuContext, job: &GpuJob) -> Result, GpuFault> { + let outcome = r.dispatch(ctx, job)?; + assert_eq!(outcome.outputs.len(), 1); + assert_eq!(outcome.data, None); + ctx.read_buffer(outcome.outputs[0]) +} + +fn invalid(result: Result) -> String { + match result { + Err(GpuFault::InvalidJob(message)) => message, + other => panic!("expected an invalid job, got {other:?}"), + } +} + +#[test] +fn the_registry_runs_craft_yuv_on_the_null_context() { + let r = registry(YuvProvider::new()); + let mut ctx = NullContext::new(WorkerKind::Main); + let px = tests::noise(64, 36); + let input = ctx.upload_buffer("rgba", &px).unwrap(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + for (w, h) in [(64, 36), (32, 18), (100, 50)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, w, h).job(input)).unwrap(); + assert_eq!(frame, cpu::convert(&px, 64, 36, c, w, h).unwrap(), "{c:?} {w}×{h}"); + assert_eq!(frame.len(), FrameLayout::new(format, w, h).unwrap().frame_bytes()); + } + } + } + } +} + +#[test] +fn parameters_read_back_as_written() { + let job = YuvJob::new(Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited), 1920, 1080, 1280, 720); + assert_eq!(job.params().0, b"fmt:nv12;matrix:bt709;range:limited;sw:1920;sh:1080;w:1280;h:720"); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let job = YuvJob::new(Conversion::new(format, matrix, range), 7, u32::MAX, 0, 4); + assert_eq!(YuvJob::parse(&job.params()), Ok(job)); + } + } + } + let job = YuvJob::new(Conversion::new(Format::P010, Matrix::Bt2020, Range::Full), 3, 5, 8, 6).job(HandleId(9)); + assert_eq!((job.provider_id.as_str(), job.inputs.as_slice(), job.outputs.len()), (PROVIDER_ID, [HandleId(9)].as_slice(), 0)); +} + +#[test] +fn bad_parameters_are_invalid_jobs() { + let good = "fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4"; + let cases: [(&[u8], &str); 14] = [ + (b"", "is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4", "`h` is missing"), + (b"fmt:nv12;fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`fmt` is given twice"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;alpha:1", "unknown key `alpha`"), + (b"fmt:NV12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4", "`NV12` is not a value of `fmt`"), + (b"fmt:nv12;matrix:bt2100;range:limited;sw:4;sh:4;w:4;h:4", "`bt2100` is not a value of `matrix`"), + (b"fmt:nv12;matrix:bt709;range:studio;sw:4;sh:4;w:4;h:4", "`studio` is not a value of `range`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:+4;sh:4;w:4;h:4", "`+4` is not a value of `sw`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:-4;w:4;h:4", "`-4` is not a value of `sh`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:;h:4", "`` is not a value of `w`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4294967296", "`4294967296` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4;", "`` is not a key:value field"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:4.0", "`4.0` is not a value of `h`"), + (b"fmt:nv12;matrix:bt709;range:limited;sw:4;sh:4;w:4;h:\xff", "not UTF-8"), + ]; + assert!(YuvJob::parse(&GpuJobParams(good.as_bytes().to_vec())).is_ok()); + for (params, want) in cases { + let message = invalid(YuvJob::parse(&GpuJobParams(params.to_vec()))); + assert!(message.starts_with("craft.yuv: ") && message.contains(want), "{message:?} for {:?}", String::from_utf8_lossy(params)); + } +} + +#[test] +fn inputs_outputs_and_sizes_are_checked_before_any_read() { + let r = registry(YuvProvider::new()); + let mut ctx = Capped::new(DeviceCaps::default()); + let c = Conversion::new(Format::I420, Matrix::Bt601, Range::Limited); + let input = ctx.upload_buffer("rgba", &tests::noise(8, 4)).unwrap(); + let mut job = YuvJob::new(c, 8, 4, 8, 4).job(input); + job.inputs.clear(); + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("expects one RGBA8 input, not 0")); + job.inputs = vec![input, input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("not 2")); + job.inputs = vec![input]; + job.outputs = vec![input]; + assert!(invalid(r.dispatch(&mut ctx, &job)).contains("names no outputs")); + // A buffer whose size is not the source's, an odd or zero side, and a missing buffer. + let wrong = [ + YuvJob::new(c, 8, 8, 8, 4).job(input), + YuvJob::new(c, 0, 4, 8, 4).job(input), + YuvJob::new(c, 8, 4, 7, 4).job(input), + YuvJob::new(c, 8, 4, 8, 0).job(input), + YuvJob::new(c, u32::MAX, u32::MAX, 8, 4).job(input), + ]; + for job in &wrong { + invalid(r.dispatch(&mut ctx, job)); + } + assert!(matches!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(HandleId(99))), Err(GpuFault::InvalidJob(_)))); + assert_eq!(ctx.reads, 0, "no job above reads its input"); + assert!(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 4, 8, 4).job(input)).is_ok()); + assert_eq!(ctx.reads, 1); +} + +#[test] +fn jobs_past_the_context_caps_are_refused() { + let r = registry(YuvProvider::new()); + let caps = DeviceCaps { max_texture_dimension_2d: 64, max_buffer_size: 16128, ..DeviceCaps::default() }; + let mut ctx = Capped::new(caps); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let small = ctx.upload_buffer("small", &tests::noise(64, 4)).unwrap(); + let wide = ctx.upload_buffer("wide", &tests::noise(66, 2)).unwrap(); + // The source and the output sides against the largest texture side. + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 66, 2, 64, 2).job(wide))).contains("66×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 66, 4).job(small))).contains("66×4")); + // NV12 read-back rows at width 64 are padded to 256 bytes: 64 × 44 packs into 4224 bytes + // but reads back through 256 × (44 + 22) = 16896, more than the 16128-byte limit; 64 × 42 + // reads back through exactly 16128. + assert_eq!(FrameLayout::new(Format::Nv12, 64, 44).unwrap().frame_bytes(), 4224); + let refused = invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 64, 4, 64, 44).job(small))); + assert!(refused.contains("16896 bytes is larger than the largest buffer, 16128"), "{refused}"); + assert!(dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 4, 64, 42).job(small)).is_ok()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_provider_with_a_device_matches_the_cpu_through_the_registry() { + let Some((device, queue)) = tests::device() else { return }; + let provider = YuvProvider::with_device(device, queue); + assert!(provider.has_device() && !YuvProvider::new().has_device()); + let r = registry(provider); + let mut ctx = NullContext::new(WorkerKind::Main); + let (noise, ramps) = (tests::noise(64, 36), tests::ramps(160, 90)); + let (n, s) = (ctx.upload_buffer("noise", &noise).unwrap(), ctx.upload_buffer("ramps", &ramps).unwrap()); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 64, 36, 64, 36).job(n)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&noise, 64, 36, c, 64, 36).unwrap(), c, "64×36 through the registry"); + } + } + // Each conversion's converter is made once and used again: the second run of a + // conversion gives the same frame. + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + for (w, h) in [(80, 46), (240, 136)] { + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&ramps, 160, 90, c, w, h).unwrap(), c, &format!("160×90 to {w}×{h} through the registry")); + assert_eq!(frame, dispatch(&r, &mut ctx, &YuvJob::new(c, 160, 90, w, h).job(s)).unwrap()); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_device_smaller_than_the_context_caps_refuses_the_job_without_a_device_error() { + let Some((device, queue)) = tests::device_with(|l| wgpu::Limits { max_texture_dimension_2d: 64, ..l }) else { return }; + let r = registry(YuvProvider::with_device(device, queue)); + // The null context's caps allow 8192, so only the device's own limit stops these. + let mut ctx = NullContext::new(WorkerKind::Main); + let c = Conversion::new(Format::Nv12, Matrix::Bt709, Range::Limited); + let big = ctx.upload_buffer("big", &tests::noise(128, 2)).unwrap(); + let small = ctx.upload_buffer("small", &tests::noise(8, 2)).unwrap(); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 128, 2, 8, 2).job(big))).contains("128×2 is larger than the largest texture side, 64")); + assert!(invalid(r.dispatch(&mut ctx, &YuvJob::new(c, 8, 2, 128, 2).job(small))).contains("128×2")); + // The device still runs a job that fits after refusing two. + let frame = dispatch(&r, &mut ctx, &YuvJob::new(c, 8, 2, 8, 2).job(small)).unwrap(); + tests::assert_close(&frame, &cpu::convert(&tests::noise(8, 2), 8, 2, c, 8, 2).unwrap(), c, "8×2 after two refusals"); +} diff --git a/crates/gpu-yuv/src/lib.rs b/crates/gpu-yuv/src/lib.rs index 220fa5b3d0..24afb1a4aa 100644 --- a/crates/gpu-yuv/src/lib.rs +++ b/crates/gpu-yuv/src/lib.rs @@ -1,7 +1,10 @@ //! RGBA to 4:2:0 Y'CbCr on the GPU, for encoders and scopes. //! +//! - [`YuvProvider`] is the `craft.yuv` [`craft_gpu::GpuProvider`]: a host registers it in a +//! [`craft_gpu::ProviderRegistry`] and dispatches [`YuvJob`]s, on the null context or on a device. //! - [`Converter`] holds the render pipelines of one [`Conversion`]: a [`Format`] (NV12, P010 or -//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full). +//! I420), a [`Matrix`] (BT.601, BT.709 or BT.2020) and a [`Range`] (limited or full), for a +//! caller that records the passes into its own command encoder. //! - [`Converter::bind`] binds a source texture view once; [`Converter::planes`] makes the plane //! textures of one output size; [`Converter::draw`] records the two passes. The source is scaled //! to the output size. @@ -16,12 +19,18 @@ pub mod cpu; mod gpu; +mod job; mod layout; mod spec; pub use gpu::{Converter, Planes, Source}; +pub use job::{PROVIDER_ID, YuvJob, YuvProvider}; pub use layout::{FrameLayout, PlaneLayout}; pub use spec::{Conversion, Error, Format, Matrix, Range}; +#[cfg(test)] +mod job_tests; +#[cfg(test)] +mod oracle_tests; #[cfg(test)] mod tests; diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs new file mode 100644 index 0000000000..2b277805f4 --- /dev/null +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -0,0 +1,335 @@ +//! Checks against sources outside this crate: code values computed here in `f64` from the Kr and +//! Kb values and the quantization each ITU-R recommendation states, the `yuv` crate's conversion +//! of the same pictures, and the plane layouts the formats' public definitions give. None of these +//! checks reads `spec::Coefficients`. +//! +//! - BT.601-7 section 2.5, : Kr 0.299, Kb 0.114. +//! - BT.709-6 items 3.2 to 3.5, : Kr 0.2126, Kb 0.0722; +//! limited range `INT[(219 E'Y + 16) 2^(n-8)]` and `INT[(224 E'C + 128) 2^(n-8)]`, where INT +//! rounds a fraction of 0.5 up. +//! - BT.2020-2 tables 4 and 5, : Kr 0.2627, Kb 0.0593, +//! quantized as in BT.709. +//! - BT.2100-3 table 9, : full range +//! `Round[(2^n - 1) E'Y]` and `Round[(2^n - 1) E'C + 2^(n-1)]`, with +//! `Round(x) = Sign(x) Floor(|x| + 0.5)`. +//! - NV12 and I420: the W3C WebCodecs `VideoPixelFormat` definitions, +//! . +//! - NV12 and P010: the Linux media API's semi-planar YUV formats and their sample 4×4 images, +//! . + +use super::*; + +const ALL: [Format; 3] = [Format::Nv12, Format::P010, Format::I420]; +const MATRICES: [Matrix; 3] = [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020]; +const RANGES: [Range; 2] = [Range::Limited, Range::Full]; + +/// Kr and Kb as each recommendation states them. +fn kr_kb(m: Matrix) -> (f64, f64) { + match m { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + } +} + +/// The unrounded luma, Cb and Cr code values of an 8-bit RGB color. +fn exact(rgb: [f64; 3], c: Conversion) -> [f64; 3] { + let (kr, kb) = kr_kb(c.matrix); + let [r, g, b] = rgb.map(|v| v / 255.0); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + let pb = (b - y) / (2.0 * (1.0 - kb)); + let pr = (r - y) / (2.0 * (1.0 - kr)); + let n = c.format.bits() as i32; + match c.range { + Range::Limited => { + let s = 2f64.powi(n - 8); + [(219.0 * y + 16.0) * s, (224.0 * pb + 128.0) * s, (224.0 * pr + 128.0) * s] + } + Range::Full => { + let m = 2f64.powi(n) - 1.0; + let half = 2f64.powi(n - 1); + [m * y, m * pb + half, m * pr + half] + } + } +} + +/// `Round(x) = Sign(x) Floor(|x| + 0.5)`, clamped to the codes of `bits`. +fn round(x: f64, bits: u32) -> u16 { + (x.signum() * (x.abs() + 0.5).floor()).clamp(0.0, f64::from((1u32 << bits) - 1)) as u16 +} + +/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either +/// way in `f32`, so either neighbor passes there. +fn rounds_to(got: u16, exact: f64, bits: u32) -> bool { + let want = round(exact, bits); + let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3; + got == want || near_half && got.abs_diff(want) <= 1 +} + +/// Every sample of a frame as its value (P010 words shifted down by 6). +fn samples(frame: &[u8], format: Format) -> Vec { + match format { + Format::P010 => frame.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b) >> 6).collect(), + Format::Nv12 | Format::I420 => frame.iter().map(|&b| u16::from(b)).collect(), + } +} + +/// The luma sample of pixel `(x, y)` and the Cb and Cr samples of the chroma texel over it, in +/// a packed frame of `w × h`. +fn at(s: &[u16], format: Format, w: usize, h: usize, x: usize, y: usize) -> [u16; 3] { + let luma = w * h; + let (cw, ch) = (w / 2, h / 2); + let c = (y / 2) * cw + x / 2; + match format { + Format::Nv12 | Format::P010 => [s[y * w + x], s[luma + 2 * c], s[luma + 2 * c + 1]], + Format::I420 => [s[y * w + x], s[luma + c], s[luma + cw * ch + c]], + } +} + +/// Channel values that include black, white, the 75% level (191), the limited-range nominal +/// levels and values one step from the ends. +const LEVELS: [u8; 9] = [0, 1, 16, 64, 128, 191, 235, 254, 255]; + +/// A picture of every color whose channels are in [`LEVELS`], each as a 2 × 2 block, so that no +/// sample depends on how chroma is subsampled. Returns the pixels, the side and the colors. +fn blocks() -> (Vec, u32, Vec<[u8; 3]>) { + let colors: Vec<[u8; 3]> = LEVELS.iter().flat_map(|&r| LEVELS.iter().flat_map(move |&g| LEVELS.iter().map(move |&b| [r, g, b]))).collect(); + let per_row = 27usize; + let side = per_row * 2; + let mut px = vec![0u8; side * side * 4]; + for (k, rgb) in colors.iter().enumerate() { + let (bx, by) = (k % per_row, k / per_row); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let i = ((by * 2 + dy) * side + bx * 2 + dx) * 4; + px[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]); + } + } + (px, side as u32, colors) +} + +/// Every block of `frame` against the equations. `slack` is 0 for the CPU and 1 for the GPU. +fn check_blocks(frame: &[u8], c: Conversion, side: u32, colors: &[[u8; 3]], slack: u16, what: &str) { + let s = samples(frame, c.format); + let side = side as usize; + for (k, rgb) in colors.iter().enumerate() { + let (x, y) = ((k % 27) * 2, (k / 27) * 2); + let got = at(&s, c.format, side, side, x, y); + let want = exact(rgb.map(f64::from), c); + for i in 0..3 { + let ok = rounds_to(got[i], want[i], c.format.bits()) || got[i].abs_diff(round(want[i], c.format.bits())) <= slack; + assert!(ok, "{what} {c:?} {rgb:?}: component {i} is {} where the equations give {:.4}", got[i], want[i]); + } + } +} + +#[test] +fn the_cpu_gives_the_codes_of_the_published_equations() { + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = cpu::convert(&px, side, side, c, side, side).unwrap(); + check_blocks(&frame, c, side, &colors, 0, "CPU"); + } + } + } +} + +#[test] +fn nominal_levels_have_the_codes_the_recommendations_state() { + // White, black and neutral chroma are 235, 16 and 128 at limited range, 255, 0 and 128 at + // full range, times 4 (and 1023 for full white) at 10 bits. Chroma reaches 240 (960) for blue's + // Cb and red's Cr, and 16 (64) for yellow's Cb and cyan's Cr. At full range those are + // Round(255.5) and Round(0.5), clamped to 255 (1023) and 1. + for format in ALL { + let ten = format.bits() == 10; + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let (white, black, mid, high, low) = match (range, ten) { + (Range::Limited, false) => (235, 16, 128, 240, 16), + (Range::Limited, true) => (940, 64, 512, 960, 64), + (Range::Full, false) => (255, 0, 128, 255, 1), + (Range::Full, true) => (1023, 0, 512, 1023, 1), + }; + let code = |rgb: [u8; 3]| { + let frame = cpu::convert(&(0..4).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect::>(), 2, 2, c, 2, 2).unwrap(); + at(&samples(&frame, format), format, 2, 2, 0, 0) + }; + assert_eq!(code([255, 255, 255]), [white, mid, mid], "{c:?} white"); + assert_eq!(code([0, 0, 0]), [black, mid, mid], "{c:?} black"); + assert_eq!(code([0, 0, 255])[1], high, "{c:?} blue Cb"); + assert_eq!(code([255, 0, 0])[2], high, "{c:?} red Cr"); + assert_eq!(code([255, 255, 0])[1], low, "{c:?} yellow Cb"); + assert_eq!(code([0, 255, 255])[2], low, "{c:?} cyan Cr"); + } + } + } +} + +fn yuv_range(r: Range) -> yuv::YuvRange { + match r { + Range::Limited => yuv::YuvRange::Limited, + Range::Full => yuv::YuvRange::Full, + } +} + +fn yuv_matrix(m: Matrix) -> yuv::YuvStandardMatrix { + match m { + Matrix::Bt601 => yuv::YuvStandardMatrix::Bt601, + Matrix::Bt709 => yuv::YuvStandardMatrix::Bt709, + Matrix::Bt2020 => yuv::YuvStandardMatrix::Bt2020, + } +} + +/// The `yuv` crate's conversion of `px` (`w × h`) as one packed frame in this crate's order. +/// P010 takes 10-bit RGB there, so each channel is scaled to 0..=1023 and rounded first. +fn yuv_convert(px: &[u8], w: u32, h: u32, c: Conversion) -> Vec { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut}; + let (range, matrix, mode) = (yuv_range(c.range), yuv_matrix(c.matrix), YuvConversionMode::Professional); + match c.format { + Format::Nv12 => { + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv_nv12(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat() + } + Format::I420 => { + let mut img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba_to_yuv420(&mut img, px, w * 4, range, matrix, mode).unwrap(); + [img.y_plane.borrow(), img.u_plane.borrow(), img.v_plane.borrow()].concat() + } + Format::P010 => { + let wide: Vec = px.iter().map(|&v| (f64::from(v) * 1023.0 / 255.0).round() as u16).collect(); + let mut img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + yuv::rgba10_to_p010(&mut img, &wide, w * 4, range, matrix).unwrap(); + [img.y_plane.borrow(), img.uv_plane.borrow()].concat().iter().flat_map(|v| v.to_le_bytes()).collect() + } + } +} + +/// The largest difference allowed from the `yuv` crate: 1 code value at 8 bits, and 2 at 10 bits, +/// where its input was rounded to 10 bits first. +fn yuv_tolerance(format: Format) -> u16 { + if format.bits() == 10 { 2 } else { 1 } +} + +#[test] +fn the_cpu_matches_the_yuv_crate() { + let (px, side, _) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let ours = samples(&cpu::convert(&px, side, side, c, side, side).unwrap(), format); + let theirs = samples(&yuv_convert(&px, side, side, c), format); + assert_eq!(ours.len(), theirs.len(), "{c:?}"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + assert!(a.abs_diff(*b) <= yuv_tolerance(format), "{c:?}: sample {i} is {a} here and {b} in the yuv crate"); + } + } + } + } +} + +#[test] +fn packed_planes_have_the_sizes_the_yuv_crate_allocates() { + use yuv::{YuvBiPlanarImageMut, YuvChromaSubsampling, YuvPlanarImageMut}; + for (w, h) in [(2, 2), (4, 4), (16, 10), (1920, 1080), (3840, 2160)] { + for format in ALL { + let l = FrameLayout::new(format, w, h).unwrap(); + let s = format.sample_bytes() as usize; + let packed: Vec<(usize, usize)> = l.planes.iter().map(|p| (p.row_bytes() as usize, p.row_bytes() as usize * p.height as usize)).collect(); + let theirs: Vec<(usize, usize)> = match format { + Format::Nv12 | Format::P010 => { + let img = YuvBiPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![(img.y_stride as usize * s, img.y_plane.borrow().len() * s), (img.uv_stride as usize * s, img.uv_plane.borrow().len() * s)] + } + Format::I420 => { + let img = YuvPlanarImageMut::::alloc(w, h, YuvChromaSubsampling::Yuv420); + vec![ + (img.y_stride as usize, img.y_plane.borrow().len()), + (img.u_stride as usize, img.u_plane.borrow().len()), + (img.v_stride as usize, img.v_plane.borrow().len()), + ] + } + }; + assert_eq!(packed, theirs, "{format} {w}×{h}: row bytes and plane bytes"); + assert_eq!(l.frame_bytes(), theirs.iter().map(|p| p.1).sum::(), "{format} {w}×{h}"); + } + } +} + +/// Sixteen different colors for a 4 × 4 picture. +fn sixteen() -> Vec<[u8; 3]> { + (0..16u32).map(|k| [(k * 17) as u8, ((k * 53 + 30) % 256) as u8, ((k * 91 + 60) % 256) as u8]).collect() +} + +/// The byte offset of luma sample `(x, y)`. +type LumaAt = fn(usize, usize) -> usize; +/// The byte offsets of the Cb and Cr samples of chroma texel `(x, y)`. +type ChromaAt = fn(usize, usize) -> (usize, usize); + +/// Where the public definitions put each sample of a 4 × 4 frame. +fn documented_offsets(format: Format) -> (LumaAt, ChromaAt) { + match format { + // "start + 0: Y'00 Y'01 Y'02 Y'03 ... start + 16: Cb00 Cr00 Cb01 Cr01, start + 20: Cb10 Cr10 Cb11 Cr11" + Format::Nv12 => (|x, y| y * 4 + x, |x, y| (16 + y * 4 + x * 2, 17 + y * 4 + x * 2)), + // Rows of 8 bytes: "start + 8: Y'10 ... start + 32: Cb00 Cr00 Cb01 Cr01, start + 40: Cb10 ..." + Format::P010 => (|x, y| y * 8 + x * 2, |x, y| (32 + y * 8 + x * 4, 34 + y * 8 + x * 4)), + // Y, then U, then V; each chroma plane has 2 rows of 2 samples. + Format::I420 => (|x, y| y * 4 + x, |x, y| (16 + y * 2 + x, 20 + y * 2 + x)), + } +} + +#[test] +fn a_4x4_frame_puts_each_sample_where_the_format_definitions_do() { + let colors = sixteen(); + let px: Vec = colors.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(); + for format in ALL { + let c = Conversion::new(format, Matrix::Bt709, Range::Limited); + let frame = cpu::convert(&px, 4, 4, c, 4, 4).unwrap(); + assert_eq!(frame.len(), 4 * 4 * 3 / 2 * format.sample_bytes() as usize, "{format}"); + let read = |offset: usize| match format { + Format::P010 => { + let word = u16::from_le_bytes([frame[offset], frame[offset + 1]]); + assert_eq!(word & 0x3f, 0, "{format}: the 6 low bits are zero"); + word >> 6 + } + Format::Nv12 | Format::I420 => u16::from(frame[offset]), + }; + let (luma, chroma) = documented_offsets(format); + for y in 0..4 { + for x in 0..4 { + let want = exact(colors[y * 4 + x].map(f64::from), c)[0]; + assert!(rounds_to(read(luma(x, y)), want, format.bits()), "{format}: luma {x},{y}"); + } + } + for y in 0..2 { + for x in 0..2 { + // Each chroma sample is the code of the average of the 2 × 2 pixels under it. + let quad = [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| colors[(y * 2 + dy) * 4 + x * 2 + dx]); + let mean = [0, 1, 2].map(|i| quad.iter().map(|p| f64::from(p[i])).sum::() / 4.0); + let want = exact(mean, c); + let (cb, cr) = chroma(x, y); + assert!(rounds_to(read(cb), want[1], format.bits()), "{format}: Cb {x},{y}"); + assert!(rounds_to(read(cr), want[2], format.bits()), "{format}: Cr {x},{y}"); + } + } + } +} + +#[test] +fn the_gpu_gives_the_codes_of_the_published_equations() { + let Some((device, queue)) = tests::device() else { return }; + let (px, side, colors) = blocks(); + for format in ALL { + for matrix in MATRICES { + for range in RANGES { + let c = Conversion::new(format, matrix, range); + let frame = tests::gpu_convert(&device, &queue, (&px, side, side), c, (side, side)); + check_blocks(&frame, c, side, &colors, 1, "GPU"); + } + } + } +} diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index cb852b8761..0ee3f5ba6b 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -100,8 +100,9 @@ impl Conversion { /// The weights and the scale of one conversion. The code value of luma is /// `dot(y, rgb) * y_scale + y_offset`, of Cb `dot(cb, rgb) * c_scale + c_offset`, and of Cr -/// `dot(cr, rgb) * c_scale + c_offset`, rounded half to even and clamped to `0..=max`, for `rgb` -/// from 0 to 1. +/// `dot(cr, rgb) * c_scale + c_offset`, rounded with halves away from zero and clamped to +/// `0..=max`, for `rgb` from 0 to 1. That rounding is `INT` in BT.709 and BT.2020 and `Round` in +/// BT.2100. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Coefficients { pub y: [f32; 3], @@ -132,7 +133,7 @@ impl Coefficients { /// The code values of luma, Cb and Cr for `rgb`. pub fn codes(&self, rgb: [f32; 3]) -> [u16; 3] { let dot = |w: [f32; 3]| w[0] * rgb[0] + w[1] * rgb[1] + w[2] * rgb[2]; - let code = |v: f32| v.round_ties_even().clamp(0.0, self.max) as u16; + let code = |v: f32| v.round().clamp(0.0, self.max) as u16; [ code(dot(self.y) * self.y_scale + self.y_offset), code(dot(self.cb) * self.c_scale + self.c_offset), @@ -163,6 +164,9 @@ pub enum Error { /// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and /// size. Layout, + /// The device reported an error (validation, out of memory, a failed map or poll) while + /// [`crate::YuvProvider`] ran a job on it. + Device(String), } impl fmt::Display for Error { @@ -177,6 +181,7 @@ impl fmt::Display for Error { Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"), Error::Layout => f.write_str("the frame layout does not match its format and size"), + Error::Device(message) => write!(f, "the device reported an error: {message}"), } } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index 1db1ef20d8..68e3a84a8f 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -194,12 +194,12 @@ fn shaders_write_no_value_wgsl_cannot_read() { // The GPU half: the passes against the CPU reference. A machine without a graphics adapter skips // these comparisons and says so on stderr. -fn device() -> Option<(wgpu::Device, wgpu::Queue)> { +pub(crate) fn device() -> Option<(wgpu::Device, wgpu::Queue)> { device_with(|l| l) } /// A device with the adapter's limits as `limits` changes them. -fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { +pub(crate) fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgpu::Device, wgpu::Queue)> { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { eprintln!("no graphics adapter: the GPU half of this test is skipped"); @@ -216,7 +216,7 @@ fn device_with(limits: impl FnOnce(wgpu::Limits) -> wgpu::Limits) -> Option<(wgp } /// `src` (its pixels, width and height) converted on the GPU to `out` (width and height). -fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { +pub(crate) fn gpu_convert(device: &wgpu::Device, queue: &wgpu::Queue, src: (&[u8], u32, u32), c: Conversion, out: (u32, u32)) -> Vec { let ((rgba, sw, sh), (w, h)) = (src, out); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -261,7 +261,7 @@ fn tolerance(format: Format) -> u16 { if format.bits() == 10 { 6 } else { 2 } } -fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { +pub(crate) fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { assert_eq!(gpu.len(), cpu.len(), "{what}"); let (g, k) = (samples(gpu, c.format), samples(cpu, c.format)); let worst = g.iter().zip(&k).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b)); @@ -271,7 +271,7 @@ fn assert_close(gpu: &[u8], cpu: &[u8], c: Conversion, what: &str) { } /// A picture with hard edges: each pixel's channels from a fixed pseudo-random sequence. -fn noise(w: u32, h: u32) -> Vec { +pub(crate) fn noise(w: u32, h: u32) -> Vec { let mut x = 0x2545_f491_u32; (0..w * h * 4) .map(|i| { @@ -284,7 +284,7 @@ fn noise(w: u32, h: u32) -> Vec { } /// A smooth picture: three ramps at different angles. -fn ramps(w: u32, h: u32) -> Vec { +pub(crate) fn ramps(w: u32, h: u32) -> Vec { (0..h) .flat_map(|y| { (0..w).flat_map(move |x| { diff --git a/docs/gpu-providers.md b/docs/gpu-providers.md index a1282b8a1e..a4d0c27d5f 100644 --- a/docs/gpu-providers.md +++ b/docs/gpu-providers.md @@ -7,6 +7,7 @@ Provider ids: - `craft.mask`: CPU stand-in for FilmCraft mask composite until WGSL lands on wgpu - `craft.composite.premul`: CPU premultiplied "over" (Normal path from `composite.wgsl`) until WGSL lands on wgpu - `craft.readback`: CPU decode of staging buffers (`f16` RGBA → `f32`, or `fmt:u8` passthrough); uses [`chunk_buffer`](../crates/gpu/src/chunk.rs) against device caps and [`f16_to_f32*`](../crates/gpu/src/readback.rs) from **craft-gpu** +- `craft.yuv`: RGBA8 to NV12, P010 or I420 with scaling, registered from **craft-gpu-yuv** (`YuvProvider`, see [its README](../crates/gpu-yuv/README.md)). It is not in `register_all()`, since it depends on wgpu. `YuvProvider::new()` converts on the CPU on any context; `YuvProvider::with_device` runs its WGSL render passes on a device the host passes in. - `{app}.*`: registered by application wasm at init Generic worker code must only call `ProviderRegistry::dispatch`: never import app gpu crates. From e4c1dc59972c278c786b451881fcdd6b723ba42e Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 18 Nov 2026 09:35:41 +0530 Subject: [PATCH 052/490] Shapes: the Triangle tool's own corner radius in the options bar, its drag and Create Triangle ShapeGeometry::Triangle carries a corner radius; its outline rounds each corner with an arc tangent to both edges, capped at half the shorter edge. ShapeToolSettings keeps the Triangle's radius apart from the Rectangle's (storytold/photocraft#13355), the Triangle bar shows it as Radius (0 to 150,000 px), and Create Triangle has one Radius field (cornerRadius in automation). --- crates/draw/src/geometry/shape.rs | 67 ++++++++++++-- crates/draw/src/ui/shape/bar.rs | 9 +- crates/draw/src/ui/shape/mod.rs | 20 ++-- crates/draw/src/ui/shape_drag/dialog.rs | 44 +++++++-- crates/draw/src/ui/shape_drag/mod.rs | 5 +- crates/draw/src/ui/shape_drag/tool.rs | 4 +- crates/draw/tests/it/shape_cells.rs | 59 ++++++++++++ crates/draw/tests/it/shape_drag.rs | 116 ++++++++++++++++++++++++ 8 files changed, 294 insertions(+), 30 deletions(-) diff --git a/crates/draw/src/geometry/shape.rs b/crates/draw/src/geometry/shape.rs index 3a8ce7a585..f1e3cdbd9b 100644 --- a/crates/draw/src/geometry/shape.rs +++ b/crates/draw/src/geometry/shape.rs @@ -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() { diff --git a/crates/draw/src/ui/shape/bar.rs b/crates/draw/src/ui/shape/bar.rs index cbe183040a..1f08eafe2f 100644 --- a/crates/draw/src/ui/shape/bar.rs +++ b/crates/draw/src/ui/shape/bar.rs @@ -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, diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 0ccad43ade..45f8e5673c 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -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, diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index ad6b6e35ab..02f6ef61dd 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -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 { 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; diff --git a/crates/draw/src/ui/shape_drag/mod.rs b/crates/draw/src/ui/shape_drag/mod.rs index 9d24fe9690..c065ede2a5 100644 --- a/crates/draw/src/ui/shape_drag/mod.rs +++ b/crates/draw/src/ui/shape_drag/mod.rs @@ -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; diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index d21a7a8182..0660c2bc5c 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -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 }, diff --git a/crates/draw/tests/it/shape_cells.rs b/crates/draw/tests/it/shape_cells.rs index 5f58967853..c9c8537e7f 100644 --- a/crates/draw/tests/it/shape_cells.rs +++ b/crates/draw/tests/it/shape_cells.rs @@ -285,3 +285,62 @@ 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, +} + +/// 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] +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)); +} diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 3eb3fd5027..9042e335ff 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -373,3 +373,119 @@ 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 { + 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 base's two arcs meet in its middle, halfway along the shortest edge. + assert!(got.iter().any(|p| near(*p, Point::new(100.0, 100.0))), "{radius}: capped at half the base: {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] +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::(&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 = + 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::().map(|dialog| dialog.options().radii); + assert_eq!(radii, Some([30.0; 4]), "the typed radius is the triangle's"); +} From d1d1667c99d7ff7d0889d549cb1f33698088909d Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 18 Nov 2026 10:11:49 +0530 Subject: [PATCH 053/490] Shapes: import ParamCurve for the triangle arc test --- crates/draw/tests/it/shape_drag.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 9042e335ff..5b447590ac 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -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; From c430dff1bf8283cdc8e289b9e20d1ba3af5a4244 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 18 Nov 2026 10:27:34 +0530 Subject: [PATCH 054/490] Shapes: the capped triangle test meets halfway along the slanted edges; allow field reassignment on the non-exhaustive settings --- crates/draw/tests/it/shape_cells.rs | 1 + crates/draw/tests/it/shape_drag.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/draw/tests/it/shape_cells.rs b/crates/draw/tests/it/shape_cells.rs index c9c8537e7f..e29ad711a4 100644 --- a/crates/draw/tests/it/shape_cells.rs +++ b/crates/draw/tests/it/shape_cells.rs @@ -296,6 +296,7 @@ struct BarHost { /// `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(); diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 5b447590ac..53a366425e 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -414,8 +414,11 @@ fn a_triangle_radius_past_what_the_shape_holds_is_capped_and_zero_is_sharp() { 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 base's two arcs meet in its middle, halfway along the shortest edge. - assert!(got.iter().any(|p| near(*p, Point::new(100.0, 100.0))), "{radius}: capped at half the base: {got:?}"); + // 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"); } @@ -425,6 +428,7 @@ fn a_triangle_radius_past_what_the_shape_holds_is_capped_and_zero_is_sharp() { /// 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; From b78899df5f623123fbd200732c414dd5ea269ed9 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:28:05 +0100 Subject: [PATCH 055/490] New Document: Photo, Print and Art & Illustration list the blank document presets PresetCategory::standard() (PhotoCraft's categories) takes the lists measured for photocraft#14040: Photo gains the default size, 3 x 2, 2 x 3 and 8 x 10; Print gains A6, B5, C4, C5, C6 and DL in ISO order; Art & Illustration lists the 1000 and 2000 pixel grids, Poster, a portrait Postcard, 1080p and 720p. DocumentPreset::pixel_sized marks the grids: they show and apply their pixels at the print resolution instead of a size in inches. --- .../form_dialogs/new_document/cards.rs | 2 +- .../form_dialogs/new_document/presets.rs | 99 ++++++++++++++----- .../tests/it/form_dialogs/new_document.rs | 90 +++++++++++++++++ 3 files changed, 164 insertions(+), 27 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs index 515e182eec..a5937fd098 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs @@ -253,7 +253,7 @@ fn cards_of(tab: TabId, session: &Session, values: &DocumentOptions, read: &Read let preset_card = |preset: &DocumentPreset| { let preset = session.orientation.map_or_else(|| preset.clone(), |orientation| preset.turned(orientation)); let mut settings = preset.options(setup.print_ppi, setup.screen_ppi); - if preset.is_print() && !matches!(values.unit, UnitKind::Pixels | UnitKind::Percent) { + if preset.in_inches() && !matches!(values.unit, UnitKind::Pixels | UnitKind::Percent) { settings.unit = values.unit; } Card { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/presets.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/presets.rs index fc9e0c208b..b5e8a47c30 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/presets.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/presets.rs @@ -265,12 +265,14 @@ pub struct DocumentPreset { pub pixels_per_inch: f64, /// Picking the card turns Artboards on (Photoshop's Web and Mobile presets). pub artboard: bool, + /// A print preset sized in pixels (a pixel grid): it shows and applies its pixels, at the app's print resolution. + pub pixel_sized: bool, } impl DocumentPreset { /// The card `id`, named `name` in English, for a page of `width` x `height` pixels at `pixels_per_inch`. pub const fn new(id: &'static str, name: &'static str, width: u32, height: u32, pixels_per_inch: f64) -> Self { - Self { id, name, width, height, pixels_per_inch, artboard: false } + Self { id, name, width, height, pixels_per_inch, artboard: false, pixel_sized: false } } /// The card turns Artboards on when picked. @@ -280,12 +282,25 @@ impl DocumentPreset { self } - /// Whether the preset is for print (300 ppi and up): its card and fields show inches at the app's print resolution; - /// screen presets stay in pixels. + /// The card keeps its pixels: it shows and applies them at the app's print resolution instead of keeping a page + /// size in inches. + #[must_use] + pub const fn pixel_sized(mut self) -> Self { + self.pixel_sized = true; + self + } + + /// Whether the preset is for print (300 ppi and up): it takes the app's print resolution; screen presets take the + /// screen resolution. pub fn is_print(&self) -> bool { self.pixels_per_inch >= 300.0 } + /// Whether the card and fields show the preset in inches: a print preset that is not [`pixel_sized`](Self::pixel_sized). + pub fn in_inches(&self) -> bool { + self.is_print() && !self.pixel_sized + } + /// The preset turned to `orientation`; a square preset stays as it is. #[must_use] pub fn turned(&self, orientation: Orientation) -> DocumentPreset { @@ -296,14 +311,15 @@ impl DocumentPreset { DocumentPreset { width: self.height, height: self.width, ..self.clone() } } - /// The preset as settings: the unit (inches for print, pixels for screen) and the resolution moved to the app's - /// print or screen resolution, keeping a print preset's physical size. + /// The preset as settings: the unit (inches for print, pixels for screen and pixel-sized presets) and the + /// resolution moved to the app's print or screen resolution, keeping a print preset's physical size and any other + /// preset's pixels. pub fn options(&self, print_ppi: f64, screen_ppi: f64) -> DocumentOptions { - let print = self.is_print(); - let wanted = if print { print_ppi } else { screen_ppi }; + let inches = self.in_inches(); + let wanted = if self.is_print() { print_ppi } else { screen_ppi }; let (width, height, pixels_per_inch) = if !(wanted.is_finite() && wanted > 0.0) { (self.width, self.height, self.pixels_per_inch) - } else if print { + } else if inches { let scale = wanted / self.pixels_per_inch; let pixels = |side: u32| (f64::from(side) * scale).round().clamp(1.0, MAX_DOCUMENT_SIDE) as u32; (pixels(self.width), pixels(self.height), wanted) @@ -313,7 +329,7 @@ impl DocumentPreset { DocumentOptions { size: PixelSize::new(width, height), pixels_per_inch, - unit: if print { UnitKind::Inches } else { UnitKind::Pixels }, + unit: if inches { UnitKind::Inches } else { UnitKind::Pixels }, ..DocumentOptions::default() } } @@ -345,12 +361,15 @@ impl PresetCategory { "photo", "Photo", vec![ + DocumentPreset::new(DEFAULT_ID, "Default Size", 2100, 1500, 300.0), + DocumentPreset::new("landscape-3x2", "Landscape, 3 x 2", 900, 600, 300.0), DocumentPreset::new("landscape-6x4", "Landscape, 6 x 4", 1800, 1200, 300.0), DocumentPreset::new("landscape-7x5", "Landscape, 7 x 5", 2100, 1500, 300.0), DocumentPreset::new("landscape-10x8", "Landscape, 10 x 8", 3000, 2400, 300.0), + DocumentPreset::new("portrait-2x3", "Portrait, 2 x 3", 600, 900, 300.0), DocumentPreset::new("portrait-4x6", "Portrait, 4 x 6", 1200, 1800, 300.0), DocumentPreset::new("portrait-5x7", "Portrait, 5 x 7", 1500, 2100, 300.0), - DocumentPreset::new("square-5x5", "Square, 5 x 5", 1500, 1500, 300.0), + DocumentPreset::new("portrait-8x10", "Portrait, 8 x 10", 2400, 3000, 300.0), ], ), PresetCategory::new( @@ -361,20 +380,28 @@ impl PresetCategory { DocumentPreset::new("legal", "Legal", 2550, 4200, 300.0), DocumentPreset::new("tabloid", "Tabloid", 3300, 5100, 300.0), DocumentPreset::new("a4", "A4", 2480, 3508, 300.0), - DocumentPreset::new("a3", "A3", 3508, 4961, 300.0), + DocumentPreset::new("a6", "A6", 1240, 1748, 300.0), DocumentPreset::new("a5", "A5", 1748, 2480, 300.0), - DocumentPreset::new("b3", "B3", 4169, 5906, 300.0), + DocumentPreset::new("a3", "A3", 3508, 4961, 300.0), + DocumentPreset::new("b5", "B5", 2079, 2953, 300.0), DocumentPreset::new("b4", "B4", 2953, 4169, 300.0), + DocumentPreset::new("b3", "B3", 4169, 5906, 300.0), + DocumentPreset::new("c4", "C4", 2705, 3827, 300.0), + DocumentPreset::new("c5", "C5", 1913, 2705, 300.0), + DocumentPreset::new("c6", "C6", 1346, 1913, 300.0), + DocumentPreset::new("dl", "DL", 1299, 2598, 300.0), ], ), PresetCategory::new( "art", "Art & Illustration", vec![ + DocumentPreset::new("grid-1000", "1000 pixel grid", 1000, 1000, 300.0).pixel_sized(), + DocumentPreset::new("grid-2000", "2000 pixel grid", 2000, 2000, 300.0).pixel_sized(), DocumentPreset::new("poster", "Poster", 5400, 7200, 300.0), - DocumentPreset::new("postcard", "Postcard", 1800, 1200, 300.0), - DocumentPreset::new("comic-book", "Comic Book", 1988, 3075, 300.0), - DocumentPreset::new("square-12x12", "Square, 12 x 12", 3600, 3600, 300.0), + DocumentPreset::new("postcard", "Postcard", 1200, 1800, 300.0), + DocumentPreset::new("video-1080p", "1080p", 1920, 1080, 72.0), + DocumentPreset::new("video-720p", "720p", 1280, 720, 72.0), ], ), PresetCategory::new( @@ -461,24 +488,34 @@ craft_ui::words! { /// The names of the built-in presets, in the order of `PRESET_IDS`. pub struct NewDocumentPresetWords { names: array [ + "newDocumentPreset.landscape3x2" = "Landscape, 3 x 2", "newDocumentPreset.landscape6x4" = "Landscape, 6 x 4", "newDocumentPreset.landscape7x5" = "Landscape, 7 x 5", "newDocumentPreset.landscape10x8" = "Landscape, 10 x 8", + "newDocumentPreset.portrait2x3" = "Portrait, 2 x 3", "newDocumentPreset.portrait4x6" = "Portrait, 4 x 6", "newDocumentPreset.portrait5x7" = "Portrait, 5 x 7", - "newDocumentPreset.square5x5" = "Square, 5 x 5", + "newDocumentPreset.portrait8x10" = "Portrait, 8 x 10", "newDocumentPreset.letter" = "Letter", "newDocumentPreset.legal" = "Legal", "newDocumentPreset.tabloid" = "Tabloid", "newDocumentPreset.a4" = "A4", - "newDocumentPreset.a3" = "A3", + "newDocumentPreset.a6" = "A6", "newDocumentPreset.a5" = "A5", - "newDocumentPreset.b3" = "B3", + "newDocumentPreset.a3" = "A3", + "newDocumentPreset.b5" = "B5", "newDocumentPreset.b4" = "B4", + "newDocumentPreset.b3" = "B3", + "newDocumentPreset.c4" = "C4", + "newDocumentPreset.c5" = "C5", + "newDocumentPreset.c6" = "C6", + "newDocumentPreset.dl" = "DL", + "newDocumentPreset.grid1000" = "1000 pixel grid", + "newDocumentPreset.grid2000" = "2000 pixel grid", "newDocumentPreset.poster" = "Poster", "newDocumentPreset.postcard" = "Postcard", - "newDocumentPreset.comicBook" = "Comic Book", - "newDocumentPreset.square12x12" = "Square, 12 x 12", + "newDocumentPreset.video1080p" = "1080p", + "newDocumentPreset.video720p" = "720p", "newDocumentPreset.webMostCommon" = "Web Most Common", "newDocumentPreset.webMinimum" = "Web Minimum", "newDocumentPreset.webLarge" = "Web Large", @@ -499,25 +536,35 @@ craft_ui::words! { } /// The ids of the built-in presets, in the order of `PresetWords::names`. -const PRESET_IDS: [&str; 33] = [ +const PRESET_IDS: [&str; 43] = [ + "landscape-3x2", "landscape-6x4", "landscape-7x5", "landscape-10x8", + "portrait-2x3", "portrait-4x6", "portrait-5x7", - "square-5x5", + "portrait-8x10", "letter", "legal", "tabloid", "a4", - "a3", + "a6", "a5", - "b3", + "a3", + "b5", "b4", + "b3", + "c4", + "c5", + "c6", + "dl", + "grid-1000", + "grid-2000", "poster", "postcard", - "comic-book", - "square-12x12", + "video-1080p", + "video-720p", "web-most-common", "web-minimum", "web-large", diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 27f9dcf8ed..631cf3aa6f 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -174,3 +174,93 @@ fn pixel_aspect_lists_the_custom_entries_and_shows_an_unknown_id_as_square() { fixture.click(&row).idle(10); assert!(shows(&fixture, "DVCPRO HD 1080 (1.5)") && shows(&fixture, "Mine"), "the built-in ratios, then the app's"); } + +/// The names of the standard category `id`, in card order. +fn standard_names(id: &str) -> Vec<&'static str> { + let categories = craft_ui::patterns::form_dialogs::PresetCategory::standard(); + categories.iter().find(|category| category.id == id).expect("a standard category").presets.iter().map(|preset| preset.name).collect() +} + +/// The standard preset `name` of category `id`. +fn standard_preset(id: &str, name: &str) -> craft_ui::patterns::form_dialogs::DocumentPreset { + let categories = craft_ui::patterns::form_dialogs::PresetCategory::standard(); + let category = categories.into_iter().find(|category| category.id == id).expect("a standard category"); + category.presets.into_iter().find(|preset| preset.name == name).expect("a standard preset") +} + +#[trial] +fn photo_print_and_art_list_the_blank_document_presets() { + assert_eq!( + standard_names("photo"), + [ + "Default Size", + "Landscape, 3 x 2", + "Landscape, 6 x 4", + "Landscape, 7 x 5", + "Landscape, 10 x 8", + "Portrait, 2 x 3", + "Portrait, 4 x 6", + "Portrait, 5 x 7", + "Portrait, 8 x 10" + ] + ); + assert_eq!(standard_names("print"), ["Letter", "Legal", "Tabloid", "A4", "A6", "A5", "A3", "B5", "B4", "B3", "C4", "C5", "C6", "DL"]); + assert_eq!(standard_names("art"), ["1000 pixel grid", "2000 pixel grid", "Poster", "Postcard", "1080p", "720p"]); + // ISO 216 / ISO 269 sizes in millimetres, at 300 ppi. + let mm = |side: f64| (side / 25.4 * 300.0).round() as u32; + for (name, width, height) in [ + ("A3", 297.0, 420.0), + ("A4", 210.0, 297.0), + ("A5", 148.0, 210.0), + ("A6", 105.0, 148.0), + ("B3", 353.0, 500.0), + ("B4", 250.0, 353.0), + ("B5", 176.0, 250.0), + ("C4", 229.0, 324.0), + ("C5", 162.0, 229.0), + ("C6", 114.0, 162.0), + ("DL", 110.0, 220.0), + ] { + let preset = standard_preset("print", name); + assert_eq!((preset.width, preset.height, preset.pixels_per_inch), (mm(width), mm(height), 300.0), "{name}"); + } + let photo = standard_preset("photo", "Portrait, 8 x 10"); + assert_eq!((photo.width, photo.height), (2400, 3000)); + let postcard = standard_preset("art", "Postcard"); + assert_eq!((postcard.width, postcard.height, postcard.pixels_per_inch), (1200, 1800, 300.0), "4 x 6 in, portrait"); + let video = standard_preset("art", "720p"); + assert_eq!((video.width, video.height, video.pixels_per_inch), (1280, 720, 72.0)); +} + +#[trial] +fn the_pixel_grids_keep_their_pixels_at_the_print_resolution() { + use craft_ui::runtime::env::UnitKind; + let grid = standard_preset("art", "1000 pixel grid"); + assert!(grid.is_print() && !grid.in_inches()); + for (print, screen) in [(300.0, 72.0), (200.0, 96.0)] { + let options = grid.options(print, screen); + assert_eq!( + (options.size.width, options.size.height, options.pixels_per_inch, options.unit), + (1000, 1000, print, UnitKind::Pixels), + "{print} ppi" + ); + } + // A print preset keeps its inches at the print resolution; a screen preset its pixels at the screen resolution. + let postcard = standard_preset("art", "Postcard").options(200.0, 96.0); + assert_eq!((postcard.size.width, postcard.size.height, postcard.pixels_per_inch, postcard.unit), (800, 1200, 200.0, UnitKind::Inches)); + let video = standard_preset("art", "720p").options(200.0, 96.0); + assert_eq!((video.size.width, video.size.height, video.pixels_per_inch, video.unit), (1280, 720, 96.0, UnitKind::Pixels)); +} + +#[trial] +fn the_art_tab_shows_the_grids_in_pixels_and_the_postcard_in_inches() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let art = fixture.by_label("Art & Illustration").expect("the Art & Illustration tab"); + fixture.click(&art).idle(10); + assert!(shows(&fixture, "1000 × 1000 px @ 300 ppi"), "the grid's card is in pixels"); + assert!(shows(&fixture, "4 × 6 in @ 300 ppi"), "the postcard's card is in inches"); +} From 2be11623702e90f1654c9e2d60777a44baa1aa87 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:04:38 +0100 Subject: [PATCH 056/490] New Document: optional Your Recent Items layout for the Recent tab The opt-in recent_items prop (photocraft#14038) heads Recent with "Your Recent Items (n)", lays its cards four to a row in about the room three preset cards take, and lists recent_defaults only while there are no recent documents. Off by default. --- .../src/patterns/form_dialogs/new_document.rs | 14 ++++- .../form_dialogs/new_document/cards.rs | 32 +++++++--- .../tests/it/form_dialogs/new_document.rs | 63 +++++++++++++++++++ 3 files changed, 99 insertions(+), 10 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs index 95b449b177..683f4e049d 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs @@ -115,6 +115,8 @@ craft_ui::words! { dvcpro_hd_1080: "newDocument.pixelAspectDvcproHd1080" = "DVCPRO HD 1080 (1.5)"; /// `{n}` is how many cards the open tab lists. presets_heading: template "newDocument.presetsHeading" = "Blank Document Presets ({n})"; + /// Recent's heading with [`NewDocumentDialog::recent_items`]: `{n}` is how many cards it lists. + recent_heading: template "newDocument.recentHeading" = "Your Recent Items ({n})"; preset_details: "newDocument.presetDetails" = "Preset Details"; default_size: "newDocument.defaultSizePlain" = "Default Size"; /// `{app}` is the application's name. @@ -140,6 +142,7 @@ struct Setup { profiles: Vec, app_name: Option