From 20368232acacc11bb5b83817ca9a62be80c6a6a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 08:56:01 -0800 Subject: [PATCH 001/235] 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/235] 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 d1d19c6edf2c01ca014794e331681643f1837a81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 11:46:48 -0800 Subject: [PATCH 003/235] 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 460b5438c0a6262135ab5759eafa81dffe8b3a27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:18:30 -0800 Subject: [PATCH 004/235] Dialogs: a Save As goes ahead when the portal answers with a file type of another shape answer() in crates/dialogs/src/portal.rs read the portal's current_filter with zvariant's tuple conversion, which panics on a structure with fewer fields than the tuple (zvariant 5.15.1, structure.rs:382). The Save dialog's thread then ended after a file was picked, and nothing was saved. filter_label reads the label only from a structure of a string and an array of (us), the (sa(us)) type the FileChooser portal documents. A current_filter of any other shape names no file type, and the answer keeps the path. A structure with more fields than (sa(us)) used to name its file type and now names none. This carries the fix from storytold/photocraft#13490 to the code that moved here from apps/photocraft/src/portal_save.rs. --- crates/dialogs/src/portal.rs | 17 +++++++++--- crates/dialogs/src/portal/tests.rs | 42 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/dialogs/src/portal.rs b/crates/dialogs/src/portal.rs index 1c6e75b04f..f75f2223bd 100644 --- a/crates/dialogs/src/portal.rs +++ b/crates/dialogs/src/portal.rs @@ -158,13 +158,22 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = results.get("current_filter").and_then(|v| filter_label(v)); Ok(Some(Saved { path, filter })) } +/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of +/// another shape. +fn filter_label(value: &Value<'_>) -> Option { + match value { + Value::Structure(s) => match s.fields() { + [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), + _ => None, + }, + _ => None, + } +} + /// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes. // pc: apps/photocraft/src/portal_save.rs:134 file_uri_path fn file_uri_path(uri: &str) -> Option { diff --git a/crates/dialogs/src/portal/tests.rs b/crates/dialogs/src/portal/tests.rs index 18cbc07e8b..26cf0b788d 100644 --- a/crates/dialogs/src/portal/tests.rs +++ b/crates/dialogs/src/portal/tests.rs @@ -10,6 +10,48 @@ fn file_uris_become_local_paths() { assert_eq!(file_uri_path("file://host/x.png"), None); } +/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string) +/// gives the path alone; `uris` of another shape is an error. +#[trial] +fn an_answer_of_another_shape_is_not_read() { + let answer_with = |uris: Value<'_>, filter: Option>| { + let mut r = HashMap::new(); + r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); + if let Some(filter) = filter { + r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); + } + answer(0, &r) + }; + let card = || Value::from(vec!["file:///tmp/card".to_string()]); + let malformed = [ + Value::from(("PNG".to_string(),)), + Value::from(("PNG".to_string(), vec![(0u32,)])), + Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])), + Value::from((1u32, vec![(0u32, "*.png".to_string())])), + Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)), + Value::from("PNG"), + ]; + for filter in malformed { + let shape = filter.value_signature().to_string(); + assert_eq!(answer_with(card(), Some(filter)), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })), "{shape}"); + } + // The shape the portal defines is still read, and so is the one `options` sends. + let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())])); + assert_eq!(answer_with(card(), Some(png)), Ok(Some(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }))); + let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"]))); + assert_eq!(filter_label(&sent), Some("Photoshop".into())); + let malformed = [ + Value::from(vec![1u32]), + Value::from(vec![("file:///tmp/card".to_string(),)]), + Value::from(Vec::::new()), + Value::from("file:///tmp/card"), + ]; + for uris in malformed { + let shape = uris.value_signature().to_string(); + assert!(answer_with(uris, None).is_err(), "{shape}"); + } +} + /// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the /// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with. #[trial] From 5926d7ead3f1e6079b029fbc5fe388947b7f0ae4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:32:21 -0800 Subject: [PATCH 005/235] Screen: the color picker portal's answer of another shape fails the pick without a panic On Wayland the screen color picker reads the Screenshot portal's PickColor answer, whose color is a (ddd) structure. It read it with zvariant's tuple conversion, which panics inside zvariant 5.15.1 (structure.rs:382) on a structure with fewer fields than the tuple. portal_color now reads the channels only from a structure of three doubles; any other shape fails the pick with "the desktop color picker returned no color". --- crates/platform/src/screen.rs | 43 ++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 0fc52b6787..8a247ab446 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -155,6 +155,19 @@ fn picked_color(rgb: [f64; 3]) -> Result { Ok(Capture::Color(rgb.map(|v| v as f32))) } +/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> { + use zbus::zvariant::Value; + match value { + Value::Structure(s) => match s.fields() { + [Value::F64(r), Value::F64(g), Value::F64(b)] => Some([*r, *g, *b]), + _ => None, + }, + _ => None, + } +} + /// The most pixels one monitor image may hold (64 M); larger captures fail with `Failed`. pub const MAX_PIXELS: usize = 64 * 1024 * 1024; @@ -231,7 +244,10 @@ fn unpack_rgba( #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod backend { - use super::{Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, usable_scale}; + use super::{ + Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, portal_color, + usable_scale, + }; const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024; /// Length limit of the property reads, in 32-bit units. @@ -437,8 +453,7 @@ mod backend { _ => return Err(failed("the desktop color picker could not sample this screen")), } let value = values.get("color").ok_or_else(|| failed("the desktop color picker returned no color"))?; - let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(failed)?.try_into().map_err(|e: zbus::zvariant::Error| failed(e))?; - picked_color([r, g, b]) + picked_color(portal_color(value).ok_or_else(|| failed("the desktop color picker returned no color"))?) } } @@ -724,4 +739,26 @@ mod tests { assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err()); assert!(checked_stride(1, 1, usize::MAX).is_err()); } + + /// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array) + /// gives no colour; a `(ddd)` value gives its channels. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[test] + fn a_color_of_another_shape_is_not_read() { + use zbus::zvariant::Value; + let malformed = [ + Value::from((0.5f64,)), + Value::from((0.5f64, 0.25f64)), + Value::from((0.5f64, 0.25f64, 1u32)), + Value::from(("red".to_string(), 0.25f64, 0.75f64)), + Value::from((0.5f64, 0.25f64, 0.75f64, 1.0f64)), + Value::from("red"), + Value::from(vec![0.5f64, 0.25, 0.75]), + ]; + for color in malformed { + let shape = color.value_signature().to_string(); + assert_eq!(portal_color(&color), None, "{shape}"); + } + assert_eq!(portal_color(&Value::from((0.5f64, 0.25f64, 0.75f64))), Some([0.5, 0.25, 0.75])); + } } From 61aaf23e7287d9f3c5a78dd4a8d231cfdf42f541 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:15:12 -0800 Subject: [PATCH 006/235] 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 0b9508e67285fc973c5cba3957f281a30c66a7f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:30:30 -0800 Subject: [PATCH 007/235] craft-quit: add a README for the close hook, quit() and the Quit menu id The crate had only rustdoc. The README states where on_close_request goes in eframe::App::logic, the rules for the app's unsaved-changes check and prompt, what quit() does on each platform, and how an app with its own menu uses QUIT_MENU_ID and on_menu_event. The workspace README links to it. --- README.md | 2 +- crates/quit/README.md | 90 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 crates/quit/README.md diff --git a/README.md b/README.md index 9512980917..7bd3598bb5 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item means stays in each app. -- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional +- [`craft-quit`](crates/quit/README.md): native macOS quit, egui close handling and an optional app menu. Unsaved-document decisions and save prompts stay in each app. - [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages diff --git a/crates/quit/README.md b/crates/quit/README.md new file mode 100644 index 0000000000..757327aa76 --- /dev/null +++ b/crates/quit/README.md @@ -0,0 +1,90 @@ +# craft-quit + +Quit a Craft app the platform's own way, and route an egui window close through that quit. On macOS +the quit is `-[NSApplication terminate:]`; on other platforms the crate does nothing and the window +closes as usual. Unsaved-document decisions and save prompts stay in each app. + +## Why macOS needs it + +An eframe app on macOS must not leave by closing its window. eframe drops the window while AppKit's +run loop is still running. In the next display cycle AppKit's Touch Bar finder tries to remove a KVO +observer from the view that is gone (`-[_NSTouchBarFinderObservation invalidate]`), which raises an +uncaught Objective-C exception, and the app crashes. `terminate:`, what ⌘Q does in winit's default +menu, ends the process before another display cycle runs. + +## Features + +| Feature | Adds | +| --- | --- | +| (none) | `quit()` | +| `egui` | `on_close_request`, `on_menu_event` and `QUIT_MENU_ID` | +| `menu` | `egui`, plus the deprecated `install_app_menu` (use `craft_menu::mac::install_app_menu`) | + +## Use + +Call `craft_quit::on_close_request(ctx)` once per frame, last in `eframe::App::logic`, after the +app's own close decision: + +```rust,ignore +fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + if ctx.input(|i| i.viewport().close_requested()) + && self.has_unsaved_changes() + && !self.discard_confirmed + { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.show_save_prompt = true; + } + craft_quit::on_close_request(ctx); // last, so it sees the app's `CancelClose` +} + +fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + // ... the app's UI, including the prompt when show_save_prompt is true ... +} +``` + +When the root window was asked to close (the close button, the app's own `ViewportCommand::Close`, +the OS) and the app did not send `CancelClose` in the same frame, `on_close_request` cancels the +close and calls `quit()`. It returns whether it took the close over. It does nothing in a child +viewport, and it does nothing on platforms where `quit()` returns `false`. + +Rules for the app: + +- Keep the unsaved-changes check in `logic`, not in `ui`. `logic` runs before `ui`, so a check in + `ui` would come after the quit. eframe also calls `logic` while the window is minimized or hidden, + when `ui` does not run. +- Keep the prompt's state in the app and draw the prompt in `ui`. Send `ViewportCommand::Close` + only after Save has succeeded and cleared the dirty state, or after Don't Save has set the + confirmation flag. Cancel, a canceled file picker and a failed save keep the app open. +- Reset the prompt and confirmation state when the decision is canceled or a new document opens. +- Let an asynchronous save finish before sending Close. +- If the window is hidden, show it again before showing the prompt. +- Save what the app keeps in `eframe::App::on_exit`. winit's `applicationWillTerminate:` runs + eframe's exit handling before the process ends. Code after `eframe::run_native` in `main` does + not run on macOS; move it to `on_exit`. + +## `quit()` + +On macOS, `quit()` schedules `terminate:` on the main queue and returns `true`. The caller keeps its +window open, and the process ends once the current event has been handled. Call it while the event +loop is running (any eframe callback is). Return to the event loop before blocking: a blocking +native dialog opened in the same callback would run the quit while winit is still handling the +event, which panics. + +On other platforms `quit()` returns `false`. + +## A Quit menu item that asks first + +muda's `PredefinedMenuItem::quit` and winit's default app menu end the process without asking the +app. An app with its own native menu gives its Quit item the id `craft_quit::QUIT_MENU_ID` and +passes its menu events to `craft_quit::on_menu_event(ctx, id)`. For that id, `on_menu_event` sends +the root window `ViewportCommand::Close`, so the app's unsaved-changes check runs as it does for the +close button, and `on_close_request` then quits. It returns `false` for other ids and leaves them +to the caller. It can be called between frames; egui keeps the command for the next frame. + +An app without a menu of its own uses `craft_menu::mac::install_app_menu`, which builds a minimal +app menu with that Quit item. `craft_quit::install_app_menu` is deprecated in its favor. + +## Notes + +- No `unsafe`: the macOS calls go through objc2's safe API. +- The macOS dependencies (objc2, objc2-app-kit, dispatch2) are already in eframe apps' lock files. From c28c2d395f32d172f9b4b6a06a21d7117e622238 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:32:12 -0800 Subject: [PATCH 008/235] keymap: Mods::to_egui gives the modifiers an egui key event carries Mods::from_egui reads egui's modifiers for a platform, but nothing went the other way: Chord::to_egui_shortcut leaves mac_cmd unset, so it does not give the Modifiers egui-winit reports for a key press on macOS. A test harness or remote control that types a chord into egui had to fold the platform itself. Mods::to_egui(platform) sets mac_cmd and command for cmd on macOS, and ctrl and command for cmd or ctrl elsewhere. A test converts all 16 combinations both ways on each platform and checks that a press built from a chord matches that chord. --- crates/keymap/src/egui.rs | 14 ++++++++++++++ crates/keymap/tests/egui.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index d340003999..72e14ee32d 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -78,6 +78,20 @@ impl Mods { Mods { cmd: mods.ctrl || mods.command, ctrl: false, alt: mods.alt, shift: mods.shift } } } + + /// The modifiers an egui key event carries for these keys on `platform`, for typing a chord + /// into egui in tests and remote control. On macOS cmd sets `mac_cmd` and `command`; elsewhere + /// cmd and ctrl both set `ctrl` and `command`, as egui-winit reports the Ctrl key. + /// [`Mods::from_egui`] reads the result back as these modifiers, with ctrl folded into cmd off + /// macOS. + pub fn to_egui(self, platform: Platform) -> Modifiers { + if platform.is_mac() { + Modifiers { alt: self.alt, ctrl: self.ctrl, shift: self.shift, mac_cmd: self.cmd, command: self.cmd } + } else { + let ctrl = self.cmd || self.ctrl; + Modifiers { alt: self.alt, ctrl, shift: self.shift, mac_cmd: false, command: ctrl } + } + } } impl Chord { diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 6133e8712f..b8362d0741 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -45,6 +45,34 @@ fn modifiers_and_shortcuts_follow_the_platform() { assert!(Modifiers { mac_cmd: true, command: true, shift: true, ..Modifiers::NONE }.matches_exact(shortcut.modifiers)); } +#[test] +fn modifiers_convert_to_egui_and_back_on_every_platform() { + let all = (0..16u8).map(|b| Mods { cmd: b & 1 != 0, ctrl: b & 2 != 0, alt: b & 4 != 0, shift: b & 8 != 0 }); + for mods in all { + assert_eq!(Mods::from_egui(&mods.to_egui(Platform::Mac), Platform::Mac), mods, "{mods:?} on Mac"); + for platform in [Platform::Windows, Platform::Linux] { + let folded = Mods { cmd: mods.cmd || mods.ctrl, ctrl: false, ..mods }; + assert_eq!(Mods::from_egui(&mods.to_egui(platform), platform), folded, "{mods:?} on {platform:?}"); + } + } + + // What egui-winit reports for the Command key on macOS and the Ctrl key elsewhere. + assert_eq!(Mods::CMD.to_egui(Platform::Mac), Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }); + assert_eq!(Mods::CTRL.to_egui(Platform::Mac), Modifiers { ctrl: true, ..Modifiers::NONE }); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + assert_eq!(Mods::CMD.to_egui(Platform::Windows), ctrl); + assert_eq!(Mods::CTRL.to_egui(Platform::Linux), ctrl); + let alt_shift = Mods { alt: true, shift: true, ..Mods::NONE }; + assert_eq!(alt_shift.to_egui(Platform::Windows), Modifiers { alt: true, shift: true, ..Modifiers::NONE }); + + // A press built from a chord matches that chord on its platform. + let presses = [("Cmd+Shift+Z", Platform::Mac), ("Ctrl+Alt+K", Platform::Mac), ("Cmd+S", Platform::Windows), ("Ctrl+S", Platform::Linux)]; + for (text, platform) in presses { + let c = chord(text); + assert!(matches(&c, c.key.to_egui(), &c.mods.to_egui(platform), platform), "{text} on {platform:?}"); + } +} + #[test] fn shifted_symbols_match_their_bindings() { let p = Platform::Windows; From f8a2f109e6c9235fe7619c1e423be53b7409ea1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:35:45 -0800 Subject: [PATCH 009/235] craft-window: the title-bar double-click follows GNOME's setting On GNOME the app draws the frame, and a double-click on the empty title-bar strip always maximized the window. The strip now reads org.gnome.desktop.wm.preferences action-double-click-titlebar through gsettings, on the same bounded reader as button-layout: minimize minimizes, none, lower, menu and toggle-shade do nothing, and the maximize actions zoom. Other desktops keep zooming and do not read the GNOME key. --- crates/window/README.md | 2 +- crates/window/src/lib.rs | 15 ++++++-- crates/window/src/title_bar.rs | 67 ++++++++++++++++++++++++++++++++-- 3 files changed, 76 insertions(+), 8 deletions(-) diff --git a/crates/window/README.md b/crates/window/README.md index e9dc47fbb4..93cc92e9a5 100644 --- a/crates/window/README.md +++ b/crates/window/README.md @@ -78,7 +78,7 @@ An app that draws over the title bar — a hidden macOS title bar with a full-si | Where the drag or double-click starts | What happens | | --- | --- | -| The strip's empty part | A drag moves the window (`ViewportCommand::StartDrag`); a double-click follows the system setting (macOS `AppleActionOnDoubleClick`: zoom, minimize or nothing; zoom elsewhere) | +| The strip's empty part | A drag moves the window (`ViewportCommand::StartDrag`); a double-click follows the system setting (macOS `AppleActionOnDoubleClick`, or `action-double-click-titlebar` on GNOME: zoom, minimize or nothing; zoom elsewhere) | | A control on the strip | The control gets it; the window stays put | | An in-window panel over the strip (an `Order::Middle` layer: a floating dock, an `egui::Window`) | The panel gets it; the window stays put | | A modal's backdrop or a tooltip (`Foreground`/`Tooltip`) | The window moves, as under AppKit's own title bar | diff --git a/crates/window/src/lib.rs b/crates/window/src/lib.rs index 94063f9bb9..b10f260637 100644 --- a/crates/window/src/lib.rs +++ b/crates/window/src/lib.rs @@ -438,12 +438,19 @@ mod platform { } /// GNOME's `button-layout`, read with `gsettings`. `None` when `gsettings` is missing, fails, - /// times out, or prints nothing usable. The child is spawned with piped output and read on a - /// worker thread; if it doesn't finish within 500 ms the child is killed and reaped, so a - /// stalled `gsettings` leaves neither a blocked process nor a parked worker. + /// times out, or prints nothing usable. pub(super) fn gsettings_button_layout() -> Option { + gsettings_wm_preference("button-layout") + } + + /// The value of `key` in `org.gnome.desktop.wm.preferences`, read with `gsettings` and printed + /// as `gsettings` prints it (strings quoted). `None` when `gsettings` is missing, fails, times + /// out, or prints nothing. The child is spawned with piped output and read on a worker thread; + /// if it doesn't finish within 500 ms the child is killed and reaped, so a stalled `gsettings` + /// leaves neither a blocked process nor a parked worker. + pub(super) fn gsettings_wm_preference(key: &str) -> Option { let mut child = Command::new("gsettings") - .args(["get", "org.gnome.desktop.wm.preferences", "button-layout"]) + .args(["get", "org.gnome.desktop.wm.preferences", key]) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) diff --git a/crates/window/src/title_bar.rs b/crates/window/src/title_bar.rs index aedc7debe3..9a6ca19c09 100644 --- a/crates/window/src/title_bar.rs +++ b/crates/window/src/title_bar.rs @@ -17,7 +17,8 @@ use std::sync::{Once, OnceLock}; -/// System Settings › Desktop & Dock › "Double-click a window's title bar to". +/// System Settings › Desktop & Dock › "Double-click a window's title bar to" on macOS, and GNOME's +/// `action-double-click-titlebar` on GNOME. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DoubleClick { Zoom, @@ -36,10 +37,35 @@ pub fn parse(defaults_output: &str) -> DoubleClick { } } +/// The value of GNOME's `org.gnome.desktop.wm.preferences action-double-click-titlebar`, as +/// `gsettings get` prints it (single-quoted). `toggle-maximize`, the GNOME default, and its +/// `-horizontally` and `-vertically` forms zoom; `minimize` minimizes; `none`, `lower`, `menu` and +/// `toggle-shade` do nothing, since an egui window cannot be lowered, shaded or given the window +/// menu. Anything else zooms. +pub fn parse_gnome(gsettings_output: &str) -> DoubleClick { + match gsettings_output.trim().trim_matches(|c| c == '\'' || c == '"') { + "minimize" => DoubleClick::Minimize, + "none" | "lower" | "menu" | "toggle-shade" => DoubleClick::Nothing, + _ => DoubleClick::Zoom, + } +} + +/// The action on desktop `kind` of Linux or a BSD: on GNOME (Budgie included), GNOME's setting as +/// `read` returns it, and zoom when `read` returns nothing. Other desktops zoom, and `read` is not +/// called, so a GNOME setting saved on the same machine does not apply on KDE or Xfce. +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +fn desktop_action(kind: crate::policy::DesktopKind, read: impl FnOnce() -> Option) -> DoubleClick { + if kind != crate::policy::DesktopKind::Gnome { + return DoubleClick::Zoom; + } + read().map_or(DoubleClick::Zoom, |v| parse_gnome(&v)) +} + static ACTION: OnceLock = OnceLock::new(); static READ: Once = Once::new(); -/// Starts reading the system setting on a background thread, once per run (macOS only). +/// Starts reading the system setting on a background thread, once per run (macOS, Linux and the +/// BSDs). fn prefetch() { READ.call_once(|| { #[cfg(all(target_os = "macos", not(test)))] @@ -54,10 +80,20 @@ fn prefetch() { let _ = ACTION.set(action); }); } + #[cfg(all(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"), not(test)))] + { + // No thread, no setting: the strip zooms. + let _ = std::thread::Builder::new().name("title-bar-setting".into()).spawn(|| { + let kind = crate::desktop::kind_from_env(&|k: &str| std::env::var(k).ok()); + // No `gsettings`, no GNOME schema or no answer in time: the GNOME default. + let action = desktop_action(kind, || crate::platform::gsettings_wm_preference("action-double-click-titlebar")); + let _ = ACTION.set(action); + }); + } }); } -/// The system setting; zoom until it has been read, and always zoom outside macOS. +/// The system setting; zoom until it has been read, and always zoom outside macOS and GNOME. pub fn action() -> DoubleClick { ACTION.get().copied().unwrap_or(DoubleClick::Zoom) } @@ -187,6 +223,31 @@ mod tests { } } + #[test] + fn parses_the_gnome_setting() { + assert_eq!(parse_gnome("'toggle-maximize'\n"), DoubleClick::Zoom); + assert_eq!(parse_gnome("'toggle-maximize-horizontally'\n"), DoubleClick::Zoom); + assert_eq!(parse_gnome("'toggle-maximize-vertically'\n"), DoubleClick::Zoom); + assert_eq!(parse_gnome("'minimize'\n"), DoubleClick::Minimize); + for nothing in ["'none'\n", "'lower'\n", "'menu'\n", "'toggle-shade'\n", "none"] { + assert_eq!(parse_gnome(nothing), DoubleClick::Nothing, "{nothing:?}"); + } + for junk in ["", "''", "'Minimize'", "'maximize'", "No such key"] { + assert_eq!(parse_gnome(junk), DoubleClick::Zoom, "{junk:?}"); + } + } + + #[test] + fn only_gnome_reads_the_gnome_setting() { + use crate::policy::DesktopKind; + assert_eq!(desktop_action(DesktopKind::Gnome, || Some("'minimize'\n".into())), DoubleClick::Minimize); + assert_eq!(desktop_action(DesktopKind::Gnome, || None), DoubleClick::Zoom); + for kind in [DesktopKind::Kde, DesktopKind::Tiling, DesktopKind::Other] { + let read = || -> Option { panic!("read the GNOME setting on {kind:?}") }; + assert_eq!(desktop_action(kind, read), DoubleClick::Zoom, "{kind:?}"); + } + } + #[test] fn tab_skips_the_empty_area() { let mut bar = Bar::new(); From 1463b8caeae31ddc95eebdfd756dbc4c0734ec58 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:43:19 -0800 Subject: [PATCH 010/235] settings: SectionError implements Display and Error A section that did not fit the settings type is reported in LoadReport::section_errors, but SectionError had no Display, so an app could only show it with Debug. It now formats as "settings section [] was reset to defaults: " and implements std::error::Error, as MigrateError does. --- crates/settings/src/error.rs | 8 ++++++++ crates/settings/tests/recovery.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/settings/src/error.rs b/crates/settings/src/error.rs index b8b97ee773..aa0a5488ec 100644 --- a/crates/settings/src/error.rs +++ b/crates/settings/src/error.rs @@ -38,6 +38,14 @@ pub struct SectionError { pub message: String, } +impl fmt::Display for SectionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "settings section [{}] was reset to defaults: {}", self.section, self.message) + } +} + +impl std::error::Error for SectionError {} + /// Why the store will not write `config.toml`. #[derive(Debug)] pub enum ReadOnlyReason { diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index f12e116219..a28fa9801b 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -47,6 +47,19 @@ fn bad_value_only_resets_its_section() { assert!(config_path(tmp.path()).exists(), "the file is not moved aside"); } +#[test] +fn section_error_displays_its_section_and_message() { + let tmp = tempfile::tempdir().unwrap(); + write_config(tmp.path(), "schema_version = 2\n[appearance]\ntheme = \"sepia\"\n"); + let (_, report) = open_in(tmp.path()); + let error = &report.section_errors[0]; + let text = error.to_string(); + assert!(text.starts_with("settings section [appearance] was reset to defaults: "), "{text}"); + assert!(text.ends_with(&error.message), "{text}"); + let source: &dyn std::error::Error = error; + assert!(source.source().is_none()); +} + #[test] fn many_unknown_keys_load_in_linear_time() { // Each key was once tried against every key accepted before it. From 4e349df893e013947c5bc1d806beac87264cf589 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:43:56 -0800 Subject: [PATCH 011/235] craft-settings: read config.toml up to a 16 MiB limit SettingsStore read config.toml with read_to_string at open, in the read-only fallback and before every save, so a file of any size was read into memory whole before parsing. The store now reads at most store::MAX_CONFIG_BYTES. A larger file is left untouched: the store opens read-only with Unreadable carrying ErrorKind::FileTooLarge, and a file that grows past the limit while the app runs makes the save return SettingsError::ReadOnly. --- crates/settings/README.md | 3 ++- crates/settings/src/store.rs | 35 +++++++++++++++++++++++++++---- crates/settings/tests/recovery.rs | 35 +++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 5 deletions(-) diff --git a/crates/settings/README.md b/crates/settings/README.md index 939397cf05..f0073b6630 100644 --- a/crates/settings/README.md +++ b/crates/settings/README.md @@ -139,6 +139,7 @@ things that do not belong in `config.toml`. | Older `schema_version` | `Settings::migrate` once per step, then saved; `report.migrated_from`. | | Newer `schema_version` | Values shown, store read-only, so an older build never overwrites a newer file. | | Migration step fails | Store read-only, file untouched. | +| Larger than `store::MAX_CONFIG_BYTES` (16 MiB) | Not read into memory; defaults; store read-only, file untouched; `report.read_only` is `Unreadable` with `ErrorKind::FileTooLarge`. | ## What happens when saving @@ -155,7 +156,7 @@ which can stay the same on FAT, HFS+ or network shares) with what it last read o | Changed, parses | Adopts it so its comments and unknown keys survive, backs it up, then writes this store's values over its known keys. | | Changed, does not parse | Moves it to `config.broken-.toml` (the edit is kept; `take_moved_aside()` returns the path to show), leaves the previous backup alone, then writes. | | Blank | Leaves the previous backup alone, then writes. | -| From a newer build, or its migration fails | Writes nothing; the store becomes read-only and the save returns `SettingsError::ReadOnly`, the same as at startup. | +| From a newer build, its migration fails, or larger than `store::MAX_CONFIG_BYTES` | Writes nothing; the store becomes read-only and the save returns `SettingsError::ReadOnly`, the same as at startup. | ### Concurrency contract diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 43ae721e87..f1477b006e 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -1,6 +1,6 @@ //! The in-memory store: load once, read every frame, save while the application runs. -use std::io::{self, Write}; +use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -16,6 +16,9 @@ use crate::recovery; /// The settings file name. pub const CONFIG_FILE: &str = "config.toml"; +/// Largest `config.toml` the store reads. A larger file is left untouched and the store is read-only. +pub const MAX_CONFIG_BYTES: u64 = 16 << 20; + /// How long after the last change a save is attempted. pub const DEFAULT_DEBOUNCE: Duration = Duration::from_millis(500); @@ -156,7 +159,7 @@ impl SettingsStore { return (store, report); } - match std::fs::read_to_string(&path) { + match read_config(&path) { Ok(text) => store.load_text(&path, &text, &mut report), Err(e) if e.kind() == io::ErrorKind::NotFound => { if let Some((value, from)) = migrate::import_legacy(&options.legacy) { @@ -291,7 +294,7 @@ impl SettingsStore { /// user's values instead of defaults. fn load_best_effort(&mut self, report: &mut LoadReport) { if let Some(path) = &self.path - && let Ok(text) = std::fs::read_to_string(path) + && let Ok(text) = read_config(path) && let Ok(mut doc) = document::parse(&text) { // A failed migration leaves the document half-upgraded; show defaults instead. @@ -380,9 +383,15 @@ impl SettingsStore { /// and a file from a newer build, or one whose migration fails, makes the store read-only /// instead of overwriting it, the same as at startup. fn check_disk(&mut self, path: &Path) -> Result, SettingsError> { - let text = match std::fs::read_to_string(path) { + let text = match read_config(path) { Ok(text) => text, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + // Same as at startup: leave the oversized file untouched and stop saving. + Err(e) if e.kind() == io::ErrorKind::FileTooLarge => { + let why = ReadOnlyReason::Unreadable(e).to_string(); + self.read_only = Some(why.clone()); + return Err(SettingsError::ReadOnly(why)); + } Err(e) => return Err(e.into()), }; // A blank file still parses, so adopting it below would replace this store's document -- @@ -416,6 +425,24 @@ impl SettingsStore { } } +/// Reads `config.toml` as text. A file larger than [`MAX_CONFIG_BYTES`] fails with +/// `ErrorKind::FileTooLarge` without being read into memory; text that is not UTF-8 fails with +/// `ErrorKind::InvalidData`, as `std::fs::read_to_string` does. +fn read_config(path: &Path) -> io::Result { + let file = std::fs::File::open(path)?; + let too_large = || io::Error::new(io::ErrorKind::FileTooLarge, format!("file is larger than {MAX_CONFIG_BYTES} bytes")); + if file.metadata()?.len() > MAX_CONFIG_BYTES { + return Err(too_large()); + } + // The length can change after the check, or be unknown (a pipe), so the read is capped too. + let mut bytes = Vec::new(); + file.take(MAX_CONFIG_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_CONFIG_BYTES { + return Err(too_large()); + } + String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + /// Exponential backoff: 1 s, 2 s, 4 s, … capped at [`MAX_RETRY_DELAY`]. pub fn retry_delay(failures: u32) -> Duration { let exp = failures.saturating_sub(1).min(16); diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index f12e116219..9bd2ef97ed 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -32,6 +32,41 @@ fn two_broken_files_get_different_names() { assert!(second.broken_moved_to.unwrap().exists()); } +/// Pads `config.toml` past the read limit; the file is sparse where the file system allows it. +fn grow_past_limit(dir: &std::path::Path) -> u64 { + let len = craft_settings::store::MAX_CONFIG_BYTES + 1; + std::fs::OpenOptions::new().write(true).open(config_path(dir)).unwrap().set_len(len).unwrap(); + len +} + +#[test] +fn oversized_file_opens_read_only_and_is_left_in_place() { + let tmp = tempfile::tempdir().unwrap(); + write_config(tmp.path(), "schema_version = 2\n[general]\nlanguage = \"de\"\n"); + let len = grow_past_limit(tmp.path()); + let (mut store, report) = open_in(tmp.path()); + assert!(matches!(&report.read_only, Some(ReadOnlyReason::Unreadable(e)) if e.kind() == std::io::ErrorKind::FileTooLarge), "{report:?}"); + assert!(report.broken_moved_to.is_none(), "{report:?}"); + assert_eq!(report.source, Source::Defaults); + assert!(matches!(store.flush(), Err(SettingsError::ReadOnly(_)))); + assert_eq!(std::fs::metadata(config_path(tmp.path())).unwrap().len(), len, "the file is untouched"); +} + +#[test] +fn file_grown_past_the_limit_while_running_is_not_overwritten() { + let tmp = tempfile::tempdir().unwrap(); + let (mut store, _) = open_in(tmp.path()); + store.flush().unwrap(); + let len = grow_past_limit(tmp.path()); + + store.update(|p| p.general.language = "fr".into()); + assert!(matches!(store.flush(), Err(SettingsError::ReadOnly(_)))); + assert!(store.is_read_only()); + assert!(store.take_moved_aside().is_empty()); + assert_eq!(std::fs::metadata(config_path(tmp.path())).unwrap().len(), len, "the file is untouched"); + assert!(matches!(store.tick(std::time::Instant::now()).status, craft_settings::SaveStatus::Idle), "no retries once read-only"); +} + #[test] fn bad_value_only_resets_its_section() { let tmp = tempfile::tempdir().unwrap(); From b44afe09f2648aa49d2830a30e5d98dd5b62f901 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:47:12 -0800 Subject: [PATCH 012/235] craft-update: a 404 on the release list is reported as a failed check check_for_update answered a 404 on the release list with Ok(None), so a requested check showed "up to date" for a repository that was renamed, deleted or made private. It now returns an error that names the repository, and a requested check shows it as the reason the check failed. --- crates/update/src/lib.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index 18d3160797..9a5d952ccf 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -52,15 +52,13 @@ pub use version::{Version, is_newer, parse as parse_version}; pub use dialog::{CheckResultDialog, CheckResultResponse, StartupPrompt, StartupPromptResponse}; /// Checks for an update against GitHub releases for the given app. +/// +/// Returns an error when GitHub does not find the repository (renamed, deleted or private). pub fn check_for_update(app: &App, http: &Http, current_version: &str) -> Result, String> { let version = self_update::current_version(app, current_version).map(|v| v.to_string()); let current_version = version.as_deref().unwrap_or(current_version); let url = format!("https://api.github.com/repos/{}/releases?per_page=30", app.repo); - match http.get_api(&url, None)? { - crate::http::Fetched::Body { text, .. } => offered_release(&text, app.repo, current_version), - crate::http::Fetched::RateLimited { .. } => Err("GitHub's request limit was reached".into()), - crate::http::Fetched::NotModified | crate::http::Fetched::NotFound => Ok(None), - } + checked_release(http.get_api(&url, None)?, app.repo, current_version) } /// Unix seconds now. @@ -68,6 +66,16 @@ pub fn now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) } +/// The answer of [`check_for_update`] for what GitHub's release list request `fetched`. +fn checked_release(fetched: crate::http::Fetched, repo: &str, current_version: &str) -> Result, String> { + match fetched { + crate::http::Fetched::Body { text, .. } => offered_release(&text, repo, current_version), + crate::http::Fetched::RateLimited { .. } => Err("GitHub's request limit was reached".into()), + crate::http::Fetched::NotFound => Err(format!("GitHub has no repository {repo}, or it is private")), + crate::http::Fetched::NotModified => Ok(None), + } +} + /// The release in GitHub's release list `json` to offer a copy running `current_version`, if any: /// the latest published release, when [`version::offers_update`] says so. fn offered_release(json: &str, repo: &str, current_version: &str) -> Result, String> { @@ -83,7 +91,8 @@ pub(crate) const TEST_AGENT: &str = "ArtCraft-Launcher-Test/0.0"; #[cfg(test)] mod offer_tests { - use super::offered_release; + use super::{checked_release, offered_release}; + use crate::http::Fetched; const REPO: &str = "storytold/photocraft"; const LIST: &str = r#"[{"tag_name":"v0.17.0","prerelease":false,"draft":false,"assets":[]}, @@ -106,4 +115,10 @@ mod offer_tests { assert_eq!(offered("0.17.0"), None); assert_eq!(offered("not a version"), None); } + + #[test] + fn a_repository_github_does_not_find_is_an_error_not_up_to_date() { + let why = checked_release(Fetched::NotFound, REPO, "0.16.4").unwrap_err(); + assert!(why.contains(REPO), "the reason names the repository: {why}"); + } } From 6cef16580bc48e73a4043e58ee512a7efd44c807 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:47:31 -0800 Subject: [PATCH 013/235] craft-update: Updater::with_check passes the app and running version to a custom check with_source's CheckSource takes no arguments and was documented for tests, so an app with its own release rules had to work out the app, the running version and the built-in check's HTTP client again. ContextSource gets a CheckContext with the app, the version the Updater compares, http() for the built-in check's client, and check_github() for the built-in check itself. with_source keeps its signature and now goes through with_check. --- crates/update/src/updater.rs | 72 ++++++++++++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 7 deletions(-) diff --git a/crates/update/src/updater.rs b/crates/update/src/updater.rs index aad1d1e8a4..c72f2ff97f 100644 --- a/crates/update/src/updater.rs +++ b/crates/update/src/updater.rs @@ -23,10 +23,36 @@ use crate::self_update::{Outcome, Restart}; use crate::translate::{Note, Translate, english}; use crate::{App, Http, Paths, Platform, Stop, check_for_update, self_update}; -/// Asks for the newest release (blocking; it runs on its own thread). Tests stand in for the network -/// with one; without it the check asks GitHub. +/// Asks for the newest release (blocking; it runs on its own thread), in place of the built-in +/// check that asks GitHub. It gets no context; [`ContextSource`] is the one that does. pub type CheckSource = Arc Result, String> + Send + Sync>; +/// Asks for the newest release for the app and version in a [`CheckContext`] (blocking; it runs on +/// the check's thread), in place of the built-in check that asks GitHub. An app with its own +/// release policy sets one with [`Updater::with_check`]; [`CheckContext::check_github`] runs the +/// built-in check from inside it. +pub type ContextSource = Arc Result, String> + Send + Sync>; + +/// What a check runs for: the app, and the version the running copy reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CheckContext { + pub app: &'static App, + /// The running version, after [`self_update::current_version`], as [`Updater`] compares it. + pub version: String, +} + +impl CheckContext { + /// The HTTP client the built-in check uses, with the User-Agent `/Update`. + pub fn http(&self) -> Result { + Http::new(&format!("{}/Update", self.app.name)) + } + + /// The built-in check: [`check_for_update`] over [`Self::http`]. + pub fn check_github(&self) -> Result, String> { + check_for_update(self.app, &self.http()?, &self.version) + } +} + /// What a requested check came to, for a window that answers Help ▸ Check for Updates, and what /// the last update came to, at the first start after it. #[derive(Clone, Debug, PartialEq, Eq)] @@ -143,7 +169,7 @@ impl From<&str> for Failure { pub struct Updater { app: &'static App, version: String, - source: Option, + source: Option, status: Status, /// The check running (or queued behind it) was asked for by the user. requested: bool, @@ -260,8 +286,16 @@ impl Updater { Note::new(READY_TEXT, &[("app", self.app.name)]) } - /// Replaces the network with `source` (tests). - pub fn with_source(mut self, source: CheckSource) -> Self { + /// Replaces the built-in check with `source`, which takes no arguments. [`Self::with_check`] + /// sets one that is passed the app and version. + pub fn with_source(self, source: CheckSource) -> Self { + self.with_check(Arc::new(move |_| source())) + } + + /// Replaces the built-in check with `source`, which is passed the app and the running version + /// on each check, so it can apply its own release policy without working them out again. + /// The launcher's version choice ([`crate::pins`]) is still read first. + pub fn with_check(mut self, source: ContextSource) -> Self { self.source = Some(source); self } @@ -471,9 +505,10 @@ impl Updater { let (source, probe, app, version, ctx) = (self.source.clone(), self.probe.clone(), self.app, self.version.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("update-check".into()).spawn(move || { let ask = || -> Found { + let check = CheckContext { app, version }; let checked: Checked = match source { - Some(ask) => ask(), - None => Http::new(&format!("{}/Update", app.name)).and_then(|http| check_for_update(app, &http, &version)), + Some(ask) => ask(&check), + None => check.check_github(), }; // Whether the copy installs the release itself is read from the installed files // here, on the check's thread, and not in `tick`. @@ -1090,6 +1125,29 @@ mod tests { assert_eq!(u.status(), &Status::Idle); } + /// A source set with `with_check` is passed the app and the version the updater compares, so + /// it decides on them without working them out again. + #[test] + fn a_check_source_is_passed_the_app_and_running_version() { + let seen = Arc::new(Mutex::new(None)); + let source: ContextSource = { + let seen = Arc::clone(&seen); + Arc::new(move |check: &CheckContext| { + *seen.lock().unwrap() = Some(check.clone()); + let running = crate::version::parse(&check.version); + let offered = newer(); + Ok(offered.version.as_ref().zip(running.as_ref()).is_some_and(|(new, cur)| crate::is_newer(new, cur)).then_some(offered)) + }) + }; + let ctx = egui::Context::default(); + let mut u = Updater::new(&PHOTOCRAFT, "0.1.0").with_check(source).with_pins_path(no_pins()).with_probe(Arc::new(|_, _| false)); + u.check_now(&ctx); + settle(&mut u, &ctx); + let seen = seen.lock().unwrap().clone().expect("the check asked its source"); + assert_eq!(seen, CheckContext { app: &PHOTOCRAFT, version: u.version.clone() }); + assert!(u.prompt_open(), "the release the source found for that version is offered"); + } + #[test] fn dismissing_a_running_check_keeps_it_quiet() { let (ctx, mut u) = (egui::Context::default(), updater(Ok(None))); From 74707e8281fed455f7efb66dd201169e3fe5f946 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:49:08 -0800 Subject: [PATCH 014/235] i18n: catalog rows are read and written through the public catalog module catalog::parse, catalog::parse_row and catalog::Entry are now public, with catalog::escape and catalog::unescape for a column's \, \n and \t, and plural_forms(locale) gives the plural form count parse checks @plural rows against. A build script or test that reads, merges or writes catalog rows can use the same parser as the lookups, so it reports the same problems for the same rows. Tests in crates/i18n/tests/catalog.rs read rows, report bad and repeated rows by line, round-trip escaping, and check plural_forms. --- crates/i18n/README.md | 5 +++ crates/i18n/src/catalog.rs | 40 +++++++++++++++++++--- crates/i18n/src/lib.rs | 10 +++++- crates/i18n/tests/catalog.rs | 65 ++++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 6 deletions(-) create mode 100644 crates/i18n/tests/catalog.rs diff --git a/crates/i18n/README.md b/crates/i18n/README.md index 1ea16d85b1..af93bc69b9 100644 --- a/crates/i18n/README.md +++ b/crates/i18n/README.md @@ -66,6 +66,11 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l returns the bad locales, and each locale's rows are parsed (and its bad rows logged with `log::warn!`) on the first lookup that reaches it, including as a fallback. `I18n::check_all()` parses every locale and returns all problems (`/: line N: …`), for a test. +- **Reading rows:** `catalog::parse(text, forms)` returns a catalog's rows (`catalog::Entry`, with + the columns unescaped) and its problems as `line N: …`, and `catalog::parse_row` checks one row; + both apply the checks the lookups apply. `plural_forms(locale)` gives `forms`. + `catalog::escape` writes a column's `\`, line breaks and tabs as `\\`, `\n` and `\t`, and + `catalog::unescape` reads them back. - **Plurals:** forms are listed in CLDR order (zero, one, two, few, many, other) for the categories whole numbers 0 to 1000 reach, from ICU4X's CLDR rules; `plural_form_counts` holds the counts craft-i18n's checker expects. `trn_decimal` picks the form from the digits shown (ICU4X plural diff --git a/crates/i18n/src/catalog.rs b/crates/i18n/src/catalog.rs index 0cb51e36c3..4a53d72734 100644 --- a/crates/i18n/src/catalog.rs +++ b/crates/i18n/src/catalog.rs @@ -1,13 +1,22 @@ //! Reading one catalog. The rules are craft-i18n's `docs/catalog-format.md`; craft-i18n's CI //! applies them strictly, and here a row that breaks one is skipped and reported, so an app built //! against a newer catalog still runs, with that string in English. +//! +//! [`I18n`](crate::I18n) reads the embedded catalogs with these functions. An app's build script +//! or test that reads, merges or writes catalog rows can use them to read rows exactly as the +//! lookups do: [`parse`] for a catalog, [`parse_row`] for one line, and [`escape`] and [`unescape`] +//! for the columns. [`plural_forms`](crate::plural_forms) gives the `forms` argument for a locale. use std::collections::HashSet; /// A row that passed, with its columns unescaped. -pub(crate) struct Entry { +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// The context column: empty, a context such as `menu`, or `@plural`, `@id` or `@msg`. pub context: String, + /// The English source text. pub source: String, + /// The translation; for `@plural`, its forms joined by `|`. pub translation: String, } @@ -15,8 +24,9 @@ pub(crate) struct Entry { const RESERVED: &[&str] = &["@plural", "@id", "@msg"]; /// The rows of a catalog whose locale has `forms` plural forms, and one problem (`line N: …`) per -/// row skipped. Of a row defined twice, the first is kept, as in craft-i18n's checker. -pub(crate) fn parse(text: &str, forms: usize) -> (Vec, Vec) { +/// row skipped. Of a row defined twice, the first is kept, as in craft-i18n's checker. A leading +/// byte order mark, `\r` line ends, empty lines and `#` comment lines are skipped. +pub fn parse(text: &str, forms: usize) -> (Vec, Vec) { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut rows = Vec::new(); let mut problems = Vec::new(); @@ -37,7 +47,9 @@ pub(crate) fn parse(text: &str, forms: usize) -> (Vec, Vec) { (rows, problems) } -pub(crate) fn parse_row(text: &str, forms: usize) -> Result { +/// One row, `context⇥source⇥translation` without its line end, checked as [`parse`] checks it; +/// the error is the problem `parse` reports after `line N: `. +pub fn parse_row(text: &str, forms: usize) -> Result { let columns: Vec<&str> = text.split('\t').collect(); let [context, source, translation] = columns.as_slice() else { return Err(format!("{} columns; expected 3", columns.len())); @@ -85,7 +97,25 @@ fn check_plural(source: &str, translation: &str, forms: usize) -> Result<(), Str Ok(()) } -fn unescape(text: &str) -> Result { +/// A column as a catalog writes it: `\` as `\\`, a line break as `\n` and a tab as `\t`. Other +/// characters are kept, so a column with another control character still gives a row that +/// [`parse_row`] rejects. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } + out +} + +/// A column as a catalog writes it, read back: `\n`, `\t` and `\\` are the only escapes, and any +/// other backslash is an error. +pub fn unescape(text: &str) -> Result { let mut out = String::with_capacity(text.len()); let mut chars = text.chars(); while let Some(c) = chars.next() { diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index 24ce578a6a..6a45c0c2c2 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -10,7 +10,7 @@ //! writes `0`–`9` without grouping. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -mod catalog; +pub mod catalog; #[cfg(feature = "collate")] mod collate; mod fold; @@ -693,6 +693,14 @@ fn bare(code: &str) -> Locale { } } +/// The forms an `@plural` row of `locale`'s catalog lists, the `forms` of [`catalog::parse`]: one +/// per category of `locale`'s CLDR plural rules that whole numbers 0 to 1000 reach (2 for `de`, 3 +/// for `ru`), or 1 for a language CLDR has no plural rules for. [`I18n`] checks rows with the same +/// count. +pub fn plural_forms(locale: &str) -> usize { + plural_rules(&locale.to_ascii_lowercase()).map_or(1, |(_, c)| c.len()) +} + /// `code`'s CLDR cardinal rules and the categories whole numbers 0..=1000 reach, in CLDR order /// (zero, one, two, few, many, other): one `@plural` form each. The rules are looked up by /// language alone: CLDR's parent of `sr-Latn` and `zh-Hant` is the root, whose only category is diff --git a/crates/i18n/tests/catalog.rs b/crates/i18n/tests/catalog.rs new file mode 100644 index 0000000000..ea4512b8e6 --- /dev/null +++ b/crates/i18n/tests/catalog.rs @@ -0,0 +1,65 @@ +//! Reading catalog rows from outside the crate, as an app's build script or test does. + +use craft_i18n::catalog::{Entry, escape, parse, parse_row, unescape}; +use craft_i18n::plural_forms; + +fn entry(context: &str, source: &str, translation: &str) -> Entry { + Entry { context: context.into(), source: source.into(), translation: translation.into() } +} + +#[test] +fn parse_reads_rows_as_the_lookups_do() { + let text = + "\u{feff}# comment\r\n\r\n\tOpen…\tÖffnen…\r\nmenu\tLine\\nbreak\tZeilen\\numbruch\n@plural\t{n} file|{n} files\t{n} Datei|{n} Dateien\n"; + let (rows, problems) = parse(text, plural_forms("de")); + assert_eq!(problems, Vec::::new()); + assert_eq!( + rows, + [ + entry("", "Open…", "Öffnen…"), + entry("menu", "Line\nbreak", "Zeilen\numbruch"), + entry("@plural", "{n} file|{n} files", "{n} Datei|{n} Dateien"), + ] + ); +} + +#[test] +fn parse_reports_bad_and_repeated_rows_by_line() { + let text = "\tOpen\tÖffnen\n\tSave\n\tOpen\tAufmachen\n\tBad\\q\tSchlecht\n"; + let (rows, problems) = parse(text, 2); + assert_eq!(rows, [entry("", "Open", "Öffnen")]); + assert_eq!( + problems, + ["line 2: 2 columns; expected 3", "line 3: defined twice (same context and source text); the first is kept", "line 4: unknown escape \\q"] + ); +} + +#[test] +fn parse_row_checks_one_row() { + assert_eq!(parse_row("@id\tlanguage.name\tDeutsch", 2), Ok(entry("@id", "language.name", "Deutsch"))); + assert_eq!(parse_row("\t{n} left\t{m} übrig", 2), Err("placeholders differ from the source text".into())); + assert_eq!(parse_row("@plural\t{n} file|{n} files\t{n} файл|{n} файла", plural_forms("ru")), Err("expected 3 nonempty plural forms".into())); +} + +#[test] +fn escape_round_trips_through_unescape_and_parse_row() { + for text in ["plain", "a\\b", "two\nlines", "tab\there", "\\n is not a line break", "trailing \\"] { + let escaped = escape(text); + assert!(!escaped.contains(['\n', '\t']), "{escaped:?}"); + assert_eq!(unescape(&escaped).as_deref(), Ok(text)); + let row = parse_row(&format!("\t{escaped}\t{escaped}"), 2).map(|e| e.translation); + assert_eq!(row.as_deref(), Ok(text)); + } + assert_eq!(escape("a\\b\nc\td"), "a\\\\b\\nc\\td"); + assert_eq!(unescape("trailing \\"), Err("trailing backslash".into())); +} + +#[test] +fn plural_forms_follow_the_cldr_rules() { + assert_eq!(plural_forms("de"), 2); + assert_eq!(plural_forms("pt-BR"), 2); + assert_eq!(plural_forms("ru"), 3); + assert_eq!(plural_forms("ar"), 6); + assert_eq!(plural_forms("ja"), 1); + assert_eq!(plural_forms("tlh"), 1); +} From 6fa28ebba79c9055c8f04063cb9669976481e653 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:50:36 -0800 Subject: [PATCH 015/235] craft-time: Tick::from_seconds_f64 clamps to Tick::MIN..=Tick::MAX as documented The doc comment promised a clamp to Tick::MIN..=Tick::MAX, but the cast saturated at the i64 bounds instead, four times past Tick::MAX, so a caller that reads seconds from a file and uses Tick::MAX as its end bound could get a time beyond it. The conversion now clamps to the documented bounds, infinities clamp to the matching bound, and NaN gives Tick::ZERO, which the doc comment now states. --- crates/time/src/lib.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/time/src/lib.rs b/crates/time/src/lib.rs index 4a3af58dfd..70b2ebd12f 100644 --- a/crates/time/src/lib.rs +++ b/crates/time/src/lib.rs @@ -33,9 +33,14 @@ impl Tick { pub const MAX: Tick = Tick(i64::MAX / 4); pub const MIN: Tick = Tick(i64::MIN / 4); - /// Seconds to ticks, clamped to [`Tick::MIN`]..=[`Tick::MAX`]. + /// Seconds to ticks, rounded to the nearest tick and clamped to [`Tick::MIN`]..=[`Tick::MAX`]. + /// Infinities clamp to the matching bound, and NaN gives [`Tick::ZERO`]. pub fn from_seconds_f64(s: f64) -> Tick { - Tick((s * TICKS_PER_SECOND as f64).round() as i64) + let ticks = (s * TICKS_PER_SECOND as f64).round(); + if ticks.is_nan() { + return Tick::ZERO; + } + Tick((ticks as i64).clamp(Tick::MIN.0, Tick::MAX.0)) } pub fn seconds(self) -> f64 { @@ -822,6 +827,18 @@ mod tests { assert_eq!(Tick(TICKS_PER_SECOND).to_rational_round(1, 1), 1); } + #[test] + fn seconds_outside_the_tick_range_clamp_to_its_bounds() { + let beyond = Tick::MAX.seconds() * 2.0; + assert_eq!(Tick::from_seconds_f64(beyond), Tick::MAX); + assert_eq!(Tick::from_seconds_f64(-beyond), Tick::MIN); + assert_eq!(Tick::from_seconds_f64(f64::INFINITY), Tick::MAX); + assert_eq!(Tick::from_seconds_f64(f64::NEG_INFINITY), Tick::MIN); + assert!(Tick::from_seconds_f64(Tick::MAX.seconds()) <= Tick::MAX); + assert!(Tick::from_seconds_f64(Tick::MIN.seconds()) >= Tick::MIN); + assert_eq!(Tick::from_seconds_f64(f64::NAN), Tick::ZERO); + } + #[test] fn test_hostile_rates_never_panic() { let zero = FrameRate { num: 0, den: 0 }; From 98eb2f740a9db13a792462377a3f3beed4b5a9e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:52:41 -0800 Subject: [PATCH 016/235] craft-quit: README states the platform, timing and error of the app menu install craft_menu::mac::install_app_menu exists only on macOS and needs a cfg guard. It is called once from the eframe app creator, and an error leaves winit's menu, whose Quit skips the unsaved-changes prompt. --- crates/quit/README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/quit/README.md b/crates/quit/README.md index 757327aa76..8a42780f05 100644 --- a/crates/quit/README.md +++ b/crates/quit/README.md @@ -82,7 +82,18 @@ close button, and `on_close_request` then quits. It returns `false` for other id to the caller. It can be called between frames; egui keeps the command for the next frame. An app without a menu of its own uses `craft_menu::mac::install_app_menu`, which builds a minimal -app menu with that Quit item. `craft_quit::install_app_menu` is deprecated in its favor. +app menu with that Quit item. `craft_menu::mac` exists only on macOS, so the call needs +`#[cfg(target_os = "macos")]`; other platforms need no call. Call it once, from the eframe app +creator: winit builds its default menu before that and replaces a menu installed earlier. The call +returns a `Result`. On error winit's menu stays, and ⌘Q quits without the unsaved-changes prompt; +the app decides whether that is fatal, and `?` passes the error out of the app creator: + +```rust,ignore +#[cfg(target_os = "macos")] +craft_menu::mac::install_app_menu(&cc.egui_ctx, "WordCraft")?; +``` + +`craft_quit::install_app_menu` is deprecated in its favor. ## Notes From c0b32e3bec372230847a10ceb386bfbf5c820428 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:54:55 -0800 Subject: [PATCH 017/235] atomic: add sweep_temp_files to remove staging files a crash left behind A crash or kill between staging and rename leaves a ..-.craft_tmp file beside the destination, and nothing removed it. sweep_temp_files(dir, min_age) removes the regular files in one folder whose names have the form temp_name gives and that were last modified at least min_age ago. It does not follow symbolic links, search subfolders, or trust the process id in the name. --- crates/atomic/README.md | 21 +++++++++- crates/atomic/src/lib.rs | 54 +++++++++++++++++++++++-- crates/atomic/tests/atomic_tests.rs | 63 ++++++++++++++++++++++++++++- 3 files changed, 133 insertions(+), 5 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index e43d1c58f7..7c178a6dc2 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee ## Core Guarantees: Atomicity vs. Durability -1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted. +1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted. 2. **Durability & Ordering Boundaries**: - **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback). - **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced. @@ -63,6 +63,25 @@ let path = Path::new("export.png"); write_new(path, b"png bytes...").expect("exclusive write"); ``` +### Removing Orphaned Staging Files + +```rust +use std::path::Path; +use std::time::Duration; +use craft_atomic::sweep_temp_files; + +// Removes staging files in scenes/ that were last modified an hour or more ago. +// Returns how many were removed. +let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0); +``` + +`sweep_temp_files` removes only regular files whose names have the staging form, never follows +a symbolic link, and does not search subfolders. A save updates its staging file's modification +time only while it writes bytes, not while it flushes or renames, and removing the staging file +makes that save fail. Choose a minimum age longer than the longest time any save into the folder, +by any process including the calling one, may go without writing, counting the final flush and +rename. Entries that cannot be removed are left in place. + ### Document Permissions and Private Data The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 08b881e17b..02b4070f15 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -14,9 +14,9 @@ //! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs //! during staging or rename, the target remains unmodified and the staging file is removed in user space. //! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and -//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the -//! consuming application; the library does not perform background sweeping. The destination file itself is -//! never corrupted. +//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming +//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging +//! files. The destination file itself is never corrupted. //! - **Durability & Ordering Boundaries**: //! Data persistence across power failures involves two sync points: //! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage @@ -600,6 +600,54 @@ pub fn temp_name(file: &str) -> String { format!(".{stem}.{pid}-{n}.craft_tmp") } +/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed. +/// +/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a +/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process +/// id in the name is not used to decide, since the system reuses process ids. A save updates its +/// staging file's modification time only while it writes bytes, not while it flushes or renames, +/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest +/// time any save into `dir`, by any process including the calling one, may go without writing, +/// counting the final flush and rename. Entries that cannot be read or removed are left in place. +/// Subfolders are not searched. +/// On `wasm32` this returns an `Unsupported` error. +pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (dir, min_age); + Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform")) + } + #[cfg(not(target_arch = "wasm32"))] + { + let now = std::time::SystemTime::now(); + let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?; + let mut removed = 0; + for entry in entries.flatten() { + if !entry.file_name().to_str().is_some_and(is_temp_name) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age); + if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() { + removed += 1; + } + } + Ok(removed) + } +} + +/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem +/// of at most 64 characters. +#[cfg(not(target_arch = "wasm32"))] +fn is_temp_name(name: &str) -> bool { + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else { + return false; + }; + let Some((pid, n)) = tail.split_once('-') else { return false }; + stem.chars().count() <= 64 && digits(pid) && digits(n) && pid.parse::().is_ok() && n.parse::().is_ok() +} + /// The end of an error message: whether an original file was left as it was. fn unchanged(existed: bool) -> &'static str { if existed { "; the original file was not changed" } else { "" } diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index b5001bc724..45d659d75e 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -1,10 +1,11 @@ #[cfg(unix)] use craft_atomic::{NewFilePermissions, WriteOptions, atomic_write, write_new}; -use craft_atomic::{atomic_write_with, or_plain_fsync, write_new_with}; +use craft_atomic::{atomic_write_with, or_plain_fsync, sweep_temp_files, temp_name, write_new_with}; use std::cell::Cell; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, SystemTime}; struct TempDir(PathBuf); impl TempDir { @@ -238,3 +239,63 @@ fn explicit_private_files_keep_callback_permissions() -> io::Result<()> { assert_no_temp(&d.0); Ok(()) } + +/// Writes the file `name` in `dir` and dates its modification time `age` in the past. +fn leftover(dir: &Path, name: &str, age: Duration) -> io::Result { + let p = dir.join(name); + std::fs::write(&p, b"interrupted save")?; + std::fs::File::options().write(true).open(&p)?.set_modified(SystemTime::now() - age)?; + Ok(p) +} + +#[test] +fn sweep_removes_only_old_staging_files() -> io::Result<()> { + let d = TempDir::new("sweep_old"); + let other = std::process::id().wrapping_add(1); + let hour = Duration::from_secs(3600); + let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?; + // A process id the system reused for this process does not protect an old orphan. + let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?; + let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), Duration::ZERO)?; + let document = leftover(&d.0, "scene.json", 2 * hour)?; + + assert_eq!(sweep_temp_files(&d.0, hour)?, 2); + assert!(!orphan.exists() && !same_pid.exists()); + assert!(recent.exists() && document.exists()); + Ok(()) +} + +#[test] +fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> { + let d = TempDir::new("sweep_lookalike"); + let other = std::process::id().wrapping_add(1); + let old = Duration::from_secs(7200); + let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?; + let kept = [ + leftover(&d.0, "notes.craft_tmp", old)?, + leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?, + leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?, + leftover(&d.0, ".scene.json.-3.craft_tmp", old)?, + leftover(&d.0, ".12-3.craft_tmp", old)?, + leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?, + leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?, + // temp_name keeps at most 64 characters of the destination's name. + leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(65)), old)?, + ]; + let longest = leftover(&d.0, &temp_name(&"s".repeat(80)), old)?; + let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp")); + std::fs::create_dir(&folder)?; + + assert_eq!(sweep_temp_files(&d.0, Duration::ZERO)?, 2); + assert!(!orphan.exists() && !longest.exists()); + assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed"); + assert!(folder.is_dir()); + Ok(()) +} + +#[test] +fn sweep_of_a_missing_folder_is_an_error() { + let d = TempDir::new("sweep_missing"); + let err = sweep_temp_files(&d.0.join("absent"), Duration::ZERO).err().map(|e| e.kind()); + assert_eq!(err, Some(io::ErrorKind::NotFound)); +} From 2dbca438d8426a5a394c04f0dc32fc21d2d6e8f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:59:12 -0800 Subject: [PATCH 018/235] fonts-build: check each font file against its manifest SHA-256 The manifest's sha256 field was copied into each face without being compared with the file. It becomes a served face's Subresource Integrity value, so a damaged or swapped file was embedded or served without a build error, and a browser refused the served face at run time. Embed now hashes every selected font file and compares it with its manifest line. A mismatch is Error::HashMismatch, handled like a missing font file: a build error with CRAFT_FONTS_REQUIRED=1, and a warning with an empty table otherwise. A field that is not 64 hex digits is not checked. The SHA-256 is now always compiled and hashes in pieces, so a file is read in 64 KiB chunks instead of being copied whole. Builds without CRAFT_FONTS_REQUIRED=1 keep each file's hash with its size and modification time in craft-fonts-sha256.txt beside the generated table, and hash a file again only when either changes; a required build hashes every file. --- crates/fonts-build/README.md | 9 +- crates/fonts-build/src/embed.rs | 90 ++++++++++++++++- crates/fonts-build/src/lib.rs | 4 +- crates/fonts-build/src/manifest.rs | 2 +- crates/fonts-build/src/sha256.rs | 153 +++++++++++++++++++++++------ crates/fonts-build/src/tests.rs | 122 ++++++++++++++++++++--- 6 files changed, 333 insertions(+), 47 deletions(-) diff --git a/crates/fonts-build/README.md b/crates/fonts-build/README.md index 941426b3c1..70415aa36b 100644 --- a/crates/fonts-build/README.md +++ b/crates/fonts-build/README.md @@ -12,7 +12,7 @@ build. The build reads a local checkout named by `CRAFT_FONTS_DIR` instead. |---|---| | `CRAFT_FONTS_DIR` unset or empty | Empty table. | | `CRAFT_FONTS_DIR` = a craft-fonts checkout | Every selected face of `fonts/manifest.txt`, embedded with `include_bytes!`. | -| `CRAFT_FONTS_DIR` set, but no manifest or a missing font file | `cargo::warning`, empty table. | +| `CRAFT_FONTS_DIR` set, but no manifest, a missing font file, or a font file whose SHA-256 is not the manifest's | `cargo::warning`, empty table. | | `CRAFT_FONTS_REQUIRED=1` (exactly `1`; other values are ignored) | Error instead when the directory is unset, unreadable, has no selected face, or has no face for a script passed to `scripts`. | Give `CRAFT_FONTS_DIR` as an absolute path: Cargo runs build scripts in the package's directory. @@ -200,3 +200,10 @@ One face per line, eight or nine fields separated by `" | "`; craft-fonts' `docs defines them. Lines starting with `#` are comments. A file field ending in `#` names face `n` of a font collection (`fonts/noto-sans-cjk/NotoSansCJK.ttc#2`); without it the index is 0. The ninth field, `role`, is `ui` on interface faces and absent elsewhere. Fields after the ninth are ignored. + +Each selected font file is hashed and compared with the line's `sha256` field, in either letter +case; a field that is not 64 hex digits is not checked. A mismatch is `Error::HashMismatch`, treated +like a missing font file: a build error with `CRAFT_FONTS_REQUIRED=1`, and a `cargo::warning` with an +empty table otherwise. Without `CRAFT_FONTS_REQUIRED=1`, the hashes are kept in +`craft-fonts-sha256.txt` beside the generated table, with each file's size and modification time, +and a file is hashed again only when one of those changes. A required build hashes every file. diff --git a/crates/fonts-build/src/embed.rs b/crates/fonts-build/src/embed.rs index c06e6d525f..6eb18e3fcc 100644 --- a/crates/fonts-build/src/embed.rs +++ b/crates/fonts-build/src/embed.rs @@ -239,7 +239,12 @@ impl Embed { let selected = match &dir { None => Err(Error::NotSet), - Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }), + Some(dir) => self + .select(dir, cargo) + // A required (release) build reads every file: a copy that keeps the size and the + // modification time would get past the cache. + .and_then(|faces| check_hashes(dir, faces, (!required).then(|| out.parent().unwrap_or(Path::new(""))))) + .and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }), }; let mut selected = selected; if let Ok(faces) = &mut selected { @@ -512,6 +517,83 @@ impl Embed { } } +/// The file, beside the generated table, that keeps each checked font file's SHA-256 with its size +/// and modification time, so a rerun of a build that is not required does not hash unchanged files +/// again. +const HASH_CACHE: &str = "craft-fonts-sha256.txt"; + +/// Check each face's file against the SHA-256 its manifest line gives: a mismatch is an +/// [`Error::HashMismatch`]. A line whose hash field is not 64 hex digits is not checked. Faces of +/// one collection share a file, which is hashed once. With `cache_dir`, a file whose size and +/// modification time match its [`HASH_CACHE`] line there is not read again. +fn check_hashes(dir: &Path, faces: Vec, cache_dir: Option<&Path>) -> Result, Error> { + let cache_file = cache_dir.map(|cache_dir| cache_dir.join(HASH_CACHE)); + let old_text = cache_file.as_ref().and_then(|cache_file| read_text_bounded(cache_file, MAX_MANIFEST_BYTES).ok()); + let old = old_text.as_deref().map(parse_hash_cache).unwrap_or_default(); + let mut new: Vec<(String, u64, u128, String)> = Vec::new(); + for face in &faces { + let expected = &face.entry.sha256; + if !crate::sha256::is_hex_digest(expected) { + continue; + } + let key = face.path.to_str().map(str::to_owned); + let stamp = file_stamp(&face.path); + let known = key.as_ref().and_then(|key| { + new.iter() + .chain(&old) + .find(|(path, size, modified, _)| path == key && stamp == Some((*size, *modified))) + .map(|(.., sha256)| sha256.clone()) + }); + let actual = match known { + Some(sha256) => sha256, + None => crate::sha256::file_hex(&face.path, MAX_FILE_BYTES).map_err(|source| Error::Read { path: face.path.clone(), source })?, + }; + if let (Some(key), Some((size, modified))) = (key, stamp) + && !new.iter().any(|(path, ..)| *path == key) + { + new.push((key, size, modified, actual.clone())); + } + if !actual.eq_ignore_ascii_case(expected) { + return Err(Error::HashMismatch { + manifest: dir.join("fonts/manifest.txt"), + file: face.entry.file.clone(), + expected: expected.clone(), + actual, + }); + } + } + let text: String = new.iter().map(|(path, size, modified, sha256)| format!("{sha256}\t{size}\t{modified}\t{path}\n")).collect(); + // The cache only saves time: a directory that can't hold it costs a rehash on the next run. + if let Some(cache_file) = cache_file + && !new.is_empty() + && old_text.as_deref() != Some(text.as_str()) + { + let _ = std::fs::write(&cache_file, text); + } + Ok(faces) +} + +/// The lines of a [`HASH_CACHE`] file: SHA-256, size, modification time in nanoseconds since the +/// epoch and path, separated by tabs. Lines that don't read are skipped. +fn parse_hash_cache(text: &str) -> Vec<(String, u64, u128, String)> { + text.lines() + .filter_map(|line| { + let mut fields = line.splitn(4, '\t'); + let sha256 = fields.next().filter(|s| crate::sha256::is_hex_digest(s))?; + let size = fields.next()?.parse().ok()?; + let modified = fields.next()?.parse().ok()?; + Some((fields.next()?.to_owned(), size, modified, sha256.to_owned())) + }) + .collect() +} + +/// A file's size and modification time in nanoseconds since the epoch, when the system gives both. +fn file_stamp(path: &Path) -> Option<(u64, u128)> { + let metadata = std::fs::metadata(path).ok()?; + let modified = metadata.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?; + Some((metadata.len(), modified.as_nanos())) +} + /// Whether the interface faces need `c`: CJK and later blocks, except emoji and other pictographs /// (the emoji faces draw them), variation selectors, tags and a byte order mark. fn needs_glyph(c: char) -> bool { @@ -750,6 +832,9 @@ pub enum Error { /// A path that goes into a `cargo::rerun-if-changed` line has a line break, which would start /// another cargo instruction. LineBreakInPath { path: PathBuf }, + /// A font file's SHA-256 is not the one its manifest line gives: the file is damaged, or the + /// checkout's files and manifest are out of step. + HashMismatch { manifest: PathBuf, file: String, expected: String, actual: String }, } impl fmt::Display for Error { @@ -786,6 +871,9 @@ impl fmt::Display for Error { write!(f, "{}: {file:?} is not a file inside the checkout", manifest.display()) } Self::LineBreakInPath { path } => write!(f, "{path:?} has a line break: cargo could not be told to watch it"), + Self::HashMismatch { manifest, file, expected, actual } => { + write!(f, "{}: {file:?} has SHA-256 {actual}, but the manifest gives {expected}", manifest.display()) + } } } } diff --git a/crates/fonts-build/src/lib.rs b/crates/fonts-build/src/lib.rs index fffd8f0985..c914323a60 100644 --- a/crates/fonts-build/src/lib.rs +++ b/crates/fonts-build/src/lib.rs @@ -8,7 +8,8 @@ //! //! - **Unset or empty:** the table is empty and the app uses its own and system fonts. //! - **Set:** every selected face in `fonts/manifest.txt` is embedded with `include_bytes!`. -//! - **Set, but not readable as a checkout:** a `cargo::warning` and an empty table. +//! - **Set, but not readable as a checkout:** a `cargo::warning` and an empty table. A selected +//! font file whose SHA-256 is not the one its manifest line gives counts as unreadable. //! - **`CRAFT_FONTS_REQUIRED=1`** (release builds; any other value is ignored): a missing or //! unreadable checkout, no selected face, or a requested script without a face is an [`Error`]. //! @@ -55,7 +56,6 @@ mod cmap; pub mod coverage; mod embed; mod manifest; -#[cfg(feature = "subset")] mod sha256; #[cfg(feature = "subset")] mod subset; diff --git a/crates/fonts-build/src/manifest.rs b/crates/fonts-build/src/manifest.rs index 69c31959c0..78b818eed0 100644 --- a/crates/fonts-build/src/manifest.rs +++ b/crates/fonts-build/src/manifest.rs @@ -30,7 +30,7 @@ pub struct ManifestEntry { pub licence: String, /// Licence text, relative to the checkout. pub licence_file: String, - /// Hex SHA-256 of the font file. + /// Hex SHA-256 of the font file. [`Embed`](crate::Embed) checks each selected file against it. pub sha256: String, /// Where the file came from. pub source: String, diff --git a/crates/fonts-build/src/sha256.rs b/crates/fonts-build/src/sha256.rs index b80f19a9ae..8370dd2712 100644 --- a/crates/fonts-build/src/sha256.rs +++ b/crates/fonts-build/src/sha256.rs @@ -1,4 +1,8 @@ -//! SHA-256 (FIPS 180-4) of a cut face, for its served file name and Subresource Integrity value. +//! SHA-256 (FIPS 180-4) of a font file, checked against its manifest line, and of a cut face, for +//! its served file name and Subresource Integrity value. + +use std::io::{self, Read as _}; +use std::path::Path; const K: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, @@ -9,38 +13,127 @@ const K: [u32; 64] = [ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; -/// The lowercase hex SHA-256 of `data`, as craft-fonts' manifest writes it. -pub(crate) fn hex(data: &[u8]) -> String { - let mut h: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; - let mut message = data.to_vec(); - message.push(0x80); - while message.len() % 64 != 56 { - message.push(0); - } - message.extend_from_slice(&(u64::try_from(data.len()).unwrap_or(u64::MAX).wrapping_mul(8)).to_be_bytes()); - for block in message.as_chunks::<64>().0 { - let mut w = [0u32; 64]; - for (i, word) in block.as_chunks::<4>().0.iter().enumerate() { - w[i] = u32::from_be_bytes(*word); +/// A SHA-256 fed in pieces, so a font file is hashed as it is read rather than copied whole. +pub(crate) struct Sha256 { + h: [u32; 8], + /// Bytes of the next block not yet compressed: `block[..filled]`. + block: [u8; 64], + filled: usize, + len: u64, +} + +impl Sha256 { + pub(crate) fn new() -> Self { + Self { + h: [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19], + block: [0; 64], + filled: 0, + len: 0, } - for i in 16..64 { - let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); - let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + + pub(crate) fn update(&mut self, mut data: &[u8]) { + self.len = self.len.wrapping_add(u64::try_from(data.len()).unwrap_or(u64::MAX)); + if self.filled > 0 { + let take = (64 - self.filled).min(data.len()); + let (head, rest) = data.split_at(take); + if let Some(free) = self.block.get_mut(self.filled..self.filled + take) { + free.copy_from_slice(head); + } + self.filled += take; + data = rest; + if self.filled < 64 { + return; + } + compress(&mut self.h, &self.block); + self.filled = 0; } - let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; - for (k, w) in K.iter().zip(w) { - let t1 = hh - .wrapping_add(e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25)) - .wrapping_add((e & f) ^ (!e & g)) - .wrapping_add(*k) - .wrapping_add(w); - let t2 = (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)).wrapping_add((a & b) ^ (a & c) ^ (b & c)); - (hh, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2)); + let (blocks, rest) = data.as_chunks::<64>(); + for block in blocks { + compress(&mut self.h, block); } - for (h, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { - *h = h.wrapping_add(v); + if let Some(start) = self.block.get_mut(..rest.len()) { + start.copy_from_slice(rest); } + self.filled = rest.len(); + } + + /// The lowercase hex digest. + pub(crate) fn finish(mut self) -> String { + let bits = self.len.wrapping_mul(8); + // A 0x80 byte and zeros up to 56 bytes into a block, then the length in bits. + let padding = if self.filled < 56 { 56 - self.filled } else { 120 - self.filled }; + let mut tail = [0u8; 64]; + tail[0] = 0x80; + self.update(tail.get(..padding).unwrap_or(&tail)); + self.update(&bits.to_be_bytes()); + self.h.iter().map(|v| format!("{v:08x}")).collect() + } +} + +fn compress(h: &mut [u32; 8], block: &[u8; 64]) { + let mut w = [0u32; 64]; + for (i, word) in block.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h; + for (k, w) in K.iter().zip(w) { + let t1 = hh + .wrapping_add(e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25)) + .wrapping_add((e & f) ^ (!e & g)) + .wrapping_add(*k) + .wrapping_add(w); + let t2 = (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)).wrapping_add((a & b) ^ (a & c) ^ (b & c)); + (hh, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2)); + } + for (h, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *h = h.wrapping_add(v); + } +} + +/// The lowercase hex SHA-256 of `data`, as craft-fonts' manifest writes it. +#[cfg(any(feature = "subset", test))] +pub(crate) fn hex(data: &[u8]) -> String { + let mut sha = Sha256::new(); + sha.update(data); + sha.finish() +} + +/// The lowercase hex SHA-256 of the regular file `path`, read in pieces; an error when it holds +/// more than `limit` bytes. +pub(crate) fn file_hex(path: &Path, limit: u64) -> io::Result { + // Opening a FIFO with no writer blocks, so refuse anything that isn't a file before opening. + if !std::fs::metadata(path)?.is_file() { + return Err(io::Error::other("not a regular file")); + } + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Err(io::Error::other("not a regular file")); + } + let mut file = file.take(limit.saturating_add(1)); + let mut sha = Sha256::new(); + let mut buffer = vec![0; 1 << 16]; + loop { + let read = match file.read(&mut buffer) { + Ok(0) => break, + Ok(read) => read, + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e), + }; + sha.update(buffer.get(..read).unwrap_or(&buffer)); + } + if sha.len > limit { + return Err(io::Error::other(format!("larger than {limit} bytes"))); } - h.iter().map(|v| format!("{v:08x}")).collect() + Ok(sha.finish()) +} + +/// Whether `value` is a SHA-256 written as 64 hex digits. +pub(crate) fn is_hex_digest(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit()) } diff --git a/crates/fonts-build/src/tests.rs b/crates/fonts-build/src/tests.rs index c8542df277..63dffe9241 100644 --- a/crates/fonts-build/src/tests.rs +++ b/crates/fonts-build/src/tests.rs @@ -693,18 +693,6 @@ mod subset { assert!(r.table.contains(&line), "{}\n{line}", r.table); } - #[test] - fn sha256_matches_the_standard_vectors() { - use crate::sha256::hex; - assert_eq!(hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); - assert_eq!(hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); - assert_eq!( - hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" - ); - assert_eq!(hex(&vec![b'a'; 1_000_000]), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); - } - /// With `CRAFT_FONTS_DIR` set to a craft-fonts checkout, cut its BIZ UDPGothic Regular. #[test] fn cuts_biz_udpgothic() { @@ -923,3 +911,113 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() { let r = run(Embed::new(), Some(&dir), None); assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo); } + +#[test] +fn sha256_matches_the_standard_vectors_in_any_pieces() { + use crate::sha256::{Sha256, file_hex, hex}; + assert_eq!(hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + assert_eq!(hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + let two_blocks = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + assert_eq!(hex(two_blocks), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); + let million = vec![b'a'; 1_000_000]; + assert_eq!(hex(&million), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); + // Pieces that start and end inside a block give the digest of the whole. + for piece in [1, 7, 55, 56, 63, 64, 65, 1000] { + let mut sha = Sha256::new(); + for chunk in million.chunks(piece) { + sha.update(chunk); + } + assert_eq!(sha.finish(), hex(&million), "{piece}-byte pieces"); + } + let scratch = Scratch::new("sha256-file"); + let file = scratch.0.join("f"); + for len in [0, 55, 56, 64, 65_537] { + let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + std::fs::write(&file, &data).unwrap(); + assert_eq!(file_hex(&file, 65_537).unwrap(), hex(&data), "{len} bytes"); + } + assert!(file_hex(&file, 65_536).unwrap_err().to_string().contains("larger than 65536 bytes")); + assert!(file_hex(&scratch.0, 10).is_err(), "a directory"); +} + +/// A checkout in `scratch` whose one face, `fonts/a.ttf`, holds `font` and whose manifest line +/// gives `sha256`. +fn hashed_checkout(scratch: &Scratch, font: &[u8], sha256: &str) -> PathBuf { + let dir = scratch.0.join("craft-fonts"); + std::fs::create_dir_all(dir.join("fonts")).unwrap(); + std::fs::write(dir.join("fonts/a.ttf"), font).unwrap(); + std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap(); + std::fs::write(dir.join("fonts/manifest.txt"), format!("Sans | Regular | fonts/a.ttf | Latn | OFL-1.1 | fonts/OFL.txt | {sha256} | src\n")) + .unwrap(); + dir +} + +#[test] +fn a_font_file_that_differs_from_its_manifest_hash_is_not_embedded() { + use crate::sha256::hex; + let scratch = Scratch::new("hash-mismatch"); + let font = b"font bytes"; + let dir = hashed_checkout(&scratch, font, &hex(font).to_ascii_uppercase()); + assert_eq!(run(Embed::new(), Some(&dir), Some("1")).result.unwrap(), ["Sans Regular"]); + + let dir = hashed_checkout(&scratch, font, &hex(b"other bytes")); + let r = run(Embed::new(), Some(&dir), Some("1")); + match &r.result { + Err(Error::HashMismatch { file, expected, actual, .. }) => { + assert_eq!((file.as_str(), expected.as_str(), actual.as_str()), ("fonts/a.ttf", hex(b"other bytes").as_str(), hex(font).as_str())); + } + other => panic!("{other:?}"), + } + assert_eq!(r.table.trim(), "&[]"); + let err = r.result.unwrap_err().to_string(); + assert!(err.contains("fonts/a.ttf") && err.contains(&hex(font)), "{err}"); + // Not required: a warning and an empty table, as for a missing font file. + let r = run(Embed::new(), Some(&dir), None); + assert!(r.result.as_ref().unwrap().is_empty()); + assert_eq!(r.table.trim(), "&[]"); + assert!(warnings(&r).iter().any(|w| w.contains("building without craft-fonts") && w.contains("SHA-256")), "{:?}", r.cargo); + // Served faces are checked too: the manifest's hash becomes their integrity value. + let served = scratch.0.join("served"); + assert!(matches!(run(Embed::new().serve(&served, "fonts/"), Some(&dir), Some("1")).result, Err(Error::HashMismatch { .. }))); + assert!(!served.join("a.ttf").exists()); +} + +/// A rerun of a build that is not required takes a file's hash from the cache beside the table +/// while its size and modification time are unchanged, and hashes it again once they change. A +/// required build hashes every file. +#[test] +fn the_hash_cache_is_used_only_while_the_file_is_unchanged_and_not_when_required() { + use crate::sha256::hex; + let scratch = Scratch::new("hash-cache"); + let font = b"font bytes"; + let dir = hashed_checkout(&scratch, font, &hex(font)); + let out = scratch.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + // The embedded faces, and the hash a mismatch warning gives as the file's. + let run_in = |required: Option<&str>| { + let env = Env { dir: Some(dir.clone().into()), required: required.map(OsString::from), out_dir: Some(out.clone().into()) }; + let mut cargo = Vec::new(); + let faces = Embed::new().run(&env, Path::new("craft_fonts.rs"), &mut cargo).map(|faces| faces.len()).ok(); + let warned = cargo.iter().find_map(|line| Some(line.split_once("has SHA-256 ")?.1.get(..64)?.to_owned())); + (faces, warned) + }; + assert_eq!(run_in(None), (Some(1), None)); + let cache = out.join("craft-fonts-sha256.txt"); + let text = std::fs::read_to_string(&cache).unwrap(); + assert!(text.starts_with(&format!("{}\t10\t", hex(font))), "{text}"); + + // A cached hash is trusted while the stamp matches: a wrong one shows in the warning. + let wrong = hex(b"cached"); + std::fs::write(&cache, text.replacen(&hex(font), &wrong, 1)).unwrap(); + assert_eq!(run_in(None), (Some(0), Some(wrong))); + // A required build reads the file instead. + assert_eq!(run_in(Some("1")), (Some(1), None)); + + // A changed file is hashed again, whatever the cache holds. + std::fs::write(dir.join("fonts/a.ttf"), b"other font bytes").unwrap(); + assert_eq!(run_in(None), (Some(0), Some(hex(b"other font bytes")))); + // An unreadable cache costs a rehash, not a failure. + std::fs::write(dir.join("fonts/a.ttf"), font).unwrap(); + std::fs::write(&cache, "not a cache line\n").unwrap(); + assert_eq!(run_in(None), (Some(1), None)); +} From 7648e5db54123a3109bcbe5268715fa43c0bff44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:13:27 -0800 Subject: [PATCH 019/235] craft-settings: do not save settings larger than the read limit A save rendered the settings and wrote them whatever their size, so a string setting near 16 MiB produced a config.toml that the next start refused to read. The save now checks the rendered text against store::MAX_CONFIG_BYTES before writing and returns SettingsError::Io with ErrorKind::FileTooLarge when it is larger. The file on disk is not backed up, moved aside or replaced, and the store keeps the change and tries again after the retry delay. The backup and the move-aside of a damaged file now happen after the size check, so a save that writes nothing also leaves the file alone. --- crates/settings/README.md | 4 +++ crates/settings/src/store.rs | 44 ++++++++++++++++++++++--------- crates/settings/tests/recovery.rs | 33 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 12 deletions(-) diff --git a/crates/settings/README.md b/crates/settings/README.md index f0073b6630..7c137e9172 100644 --- a/crates/settings/README.md +++ b/crates/settings/README.md @@ -158,6 +158,10 @@ which can stay the same on FAT, HFS+ or network shares) with what it last read o | Blank | Leaves the previous backup alone, then writes. | | From a newer build, its migration fails, or larger than `store::MAX_CONFIG_BYTES` | Writes nothing; the store becomes read-only and the save returns `SettingsError::ReadOnly`, the same as at startup. | +When the settings would render to more than `store::MAX_CONFIG_BYTES`, the save writes nothing +and returns `SettingsError::Io` with `ErrorKind::FileTooLarge`. The file on disk stays as it was, +and the store keeps the changes and tries again after the retry delay. + ### Concurrency contract Saving is **best effort, last writer wins**, not multi-process locking. Hand edits and a diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index f1477b006e..0b1779ceba 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -352,12 +352,19 @@ impl SettingsStore { self.dirty = false; return Ok(()); }; - if let Some(on_disk) = self.check_disk(&path)? { - recovery::write_backup(&path, &on_disk)?; - } + let on_disk = self.check_disk(&path)?; merge_into(&mut self.doc, &self.value).map_err(|e| SettingsError::Serialize(e.to_string()))?; set_schema_version(&mut self.doc, T::SCHEMA_VERSION); let text = document::render(&self.doc); + // A file over the limit would not be read back at the next start; keep the old file. + if text.len() as u64 > MAX_CONFIG_BYTES { + return Err(too_large().into()); + } + match on_disk { + OnDisk::Keep => {} + OnDisk::Backup(old) => recovery::write_backup(&path, &old)?, + OnDisk::MoveAside => self.moved_aside.push(recovery::move_aside(&path)?), + } craft_atomic::WriteOptions::default().with_new_file_permissions(craft_atomic::NewFilePermissions::Private).atomic_write_with( &path, |file| { @@ -373,8 +380,8 @@ impl SettingsStore { Ok(()) } - /// Looks at the file on disk just before a save, and returns its text when it is a good - /// backup (it parses and is not blank). + /// Looks at the file on disk just before a save, and returns what the save does with it once + /// the new text is ready: back it up (it parses and is not blank), move it aside, or keep it. /// /// The contract is best effort, not multi-process locking: if another instance or a hand /// edit changed the file since this store last read or wrote it, the new document is adopted @@ -382,10 +389,10 @@ impl SettingsStore { /// A file that no longer parses is moved aside (the edit is kept, the previous backup stays), /// and a file from a newer build, or one whose migration fails, makes the store read-only /// instead of overwriting it, the same as at startup. - fn check_disk(&mut self, path: &Path) -> Result, SettingsError> { + fn check_disk(&mut self, path: &Path) -> Result { let text = match read_config(path) { Ok(text) => text, - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(OnDisk::Keep), // Same as at startup: leave the oversized file untouched and stop saving. Err(e) if e.kind() == io::ErrorKind::FileTooLarge => { let why = ReadOnlyReason::Unreadable(e).to_string(); @@ -399,11 +406,10 @@ impl SettingsStore { // blank text is never written as a backup either, so the content would be lost. A blank // file is not an edit to adopt: keep what this store loaded and leave the file alone. if text.trim().is_empty() { - return Ok(None); + return Ok(OnDisk::Keep); } let Ok(mut doc) = document::parse(&text) else { - self.moved_aside.push(recovery::move_aside(path)?); - return Ok(None); + return Ok(OnDisk::MoveAside); }; if self.seen_text.as_deref() != Some(text.as_str()) { match migrate::upgrade::(&mut doc) { @@ -421,16 +427,25 @@ impl SettingsStore { } } } - Ok((!text.trim().is_empty()).then_some(text)) + Ok(OnDisk::Backup(text)) } } +/// What a save does with the file on disk before writing; see [`SettingsStore::check_disk`]. +enum OnDisk { + /// Missing or blank: leave it, and leave the previous backup alone. + Keep, + /// Parses: copy it to the backup. + Backup(String), + /// Does not parse: move it aside so the edit is kept. + MoveAside, +} + /// Reads `config.toml` as text. A file larger than [`MAX_CONFIG_BYTES`] fails with /// `ErrorKind::FileTooLarge` without being read into memory; text that is not UTF-8 fails with /// `ErrorKind::InvalidData`, as `std::fs::read_to_string` does. fn read_config(path: &Path) -> io::Result { let file = std::fs::File::open(path)?; - let too_large = || io::Error::new(io::ErrorKind::FileTooLarge, format!("file is larger than {MAX_CONFIG_BYTES} bytes")); if file.metadata()?.len() > MAX_CONFIG_BYTES { return Err(too_large()); } @@ -443,6 +458,11 @@ fn read_config(path: &Path) -> io::Result { String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) } +/// The `ErrorKind::FileTooLarge` error for a file larger than [`MAX_CONFIG_BYTES`]. +fn too_large() -> io::Error { + io::Error::new(io::ErrorKind::FileTooLarge, format!("file is larger than {MAX_CONFIG_BYTES} bytes")) +} + /// Exponential backoff: 1 s, 2 s, 4 s, … capped at [`MAX_RETRY_DELAY`]. pub fn retry_delay(failures: u32) -> Duration { let exp = failures.saturating_sub(1).min(16); diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index 9bd2ef97ed..6413ecaa62 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -67,6 +67,39 @@ fn file_grown_past_the_limit_while_running_is_not_overwritten() { assert!(matches!(store.tick(std::time::Instant::now()).status, craft_settings::SaveStatus::Idle), "no retries once read-only"); } +#[test] +fn settings_too_large_to_read_back_are_not_written() { + let tmp = tempfile::tempdir().unwrap(); + let (mut store, _) = open_in(tmp.path()); + store.flush().unwrap(); + let before = read_config(tmp.path()); + + let huge = "a".repeat(craft_settings::store::MAX_CONFIG_BYTES as usize); + store.update(|p| p.general.language = huge); + assert!(matches!(store.flush(), Err(SettingsError::Io(e)) if e.kind() == std::io::ErrorKind::FileTooLarge)); + assert_eq!(read_config(tmp.path()), before, "the file is untouched"); + assert!(!store.is_read_only()); + assert!(store.is_dirty(), "the change is kept for a later save"); + + store.update(|p| p.general.language = "fr".into()); + store.flush().unwrap(); + assert!(read_config(tmp.path()).contains("language = \"fr\"")); +} + +#[test] +fn settings_too_large_to_save_leave_a_broken_file_in_place() { + let tmp = tempfile::tempdir().unwrap(); + let (mut store, _) = open_in(tmp.path()); + store.flush().unwrap(); + write_config(tmp.path(), "not = [toml"); + + let huge = "a".repeat(craft_settings::store::MAX_CONFIG_BYTES as usize); + store.update(|p| p.general.language = huge); + assert!(matches!(store.flush(), Err(SettingsError::Io(e)) if e.kind() == std::io::ErrorKind::FileTooLarge)); + assert_eq!(read_config(tmp.path()), "not = [toml", "the file is untouched"); + assert!(store.take_moved_aside().is_empty()); +} + #[test] fn bad_value_only_resets_its_section() { let tmp = tempfile::tempdir().unwrap(); From a626b0d5c6c8ebf4170bf7a5295105dcaf1c150e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:16:32 -0800 Subject: [PATCH 020/235] craft-update: a copy running a pre-release is offered the next pre-release check_for_update read GitHub's release list for stable releases only, so a build that is itself a published pre-release (0.1.0-alpha.3) was never offered the next alpha. A copy whose version carries a release channel label (alpha, beta, rc, nightly) now also considers pre-releases and is offered the newest release by semver precedence. Stable copies and builds from source (-dev, -integration) are offered stable releases only, as before. --- crates/update/src/lib.rs | 68 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index 18d3160797..53e30a39fb 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -69,13 +69,15 @@ pub fn now() -> i64 { } /// The release in GitHub's release list `json` to offer a copy running `current_version`, if any: -/// the latest published release, when [`version::offers_update`] says so. +/// the latest published release, when [`version::offers_update`] says so. A copy running a published +/// pre-release (`0.1.0-alpha.3`, `0.17.0-rc.1`) also considers pre-releases, so it is offered the next +/// one; a stable copy and a build from source are offered stable releases only. fn offered_release(json: &str, repo: &str, current_version: &str) -> Result, String> { - let latest = crate::release::parse_github_release_list(json, repo, false)?; - Ok(latest.filter(|release| { - let running = crate::version::parse(current_version); - release.version.as_ref().zip(running.as_ref()).is_some_and(|(rel_v, cur_v)| crate::version::offers_update(rel_v, cur_v)) - })) + let running = crate::version::parse(current_version); + let prereleases = running.as_ref().is_some_and(|v| !crate::version::is_stable(v) && !crate::version::is_local_build(v)); + let latest = crate::release::parse_github_release_list(json, repo, prereleases)?; + Ok(latest + .filter(|release| release.version.as_ref().zip(running.as_ref()).is_some_and(|(rel_v, cur_v)| crate::version::offers_update(rel_v, cur_v)))) } #[cfg(test)] @@ -106,4 +108,58 @@ mod offer_tests { assert_eq!(offered("0.17.0"), None); assert_eq!(offered("not a version"), None); } + + const PRERELEASES: &str = r#"[{"tag_name":"v0.1.0-alpha.4","prerelease":true,"draft":false,"assets":[]}, + {"tag_name":"v0.1.0-alpha.5","prerelease":true,"draft":true,"assets":[]}, + {"tag_name":"v0.1.0-alpha.3","prerelease":true,"draft":false,"assets":[]}, + {"tag_name":"v0.0.9","prerelease":false,"draft":false,"assets":[]}]"#; + + fn offered_from(json: &str, running: &str) -> Option { + offered_release(json, REPO, running).unwrap().map(|release| release.tag) + } + + #[test] + fn a_prerelease_build_is_offered_the_next_prerelease() { + assert_eq!(offered_from(PRERELEASES, "0.1.0-alpha.3"), Some("v0.1.0-alpha.4".into())); + assert_eq!(offered_from(PRERELEASES, "0.1.0-alpha.4"), None, "a draft is never offered"); + assert_eq!(offered_from(PRERELEASES, "0.1.0-alpha.4+build.7"), None); + // A release flagged as a pre-release on GitHub counts as one even when its tag has no label. + let flagged = r#"[{"tag_name":"v0.2.0","prerelease":true,"draft":false,"assets":[]}]"#; + assert_eq!(offered_from(flagged, "0.1.0-alpha.4"), Some("v0.2.0".into())); + } + + #[test] + fn stable_copies_and_builds_from_source_are_not_offered_prereleases() { + assert_eq!(offered_from(PRERELEASES, "0.0.9"), None); + assert_eq!(offered_from(PRERELEASES, "0.0.8"), Some("v0.0.9".into())); + assert_eq!(offered_from(PRERELEASES, "0.0.8-dev"), Some("v0.0.9".into())); + assert_eq!(offered_from(PRERELEASES, "0.1.0-integration.20261120.a20dfd16"), None); + } + + /// The pre-release precedence examples of Semantic Versioning 2.0.0, section 11 + /// (): + /// `1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0`. + #[test] + fn prereleases_are_offered_in_semver_precedence() { + let order = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"]; + let list = order + .iter() + .rev() + .map(|v| format!(r#"{{"tag_name":"v{v}","prerelease":{},"draft":false,"assets":[]}}"#, v.contains('-'))) + .collect::>() + .join(","); + let list = format!("[{list}]"); + for running in &order[..order.len() - 1] { + assert_eq!(offered_from(&list, running), Some("v1.0.0".into()), "{running}"); + } + for (i, running) in order.iter().enumerate().take(order.len() - 1) { + let list = order[..=i + 1] + .iter() + .rev() + .map(|v| format!(r#"{{"tag_name":"v{v}","prerelease":true,"draft":false,"assets":[]}}"#)) + .collect::>() + .join(","); + assert_eq!(offered_from(&format!("[{list}]"), running), Some(format!("v{}", order[i + 1])), "{running}"); + } + } } From 202e90d1ba9739f4b76f9a2cc2e92eb117380c36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:25:26 -0800 Subject: [PATCH 021/235] atomic: sweep_temp_files keeps names with zero-padded numbers temp_name writes the process id and the counter without leading zeros, so a name such as .scene.json.012-0.craft_tmp is not one it gives. The name check now rejects a numeric field with a leading zero, except a lone 0. --- crates/atomic/src/lib.rs | 3 ++- crates/atomic/tests/atomic_tests.rs | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 02b4070f15..e9b76091bc 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -640,7 +640,8 @@ pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result< /// of at most 64 characters. #[cfg(not(target_arch = "wasm32"))] fn is_temp_name(name: &str) -> bool { - let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + // Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed. + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0')); let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else { return false; }; diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index 45d659d75e..8356e9819a 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -279,6 +279,9 @@ fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> { leftover(&d.0, ".12-3.craft_tmp", old)?, leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?, leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?, + // temp_name writes the process id and the counter without leading zeros. + leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?, + leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?, // temp_name keeps at most 64 characters of the destination's name. leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(65)), old)?, ]; From b0f09a0651d19b16e8363ca2cf02a18cea96de0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:40:16 -0800 Subject: [PATCH 022/235] craft-settings: keep an adopted outside edit as the save baseline When a save adopted a changed config.toml and then failed (settings too large to write, a backup or write error), the store kept the adopted document but still compared later reads against the text it had loaded before. If the outside edit was then undone, the next save skipped the file on disk and wrote the undone edit's comments and keys back. The store now records the adopted text as its baseline together with the document. --- crates/settings/src/store.rs | 7 ++++++- crates/settings/tests/recovery.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 0b1779ceba..3ae2cb47c0 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -418,7 +418,12 @@ impl SettingsStore { self.read_only = Some(why.clone()); return Err(SettingsError::ReadOnly(why)); } - Ok(_) => self.doc = doc, + // The adopted text is the new baseline, so a save that fails after this point + // still compares the next disk read against the document the store now holds. + Ok(_) => { + self.doc = doc; + self.seen_text = Some(text.clone()); + } // Same as at startup: leave the outside file untouched and stop saving. Err(e) => { let why = ReadOnlyReason::Migration(e).to_string(); diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index 6413ecaa62..b94027f47c 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -100,6 +100,32 @@ fn settings_too_large_to_save_leave_a_broken_file_in_place() { assert!(store.take_moved_aside().is_empty()); } +#[test] +fn rejected_save_keeps_the_adopted_file_as_the_baseline() { + let tmp = tempfile::tempdir().unwrap(); + write_config(tmp.path(), "schema_version = 2\n\n# note a\n[plugins]\nenabled = true\n"); + let (mut store, _) = open_in(tmp.path()); + store.flush().unwrap(); + let first = read_config(tmp.path()); + + // Edited outside the app, then a save too large to write adopts the edit and fails. + write_config(tmp.path(), &format!("{first}\n# note b\n[extra]\nkept = true\n")); + let huge = "a".repeat(craft_settings::store::MAX_CONFIG_BYTES as usize); + store.update(|p| p.general.language = huge); + assert!(matches!(store.flush(), Err(SettingsError::Io(e)) if e.kind() == std::io::ErrorKind::FileTooLarge)); + + // The outside edit is undone before the next save. + write_config(tmp.path(), &first); + store.update(|p| p.general.language = "fr".into()); + store.flush().unwrap(); + + let text = read_config(tmp.path()); + assert!(text.contains("# note a"), "{text}"); + assert!(!text.contains("# note b"), "{text}"); + assert!(!text.contains("[extra]"), "{text}"); + assert!(text.contains("language = \"fr\""), "{text}"); +} + #[test] fn bad_value_only_resets_its_section() { let tmp = tempfile::tempdir().unwrap(); From 6b21ee82277812bac4c96a91aef7caa4de5e7963 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:06:59 -0800 Subject: [PATCH 023/235] vendor: the hayro SOURCE.json manifests record the committed files' sha256 53 `sha256` entries in the SOURCE.json files of hayro, hayro-cmap, hayro-interpret, hayro-jbig2, hayro-postscript and hayro-syntax did not match the committed files. 49 of them are files that #2472 changed; the other 4 were already stale before it. Each entry now holds the SHA-256 of the file's blob at this commit. The `source_sha256` and `source_git_blob` fields are unchanged. --- vendor/hayro-cmap/SOURCE.json | 6 ++-- vendor/hayro-interpret/SOURCE.json | 50 ++++++++++++++--------------- vendor/hayro-jbig2/SOURCE.json | 2 +- vendor/hayro-postscript/SOURCE.json | 2 +- vendor/hayro-syntax/SOURCE.json | 42 ++++++++++++------------ vendor/hayro/SOURCE.json | 4 +-- 6 files changed, 53 insertions(+), 53 deletions(-) diff --git a/vendor/hayro-cmap/SOURCE.json b/vendor/hayro-cmap/SOURCE.json index 2c72f523fb..7a6120ae9e 100644 --- a/vendor/hayro-cmap/SOURCE.json +++ b/vendor/hayro-cmap/SOURCE.json @@ -74,7 +74,7 @@ "path": "src/bcmap/mod.rs", "source_sha256": "38dafbd8fcb5ca6f647d70d02cdb5af532ea7f2a3ac3f7ac8d1dea23abc93058", "source_git_blob": "997bc00d85db1504c63cf56e3cb157410ebdb0bb", - "sha256": "3d0ea5e34bc92c40a250923ecb71b48571100bba5cc4664ea2c46d51086fe6be" + "sha256": "c9a07d146408aefc2dd03df9209721f4e6e576f5d941f2fc5e658af045c6adfe" }, { "path": "src/bcmap/reader.rs", @@ -86,13 +86,13 @@ "path": "src/lib.rs", "source_sha256": "d666b3d8e4d37fc06c299a60ab9748ae17badcea271ff2cf864dcee76e27648c", "source_git_blob": "fb42ff37ec9ccece66d33d1888bd25963cbf1171", - "sha256": "d6b9c6fa8de00942dd4cdfbd43578d3e53f8a3a6cf1e3563b345a9f6f35bc5e8" + "sha256": "9dd76a9c6e50725851f3b50c35264a222c968e253c2f8d37ad5a11b960a1cb02" }, { "path": "src/parse.rs", "source_sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b", "source_git_blob": "a936209275ffca797912dec052dc03ddb0d2dce4", - "sha256": "1999127f05b59bdd55e2a7349dafc0b2213238201da37f7c35cd698996f2dc6b" + "sha256": "373b1044800b231d96d40baeb089c5224a9a8ca4925aacfec58b215cd64bea8b" } ] } diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index bffa37b555..f300abf314 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -20,13 +20,13 @@ "path": "Cargo.lock", "source_sha256": "a8a0e3460e43e7305385c01c3060ed34e4fdf13495d61b8a6bd1314d8a1c91a1", "source_git_blob": "c10e1749882fc27c11322f338b7e7f9568643b3c", - "sha256": "a8a0e3460e43e7305385c01c3060ed34e4fdf13495d61b8a6bd1314d8a1c91a1" + "sha256": "c9109a3318b0ae9bd674ef44244725d11c8cd7733ee0993396a4af8051b3ca5c" }, { "path": "Cargo.toml", "source_sha256": "cdb6fc309585747b98c029d2e2d48f31bc06595871aa3cce041786e5f78f61bf", "source_git_blob": "8141e63df329caeebd66392643848cdbdae5fb4e", - "sha256": "cdb6fc309585747b98c029d2e2d48f31bc06595871aa3cce041786e5f78f61bf" + "sha256": "fada6f6980bb507802ebb15a743e233af5ace27ec04cd1fa2226d62df219676b" }, { "path": "Cargo.toml.orig", @@ -176,49 +176,49 @@ "path": "src/cache.rs", "source_sha256": "76b5dc066330666a50a32124856306b72c98e646346263bd8a269bc99e5a0d42", "source_git_blob": "e253a7b8c7dbfbfa2f7dc1f6c582559962060b94", - "sha256": "c63ed890ead39cc6205746063f90689b7a617e8c14a35e6ee1b955550d1230a5" + "sha256": "de57929a3207a0a19f0ed7827ec040ef79364507094f41848bd6cfa9ace26874" }, { "path": "src/color.rs", "source_sha256": "799ce29bb5e59c8fc94db202873e48c2047dd35962e6f26efd215156c47158c1", "source_git_blob": "56bb04f24c04ba33ab6bf99c02a24735670959ad", - "sha256": "72935834f00f5f04f1baa418e12040b5a413e8620be7356337605a0ab63f5c7a" + "sha256": "00b8c834f3a70ea06bbd89e78e4668ce490129906fb9a9757b128296c0a2c5bc" }, { "path": "src/context.rs", "source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56", "source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137", - "sha256": "221174b2b65824e1489e8d0f61ac5c81b828caf7f5c7053e27c84a6657857f4c" + "sha256": "3beef4bd55188e042c6eea83aa77ebeca259f9c503deab671352a479d575eb61" }, { "path": "src/convert.rs", "source_sha256": "a361962285ef6153b4c10f75c8c7e31a2267b12481f85e5ff520915e79a6f0ba", "source_git_blob": "e768911415945256824d9759b4aa0490e0c80377", - "sha256": "a361962285ef6153b4c10f75c8c7e31a2267b12481f85e5ff520915e79a6f0ba" + "sha256": "e42c82eb291fd02261a2b93aebeb7d8c9c95f0a1d733263f9658c72921ddb56b" }, { "path": "src/device.rs", "source_sha256": "6f0c1203d1e60724cdd11e9a230249247a70f578c4a7ccb9bf39a23411b32db6", "source_git_blob": "36c64a23fd23f6c4abad941077cf93296a67841f", - "sha256": "8fff824fd81c36dc20a194697b10cd752928b09301f9287b0bb6ed00978ac723" + "sha256": "2b227f7feb2a75baaea325a043efa3a27c276ba2cfbd7e61a1ae55375c219d0a" }, { "path": "src/encode.rs", "source_sha256": "674a97c48cc62e9a218f843246776528173c36c00aa96a1e4c291c1d912c29c6", "source_git_blob": "b3f830ba2dcdb7069ea73706be43c55be398f670", - "sha256": "46c9773f05c329cad20f3126394f89a551ee393569c58911b0a921be8c020376" + "sha256": "66e5a22c1125e8918f2f2a0b84324fcf3b0ad25e6b182d4277e90fc5163cee06" }, { "path": "src/font/blob.rs", "source_sha256": "30a9dadf498829ee03eb1ddc6deaeb09a06ee42415f288d46f4a67640582c575", "source_git_blob": "6eabc26b9bc30bdc51f0b5fdd5e4b556d7583ec5", - "sha256": "8c39f3ef95c48054d4aacaeb17189193c075df42fc767eee596bc4dbf2453d5f" + "sha256": "831e96f92127faa7225d5cde341e9308ddf0f440b6a20280c14bbc712bc4f72e" }, { "path": "src/font/cid.rs", "source_sha256": "c1dbe7fe5b7f7092d97b84063008df54aebf87db4ba1fdb3a179fab9fe6674b8", "source_git_blob": "b99dcbc116ca1169df3a229eafd05ee5b9204626", - "sha256": "6c9927c47893edacab4a3258d4ec72b4d3cc2dd25c518e308884321110847ab6" + "sha256": "a2e240a3ca36da75c9e353cbbf9db873d446f263d21c6c252ff01559bf9f83e1" }, { "path": "src/font/generated/glyph_names.rs", @@ -290,7 +290,7 @@ "path": "src/font/mod.rs", "source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313", "source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7", - "sha256": "c0c903cb8a33ab863412c407ad10181adec0d22b81c899fc5225de14d8878091" + "sha256": "b58ee45b8c4a4d1de36eadc11363a8620ac56202646c937c1a012539372883bc" }, { "path": "src/font/outline.rs", @@ -302,25 +302,25 @@ "path": "src/font/standard_font.rs", "source_sha256": "af3c51592c086671cb127745d4351d1380ef1212aee325099f1e933607995d7d", "source_git_blob": "139454a0b21eb992e9e52bf73c85e965c0f86cda", - "sha256": "01241c51fe85d94fa1bc3963e16a45be7c292104b204c37704e636ba2c0b0c5d" + "sha256": "03c8e9ffd3726e13713a6e8f5e25ef246939e52d77fcaa412a72344d2eb41790" }, { "path": "src/font/true_type.rs", "source_sha256": "278fed0cddcc43cc7d616200dcefb45720db9d560f54e41a82c281c3163b411d", "source_git_blob": "b36266985942b4d7e2970f9edf7329c4edbcfa11", - "sha256": "a1262fd7efcf358b85b7863c97733a40e5df4295a9d1b54f66b1bada5898f600" + "sha256": "8ba289682e9835fb9b6b7983eb1192c7eaa80e6467eed64b90d387682bee9776" }, { "path": "src/font/type1.rs", "source_sha256": "431b1fe86ca51bd993e81084a64c3e8ed8b90a67385a30eb4ffedfdd98c6f96b", "source_git_blob": "02f76bfb8095041e3d54df014190047de46be4c5", - "sha256": "af73de5038ee590bb062ee1e610a60e5e4f51d109ae765922ce9669b4e36ce95" + "sha256": "5df2d753500f0e52ee33c05ab1027185a7f2d8a56227dd58cb1a3da7a253fc85" }, { "path": "src/font/type3.rs", "source_sha256": "bc33784f0dd3e599028b28b3696b9e4380cbff08f4c4e6299dee51f8df5eb08f", "source_git_blob": "c0e0d0b2df8f38183b8e23e9e8f644c0b81d0529", - "sha256": "1778362c6c4a5cb015e756fd3f36afd7482f20a230dde0206f4339da922eaca4" + "sha256": "ab13ed284836e01bed3fb28cdbe3c44e63195d06157e9c6505c8a12ca740527c" }, { "path": "src/function/mod.rs", @@ -362,31 +362,31 @@ "path": "src/interpret/mod.rs", "source_sha256": "2b002323055bc19aa497e92c81ad8e06dc60ee03686cad89366df4ac7c7a06b2", "source_git_blob": "fe08fc284ba7c914d1414b68a5a346674a6f910f", - "sha256": "3f8958e8d234f00b24478acb8081aa1aaffdca6b8a12b24c4abc6f534ce09a05" + "sha256": "48e6ae1a3231d121bfaac5836b38174712eb055b78352f62747e807a9b6aef10" }, { "path": "src/interpret/path.rs", "source_sha256": "a5defbc4b883b262662f7e7474a00ec1f97dbef8c03b8669859f624f5d02344b", "source_git_blob": "838ea099f11d918d6e333e32503368be864689f8", - "sha256": "0e4d2dc0a2d5a2c5cdc0d1d9358fcf3b0854e8d24d002ce1830a1b4def786bc8" + "sha256": "a334e71b6ea0b2a3014b865b8b48e7b558033fe310effc202ca03e06926b0572" }, { "path": "src/interpret/state.rs", "source_sha256": "dce778291b13f6df83c8c13aee22f60edd033ec9f7d89309ef148d46d3ba9814", "source_git_blob": "95b773fb5cc434ab8db362d00e4e5180a8b740c9", - "sha256": "bc5e73c3b29cdfe9d5f5036ea82beb2cf5a12ccd8a8c93277c15670b5f81ec08" + "sha256": "e48f5874edd4db8db4453dfc1f3b13fe23801d2534f8aabfb132694ef87be68f" }, { "path": "src/interpret/text.rs", "source_sha256": "35eafa80147aea635bdef127c33ace20e1695e11e87c7bfe1e035c886806ff30", "source_git_blob": "ddec0400ea7a639c14769ac9ee7e137d000b3efd", - "sha256": "b34117d28ca7987833626f2e938abe4dd5d02ea869db7b0bdc1b8a264d775f9c" + "sha256": "ef5c39c97b54d08837763ca597f70d27f2dc2865cec11fb411400509d9fffe8c" }, { "path": "src/lib.rs", "source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9", "source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4", - "sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9" + "sha256": "3473d9640da637f95252611d1edb601efa9327c117d5580913c670dda696dd6e" }, { "path": "src/log.rs", @@ -398,13 +398,13 @@ "path": "src/ocg.rs", "source_sha256": "439455f65b8ad6ed9b0306536c2f75fa5f3fdda42ed4ca351ec3d340c38dc330", "source_git_blob": "c59b70df4be6a83485360dacd76bead9f80c7f94", - "sha256": "35dadd9fc07e3e5754e208fc5c0c588776ff6bff249aa0eee9848a8fde8b4f08" + "sha256": "0d1ebb4ce39088e3959096ff100383e3c5aca7b5164d582842339c9fb05cc9d1" }, { "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "e57d4de60126eafa0da2113af12bbbde1aabd15554f1ee26f6551b8219f4ede5" + "sha256": "1ee9705afa285ddeb4c287e83e86906bdcc525a738b41d17164d1f751e2c01b6" }, { "path": "src/shading.rs", @@ -416,13 +416,13 @@ "path": "src/soft_mask.rs", "source_sha256": "6cd9c59c0cff580879c1f06ff40f3537c04b719bdb3ea59008fa1ab7559db5dd", "source_git_blob": "4d97d565b53c820fa927fbba8c3dda6acead7f34", - "sha256": "fe3da157602bf5b16a452ecbe1d8d554af992a5b9dfaa771dd23c2e2e66d730b" + "sha256": "b019e76429285f0e4b56217374ae15889902fa90fc432a84545efc5d380a4985" }, { "path": "src/types.rs", "source_sha256": "0e66569b8a7dc243b0a384cf1d3615ca62bf660b5324236f2594609bdfddfd46", "source_git_blob": "64d2b849bdd3fdcd4ebfd76845edcef77b625fbd", - "sha256": "669fb4a9427193a962b7cda70656b688795ea691f67ae52333124807ba88006c" + "sha256": "81f95dd47f62be9815472d16e7a81958f27eceeffc658582fd367ac778271af1" }, { "path": "src/util.rs", @@ -434,7 +434,7 @@ "path": "src/x_object.rs", "source_sha256": "e1c51e96a335c32c122011b2d05c5020c36a33c2c73342ba173c28a3e2fe0219", "source_git_blob": "21b134ce8cd9604399cd0776febf923d69c02673", - "sha256": "d752a8c44c0a3918e9fc130c4e59a1708ae7bfa2a3c95b700dfe77da15f43f66" + "sha256": "5990bc0fe3e1b9c131027b294d8308dd3b545ff87315f22f4c3ad5bfd863f01d" } ], "compatibility_reference": { diff --git a/vendor/hayro-jbig2/SOURCE.json b/vendor/hayro-jbig2/SOURCE.json index 0568ac878b..8597090d67 100644 --- a/vendor/hayro-jbig2/SOURCE.json +++ b/vendor/hayro-jbig2/SOURCE.json @@ -176,7 +176,7 @@ "path": "src/segment.rs", "source_sha256": "58d9fd05a15358b4ca945ffa3b8c1872f4ea57f8bbe50e8db3c6fce5bcac2914", "source_git_blob": "35c17c38af62b1fece4e280cda923cdcb23a8661", - "sha256": "c64e2845dbdd26e33b5461acde399ba4820f9942e9090a32782f44ff0fd5e61f" + "sha256": "2d37e9f558b8e453e5ab2da55ca2ff9722c74298e55a0f34805bda42561baf9a" }, { "path": "src/simd.rs", diff --git a/vendor/hayro-postscript/SOURCE.json b/vendor/hayro-postscript/SOURCE.json index 06e922bccd..0edf1a912f 100644 --- a/vendor/hayro-postscript/SOURCE.json +++ b/vendor/hayro-postscript/SOURCE.json @@ -70,7 +70,7 @@ "path": "src/lib.rs", "source_sha256": "357a6f5a549cb1a0214f8a00fe529ce0486f566fc7174c8deccd79e8c8e1f8bd", "source_git_blob": null, - "sha256": "357a6f5a549cb1a0214f8a00fe529ce0486f566fc7174c8deccd79e8c8e1f8bd" + "sha256": "b4c5c9272dd70013db5add11e060374453a82093ace1df06f05347f7af7e608a" }, { "path": "src/name.rs", diff --git a/vendor/hayro-syntax/SOURCE.json b/vendor/hayro-syntax/SOURCE.json index e68a7b4a4e..1f4247fe97 100644 --- a/vendor/hayro-syntax/SOURCE.json +++ b/vendor/hayro-syntax/SOURCE.json @@ -68,13 +68,13 @@ "path": "src/content/mod.rs", "source_sha256": "b0f36badb2688c90691c27a4e5dcdfec7639858081553242744dd7bc39ffc0d0", "source_git_blob": "8e47324d0b0bd90ed15efe5ff1e9de0cb46e75d9", - "sha256": "ae0b0596d2304adc4109294cc7af681698071060d9e8cd6d44f0bb46baffec6b" + "sha256": "09db511a1faff15a2adcf70a3d4ae526a481026a95391cb6d87e32f17ddbe625" }, { "path": "src/content/ops.rs", "source_sha256": "b29f00f4570a2dc061b2189cf2a96a499ffe424abfb846dd4cec99cc1ef8901f", "source_git_blob": "b066165841182b9b1e5ba350000744e705e95f86", - "sha256": "b29f00f4570a2dc061b2189cf2a96a499ffe424abfb846dd4cec99cc1ef8901f" + "sha256": "8f902dc69b35ec0eebaf3983de6031bbe3718c1b9d8cc1c549497fa9ab577704" }, { "path": "src/content/ops_generated.rs", @@ -98,7 +98,7 @@ "path": "src/crypto/mod.rs", "source_sha256": "6fca01cee7e67f3aaf435101b7ea98fa4fe23f807eadeaec63ee1c2ece759189", "source_git_blob": "15371514c10dc993b335edfec19a3f989b497954", - "sha256": "9e0fc0edf48217b01acfcf7bcd3ebe0673f225f0c3857bf887efd0b0f31a74b2" + "sha256": "bc89905e8c24197656a045ccc52cfcfbc61c4e1f996b4d3655f061789b1fbbb3" }, { "path": "src/crypto/rc4.rs", @@ -128,7 +128,7 @@ "path": "src/data.rs", "source_sha256": "c8dc5a157358e024d73e405333ecac01e94ba6880488d5a10b952bd3fc47fd41", "source_git_blob": "9d5e2030f8d6dab7167cd2c5d8da36a7e5688c34", - "sha256": "83c4417cfe9b301ef0fce8dc2f6a7f694d025e1fd82a68db6acded31155d3bee" + "sha256": "83b9c8823d9fe58c0bf8a24e8ce48b2a08b28e26744aa14bc1de72633e41fc5a" }, { "path": "src/filter/ascii_85.rs", @@ -146,7 +146,7 @@ "path": "src/filter/ccitt.rs", "source_sha256": "45d7eb89934d28cff97a00c7b264010bccfd14f3d511e1307ad50a9fef3b53c8", "source_git_blob": "685d680d2fbadce608a9bd3ca925c2ccc6c5d641", - "sha256": "67d17a339639eb0fef4cc6c745b579c6ba9ae3f2f67fd3bacb1bf1389aa5ffab" + "sha256": "0b0127c43f84d154341a33ec385c4885f75900eaee97d7eb24d108fa6ccf0db8" }, { "path": "src/filter/dct.rs", @@ -158,25 +158,25 @@ "path": "src/filter/jbig2.rs", "source_sha256": "0ac3c16e02cb13f2d5fe401edd35949320662906c3906cb39fe743acd5e32b09", "source_git_blob": "d87253f536e6b8ac18323f1f06164b516ad775df", - "sha256": "294de5b38201a095c0dcde97ddbba2563d33874deede190b31869d3bcb110fd1" + "sha256": "7746b6b8982619ce14e4b1ee01ba32cd61ff1f4c6a2dffec4bfb0b543ff4afa9" }, { "path": "src/filter/jpx.rs", "source_sha256": "c9f068629c9cbe79af6793c3c125df4631ca1455691cb1335b44ff43cb1b4056", "source_git_blob": "74efd8b31e2b2935ff2bbceda2c1ffd36ea9c20d", - "sha256": "81213936de6d1c6b63bea041a1f88a71753e3b4238a08d9bbc7dbdfaca0970a0" + "sha256": "17e0778c83647c1a892ed1ad18f3efe5622571fbe9638175fcedac07f1e93c31" }, { "path": "src/filter/lzw_flate.rs", "source_sha256": "db51a57effe90ad9db2d314e16081ce90e3ef99e5a5f46fcc4bdbdacfd13a528", "source_git_blob": "f1ab1aae73e4c84ec0993a6eb96594018ca7cc91", - "sha256": "460055f809889a36cd91ce391290410b7520cb7e36c613e0e08a7a8f3540dfb7" + "sha256": "9a077f61e31ba1003c999b3db5a0fa3d1acc610100a3aec4bbb89fd7b7babf00" }, { "path": "src/filter/mod.rs", "source_sha256": "0af7145ab16b15b7a60c4b57efecb9bd5fd0cfdc9bb5f9388abb695386e63e49", "source_git_blob": "06bda29487d62c25dc39c1ee109091cb17e3867f", - "sha256": "74127a32b9ac86e33f41ac10f9a51a95849caca9211b0f7ee7eb535f5a59d063" + "sha256": "2270c0dd4cdec0308ffa8be0b85f4773fd1e69d141ae58b28d10bf1a239708ca" }, { "path": "src/filter/run_length.rs", @@ -212,7 +212,7 @@ "path": "src/object/array.rs", "source_sha256": "6fbddf05724848db2389068a0504cff6b0783e35baa58e64bf2a31d48a1042ea", "source_git_blob": "d39230f7dbf114dd202a16b21f7a6bb70be5ead3", - "sha256": "8d5704b638f5198ec74604a3fd88a32dee553b6dc2a7010e746ef5e459759ed6" + "sha256": "e71816b498b005c9313c0ef2d67fc7da2e927cfe5ff865ec90f23d9031b8684d" }, { "path": "src/object/bool.rs", @@ -230,7 +230,7 @@ "path": "src/object/dict.rs", "source_sha256": "bcfefabe931614b79ea54940d02fce534eb2363f1b75a03d6428fd7a04c57981", "source_git_blob": "1e016b567e8ec17801fa8282c47f653092839cb5", - "sha256": "0ec184d3d5368ad67cac0af4c2f98914cc02d2ee7e169276e9ed929ffdb287f2" + "sha256": "e81e4e394253e248cf9a6a75908c2950d325f79a36d1b7a7c98bd31c22936ed8" }, { "path": "src/object/indirect.rs", @@ -242,7 +242,7 @@ "path": "src/object/mod.rs", "source_sha256": "6188f89366cdb1bcfc0742c778dd5997447ad79015b9994fcaa9437cb006e615", "source_git_blob": "d692db8b385600474db3dbda9ee7c0da01713c04", - "sha256": "6188f89366cdb1bcfc0742c778dd5997447ad79015b9994fcaa9437cb006e615" + "sha256": "667a77bdc9bd0b36ea52f5f4361cf1d352bde1f7babb08be8430b18eea725642" }, { "path": "src/object/name.rs", @@ -272,13 +272,13 @@ "path": "src/object/ref.rs", "source_sha256": "b5ff0720a3946ef6e77922c8f56e4a0cacd7bbdb13280b9583740b5fd8a7c8fd", "source_git_blob": "71951f4d82b1e281c67bde79d1179766f4fd515f", - "sha256": "b5ff0720a3946ef6e77922c8f56e4a0cacd7bbdb13280b9583740b5fd8a7c8fd" + "sha256": "eebd7565edbfdb5c78fd5039120d2dd890b49cd8ce9c3be00d69f0436d8282c4" }, { "path": "src/object/stream.rs", "source_sha256": "f5229eb2f52c9918830027c93112e042a9e97d34b5fec72f97dcc7de8c5410ac", "source_git_blob": "a80f0730cba317ed3771cee61d6a7ab18de296d7", - "sha256": "ce9b81f31963cd0474aba253d7c9937f78cd3a1034b6811ccf4cbdf68c3769b6" + "sha256": "e42187207336e5940005968d38377da8686d5fb1861612e4c0a1cf368d9738d6" }, { "path": "src/object/string.rs", @@ -290,25 +290,25 @@ "path": "src/object/tuple.rs", "source_sha256": "eeaf3f14a962fc98a109d1a74d7e70e069816d909e5e55766361658ef7b26aea", "source_git_blob": "4a7190e91653c9fb47539dfec0edd631a99a3618", - "sha256": "eeaf3f14a962fc98a109d1a74d7e70e069816d909e5e55766361658ef7b26aea" + "sha256": "6d75aa5cf53456a6666006ecf14b1726f3b7d713ea03efbfebb151fdc7a549a8" }, { "path": "src/page.rs", "source_sha256": "17be32b2eaa03a3367f1f20040556f7ee5b207588cf44a1af3e5253386fb46f9", "source_git_blob": "d7f0ec953722a938508f1f31f0adaecc0a181d20", - "sha256": "b860e2a1d24eff3e3dab57f195a7c99c108f107eb3387ce917d47a9190a8053c" + "sha256": "b1d8518fdecdcffef289ba7008b27af15676f743f7f0650b5deb9bce45018084" }, { "path": "src/pdf.rs", "source_sha256": "b6938cd27757a20dca83b49db46d73ab32a0ca2a474a0c4517d1d82b71a1be1c", "source_git_blob": "c196cb14acc1bfd4dd572d7fedd8345b40e44873", - "sha256": "e3c2b63122a7e6a6266aed7b3c58c7983e95595797dc1ab95500717ffff28dc9" + "sha256": "47a3e69e3fd7189bfa8d8f64b1f51ad433042f5f3392431c0200f6343a632c7b" }, { "path": "src/reader.rs", "source_sha256": "f2f10a5cddecd70dae36304f432d052f4d7fdf5113dc4473a06de502375c4f2e", "source_git_blob": "818f767f7b982bbe759f9c81dc91f0ddce335d25", - "sha256": "a5ff6b8a90d3db6672b886558b1a1c13730eabbff4105233bcac637ac5324bfe" + "sha256": "9730728810ca2a37026805f66d6ffd83484338733eb4ad8990591ee4357c72f7" }, { "path": "src/sync.rs", @@ -338,13 +338,13 @@ "path": "src/xref.rs", "source_sha256": "51ffeeb7d4ac035bae2cd5ba9288c180088ae06cdcefe2b29dfeda560a793aa0", "source_git_blob": "20e33a410489d42e438a3f2b87d70c7bb8d66eae", - "sha256": "920adb9a303f92f3fed721242e5d0976d36ebc2a3e16ef55e19e254a0d16d564" + "sha256": "a24252b9af3b2851ef9bb613980a0d929db079580cd388c440231a04cde103e4" }, { "path": "src/decode_limits_tests.rs", "source_sha256": null, "source_git_blob": null, - "sha256": "0c486b89709267199242934da6568ac20aa3eb5f3269bd227bace3940aecb09e" + "sha256": "2d1ae219db8f68a4f5212a6ec1398866c0add9f14b78a08518328f2b2d46905e" }, { "path": "src/cancel.rs", @@ -356,7 +356,7 @@ "path": "src/filter/cancellation_tests.rs", "source_sha256": null, "source_git_blob": null, - "sha256": "d0d4054aa80ed9a732778f6a391ef12d327a3ce34de859704940445b8e10906e" + "sha256": "a18f19629780545a2812fcd8866db9875f3cd048ed67a0d307c0192e16b1b4e9" } ], "compatibility_reference": { diff --git a/vendor/hayro/SOURCE.json b/vendor/hayro/SOURCE.json index b6d1d67ea8..09ce23dd98 100644 --- a/vendor/hayro/SOURCE.json +++ b/vendor/hayro/SOURCE.json @@ -62,13 +62,13 @@ "path": "src/lib.rs", "source_sha256": "682db2a32fbf4d875c0e9dd7ac5dc875a6b09ade375efbce6f104de9197de078", "source_git_blob": "6333ed5808ae0cf9cf158e4730e973c1d7089bab", - "sha256": "8b17f78900e6f15b0d458629d69c954e436a3e8b97c01563c884456b87379d9f" + "sha256": "a39d81cf000123e2daa2ebfd21200bbf130036e0f132f0253bde6fa91299f61c" }, { "path": "src/renderer.rs", "source_sha256": "f7ff7bd088ceb43823ede33151138384af331cf71403f7d23f7b2937212efc3b", "source_git_blob": "6aa53716ad2d0203a8058b2f7271515b4fc1db22", - "sha256": "d9cf21375b8957684a8d18b84ed8aac4c340212e9d6154b09f26ab7981b83a95" + "sha256": "fee95f6d6d64a3dacbf2265a09a3e28ddda3d897fd06d1e374655ecbaf1f82fa" } ] } From ed647a5d49c88c3ade7486267a329ab5d5ffb485 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:35 -0800 Subject: [PATCH 024/235] Canvas: the body's tool pass carries the text the editor part pastes The framework takes a paste event out of egui's input and keeps its text for the focused component, so a canvas body that applies its editor's Edit(Paste) could only read the installed clipboard, which fails where the system clipboard can't be opened (a Wayland session where arboard finds no data-control protocol). ToolPass::pasted now holds the text the platform's paste event carried in the pass of that paste: Ctrl+V's, or the one a Paste command asks the platform for. --- crates/ui-canvas/src/canvas/mod.rs | 13 ++++++++ crates/ui-canvas/tests/it/canvas/editor.rs | 36 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9cab..ad3724c1bd 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -240,6 +240,8 @@ pub struct Canvas<'a> { settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. context_key: bool, + /// The text of the paste the editor part takes this pass, taken in `update` with its inputs. + pasted: Option>, /// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)). ease: Option, /// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional @@ -316,6 +318,7 @@ impl<'a> Canvas<'a> { snap: None, settled: None, context_key: false, + pasted: None, ease: None, follows_pointer: false, tool_regions: Vec::new(), @@ -689,6 +692,7 @@ impl<'a> Canvas<'a> { navigation: self.navigation, editor_input: self.editor_input.clone(), editor: cx.editor_handle(), + pasted: self.pasted.clone(), } } @@ -758,6 +762,11 @@ pub struct ToolPass { pub editor_input: Arc<[EditorInput]>, /// The editor part of this pass, through which the body reports its editor state; `None` without an editor. pub editor: Option, + /// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of + /// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's, + /// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the + /// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one. + pub pasted: Option>, } impl ToolPass { @@ -863,6 +872,10 @@ impl Component for Canvas<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { // Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`. self.editor_input = cx.editor_input().collect::>().into(); + self.pasted = match cx.clipboard().paste() { + crate::runtime::pending::Pending::Ready(content) => content.text.clone(), + _ => None, + }; // Left untaken: the canvas's generic context request is recorded as for a secondary click. self.context_key = cx.intents().untaken(&Intent::ContextMenu); // The canvas is no value component: it reads and writes its view's binding itself, as a container does. diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f3..4cf2f9cd83 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,7 +2,7 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; @@ -88,6 +88,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the ); } +/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`. +type PassPaste = (Vec, Option); + +/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass: +/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't +/// be opened. +#[trial] +fn a_paste_events_text_reaches_the_body_with_the_editors_paste() { + let seen: Rc>> = Rc::default(); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).show_at(ui, room, |_, body| { + let Some(pass) = tool_pass(&body.env) else { return }; + shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned))); + }); + }); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + seen.borrow_mut().clear(); + fixture.frame(vec![Event::Paste("from the platform".into())]); + fixture.frame(vec![]); + let passes = seen.take(); + let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect(); + assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}"); + for (inputs, text) in &pasted { + assert_eq!(text.as_deref(), Some("from the platform")); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}"); + } + assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}"); +} + /// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines, /// so its caret reaches the input method and no empty text is announced on the canvas's node. #[trial] From 81e67a6130619f7413883b22a98e9c83d60761ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:10:32 -0800 Subject: [PATCH 025/235] craft-cdr: write .cmx files in the layouts the reader reads write_cmx writes a Drawing as a .cmx exchange file with 32-bit coordinates, in exactly the layouts read_cmx reads (rows R53 to R63): pages with their sizes and the edges of their art, layers with their names, groups, and curves with uniform fills and outlines in the color, pen, line type, dash, outline, arrowhead and screen tables. Rectangles and ellipses are written as curves; a rectangle keeps round corners under a matrix that keeps right angles. What the file can't hold is refused or reported. Coordinates past the 32-bit range, page sides that round to 0, more than 65,535 pages, layers or table entries, groups nested deeper than the reader reads and files past the RIFF size are an Error::Limit. Written reports paths split or cut into several curves, rounded dashes, nonzero fills that may fill differently even-odd, names that open shortened, spot colors at a tint too low to keep their look, with no name or with no known look, and art left out or written opaque, unclipped or unlocked (hidden art, guide and grid layers, master layers, guidelines, transparency, clipping). PROVENANCE.md gets a "Written fields" table that lists every field the writer sets with the row it rests on, and row R74 for the screen table the public sample files carry. The header's index offsets, the index chunks and the counts and offsets inside page, layer and group records are not written. --- crates/cdr/Cargo.toml | 2 +- crates/cdr/PROVENANCE.md | 37 +- crates/cdr/README.md | 17 + crates/cdr/src/cmx_write.rs | 1222 ++++++++++++++++++++++++++++++ crates/cdr/src/lib.rs | 17 +- crates/cdr/src/records.rs | 6 +- crates/cdr/tests/it/cmx_write.rs | 1111 +++++++++++++++++++++++++++ crates/cdr/tests/it/main.rs | 1 + 8 files changed, 2407 insertions(+), 6 deletions(-) create mode 100644 crates/cdr/src/cmx_write.rs create mode 100644 crates/cdr/tests/it/cmx_write.rs diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml index a13195b000..f5d5d79c0c 100644 --- a/crates/cdr/Cargo.toml +++ b/crates/cdr/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-cdr" -description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers; and a .cmx writer in the layouts it reads" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index b710c7d4b2..fd9044cdb4 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -119,9 +119,44 @@ file is committed. | R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | | R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | | R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | -| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample | | R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | | R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | | R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | | R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | | R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | +| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | + +## Written fields + +`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table +lists every field it sets. `own` marks a value the reader does not read, which the writer sets as +the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the +index chunks (`LIST indx`), and the instruction counts, file offsets and bounds that the CX files +also keep in their page, layer and group records are not written: no public source describes +them, and the reader finds every chunk by its id and walks the instructions in order. + +| Field written | Rows | Status | +|---|---|---| +| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample | +| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) | +| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | +| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | +| Table counts and field lists | R55 | sample | +| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) | +| `rpen` field 1: the width | R57 | public-notes | +| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own | +| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes | +| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes | +| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample | +| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample | +| `rota`: one pair of 0 | R59 | sample | +| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample | +| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) | +| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) | +| Begin page, field 4: the page's width and height | R61 | public-notes | +| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name in 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) | +| Begin layer, field 4: the name in UTF-16 | R62 | public-notes | +| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) | +| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) | +| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every node, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index dd66bdccc0..5759c11109 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -77,6 +77,23 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h path is left out and the objects it clips are read without it. Files in big-endian byte order and files with 16-bit coordinates are refused. +`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx` +reads: pages with their sizes, layers with their names, groups, and curves with uniform fills and +outlines. Rectangles and ellipses are written as curves, and a clipping container as a group of its +fill, the objects it clips (unclipped) and its outline. Hidden layers, groups and shapes, guide and +grid layers, guidelines and master layers are left out; opacity, blend modes, fill rules and locked +states are not written, desktop layers are written as drawing layers, and a spot color with no +name opens as a process color; every use of a named spot color takes the look of its use at the +strongest tint. A coordinate +past the 32-bit range, or more than 65,535 pages, layers on a page or different colors, pens or +outlines, is an error. The returned `Written` reports paths split or cut into several curves, +dashes rounded to whole outline widths, nonzero fills that may fill differently, names that open +shortened, spot colors at a 0% tint, with no name or with no known look (written black), and what +was left out or written opaque, +unclipped or unlocked. The header's index offsets and the index chunks (`LIST indx`) are not +written, so a reader must find the chunks by their ids, as `read_cmx` does. `PROVENANCE.md`'s +"Written fields" table lists every field it sets. + ## Provenance `PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs new file mode 100644 index 0000000000..cc662ce3ea --- /dev/null +++ b/crates/cdr/src/cmx_write.rs @@ -0,0 +1,1222 @@ +//! Writer for `.cmx` exchange files with 32-bit coordinates, in the layouts [`crate::read_cmx`] +//! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and +//! arrowhead tables (R55 to R59) and one `page` chunk of instructions for each page (R60): pages, +//! layers, groups and curves (R61, R62) with uniform fills and outlines (R63). `PROVENANCE.md`'s +//! "Written fields" lists every field the writer sets and where its layout comes from. +//! +//! Rectangles and ellipses are written as curves. A clipping container is written as a group of +//! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, +//! guide and grid layers, guidelines and master layers are left out. Opacity, blend modes, fill +//! rules (a curve fills even-odd) and locked states are not written, and [`Written`] reports each +//! of these that the drawing held. The drawing's version is not written either; the file opens +//! with version 0. + +use std::collections::HashMap; +use std::hash::Hash; + +use crate::Error; +use crate::model::{Blend, Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Path, Pt, Segment, Shape, SubPath}; + +/// The size of a coordinate unit written: 0.1 µm, the unit of every sample file with 32-bit +/// coordinates (R54). +const UNIT_METERS: f64 = 1e-7; +/// Coordinate units per point. +const UNITS_PER_PT: f64 = 0.0254 / 72.0 / UNIT_METERS; +/// The most points one curve holds: its points field is at most 65,535 bytes long with its 3-byte +/// header, and holds a u16 count and 9 bytes for each point (R55, R62). +pub const MAX_CURVE_POINTS: usize = (u16::MAX as usize - 3 - 2) / 9; +/// The most UTF-16 units of a layer name or a color name written, as many as the reader takes in +/// (it keeps the first [`crate::records::MAX_NAME`] and a hash of the rest). +const MAX_NAME_UNITS: usize = 4096; +/// The most 8-bit characters of a layer name written, as many as the reader keeps. +const MAX_NAME_BYTES: usize = crate::records::MAX_NAME; +/// The most entries one table holds: its count is a u16 (R55), and objects name entries by a u16 +/// from 1. +const MAX_ENTRIES: usize = u16::MAX as usize; +/// The screen entry's field 1, as the sample files with 32-bit coordinates write it (R74). +const SCREEN: [u8; 13] = [0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xa5, 0xae, 0x02, 0x00]; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const CURVE: i16 = 67; + +// Point type bytes (R16): bits 7 and 6 give the operation, bit 3 closes the subpath. Bit 2, which +// the reader does not read, is set on every node, as the test files of `synth_cmx` set it. +const MOVE: u8 = 0x04; +const LINE: u8 = 0x44; +const CURVE_END: u8 = 0x84; +const CONTROL: u8 = 0xC0; +const CLOSES: u8 = 0x08; + +/// A written file and what it changed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Written { + pub bytes: Vec, + /// A path held more than [`MAX_CURVE_POINTS`] points and was written as several curves in a + /// group, so overlapping parts of its fill may draw differently. + pub split_paths: bool, + /// A filled or outlined shape had a subpath of more than [`MAX_CURVE_POINTS`] points, which was + /// cut into open pieces, so its fill draws differently and its outline gets caps, and starts + /// its dashes again, where the pieces meet. + pub cut_subpaths: bool, + /// A dash or gap length was rounded to a whole number of outline widths, the unit the dash + /// table stores (R57), or held to the 65,535 widths a length there holds. + pub rounded_dashes: bool, + /// A layer or spot color name is longer than the 256 UTF-16 units the reader keeps whole, or + /// ends in NUL characters, which the reader drops, so it opens shortened. Past 4,096 units it + /// is also cut when written. Two spot colors whose names differ only in what is cut or dropped + /// open as one. A layer name that holds a NUL opens cut there, and one of only white space + /// opens with no name. + pub long_names: bool, + /// A spot color's tint is too low for its ink's look to open again: the record stores the color + /// with its tint applied in 8-bit values (R14), so at 0 % it is white and at a low tint the + /// look opens changed. + pub zero_tints: bool, + /// A shape filled with the nonzero rule may fill differently with the even-odd rule every + /// curve is written with: one of its cubics loops, one of its subpaths crosses or touches + /// itself or loops over itself, or two turn the same way and their boxes overlap, measured + /// with each cubic flattened to 16 lines. Past 50,000,000 comparisons of edges and boxes in one file, a shape is taken to fill + /// differently. + pub nonzero_fills: bool, + /// A spot color has no name, so it opens as a process color, its look at its tint: the reader + /// takes a color without a name as a process color. + pub unnamed_spots: bool, + /// A spot color's look is unknown in every use of its name (or, for a spot color with no name, + /// in that use), so it is written, and opens, as black at its tint. + pub unknown_looks: bool, + /// The drawing held what the file does not hold: hidden layers, groups or shapes, guide and + /// grid layers, guidelines and master layers (left out), opacity below 1 or a blend mode + /// (written opaque and normal), clipping (written unclipped), locked layers, groups or shapes + /// (written unlocked), art on a desktop layer (written on a drawing layer), shapes whose paths + /// have no segments (left out) or a layer with nothing on it (written, and left out by the + /// reader). + pub left_out: bool, +} + +/// Write `drawing` as a `.cmx` file. Coordinates are rounded to 0.1 µm. A page without its own +/// size takes the drawing's; with neither, it opens with no size. A point, page +/// size or outline width past what 32-bit coordinates hold is an [`Error::Limit`], as are a +/// negative or NaN outline width, a page side that rounds to 0, more than 65,535 pages, layers on +/// a page or different colors, pens or outlines, a stored dash pattern (an all-zero one is solid +/// and stores none) of more than 32,765 lengths (one table entry), groups nested deeper than the reader reads, and a file past what its 32-bit +/// chunk size holds; nothing is written then. +pub fn write(drawing: &Drawing) -> Result { + let mut w = Writer { + looks: spot_looks(drawing), + crossing_budget: CROSSING_BUDGET, + left_out: !drawing.master.is_empty() || !drawing.guides.is_empty(), + ..Writer::default() + }; + // The RIFF chunk's size, counted as each child is made: the form type, then the children, each a + // whole chunk with its pad byte. + let mut size = 4u32; + let mut children = Vec::new(); + let mut add = |c: Vec| -> Result<(), Error> { + size = u32::try_from(c.len()).ok().and_then(|n| size.checked_add(n)).ok_or(Error::Limit("chunk size"))?; + children.push(c); + Ok(()) + }; + add(chunk(b"cont", &cont())?)?; + for (n, page) in drawing.pages.iter().enumerate() { + add(w.page(n, page.size.or(drawing.page_size), &page.layers)?)?; + } + // A drawing with no pages but a page size is written as one empty page of that size. + if drawing.pages.is_empty() && drawing.page_size.is_some() { + add(w.page(0, drawing.page_size, &[])?)?; + } + for c in w.tables.chunks()? { + add(c)?; + } + let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; + bytes.extend(b"RIFF"); + bytes.extend(size.to_le_bytes()); + bytes.extend(b"CMX1"); + for c in children { + bytes.extend(c); + } + Ok(Written { + bytes, + split_paths: w.split_paths, + cut_subpaths: w.cut_subpaths, + rounded_dashes: w.rounded_dashes, + long_names: w.long_names, + zero_tints: w.zero_tints, + nonzero_fills: w.nonzero_fills, + unnamed_spots: w.unnamed_spots, + unknown_looks: w.unknown_looks, + left_out: w.left_out, + }) +} + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). A body past +/// what the size holds is an [`Error::Limit`]. +fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { + let size = u32::try_from(body.len()).map_err(|_| Error::Limit("chunk size"))?; + let mut out = Vec::with_capacity(body.len() + 9); + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + Ok(out) +} + +/// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 +/// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files; the rest are zeros. +fn cont() -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = b'4'; + c[54] = b'2'; + c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); + c +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). `None` when the +/// data does not fit the length. +fn field(tag: u8, data: &[u8]) -> Option> { + let len = u16::try_from(data.len() + 3).ok()?; + let mut f = Vec::with_capacity(data.len() + 3); + f.push(tag); + f.extend(len.to_le_bytes()); + f.extend(data); + Some(f) +} + +/// A field list: the fields, then 0xff (R55). +fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// An instruction: the short form when its size fits a u16 below 0xFFFF, else the long form +/// (R60). +fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = Vec::with_capacity(body.len() + 8); + match u16::try_from(body.len() + 4).ok().filter(|n| *n != u16::MAX) { + Some(n) => i.extend(n.to_le_bytes()), + None => { + i.extend(u16::MAX.to_le_bytes()); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + } + } + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// A length in points as coordinate units. +fn units(v: f64) -> Result { + let u = (v * UNITS_PER_PT).round(); + if u.is_finite() && u >= f64::from(i32::MIN) && u <= f64::from(i32::MAX) { Ok(u as i32) } else { Err(Error::Limit("coordinate range")) } +} + +/// A length that can't be negative (a width) in coordinate units. +fn width_units(v: f64) -> Result { + let u = (v.max(0.0) * UNITS_PER_PT).round(); + if u.is_finite() && u <= f64::from(u32::MAX) { Ok(u as u32) } else { Err(Error::Limit("coordinate range")) } +} + +/// The distinct entries of one table, in the order they were first used, and the 1-based index of +/// each. +struct Table { + entries: Vec, + index: HashMap, +} + +impl Default for Table { + fn default() -> Self { + Table { entries: Vec::new(), index: HashMap::new() } + } +} + +impl Table { + /// The 1-based index of `k`, added when it is new. + fn index(&mut self, k: K) -> Result { + if let Some(i) = self.index.get(&k) { + return Ok(*i); + } + if self.entries.len() >= MAX_ENTRIES { + return Err(Error::Limit("table entries")); + } + let i = u16::try_from(self.entries.len() + 1).map_err(|_| Error::Limit("table entries"))?; + self.entries.push(k.clone()); + self.index.insert(k, i); + Ok(i) + } +} + +/// A color as it is stored, so equal colors share an entry. +#[derive(Clone, PartialEq, Eq, Hash)] +struct ColorKey { + model: u16, + values: [u8; 4], + name: Option, +} + +/// The tables the instructions refer to (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Table, + /// Widths in coordinate units. + pens: Table, + /// Flags, and the caps and join. + line_types: Table<(u8, u8)>, + dashes: Table>, + /// Line type, color, pen and dashes (the screen and the arrowheads are always the first). + outlines: Table<[u16; 4]>, +} + +impl Tables { + fn chunks(&self) -> Result>, Error> { + let table = |id: &[u8; 4], entries: Vec>| -> Result, Error> { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + chunk(id, &d) + }; + let one = |tag: u8, data: &[u8]| field(tag, data).map(|f| fields(&[f])).ok_or(Error::Limit("table entry size")); + let colors = self.colors.entries.iter().map(color_entry).collect::, _>>()?; + // A pen: the width, an aspect of 100 percent, an angle of 0 and a matrix of type 1 + // (R57). + let pens = self + .pens + .entries + .iter() + .map(|w| { + let mut d = w.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + one(1, &d) + }) + .collect::, _>>()?; + let line_types = self.line_types.entries.iter().map(|(f, cj)| one(1, &[*f, *cj])).collect::, _>>()?; + let dashes = self + .dashes + .entries + .iter() + .map(|d| { + let mut b = (d.len() as u16).to_le_bytes().to_vec(); + b.extend(d.iter().flat_map(|x| x.to_le_bytes())); + one(1, &b) + }) + .collect::, _>>()?; + // An outline: line type, screen, color, arrowhead pair, pen and dash pattern (R58). + let outlines = self + .outlines + .entries + .iter() + .map(|[line, color, pen, dash]| one(1, &[*line, 1, *color, 1, *pen, *dash].map(u16::to_le_bytes).concat())) + .collect::, _>>()?; + // One arrowhead pair with no arrowheads, which every outline names (R59). + let mut rota = 1u16.to_le_bytes().to_vec(); + rota.extend([0; 4]); + Ok(vec![ + table(b"rclr", colors)?, + table(b"rpen", pens)?, + table(b"rott", line_types)?, + table(b"rdot", dashes)?, + table(b"rotl", outlines)?, + chunk(b"rota", &rota)?, + // One screen, which every outline names (R74). + table(b"rscr", vec![one(1, &SCREEN)?])?, + ]) + } +} + +/// A color as a color record (R14): the model and four value bytes. A spot color is model 21, its +/// look at its tint in blue, green and red with the tint in percent, and its name; with no look it +/// is black at its tint. +fn color_key(c: &Color) -> ColorKey { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let pct = |v: f32| (v.clamp(0.0, 1.0) * 100.0).round() as u8; + match c { + Color::Rgb([r, g, b]) => ColorKey { model: 5, values: [byte(*b), byte(*g), byte(*r), 0], name: None }, + Color::Cmyk([c, m, y, k]) => ColorKey { model: 2, values: [pct(*c), pct(*m), pct(*y), pct(*k)], name: None }, + Color::Gray(k) => ColorKey { model: 9, values: [byte(1.0 - k), 0, 0, 0], name: None }, + Color::Registration => ColorKey { model: 20, values: [0; 4], name: None }, + Color::Spot { name, tint, look } => { + // The look is mixed at the whole percent stored, the tint the reader takes it back + // out at. + let stored = pct(*tint); + let t = f32::from(stored) / 100.0; + let [r, g, b] = look.unwrap_or([0.0; 3]).map(|v| 1.0 - (1.0 - v.clamp(0.0, 1.0)) * t); + ColorKey { model: 21, values: [byte(b), byte(g), byte(r), stored], name: Some(name.clone()) } + } + } +} + +/// A color entry (R56): field 10 holds a property list, a u32 length then parts of a u8 kind, a u32 +/// length and the body (R11): part 1 the color record (model, palette 5, 4 zero bytes, the +/// values; R14), and for a named color part 3, a u32 count and UTF-16 units. +fn color_entry(k: &ColorKey) -> Result, Error> { + let mut list = vec![1u8]; + list.extend(12u32.to_le_bytes()); + list.extend(k.model.to_le_bytes()); + list.extend(5u16.to_le_bytes()); + list.extend([0; 4]); + list.extend(k.values); + if let Some(name) = &k.name { + let units = utf16_prefix(name); + list.push(3); + list.extend((4 + 2 * units.len() as u32).to_le_bytes()); + list.extend((units.len() as u32).to_le_bytes()); + list.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (list.len() as u32).to_le_bytes().to_vec(); + rec.extend(list); + Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?])) +} + +#[derive(Default)] +struct Writer { + tables: Tables, + /// The look of each named spot color, from [`spot_looks`]. + looks: HashMap, + /// The comparisons [`may_fill_differently`] may still make. + crossing_budget: u64, + /// The groups open where the next instruction is written. + open_groups: usize, + /// The smallest and largest x and y the curves written on the current page reach, in + /// coordinate units. + bounds: Option<[i32; 4]>, + split_paths: bool, + cut_subpaths: bool, + rounded_dashes: bool, + long_names: bool, + zero_tints: bool, + nonzero_fills: bool, + unnamed_spots: bool, + unknown_looks: bool, + left_out: bool, +} + +/// Whether a spot color's `name`, as written, reads back as no name: the reader drops trailing NULs. +fn unnamed(name: &str) -> bool { + utf16_prefix(name).iter().all(|u| *u == 0) +} + +/// Whether `name` opens shortened: it is longer than the UTF-16 units the reader keeps whole, or +/// it ends in NULs, which the reader drops. +fn shortened(name: &str) -> bool { + name.ends_with('\0') || name.encode_utf16().nth(crate::records::MAX_NAME).is_some() +} + +/// `name` in UTF-16, cut after its last whole character within [`MAX_NAME_UNITS`] units. +fn utf16_prefix(name: &str) -> Vec { + let mut units = Vec::new(); + let mut buf = [0u16; 2]; + for c in name.chars() { + let enc = c.encode_utf16(&mut buf); + if units.len() + enc.len() > MAX_NAME_UNITS { + break; + } + units.extend_from_slice(enc); + } + units +} + +/// The look of each named spot color in `drawing`, master layers included, from the use at the +/// strongest tint that gives one. +fn spot_looks(drawing: &Drawing) -> HashMap { + let mut looks: HashMap = HashMap::new(); + let layers = drawing.pages.iter().flat_map(|p| &p.layers).chain(&drawing.master); + let mut stack: Vec<&Object> = layers.flat_map(|l| &l.objects).collect(); + while let Some(o) = stack.pop() { + let shape = match o { + Object::Shape(s) => s, + Object::Group { objects, .. } => { + stack.extend(objects); + continue; + } + Object::Clip { container, objects } => { + stack.extend(objects); + container + } + }; + for c in shape.fill.iter().chain(shape.outline.as_ref().map(|o| &o.color)) { + if let Color::Spot { name, tint, look: Some(look) } = c + && !unnamed(name) + { + let known = looks.entry(name.clone()).or_insert((*tint, *look)); + if *tint > known.0 { + *known = (*tint, *look); + } + } + } + } + looks.into_iter().map(|(name, (_, look))| (name, look)).collect() +} + +impl Writer { + /// The 1-based color entry of `c`. A named spot color takes its ink's look: the look of the + /// use of its name at the strongest tint, hidden uses included. + fn color(&mut self, c: &Color) -> Result { + let key = match c { + Color::Spot { name, tint, .. } if self.looks.contains_key(name) => { + color_key(&Color::Spot { name: name.clone(), tint: *tint, look: self.looks.get(name).copied() }) + } + _ => color_key(c), + }; + if let Color::Spot { name, look, .. } = c { + self.unnamed_spots |= unnamed(name); + self.long_names |= shortened(name); + // The reader takes the tint back out of the stored color; at a low tint the 8-bit + // values do not hold enough of the look for that. + let [b, g, r] = [key.values[0], key.values[1], key.values[2]].map(|v| f32::from(v) / 255.0); + let back = crate::records::untinted([r, g, b], f32::from(key.values[3]) / 100.0); + let want = self.looks.get(name).copied().or(*look).unwrap_or([0.0; 3]); + self.zero_tints |= key.values[3] == 0 || back.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0); + self.unknown_looks |= look.is_none() && !self.looks.contains_key(name); + } + self.tables.colors.index(key) + } + + /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60). + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result, Error> { + let mut out = Vec::new(); + self.bounds = None; + // The model holds layers and objects front to back; the file lists them back to front. + let mut written = 0; + for layer in layers.iter().rev() { + // A desktop layer is written as a drawing layer, which is how the reader takes it. + self.left_out |= !layer.guides.is_empty() || layer.flags.locked || (layer.kind == LayerKind::Desktop && !layer.objects.is_empty()); + // The reader leaves out a layer that holds nothing. + self.left_out |= layer.objects.is_empty(); + // Guide and grid layers hold construction art, which a reader takes as drawing art. + if layer.flags.hidden || matches!(layer.kind, LayerKind::Guides | LayerKind::Grid) { + self.left_out = true; + continue; + } + // The reader also stops a layer's name at its first NUL and takes a blank name as none. + let name = &layer.name; + self.long_names |= shortened(name) || name.contains('\0') || (!name.is_empty() && name.trim().is_empty()); + out.extend(instr(BEGIN_LAYER, &layer_fields(n, written, &layer.name)?)); + written += 1; + self.objects(&layer.objects, &mut out)?; + out.extend(instr(END_LAYER, &[])); + } + out.extend(instr(END_PAGE, &[])); + let begin = begin_page(n, size, self.bounds.take())?; + if u32::try_from(begin.len() + out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + let mut page = begin; + page.extend(out); + chunk(b"page", &page) + } + + /// The shown `objects` (front to back) in the order they are drawn. Groups are walked with a + /// stack, not by recursion. + fn objects(&mut self, objects: &[Object], out: &mut Vec) -> Result<(), Error> { + // Each entry: the objects of a list still to write, back to front, whether a group ends + // after them, and a clipping container's outline drawn over them. + type Level<'a> = (std::iter::Rev>, bool, Option); + let mut stack: Vec> = vec![(objects.iter().rev(), false, None)]; + while let Some((iter, _, _)) = stack.last_mut() { + // A page chunk holds at most what its 32-bit size counts. + if u32::try_from(out.len()).is_err() { + return Err(Error::Limit("chunk size")); + } + let Some(o) = iter.next() else { + if let Some((_, ends, over)) = stack.pop() { + if let Some(s) = over { + self.shape(&s, out)?; + } + if ends { + self.end_group(out); + } + } + continue; + }; + match o { + // A hidden clipping container hides what it clips too. + Object::Shape(s) | Object::Clip { container: s, .. } if s.flags.hidden => self.left_out = true, + Object::Group { flags, .. } if flags.hidden => self.left_out = true, + Object::Shape(s) => self.shape(s, out)?, + Object::Group { objects, flags } => { + self.left_out |= flags.locked; + self.begin_group(out)?; + stack.push((objects.iter().rev(), true, None)); + } + Object::Clip { container, objects } => { + self.left_out = true; + self.begin_group(out)?; + // The container's fill is drawn behind the objects it clips and its outline + // over them; an outline behind the fill is drawn behind them too. A container + // with neither draws nothing and is not written. + let mut over = None; + match &container.outline { + Some(o) if !o.behind_fill && container.fill.is_some() => { + self.shape(&Shape { outline: None, ..(**container).clone() }, out)?; + over = Some(Shape { fill: None, ..(**container).clone() }); + } + Some(o) if !o.behind_fill => over = Some((**container).clone()), + None if container.fill.is_none() => {} + _ => self.shape(container, out)?, + } + stack.push((objects.iter().rev(), true, over)); + } + } + } + Ok(()) + } + + /// Begin a group. A group inside as many groups as the reader opens ([`crate::Limits`]'s + /// default depth) is an [`Error::Limit`]: the reader leaves out what it holds. + fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { + if self.open_groups >= crate::Limits::default().depth { + return Err(Error::Limit("nesting depth")); + } + self.open_groups += 1; + out.extend(group()); + Ok(()) + } + + fn end_group(&mut self, out: &mut Vec) { + self.open_groups = self.open_groups.saturating_sub(1); + out.extend(instr(END_GROUP, &[])); + } + + /// A shape as one curve, or as a group of curves when its path holds more than + /// [`MAX_CURVE_POINTS`] points. + fn shape(&mut self, s: &Shape, out: &mut Vec) -> Result<(), Error> { + self.left_out |= s.opacity < 1.0 || s.blend != Blend::Normal || s.flags.locked; + let points = points_of(&s.geometry, &s.matrix)?; + let curves = split(&points); + // A path with no segments draws nothing, and the file has no curve for it. + if curves.is_empty() { + self.left_out = true; + return Ok(()); + } + // A shape written as several curves paints all its fill and then all its outline (the + // other way round for an outline behind the fill); one curve carries both. + let passes: Vec<(Option<&Color>, Option<&Outline>)> = match (&s.fill, &s.outline) { + (Some(f), Some(o)) if curves.len() > 1 && o.behind_fill => vec![(None, Some(o)), (Some(f), None)], + (Some(f), Some(o)) if curves.len() > 1 => vec![(Some(f), None), (None, Some(o))], + (f, o) => vec![(f.as_ref(), o.as_ref())], + }; + let mut attrs = Vec::with_capacity(passes.len()); + for (f, o) in passes { + attrs.push(self.attributes(f, o, &s.matrix)?); + } + if !self.nonzero_fills + && s.nonzero + && s.fill.is_some() + && let Geometry::Path(p) = &s.geometry + { + self.nonzero_fills = may_fill_differently(p, &mut self.crossing_budget); + } + self.cut_subpaths |= (s.fill.is_some() || s.outline.is_some()) && points.iter().any(|sp| sp.len() > MAX_CURVE_POINTS); + if curves.len() > 1 { + self.split_paths = true; + self.begin_group(out)?; + } + let mut bodies = Vec::with_capacity(curves.len()); + for c in &curves { + let mut g = (c.len() as u16).to_le_bytes().to_vec(); + // The points as written, in coordinate units. + let mut written = Vec::with_capacity(c.len()); + for (p, t) in c.iter() { + let (x, y) = (units(p.x)?, units(p.y)?); + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + written.push((Pt { x: f64::from(x), y: f64::from(y) }, *t)); + } + // The page's art edges take in the written curve itself: its anchors and each cubic's + // extremes, rounded outward. + for (i, (p, t)) in written.iter().enumerate() { + let [x0, y0, x1, y1] = match (t >> 6, i.checked_sub(3).and_then(|s| written.get(s..i))) { + (2, Some([(a, _), (b, _), (d, _)])) => cubic_extent(*a, *b, *d, *p), + (3, _) => continue, + _ => [p.x, p.y, p.x, p.y], + }; + // Within the anchors and control points, which are i32, so the casts keep them. + let (x0, y0, x1, y1) = (x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32); + let b = self.bounds.get_or_insert([x0, y0, x1, y1]); + *b = [b[0].min(x0), b[1].min(y0), b[2].max(x1), b[3].max(y1)]; + } + g.extend(c.iter().map(|(_, t)| *t)); + bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); + } + for a in &attrs { + let f1 = field(1, a).ok_or(Error::Limit("rendering attributes size"))?; + for f2 in &bodies { + out.extend(instr(CURVE, &fields(&[f1.clone(), f2.clone()]))); + } + } + if curves.len() > 1 { + self.end_group(out); + } + Ok(()) + } + + /// Rendering attributes (R63): the mask, then the uniform fill's field list (fill type 1 and a + /// field 1 of the color entry and screen entry 1, R74) and the outline's (its `rotl` entry). + fn attributes(&mut self, fill: Option<&Color>, outline: Option<&Outline>, matrix: &Matrix) -> Result, Error> { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1); + let mut a = vec![mask]; + if let Some(c) = fill { + let index = self.color(c)?; + let mut v = 1u16.to_le_bytes().to_vec(); + v.extend(fields(&[field(1, &[index.to_le_bytes(), 1u16.to_le_bytes()].concat()).ok_or(Error::Limit("fill size"))?])); + a.extend(fields(&[field(1, &v).ok_or(Error::Limit("fill size"))?])); + } + if let Some(o) = outline { + // The points are written placed by the matrix, so an outline that scales with the + // shape takes the matrix's scale into its width, as the engine applies it (R50). + let [m0, m1, m2, m3, _, _] = matrix.0; + let scale = if o.scale_with { (m0 * m3 - m1 * m2).abs().sqrt() } else { 1.0 }; + let index = self.outline(o, scale)?; + a.extend(fields(&[field(1, &index.to_le_bytes()).ok_or(Error::Limit("outline size"))?])); + } + Ok(a) + } + + /// The `rotl` entry of an outline (R57, R58): its line type (2 solid, 4 dashed, 8 behind the + /// fill, 16 scaled with the object; the caps in the low 4 bits and the join in the high 4 + /// bits), color, pen and dash pattern. `scale` multiplies the width. + fn outline(&mut self, o: &Outline, scale: f64) -> Result { + // A pattern of zero lengths draws a solid line (R57). + let lengths: &[f64] = if o.dashes.iter().all(|d| *d <= 0.0) { &[] } else { &o.dashes }; + // One table entry holds a u16 count and the lengths in a field of at most 65,535 bytes. + if lengths.len() > (usize::from(u16::MAX) - 3 - 2) / 2 { + return Err(Error::Limit("table entry size")); + } + let mut dashes: Vec = lengths.iter().map(|d| d.max(0.0).round().min(f64::from(u16::MAX)) as u16).collect(); + if lengths.iter().zip(&dashes).any(|(d, r)| *d != f64::from(*r)) { + self.rounded_dashes = true; + } + // Marks (the even entries) that all round to nothing would draw nothing, and lengths that + // all round to nothing would draw a solid line: the positive ones are kept as short as the + // table allows (gaps only in the second case). + let all_zero = dashes.iter().all(|d| *d == 0); + let marks_gone = dashes.iter().step_by(2).all(|d| *d == 0) && lengths.iter().step_by(2).any(|d| *d > 0.0); + if !dashes.is_empty() && (all_zero || marks_gone) { + for (i, (r, d)) in dashes.iter_mut().zip(lengths).enumerate() { + if *r == 0 && *d > 0.0 && (all_zero || i % 2 == 0) { + *r = 1; + } + } + self.rounded_dashes = true; + } + let dashed = !dashes.is_empty(); + let flags = 2 | if dashed { 4 } else { 0 } | if o.behind_fill { 8 } else { 0 } | if o.scale_with { 16 } else { 0 }; + let cap = match o.cap { + Cap::Butt => 0, + Cap::Round => 1, + Cap::Square => 2, + }; + let join = match o.join { + Join::Miter => 0, + Join::Round => 1, + Join::Bevel => 2, + }; + let line = self.tables.line_types.index((flags, cap | (join << 4)))?; + let color = self.color(&o.color)?; + // A pen of width 0 reads as a hairline, so a thinner positive width is written as one unit. + if o.width.is_nan() || o.width < 0.0 { + return Err(Error::Limit("outline width")); + } + let width = o.width * scale; + if width.is_nan() { + return Err(Error::Limit("outline width")); + } + let pen = self.tables.pens.index(if width > 0.0 { width_units(width)?.max(1) } else { 0 })?; + // A solid outline names an empty pattern, as the sample files' solid outlines do (R58). + let dash = self.tables.dashes.index(dashes)?; + self.tables.outlines.index([line, color, pen, dash]) + } +} + +/// Begin page `n` (from 0; R61): field 1 the page number from 1, a u32 of flags and the left, +/// top, right and bottom edges of `bounds`, the page's art (smallest x and y, largest x and y), +/// or of the page around its center when it has no art; field 4 its width and height. Without a +/// size the edges are all 0, which the reader takes as no size. +fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result, Error> { + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("pages"))?; + let mut d = number.to_le_bytes().to_vec(); + d.extend(0u32.to_le_bytes()); + let mut list = Vec::new(); + let mut size_field = None; + let mut edges = [0i32; 4]; + if let Some((w, h)) = size { + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + edges = match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }; + let mut s = wu.to_le_bytes().to_vec(); + s.extend(hu.to_le_bytes()); + size_field = Some(s); + } + for v in edges { + d.extend(v.to_le_bytes()); + } + list.push(field(1, &d).ok_or(Error::Limit("page size"))?); + if let Some(s) = size_field { + list.push(field(4, &s).ok_or(Error::Limit("page size"))?); + } + Ok(instr(BEGIN_PAGE, &fields(&list))) +} + +/// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. +fn windows_1252_byte(c: char) -> u8 { + match u8::try_from(u32::from(c)) { + Ok(b) if !(0x80..0xa0).contains(&b) => b, + _ => crate::records::CP1252_HIGH.iter().position(|h| *h == c && c != '\u{FFFD}').and_then(|i| u8::try_from(0x80 + i).ok()).unwrap_or(b'?'), + } +} + +/// A layer's fields (R62): field 1 the page number and the layer number (u16 each, from 1), 8 zero +/// bytes, then the name as a u16 count and 8-bit characters (Windows-1252: characters the code +/// page has no byte for are written as `?`); field 4 the name as a u32 count and UTF-16 units. +/// `page` and `n` count the pages and the page's layers written from 0; past 65,535 layers is an +/// [`Error::Limit`]. +fn layer_fields(page: usize, n: usize, name: &str) -> Result, Error> { + // A blank name, up to the first NUL where the reader stops, is written empty in both fields, + // so it opens with no name. + let blank = name.split('\0').next().unwrap_or_default().trim().is_empty(); + let narrow: Vec = if blank { Vec::new() } else { name.chars().map(windows_1252_byte).take(MAX_NAME_BYTES).collect() }; + let page = u16::try_from(page + 1).map_err(|_| Error::Limit("pages"))?; + let number = u16::try_from(n + 1).map_err(|_| Error::Limit("layers"))?; + let mut d = page.to_le_bytes().to_vec(); + d.extend(number.to_le_bytes()); + d.extend([0; 8]); + d.extend((narrow.len() as u16).to_le_bytes()); + d.extend(&narrow); + let units = if blank { Vec::new() } else { utf16_prefix(name) }; + let mut wide = (units.len() as u32).to_le_bytes().to_vec(); + wide.extend(units.iter().flat_map(|u| u.to_le_bytes())); + let f1 = field(1, &d).ok_or(Error::Limit("layer name"))?; + let f4 = field(4, &wide).ok_or(Error::Limit("layer name"))?; + Ok(fields(&[f1, f4])) +} + +/// Begin a group: field 1 of 26 zero bytes, as the test files of `synth_cmx` hold. +fn group() -> Vec { + instr(BEGIN_GROUP, &fields(&[field(1, &[0; 26]).unwrap_or_default()])) +} + +/// A subpath's points and their type bytes (R16), placed by `m`. +type Points = Vec<(Pt, u8)>; + +/// The subpaths of a geometry as points and type bytes, one list for each subpath. A closed +/// subpath ends back at its start, on a node that carries the closing bit. +fn points_of(g: &Geometry, m: &Matrix) -> Result, Error> { + let (path, m) = match g { + Geometry::Path(p) => (std::borrow::Cow::Borrowed(p), Matrix(m.0)), + Geometry::Rect { w, h, radii } => { + let (w, h, radii, m) = fold_scale(*w, *h, *radii, m); + (std::borrow::Cow::Owned(rect_path(w, h, radii)), m) + } + Geometry::Ellipse { w, h } => (std::borrow::Cow::Owned(ellipse_path(*w, *h)), Matrix(m.0)), + }; + path.subpaths.iter().filter(|s| !s.segments.is_empty()).map(|s| subpath_points(s, &m)).collect() +} + +/// A rectangle placed by `m` with the scale of `m` taken into its size, when the matrix keeps right +/// angles: the width and height times the matrix's scale along each, the radii times the square +/// root of its area scale, and the matrix left with its rotation, mirroring and offset. The +/// corners then stay round. Other matrices are kept whole. +fn fold_scale(w: f64, h: f64, radii: [f64; 4], m: &Matrix) -> (f64, f64, [f64; 4], Matrix) { + let [m0, m1, m2, m3, m4, m5] = m.0; + let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); + let square = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy; + if !square || !m.0.iter().all(|c| c.is_finite()) { + return (w, h, radii, Matrix(m.0)); + } + let k = (sx * sy).sqrt(); + (w * sx, h * sy, radii.map(|r| r * k), Matrix([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5])) +} + +/// A subpath's points; more than memory holds is an [`Error::Limit`]. +fn subpath_points(s: &SubPath, m: &Matrix) -> Result { + let size = |segs: &[Segment]| segs.iter().fold(1usize, |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })); + // The closing bit on the last node closes a subpath that fits in one curve. One that is cut + // into open pieces ends with a line back to its start instead. + let open_end = s.closed && last_point(&s.segments).is_some_and(|p| p != s.start); + let closing = (open_end && size(&s.segments) > MAX_CURVE_POINTS).then_some(Segment::Line(s.start)); + let count = size(&s.segments).saturating_add(usize::from(closing.is_some())); + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Error::Limit("path size"))?; + out.push((m.apply(s.start), if s.closed { MOVE | CLOSES } else { MOVE })); + for seg in s.segments.iter().chain(closing.as_ref()) { + match seg { + Segment::Line(p) => out.push((m.apply(*p), LINE)), + Segment::Cubic(c1, c2, p) => { + out.push((m.apply(*c1), CONTROL)); + out.push((m.apply(*c2), CONTROL)); + out.push((m.apply(*p), CURVE_END)); + } + } + } + if s.closed + && let Some(end) = out.last_mut() + { + end.1 |= CLOSES; + } + Ok(out) +} + +fn last_point(segments: &[Segment]) -> Option { + segments.last().map(|s| match s { + Segment::Line(p) | Segment::Cubic(_, _, p) => *p, + }) +} + +/// The subpaths gathered into curves of at most [`MAX_CURVE_POINTS`] points, whole subpaths kept +/// together where they fit. A subpath longer than that is cut into open pieces that meet end to +/// start, each piece cut after a node. +fn split(subpaths: &[Points]) -> Vec { + let mut curves: Vec = vec![Vec::new()]; + for sp in subpaths { + if sp.len() > MAX_CURVE_POINTS { + let mut rest: &[(Pt, u8)] = sp; + while rest.len() > 1 { + // Cut after a node, never between a curve's control points and its end. + let mut take = rest.len().min(MAX_CURVE_POINTS); + while take > 1 && rest.get(take - 1).is_some_and(|(_, t)| *t == CONTROL) { + take -= 1; + } + if take < 2 { + break; + } + let piece: Points = rest[..take].iter().enumerate().map(|(i, (p, t))| if i == 0 { (*p, MOVE) } else { (*p, *t & !CLOSES) }).collect(); + if curves.last().is_some_and(|c| !c.is_empty()) { + curves.push(Vec::new()); + } + curves.push(piece); + rest = &rest[take - 1..]; + } + continue; + } + if curves.last().is_some_and(|c| c.len() + sp.len() > MAX_CURVE_POINTS) { + curves.push(Vec::new()); + } + if let Some(c) = curves.last_mut() { + c.extend_from_slice(sp); + } + } + curves.retain(|c| !c.is_empty()); + curves +} + +/// The lines each cubic is flattened to for [`may_fill_differently`]. +const CURVE_STEPS: u32 = 16; + +/// The pairs of edges and of subpath boxes [`may_fill_differently`] may compare in one export; +/// past it a shape is taken to fill differently. +const CROSSING_BUDGET: u64 = 50_000_000; + +/// The pairs among `n` items, saturating. +fn pairs(n: u64) -> u64 { + n.saturating_mul(n.saturating_sub(1)) / 2 +} + +/// Take `cost` comparisons off `budget`; false, and the budget emptied, when it does not cover +/// them. +fn charge(budget: &mut u64, cost: u64) -> bool { + match budget.checked_sub(cost) { + Some(left) => { + *budget = left; + true + } + None => { + *budget = 0; + false + } + } +} + +/// The closed polygon of a subpath with each cubic flattened to [`CURVE_STEPS`] lines, without +/// repeated points. +fn flatten(s: &SubPath) -> Vec { + let mut pts = vec![s.start]; + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => { + pts.push(p); + last = p; + } + Segment::Cubic(c1, c2, p) => { + for i in 1..=CURVE_STEPS { + let t = f64::from(i) / f64::from(CURVE_STEPS); + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + pts.push(Pt { x: a * last.x + b * c1.x + c * c2.x + d * p.x, y: a * last.y + b * c1.y + c * c2.y + d * p.y }); + } + last = p; + } + } + } + pts.dedup(); + if pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + pts +} + +/// Whether `p` may fill differently even-odd than nonzero: one of its cubics loops, a subpath +/// crosses itself or turns around other than once, measured with the cubics flattened, or two of +/// its subpaths turn the same way and their boxes, control points included, overlap. Subpaths +/// that turn opposite ways, such as a letter's counter inside the letter, and subpaths apart from +/// each other, fill the same either way. `budget` counts down the comparisons, and is charged for +/// a subpath's edges before the subpath is flattened. +fn may_fill_differently(p: &Path, budget: &mut u64) -> bool { + let n = p.subpaths.len(); + // The boxes of every two subpaths are compared. + if !charge(budget, pairs(n as u64)) { + return true; + } + let mut polygons = Vec::with_capacity(n); + for s in &p.subpaths { + let points = + s.segments.iter().fold(1u64, |k, seg| k.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { u64::from(CURVE_STEPS) })); + if !charge(budget, pairs(points)) { + return true; + } + let mut last = s.start; + for seg in &s.segments { + match *seg { + Segment::Line(p) => last = p, + Segment::Cubic(c1, c2, p) => { + if cubic_loops(last, c1, c2, p) { + return true; + } + last = p; + } + } + } + let pts = flatten(s); + if loops(&pts) || crosses(&pts) { + return true; + } + polygons.push(pts); + } + if n < 2 { + return false; + } + // Each subpath's turn (`None` when its area sums to 0, which matches either way) and box. + let shapes: Vec<(Option, [f64; 4])> = polygons + .iter() + .zip(&p.subpaths) + .map(|(pts, s)| { + // The area is summed from the first point, so far-off coordinates keep their precision. + let o = pts.first().copied().unwrap_or(s.start); + let area: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y)).sum(); + // The box holds every point, control points included, so it holds the curves too. + let controls = std::iter::once(s.start).chain(s.segments.iter().flat_map(|seg| match *seg { + Segment::Line(a) => vec![a], + Segment::Cubic(a, b, c) => vec![a, b, c], + })); + let bounds = controls.fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, q| [b[0].min(q.x), b[1].min(q.y), b[2].max(q.x), b[3].max(q.y)]); + ((area != 0.0).then_some(area > 0.0), bounds) + }) + .collect(); + shapes.iter().enumerate().any(|(i, (turn, a))| { + shapes[i + 1..] + .iter() + .any(|(other, b)| (turn.is_none() || other.is_none() || turn == other) && a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]) + }) +} + +/// The smallest x and y and the largest x and y the cubic from `p0` through `c1` and `c2` to `p3` +/// reaches: its ends and the points where it turns along either axis. +fn cubic_extent(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> [f64; 4] { + let at = |t: f64, a: f64, b: f64, c: f64, d: f64| { + let u = 1.0 - t; + u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d + }; + // The parameters in 0 to 1 where one coordinate's derivative is 0. + let turns = |a: f64, b: f64, c: f64, d: f64| -> Vec { + let (qa, qb, qc) = (-a + 3.0 * b - 3.0 * c + d, 2.0 * (a - 2.0 * b + c), b - a); + let mut ts = Vec::new(); + if qa.abs() < 1e-12 { + if qb.abs() > 1e-12 { + ts.push(-qc / qb); + } + } else { + let disc = qb * qb - 4.0 * qa * qc; + if disc >= 0.0 { + // Each root from the form that adds numbers of one sign, so neither cancels. + let q = -0.5 * (qb + qb.signum() * disc.sqrt()); + ts.push(q / qa); + if q != 0.0 { + ts.push(qc / q); + } + } + } + ts.retain(|t| (0.0..=1.0).contains(t)); + ts + }; + // An extreme between the ends is evaluated with rounding, so it is widened by a little more + // than that rounding: the edges then hold the curve. + let slack = |v: f64| v.abs() * 4.0 * f64::EPSILON + 1e-12; + let mut e = [p0.x.min(p3.x), p0.y.min(p3.y), p0.x.max(p3.x), p0.y.max(p3.y)]; + for t in turns(p0.x, c1.x, c2.x, p3.x) { + let x = at(t, p0.x, c1.x, c2.x, p3.x); + e = [e[0].min(x - slack(x)), e[1], e[2].max(x + slack(x)), e[3]]; + } + for t in turns(p0.y, c1.y, c2.y, p3.y) { + let y = at(t, p0.y, c1.y, c2.y, p3.y); + e = [e[0], e[1].min(y - slack(y)), e[2], e[3].max(y + slack(y))]; + } + e +} + +/// Whether the cubic from `p0` through `c1` and `c2` to `p3` crosses itself. With the cubic as +/// `a t³ + b t² + c t + p0`, two parameters `s` and `t` meet where `a (σ² − π) + b σ + c = 0`, with +/// `σ = s + t` and `π = s t`; the cubic loops when `s` and `t` are distinct and both in 0 to 1. +fn cubic_loops(p0: Pt, c1: Pt, c2: Pt, p3: Pt) -> bool { + let cross = |u: (f64, f64), v: (f64, f64)| u.0 * v.1 - u.1 * v.0; + let a = (-p0.x + 3.0 * c1.x - 3.0 * c2.x + p3.x, -p0.y + 3.0 * c1.y - 3.0 * c2.y + p3.y); + let b = (3.0 * p0.x - 6.0 * c1.x + 3.0 * c2.x, 3.0 * p0.y - 6.0 * c1.y + 3.0 * c2.y); + let r = (3.0 * p0.x - 3.0 * c1.x, 3.0 * p0.y - 3.0 * c1.y); + let det = cross(a, b); + if det == 0.0 || !det.is_finite() { + return false; + } + // u = σ² − π. + let (u, sum) = (cross(r, b) / det, cross(a, r) / det); + let disc = 4.0 * u - 3.0 * sum * sum; + if disc.is_nan() || disc <= 0.0 { + return false; + } + let q = disc.sqrt(); + let (s, t) = ((sum - q) / 2.0, (sum + q) / 2.0); + // The start meeting the end closes the curve; that is no crossing. + let closes = s.abs() < 1e-9 && (t - 1.0).abs() < 1e-9; + // Rounding can put a parameter of 0 or 1 just outside the range. + let inside = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); + inside(s) && inside(t) && !closes +} + +/// Whether the closed polygon through `pts` turns around other than once: the sum of its turning +/// angles is not one full turn either way. +fn loops(pts: &[Pt]) -> bool { + let edges: Vec<(f64, f64)> = + pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| (b.x - a.x, b.y - a.y)).filter(|(x, y)| x.hypot(*y) > 1e-9).collect(); + if edges.len() < 3 { + return false; + } + let turning: f64 = edges.iter().zip(edges.iter().cycle().skip(1)).map(|(a, b)| (a.0 * b.1 - a.1 * b.0).atan2(a.0 * b.0 + a.1 * b.1)).sum(); + (turning / std::f64::consts::TAU).round().abs() != 1.0 +} + +/// Whether two edges of the closed polygon through `pts` that are not neighbors cross, touch or run +/// along each other: the subpath comes back to a place it has been. +fn crosses(pts: &[Pt]) -> bool { + let n = pts.len(); + if n < 4 { + return false; + } + // Which side of the line from `a` to `b` the point `c` is on: 1, -1, or 0 on the line. + let side = |a: Pt, b: Pt, c: Pt| { + let v = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + i8::from(v > 0.0) - i8::from(v < 0.0) + }; + let edge = |i: usize| (pts[i], pts[(i + 1) % n]); + (0..n).any(|i| { + let (a, b) = edge(i); + // Edge i shares a point with edges i - 1 and i + 1, and edge 0 with edge n - 1. + (i + 2..n).filter(|j| !(i == 0 && *j == n - 1)).any(|j| { + let (c, d) = edge(j); + let (sc, sd) = (side(a, b, c), side(a, b, d)); + if sc == 0 && sd == 0 { + // On one line: they meet when their spans along it meet. + let along = |q: Pt| (q.x - a.x) * (b.x - a.x) + (q.y - a.y) * (b.y - a.y); + let (tc, td, tb) = (along(c), along(d), along(b)); + return tc.min(td).max(0.0) <= tc.max(td).min(tb); + } + sc * sd <= 0 && side(c, d, a) * side(c, d, b) <= 0 + }) + }) +} + +/// A rectangle from the origin to (`w`, `h`) with its corners rounded by `radii`, counterclockwise +/// from the corner at (`w`, 0), as [`Geometry::Rect`] gives them. On each edge a corner's radius +/// reaches no further than where its neighbor's begins, unless that leaves it less than half the +/// edge. +fn rect_path(w: f64, h: f64, radii: [f64; 4]) -> Path { + // A quarter circle as a cubic: the control points lie this share of the radius from the ends. + const K: f64 = 0.552_284_749_830_793_6; + // A negative or NaN radius leaves its corner square. + let radii = radii.map(|r| if r.is_finite() { r.max(0.0) } else { 0.0 }); + // Edge i runs from corner i to corner i + 1: the height, the width, the height, the width. + let len = |i: usize| if i.is_multiple_of(2) { h.abs() } else { w.abs() }; + // On each of its edges a corner reaches up to where its neighbor's corner begins, and at + // least halfway. + let room = |len: f64, other: f64| (len - other).max(len / 2.0); + let radii: [f64; 4] = std::array::from_fn(|i| { + let (next, prev) = ((i + 1) % 4, (i + 3) % 4); + radii[i].min(room(len(i), radii[next])).min(room(len(prev), radii[prev])) + }); + let corners = [Pt { x: w, y: 0.0 }, Pt { x: w, y: h }, Pt { x: 0.0, y: h }, Pt { x: 0.0, y: 0.0 }]; + // `r` along the edge from `c` toward `to`. + let sign = |d: f64| { + if d > 0.0 { + 1.0 + } else if d < 0.0 { + -1.0 + } else { + 0.0 + } + }; + let toward = |c: Pt, to: Pt, r: f64| Pt { x: c.x + sign(to.x - c.x) * r, y: c.y + sign(to.y - c.y) * r }; + let mut segments = Vec::new(); + let mut start = None; + for (i, (&c, r)) in corners.iter().zip(radii).enumerate() { + let (prev, next) = (corners[(i + 3) % 4], corners[(i + 1) % 4]); + // The corner is entered along the edge from the previous corner and left toward the next. + let (a, b) = (toward(c, prev, r), toward(c, next, r)); + match start { + None => start = Some(a), + Some(_) => segments.push(Segment::Line(a)), + } + if r > 0.0 { + let c1 = Pt { x: a.x + (c.x - a.x) * K, y: a.y + (c.y - a.y) * K }; + let c2 = Pt { x: b.x + (c.x - b.x) * K, y: b.y + (c.y - b.y) * K }; + segments.push(Segment::Cubic(c1, c2, b)); + } + } + let start = start.unwrap_or(corners[0]); + segments.push(Segment::Line(start)); + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} + +/// The ellipse in the box from the origin to (`w`, `h`) as four cubics. +fn ellipse_path(w: f64, h: f64) -> Path { + const K: f64 = 0.552_284_749_830_793_6; + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let p = |x: f64, y: f64| Pt { x: cx + x, y: cy + y }; + let start = p(rx, 0.0); + let segments = vec![ + Segment::Cubic(p(rx, ry * K), p(rx * K, ry), p(0.0, ry)), + Segment::Cubic(p(-rx * K, ry), p(-rx, ry * K), p(-rx, 0.0)), + Segment::Cubic(p(-rx, -ry * K), p(-rx * K, -ry), p(0.0, -ry)), + Segment::Cubic(p(rx * K, -ry), p(rx, -ry * K), start), + ]; + Path { subpaths: vec![SubPath { start, segments, closed: true }] } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 64cdae512a..91afe52367 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -7,7 +7,8 @@ //! //! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not -//! panic. Nothing here writes `.cdr` or `.cmx` files. +//! panic. [`write_cmx`] writes `.cmx` files in the layouts the reader reads; nothing here writes +//! `.cdr` files. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -16,6 +17,7 @@ use std::fmt; mod build; mod bytes; mod cmx; +mod cmx_write; mod geometry; mod inline; mod layout; @@ -32,6 +34,7 @@ pub mod synth_cmx; mod wl; mod zip; +pub use cmx_write::{MAX_CURVE_POINTS, Written}; pub use limits::Limits; pub use model::{Drawing, Warning}; @@ -108,3 +111,15 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { let mut budget = limits::Budget::new(limits); cmx::drawing(bytes, &mut budget) } + +/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts +/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and +/// outlines. A coordinate past the 32-bit range, a page side that rounds to 0, more than 65,535 +/// pages, layers on a page or different colors, pens or outlines, a dash pattern of more than +/// 32,765 lengths, groups nested deeper than [`Limits`]' default depth, or a chunk past its 32-bit +/// size, is an [`Error::Limit`]. [`Written`] reports what the file could not hold as it was. The +/// header's index offsets and the index chunks are not written, so a reader must find the chunks +/// by their ids, as [`read_cmx`] does. +pub fn write_cmx(drawing: &Drawing) -> Result { + cmx_write::write(drawing) +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs index 49adcedc7e..49000468c9 100644 --- a/crates/cdr/src/records.rs +++ b/crates/cdr/src/records.rs @@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4; const MAX_OUTLINE_RECORDS: usize = 16; /// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of /// a layer's. -const MAX_NAME: usize = 256; +pub(crate) const MAX_NAME: usize = 256; /// A header field: u16 in short files, u32 otherwise. fn word(r: &mut Rd, p: &Profile) -> Option { @@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option { } /// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). -fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { +pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { if tint <= 0.0 { return rgb; } @@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option) -> String { /// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes /// are Latin-1. -const CP1252_HIGH: [char; 32] = [ +pub(crate) const CP1252_HIGH: [char; 32] = [ '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', ]; diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs new file mode 100644 index 0000000000..af85ce0a79 --- /dev/null +++ b/crates/cdr/tests/it/cmx_write.rs @@ -0,0 +1,1111 @@ +//! Writing `.cmx` files: what [`write_cmx`] writes reads back through [`read_cmx`] as the same +//! drawing, and what it can't hold is refused or reported. + +use craft_cdr::model::{ + Cap, Color, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, +}; +use craft_cdr::{Error, Limits, MAX_CURVE_POINTS, is_cmx, read_cmx, write_cmx}; +use proptest::prelude::*; + +fn layer(name: &str, objects: Vec) -> Layer { + Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } +} + +fn drawing(pages: Vec) -> Drawing { + Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() } +} + +fn square(x: f64, y: f64, side: f64) -> Geometry { + let p = |x, y| Pt { x, y }; + Geometry::Path(Path { + subpaths: vec![SubPath { + start: p(x, y), + segments: vec![Segment::Line(p(x + side, y)), Segment::Line(p(x + side, y + side)), Segment::Line(p(x, y + side))], + closed: true, + }], + }) +} + +fn outline(color: Color) -> Outline { + Outline { width: 2.0, color, cap: Cap::Round, join: Join::Bevel, dashes: Vec::new(), behind_fill: false, scale_with: false } +} + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// Every point (anchors and controls) of a geometry that is a path. +fn points(g: &Geometry) -> Vec { + let Geometry::Path(p) = g else { panic!("not a path: {g:?}") }; + let mut out = Vec::new(); + for sp in &p.subpaths { + out.push(sp.start); + for s in &sp.segments { + match s { + Segment::Line(a) => out.push(*a), + Segment::Cubic(a, b, c) => out.extend([*a, *b, *c]), + } + } + } + out +} + +fn bounds(g: &Geometry) -> (f64, f64, f64, f64) { + points(g).iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.x), b.1.min(p.y), b.2.max(p.x), b.3.max(p.y))) +} + +/// Within a coordinate unit of 0.1 µm (0.000283 pt), in points. +fn near(a: f64, b: f64) -> bool { + (a - b).abs() <= 0.0003 +} + +fn near_color(a: &Color, b: &Color) -> bool { + let close = |x: &[f32], y: &[f32], tol: f32| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (p - q).abs() <= tol); + match (a, b) { + (Color::Rgb(x), Color::Rgb(y)) => close(x, y, 1.0 / 255.0), + (Color::Cmyk(x), Color::Cmyk(y)) => close(x, y, 0.005), + (Color::Gray(x), Color::Gray(y)) => (x - y).abs() <= 1.0 / 255.0, + (Color::Registration, Color::Registration) => true, + (Color::Spot { name: n, tint: t, look: l }, Color::Spot { name: m, tint: u, look: k }) => { + n == m && (t - u).abs() <= 0.005 && close(&l.unwrap_or_default(), &k.unwrap_or_default(), 2.0 / 255.0) + } + _ => false, + } +} + +fn round_trip(d: &Drawing) -> Drawing { + let w = write_cmx(d).unwrap(); + assert!(is_cmx(&w.bytes)); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + back +} + +#[test] +fn a_drawing_reads_back_as_written() { + let red = Color::Rgb([1.0, 0.2, 0.0]); + let cyan = Color::Cmyk([0.6, 0.0, 0.13, 0.05]); + let spot = Color::Spot { name: "Ink 300".into(), tint: 0.4, look: Some([0.0, 0.4, 0.8]) }; + let dashed = + Outline { dashes: vec![3.0, 1.0], behind_fill: true, scale_with: true, cap: Cap::Square, join: Join::Miter, ..outline(Color::Gray(0.75)) }; + let back_layer = layer( + "Art", + vec![ + Object::Shape(Box::new(Shape::new(square(-50.0, -50.0, 100.0), Matrix::IDENTITY, Some(red.clone()), Some(outline(Color::Registration))))), + Object::Group { + objects: vec![ + Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(cyan.clone()), Some(dashed.clone())))), + Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 10.0), Matrix::IDENTITY, Some(spot.clone()), None))), + ], + flags: Flags::default(), + }, + ], + ); + let front_layer = + layer("Über", vec![Object::Shape(Box::new(Shape::new(square(5.0, 5.0, 1.0), Matrix::IDENTITY, None, Some(outline(cyan.clone())))))]); + let d = drawing(vec![ + Page { size: Some((595.0, 842.0)), layers: vec![front_layer, back_layer] }, + Page { + size: Some((200.0, 100.0)), + layers: vec![layer( + "Second", + vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.3)), None)))], + )], + }, + ]); + let back = round_trip(&d); + assert_eq!(back.pages.len(), 2); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 595.0) && near(h, 842.0)); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Über", "Art"], "layers keep their order and names"); + let art = &back.pages[0].layers[1].objects; + let s = shape(&art[0]); + assert!(near_color(s.fill.as_ref().unwrap(), &red)); + assert_eq!(s.outline.as_ref().unwrap().color, Color::Registration); + let (x0, y0, x1, y1) = bounds(&s.geometry); + assert!(near(x0, -50.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, 50.0)); + let Object::Group { objects, .. } = &art[1] else { panic!("not a group: {:?}", art[1]) }; + let o = shape(&objects[0]).outline.clone().unwrap(); + assert!(near_color(shape(&objects[0]).fill.as_ref().unwrap(), &cyan)); + assert!(near(o.width, 2.0) && near_color(&o.color, &Color::Gray(0.75))); + assert_eq!((o.cap, o.join, o.dashes, o.behind_fill, o.scale_with), (Cap::Square, Join::Miter, vec![3.0, 1.0], true, true)); + assert!(near_color(shape(&objects[1]).fill.as_ref().unwrap(), &spot), "{:?}", shape(&objects[1]).fill); + assert!(shape(&objects[1]).outline.is_none()); + let front = shape(&back.pages[0].layers[0].objects[0]); + assert!(front.fill.is_none() && front.outline.as_ref().is_some_and(|o| o.cap == Cap::Round && o.join == Join::Bevel)); + let (w, h) = back.pages[1].size.unwrap(); + assert!(near(w, 200.0) && near(h, 100.0)); +} + +#[test] +fn rectangles_and_ellipses_are_written_as_curves_in_their_place() { + let m = Matrix([1.0, 0.0, 0.0, 1.0, 10.0, -20.0]); + let rect = Shape::new(Geometry::Rect { w: 40.0, h: -30.0, radii: [5.0, 0.0, 50.0, 2.0] }, m, Some(Color::Gray(1.0)), None); + let ellipse = Shape::new(Geometry::Ellipse { w: 20.0, h: 10.0 }, m, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(rect)), Object::Shape(Box::new(ellipse))])] }]); + let back = round_trip(&d); + let objects = &back.pages[0].layers[0].objects; + let (x0, y0, x1, y1) = bounds(&shape(&objects[0]).geometry); + assert!(near(x0, 10.0) && near(y0, -50.0) && near(x1, 50.0) && near(y1, -20.0), "{:?}", (x0, y0, x1, y1)); + let Geometry::Path(p) = &shape(&objects[1]).geometry else { panic!() }; + assert!(p.subpaths[0].closed && p.subpaths[0].segments.iter().all(|s| matches!(s, Segment::Cubic(..)))); + let (x0, y0, x1, y1) = bounds(&shape(&objects[1]).geometry); + assert!(near(x0, 10.0) && near(x1, 30.0) && near(y0, -20.0) && near(y1, -10.0)); +} + +#[test] +fn a_path_past_the_points_a_curve_holds_is_written_as_a_group_of_curves() { + let n = MAX_CURVE_POINTS * 2 + 10; + let segments = (1..n).map(|i| Segment::Line(Pt { x: i as f64 * 0.01, y: (i % 2) as f64 })).collect(); + let long = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(long))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.split_paths && w.cut_subpaths, "an outline gets caps where the pieces meet"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert!(objects.len() >= 3); + // The pieces meet end to start, so every point is kept, the joins twice. + let total: usize = objects.iter().map(|o| points(&shape(o).geometry).len()).sum(); + assert_eq!(total, n + objects.len() - 1); + // A filled shape cut into pieces is reported. + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!() }; + let filled = Shape { fill: Some(Color::Gray(0.5)), ..(**s).clone() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(filled))])] }]); + assert!(write_cmx(&d).unwrap().cut_subpaths); +} + +#[test] +fn names_the_reader_shortens_are_reported() { + // A name as long as the reader keeps whole reads back whole. + let kept = "k".repeat(256); + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, None))); + let d = drawing(vec![Page { size: None, layers: vec![layer(&kept, vec![plain])] }]); + let w = write_cmx(&d).unwrap(); + assert!(!w.long_names); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].name, kept); + let long = "n".repeat(257); + let spot = |name: &str| Color::Spot { name: name.into(), tint: 1.0, look: None }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(spot(&long)), None); + let short = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s.clone()))])] }]); + assert!(write_cmx(&short).unwrap().long_names, "a long spot name"); + let named = drawing(vec![Page { size: None, layers: vec![layer(&long, vec![Object::Shape(Box::new(Shape { fill: None, ..s.clone() }))])] }]); + assert!(write_cmx(&named).unwrap().long_names, "a long layer name"); + // Two long spot names that differ only past what the reader keeps still read back apart. + let other = format!("{}m", "n".repeat(256)); + let t = Shape { fill: Some(spot(&other)), ..s.clone() }; + let both = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s)), Object::Shape(Box::new(t))])] }]); + let back = read_cmx(&write_cmx(&both).unwrap().bytes, Limits::default()).unwrap(); + let names: Vec = back.pages[0].layers[0] + .objects + .iter() + .filter_map(|o| match shape(o).fill.as_ref() { + Some(Color::Spot { name, .. }) => Some(name.clone()), + _ => None, + }) + .collect(); + assert!(names.len() == 2 && names[0] != names[1], "{names:?}"); +} + +#[test] +fn a_spot_color_at_no_tint_is_reported() { + let spot = |tint| Color::Spot { name: "Ink".into(), tint, look: Some([0.0, 0.0, 1.0]) }; + let file = |c| { + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) + }; + assert!(write_cmx(&file(spot(0.0))).unwrap().zero_tints); + assert!(!write_cmx(&file(spot(0.05))).unwrap().zero_tints); +} + +#[test] +fn coordinates_past_the_32_bit_range_are_refused() { + let far = Shape::new(square(1e6, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(1.0)), None); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(far))])] }]); + assert_eq!(write_cmx(&d), Err(Error::Limit("coordinate range"))); +} + +#[test] +fn dash_lengths_are_rounded_to_whole_outline_widths() { + let o = Outline { dashes: vec![2.4, 0.2], ..outline(Color::Gray(1.0)) }; + let s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)); + let d = drawing(vec![Page { size: None, layers: vec![layer("", vec![Object::Shape(Box::new(s))])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![2.0, 0.0]); +} + +fn one_shape(s: Shape) -> Drawing { + drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]) +} + +#[test] +fn a_page_without_its_own_size_takes_the_drawings() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.page_size = Some((300.0, 200.0)); + let (w, h) = round_trip(&d).pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0), "{w} {h}"); +} + +#[test] +fn pages_are_numbered_in_their_order() { + let page = |side| Page { + size: Some((100.0, 100.0)), + layers: vec![layer("L", vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, side), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))])], + }; + let bytes = write_cmx(&drawing(vec![page(1.0), page(2.0)])).unwrap().bytes; + // Each page chunk starts with its begin-page instruction: a u16 size, the code 9, then field 1 + // (a tag and a u16 length) whose first u16 is the page number. + let numbers: Vec = bytes + .windows(4) + .enumerate() + .filter(|(_, w)| *w == b"page") + .map(|(i, _)| { + let body = &bytes[i + 8..]; + assert_eq!(i16::from_le_bytes([body[2], body[3]]), 9); + u16::from_le_bytes([body[7], body[8]]) + }) + .collect(); + assert_eq!(numbers, [1, 2]); +} + +/// Field 1 of each entry of the table chunk `id`: a u16 count, then a field list per entry (a tag, +/// a u16 length counting the 3 header bytes, the data; 0xff after the last field). +fn table_entries(bytes: &[u8], id: &[u8; 4]) -> Vec> { + let at = bytes.windows(4).position(|w| w == id).unwrap_or_else(|| panic!("no {id:?} chunk")) + 8; + let count = usize::from(u16::from_le_bytes([bytes[at], bytes[at + 1]])); + let mut p = at + 2; + let mut out = Vec::new(); + for _ in 0..count { + let mut first = None; + while bytes[p] != 0xff { + let len = usize::from(u16::from_le_bytes([bytes[p + 1], bytes[p + 2]])); + if bytes[p] == 1 { + first = Some(bytes[p + 3..p + len].to_vec()); + } + p += len; + } + p += 1; + out.push(first.expect("field 1")); + } + out +} + +#[test] +fn every_outline_names_a_screen_and_a_dash_pattern_the_file_holds() { + let solid = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let dashed = Shape::new(square(2.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(Outline { dashes: vec![3.0, 1.0], ..outline(Color::Gray(1.0)) })); + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![Object::Shape(Box::new(solid)), Object::Shape(Box::new(dashed))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let (screens, dashes) = (table_entries(&bytes, b"rscr"), table_entries(&bytes, b"rdot")); + let outlines = table_entries(&bytes, b"rotl"); + assert_eq!(outlines.len(), 2); + let counts: Vec = outlines + .iter() + .map(|o| { + let entry = |i: usize| usize::from(u16::from_le_bytes([o[2 * i], o[2 * i + 1]])); + assert!((1..=screens.len()).contains(&entry(1)), "the screen entry exists"); + let dash = entry(5); + assert!((1..=dashes.len()).contains(&dash), "the dash entry exists"); + u16::from_le_bytes([dashes[dash - 1][0], dashes[dash - 1][1]]) + }) + .collect(); + // A solid outline names an empty pattern; the dashed one names its two lengths. + assert_eq!(counts.len(), 2); + assert!(counts.contains(&0) && counts.contains(&2), "{counts:?}"); +} + +#[test] +fn an_outline_that_scales_with_its_shape_keeps_its_drawn_width() { + let m = Matrix([3.0, 0.0, 0.0, 3.0, 0.0, 0.0]); + let width = |scale_with| { + let o = Outline { scale_with, dashes: vec![2.0, 1.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), m, None, Some(o)))); + let o = shape(&back.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert_eq!(o.dashes, vec![2.0, 1.0], "dashes stay in outline widths"); + o.width + }; + assert!(near(width(true), 6.0) && near(width(false), 2.0)); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_stays_solid() { + let o = Outline { dashes: vec![0.0, 0.0], ..outline(Color::Gray(1.0)) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap(); + assert!(!w.rounded_dashes); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes.is_empty()); +} + +#[test] +fn a_spot_color_at_a_low_tint_keeps_its_ink() { + let black = Color::Spot { name: "Ink".into(), tint: 0.0051, look: Some([0.0, 0.0, 0.0]) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(black), None))); + let Some(Color::Spot { look: Some(look), .. }) = shape(&back.pages[0].layers[0].objects[0]).fill.clone() else { panic!("not a spot color") }; + assert!(look.iter().all(|v| *v < 0.1), "{look:?}"); +} + +#[test] +fn hidden_art_is_left_out_and_what_the_file_cant_hold_is_reported() { + let plain = || Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + assert!(!write_cmx(&one_shape(plain())).unwrap().left_out); + let hidden = Shape { flags: Flags { hidden: true, locked: false }, ..plain() }; + let mut hidden_layer = layer("Hidden", vec![Object::Shape(Box::new(plain()))]); + hidden_layer.flags.hidden = true; + let d = drawing(vec![Page { + size: None, + layers: vec![hidden_layer, layer("Shown", vec![Object::Shape(Box::new(hidden)), Object::Shape(Box::new(plain()))])], + }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers.len(), 1); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(write_cmx(&one_shape(Shape { opacity: 0.5, ..plain() })).unwrap().left_out, "transparency"); + let mut master = one_shape(plain()); + master.master = vec![layer("Master", vec![Object::Shape(Box::new(plain()))])]; + assert!(write_cmx(&master).unwrap().left_out, "a master layer"); +} + +#[test] +fn a_clipping_containers_outline_is_drawn_over_what_it_clips() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(outline(Color::Gray(1.0)))); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }]); + let w = write_cmx(&d).unwrap(); + assert!(w.left_out, "the clip itself is not written"); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Front to back: the container's outline, the clipped shape, the container's fill. + let kinds: Vec<(bool, bool)> = objects.iter().map(|o| (shape(o).fill.is_some(), shape(o).outline.is_some())).collect(); + assert_eq!(kinds, [(false, true), (true, false), (true, false)]); + assert!(near_color(shape(&objects[2]).fill.as_ref().unwrap(), &Color::Gray(0.2))); +} + +#[test] +fn a_hidden_clipping_container_hides_what_it_clips() { + let mut container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.2)), None); + container.flags.hidden = true; + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let shown = Object::Shape(Box::new(Shape::new(square(20.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip, shown])] }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + assert_eq!(back.pages[0].layers[0].objects.len(), 1); + assert!(matches!(back.pages[0].layers[0].objects[0], Object::Shape(_))); +} + +#[test] +fn guide_and_grid_layers_are_left_out() { + let art = || vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let kinds = [LayerKind::Guides, LayerKind::Grid]; + let mut layers: Vec = kinds.iter().map(|k| Layer { kind: *k, ..layer("Construction", art()) }).collect(); + layers.push(layer("Art", art())); + let w = write_cmx(&drawing(vec![Page { size: None, layers }])).unwrap(); + assert!(w.left_out); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let names: Vec<&str> = back.pages[0].layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Art"]); +} + +#[test] +fn locked_art_is_reported() { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + s.flags.locked = true; + assert!(write_cmx(&one_shape(s)).unwrap().left_out); +} + +#[test] +fn nonzero_fills_that_may_fill_differently_are_reported() { + let p = |x, y| Pt { x, y }; + // Two squares turning the same way, one inside the other: nonzero fills the inner one, + // even-odd leaves it a hole. + let ring = |cw: bool, x: f64, side: f64| { + let corners = [p(x, x), p(x + side, x), p(x + side, x + side), p(x, x + side)]; + let pts: Vec = if cw { corners.into_iter().rev().collect() } else { corners.to_vec() }; + SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true } + }; + let filled = |inner_cw: bool, nonzero: bool| { + let geometry = Geometry::Path(Path { subpaths: vec![ring(false, 0.0, 10.0), ring(inner_cw, 2.0, 5.0)] }); + let s = Shape { nonzero, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + write_cmx(&one_shape(s)).unwrap().nonzero_fills + }; + assert!(filled(false, true), "same turn, nested"); + assert!(!filled(true, true), "a counter turning the other way fills the same"); + assert!(!filled(false, false), "an even-odd fill is written as it is"); +} + +#[test] +fn a_subpath_crossing_itself_with_one_net_turn_is_reported() { + let p = |x, y| Pt { x, y }; + // One net turn, but the inside around (1.25, 2.5) is wound twice. + let pts = [p(4.0, 1.0), p(3.0, 1.0), p(0.0, 4.0), p(0.0, 1.0), p(4.0, 4.0), p(0.0, 3.0)]; + let sub = SubPath { start: pts[0], segments: pts[1..].iter().map(|q| Segment::Line(*q)).collect(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); + // A plain square crosses nothing. + let plain = Shape { nonzero: true, ..Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(plain)).unwrap().nonzero_fills); +} + +#[test] +fn a_curve_crossing_where_its_control_points_dont_is_reported() { + let p = |x, y| Pt { x, y }; + // M0 0 C0 10 10 10 10 0 L12 16 -4 11 -4 -1 12 -6 2 9 Z winds twice around (2.5, 7.5). + let mut segments = vec![Segment::Cubic(p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0))]; + segments.extend([p(12.0, 16.0), p(-4.0, 11.0), p(-4.0, -1.0), p(12.0, -6.0), p(2.0, 9.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_closing_line_back_to_the_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + // Clockwise, with the closing line written out. + let segments = [p(0.0, 10.0), p(10.0, 10.0), p(10.0, 0.0), p(0.0, 0.0)].map(Segment::Line).to_vec(); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn an_ink_takes_its_look_from_its_strongest_tint_and_from_master_layers() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look }; + let filled = |c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))); + let red = Some([1.0, 0.0, 0.0]); + // The 0% use, whose look is white, is met first. + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(1.0, None)), filled(ink(1.0, red)), filled(ink(0.0, Some([1.0; 3])))])], + }]); + let back = round_trip(&d); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); + let mut d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![filled(ink(1.0, None))])] }]); + d.master = vec![layer("Master", vec![filled(ink(1.0, red))])]; + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(1.0, red))); +} + +#[test] +fn an_empty_layer_and_a_name_ending_in_nul_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let empty = drawing(vec![Page { size: None, layers: vec![layer("Empty", Vec::new()), layer("L", vec![plain()])] }]); + assert!(write_cmx(&empty).unwrap().left_out); + let padded = drawing(vec![Page { size: None, layers: vec![layer("L\0", vec![plain()])] }]); + assert!(write_cmx(&padded).unwrap().long_names); +} + +#[test] +fn a_subpath_going_over_its_edges_again_is_reported() { + let p = |x, y| Pt { x, y }; + // The square right of the start twice counterclockwise, then the square left of it once + // clockwise: one net turn, and the right square wound twice. + let pts = [(1, 0), (1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0), (-1, 0), (-1, 1), (0, 1)].map(|(x, y)| p(f64::from(x), f64::from(y))); + let sub = SubPath { start: p(0.0, 0.0), segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_shape_with_no_segments_is_reported() { + let empty = Shape::new(Geometry::Path(Path::default()), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let w = write_cmx(&one_shape(empty)).unwrap(); + assert!(w.left_out); +} + +#[test] +fn a_page_side_that_rounds_to_nothing_is_refused() { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some((0.000_01, 720.0)); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size"))); +} + +#[test] +fn layer_names_the_reader_cuts_or_drops_are_reported() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let named = |name: &str| write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(name, vec![plain()])] }])).unwrap().long_names; + assert!(named("Art\0backup"), "cut at the NUL"); + assert!(named(" "), "blank"); + assert!(!named("Art")); +} + +#[test] +fn an_unfilled_clipping_containers_outline_keeps_its_place() { + // Front to back, whether the outline comes first: over the clipped shape, unless it is drawn + // behind the fill. + for behind_fill in [false, true] { + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(o)); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert_eq!(shape(&objects[0]).outline.is_some(), !behind_fill, "behind_fill {behind_fill}"); + } +} + +#[test] +fn a_page_size_of_nothing_is_refused() { + for size in [(0.0, 720.0), (-10.0, 720.0), (f64::NAN, 720.0)] { + let mut d = one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)); + d.pages[0].size = Some(size); + assert_eq!(write_cmx(&d), Err(Error::Limit("page size")), "{size:?}"); + } +} + +#[test] +fn an_ink_with_no_known_look_is_reported() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let written = |c| write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap().unknown_looks; + assert!(written(ink(None))); + assert!(!written(ink(Some([1.0, 0.0, 0.0])))); +} + +#[test] +fn loops_meeting_at_one_point_are_reported() { + let p = |x, y| Pt { x, y }; + let o = p(0.0, 0.0); + // Three triangles from the origin; the second, inside the first, is wound twice. + let pts = [p(5.0, 0.0), p(2.0, 5.0), o, p(3.0, 1.0), p(2.0, 3.0), o, p(-5.0, 1.0), p(-2.0, 4.0)]; + let sub = SubPath { start: o, segments: pts.map(Segment::Line).to_vec(), closed: true }; + let s = Shape { nonzero: true, ..Shape::new(Geometry::Path(Path { subpaths: vec![sub] }), Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_very_thin_outline_stays_thinner_than_a_hairline() { + let o = Outline { width: 0.000_1, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + let width = shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().width; + assert!(width > 0.0 && width < 0.01, "{width}"); +} + +#[test] +fn nested_contours_far_from_the_origin_are_still_compared() { + let p = |x, y| Pt { x, y }; + let ring = |x: f64, side: f64| SubPath { + start: p(x, x), + segments: [p(x + side, x), p(x + side, x + side), p(x, x + side)].map(Segment::Line).to_vec(), + closed: true, + }; + let far = 1.0e8; + let geometry = Geometry::Path(Path { subpaths: vec![ring(far, 10.0), ring(far + 2.0, 1.0)] }); + let back_home = Matrix([1.0, 0.0, 0.0, 1.0, -far, -far]); + let s = Shape { nonzero: true, ..Shape::new(geometry, back_home, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_without_a_size_still_writes_its_four_edges() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // The begin-page instruction: a u16 size, the code 9, then field 1: a tag and its length. + assert_eq!(i16::from_le_bytes([bytes[at + 2], bytes[at + 3]]), 9); + let len = usize::from(u16::from_le_bytes([bytes[at + 5], bytes[at + 6]])); + assert_eq!(len - 3, 2 + 4 + 16, "the page number, the flags and four edges"); +} + +#[test] +fn spot_colors_with_no_name_share_no_look() { + let unnamed = |look| Color::Spot { name: String::new(), tint: 1.0, look }; + let shapes = [unnamed(None), unnamed(Some([1.0, 0.0, 0.0]))] + .map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.unnamed_spots && w.unknown_looks); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.0, 0.0, 0.0])), "{fill:?}"); +} + +#[test] +fn a_cubic_looping_between_its_samples_is_reported() { + let p = |x, y| Pt { x, y }; + // (s² − 1, s³ − s) for s from −2 to 30 crosses itself at s = −1 and 1. + let mut segments = vec![Segment::Cubic(p(-119.0 / 3.0, 334.0 / 3.0), p(259.0, -5458.0 / 3.0), p(899.0, 26970.0))]; + segments.extend([p(-10.0, 26970.0), p(-10.0, -6.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(3.0, -6.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_edges_of_its_art() { + // A small square off the center of a large page. + let d = drawing(vec![Page { + size: Some((600.0, 800.0)), + layers: vec![layer( + "L", + vec![Object::Shape(Box::new(Shape::new(square(100.0, 50.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))], + )], + }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + // Field 1 of the begin-page instruction: the page number, the flags, then the left, top, right + // and bottom edges as i32 in 0.1 µm. + let edge = |i: usize| f64::from(i32::from_le_bytes(bytes[at + 13 + 4 * i..at + 17 + 4 * i].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + let (l, t, r, b) = (edge(0), edge(1), edge(2), edge(3)); + assert!(near(l, 100.0) && near(t, 60.0) && near(r, 110.0) && near(b, 50.0), "{l} {t} {r} {b}"); +} + +#[test] +fn an_outline_width_that_is_not_a_width_is_refused() { + for width in [f64::NAN, -1.0] { + let o = Outline { width, ..outline(Color::Gray(1.0)) }; + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))), Err(Error::Limit("outline width"))); + } +} + +#[test] +fn a_dash_rounded_away_is_reported() { + let o = Outline { dashes: vec![0.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_cubic_closing_on_its_start_is_no_crossing() { + let p = |x, y| Pt { x, y }; + let segments = vec![Segment::Cubic(p(1.0, 0.0), p(0.0, 1.0), p(0.0, 0.0))]; + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_negative_width_is_refused_whatever_its_scale() { + let o = Outline { width: -1.0, scale_with: true, ..outline(Color::Gray(1.0)) }; + let flat = Matrix([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), flat, None, Some(o)))), Err(Error::Limit("outline width"))); +} + +#[test] +fn a_page_as_wide_as_the_size_field_holds_is_written() { + // A width that rounds to u32::MAX coordinate units of 0.1 µm, and whose half rounds past what + // an i32 holds. + let widest = (f64::from(u32::MAX) + 0.4) * 1e-7 / 0.0254 * 72.0; + let art = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + for layers in [vec![layer("L", vec![Object::Shape(Box::new(art))])], Vec::new()] { + let d = drawing(vec![Page { size: Some((widest, 100.0)), layers }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, _) = back.pages[0].size.unwrap(); + assert!((w - widest).abs() < 0.01, "{w}"); + } +} + +#[test] +fn a_page_gives_the_edges_its_curves_reach() { + let p = |x, y| Pt { x, y }; + // An arch whose control points reach 100 pt and whose curve reaches 75 pt. + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 100.0), p(100.0, 100.0), p(100.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 75.0), "{top}"); +} + +#[test] +fn dashes_too_short_to_store_keep_their_gaps_of_nothing() { + let o = Outline { dashes: vec![0.4, 0.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 0.0]); +} + +#[test] +fn a_rounded_corner_beside_square_ones_keeps_its_radius() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [75.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + // The corner at (100, 0) is entered from (100 − 75, 0) and left toward (100, 75). + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 25.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 75.0)), "{pts:?}"); +} + +#[test] +fn many_contours_apart_fill_the_same_either_way() { + let p = |x, y| Pt { x, y }; + let triangle = |i: u32| { + let x = f64::from(i) * 3.0; + SubPath { start: p(x, 0.0), segments: vec![Segment::Line(p(x + 1.0, 0.0)), Segment::Line(p(x, 1.0))], closed: true } + }; + let geometry = Geometry::Path(Path { subpaths: (0..1001).map(triangle).collect() }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(!write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_page_gives_the_top_of_a_nearly_flat_cubic() { + let p = |x, y| Pt { x, y }; + // The end one coordinate unit above the start keeps the y derivative quadratic. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 10000.0), p(1.0, 10000.0), p(1.0, unit))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = f64::from(i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap())) / (0.0254 / 72.0 / 1e-7); + assert!(near(top, 7500.0), "{top}"); +} + +#[test] +fn a_rounded_rectangle_scaled_unevenly_keeps_round_corners() { + // 100 pt square, 10 pt corners, stretched 4 times across: 400 by 100 pt with 20 pt corners. + let rect = + Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [10.0; 4] }, Matrix([4.0, 0.0, 0.0, 1.0, 0.0, 0.0]), Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (400, 0) is entered 20 pt along the bottom edge and left 20 pt up the side. + assert!(pts.iter().any(|q| near(q.x, 380.0) && near(q.y, 0.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 400.0) && near(q.y, 20.0)), "{pts:?}"); +} + +#[test] +fn a_dash_length_off_a_whole_width_by_a_little_is_reported() { + let o = Outline { dashes: vec![1.000_000_5, 1.0], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn only_overlapping_corners_shrink() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 80.0, 10.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // The corner at (0, 100) keeps its 10 pt: it is left toward (0, 90). + assert!(pts.iter().any(|q| near(q.x, 0.0) && near(q.y, 90.0)), "{pts:?}"); + // The two 80 pt corners on the right edge meet at its middle. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 50.0)), "{pts:?}"); +} + +#[test] +fn a_closed_contour_that_fits_one_curve_stays_one_curve() { + let p = |x, y| Pt { x, y }; + // MAX_CURVE_POINTS anchors, the last away from the start: the closing bit closes it. + let n = MAX_CURVE_POINTS; + let segments = (1..n).map(|i| Segment::Line(p(i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1.0 }))).collect(); + let s = Shape::new( + Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }), + Matrix::IDENTITY, + None, + Some(outline(Color::Gray(1.0))), + ); + let w = write_cmx(&one_shape(s)).unwrap(); + assert!(!w.split_paths && !w.cut_subpaths); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let Geometry::Path(path) = &shape(&back.pages[0].layers[0].objects[0]).geometry else { panic!() }; + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); +} + +#[test] +fn a_page_gives_the_edges_of_the_curve_as_written() { + let p = |x, y| Pt { x, y }; + // Controls 0.6 units up round to 1 unit, so the written curve peaks at 0.75 units. + let unit = 1e-7 / 0.0254 * 72.0; + let arch = SubPath { start: p(0.0, 0.0), segments: vec![Segment::Cubic(p(0.0, 0.6 * unit), p(1.0, 0.6 * unit), p(1.0, 0.0))], closed: false }; + let s = Shape::new(Geometry::Path(Path { subpaths: vec![arch] }), Matrix::IDENTITY, None, Some(outline(Color::Gray(1.0)))); + let d = drawing(vec![Page { size: Some((600.0, 800.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let bytes = write_cmx(&d).unwrap().bytes; + let at = bytes.windows(4).position(|w| w == b"page").expect("a page chunk") + 8; + let top = i32::from_le_bytes(bytes[at + 17..at + 21].try_into().unwrap()); + assert!(top >= 1, "{top}"); +} + +#[test] +fn a_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(!back.pages[0].layers[0].name.contains('?'), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_larger_corner_reaches_where_its_smaller_neighbor_begins() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [80.0, 40.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + // On the right edge the 80 pt corner is held to 60 pt and the 40 pt one keeps its radius. + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 60.0)), "{pts:?}"); + assert!(pts.iter().any(|q| near(q.x, 60.0) && near(q.y, 100.0)), "{pts:?}"); +} + +#[test] +fn a_long_blank_layer_name_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer(&" ".repeat(257), vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(back.pages[0].layers[0].name.trim().is_empty(), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn a_spot_color_with_no_name_at_no_tint_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.0, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && w.zero_tints); +} + +#[test] +fn a_drawing_with_no_pages_keeps_its_page_size() { + let mut d = drawing(Vec::new()); + d.page_size = Some((300.0, 200.0)); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + let (w, h) = back.pages[0].size.unwrap(); + assert!(near(w, 300.0) && near(h, 200.0)); +} + +#[test] +fn layers_give_their_page_and_their_number() { + let plain = || Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let page = || Page { size: None, layers: vec![layer("A", vec![plain()]), layer("B", vec![plain()])] }; + let bytes = write_cmx(&drawing(vec![page(), page()])).unwrap().bytes; + // Each begin-layer instruction: a u16 size, the code 11, field 1 (a tag and a u16 length), then + // the page number and the layer number. + let mut numbers = Vec::new(); + let mut at = 0; + while let Some(i) = bytes[at..].windows(4).position(|w| w == b"page") { + let start = at + i + 8; + let end = start + u32::from_le_bytes(bytes[at + i + 4..start].try_into().unwrap()) as usize; + let mut p = start; + while p < end { + let size = usize::from(u16::from_le_bytes([bytes[p], bytes[p + 1]])); + assert!(size >= 4 && p + size <= end, "an instruction of {size} bytes at {p}"); + if i16::from_le_bytes([bytes[p + 2], bytes[p + 3]]) == 11 { + numbers.push((u16::from_le_bytes([bytes[p + 7], bytes[p + 8]]), u16::from_le_bytes([bytes[p + 9], bytes[p + 10]]))); + } + p += size; + } + at = end; + } + assert_eq!(numbers, [(1, 1), (1, 2), (2, 1), (2, 2)]); +} + +#[test] +fn a_uniform_fill_names_the_screen_the_file_holds() { + let bytes = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))).unwrap().bytes; + // The fill's field 1: a tag, a length of 7, the color entry 1 and the screen entry 1. + assert!(bytes.windows(7).any(|w| w == [1, 7, 0, 1, 0, 1, 0])); + assert_eq!(table_entries(&bytes, b"rscr").len(), 1); +} + +#[test] +fn an_unpainted_clipping_container_is_not_written() { + let container = Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, None); + let child = Shape::new(square(2.0, 2.0, 5.0), Matrix::IDENTITY, Some(Color::Gray(0.8)), None); + let clip = Object::Clip { container: Box::new(container), objects: vec![Object::Shape(Box::new(child))] }; + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", vec![clip])] }])); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + assert_eq!(objects.len(), 1, "only the clipped shape"); +} + +#[test] +fn groups_nested_deeper_than_the_reader_reads_are_refused() { + let nest = |depth: usize| { + let mut o = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + for _ in 0..depth { + o = Object::Group { objects: vec![o], flags: Flags::default() }; + } + drawing(vec![Page { size: None, layers: vec![layer("L", vec![o])] }]) + }; + let deepest = Limits::default().depth; + assert!(round_trip(&nest(deepest)).pages[0].layers.len() == 1, "as deep as the reader reads"); + assert_eq!(write_cmx(&nest(deepest + 1)), Err(Error::Limit("nesting depth"))); +} + +#[test] +fn a_negative_radius_leaves_its_corner_square() { + let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [-20.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); + let back = round_trip(&one_shape(rect)); + let pts = points(&shape(&back.pages[0].layers[0].objects[0]).geometry); + assert!(pts.iter().any(|q| near(q.x, 100.0) && near(q.y, 0.0)), "{pts:?}"); +} + +#[test] +fn every_use_of_an_ink_takes_the_look_of_its_strongest_tint() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let filled = |c, hidden| { + let mut s = Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None); + s.flags.hidden = hidden; + Object::Shape(Box::new(s)) + }; + let d = drawing(vec![Page { + size: None, + layers: vec![layer("L", vec![filled(ink(0.5, [0.0, 1.0, 0.0]), false), filled(ink(1.0, [1.0, 0.0, 0.0]), true)])], + }]); + let back = read_cmx(&write_cmx(&d).unwrap().bytes, Limits::default()).unwrap(); + assert!(near_color(shape(&back.pages[0].layers[0].objects[0]).fill.as_ref().unwrap(), &ink(0.5, [1.0, 0.0, 0.0]))); +} + +#[test] +fn a_name_that_is_only_nuls_as_written_is_reported() { + let name = format!("{}Ink", "\0".repeat(4096)); + let c = Color::Spot { name, tint: 1.0, look: Some([1.0, 0.0, 0.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None))).unwrap(); + assert!(w.unnamed_spots && w.long_names); +} + +#[test] +fn a_tint_too_low_to_keep_the_look_is_reported() { + let pale = Color::Spot { name: "Pale".into(), tint: 0.01, look: Some([1.0, 0.85, 0.85]) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(pale), None))).unwrap().zero_tints); +} + +#[test] +fn a_shape_split_into_curves_paints_its_fill_before_its_outline() { + let p = |x, y| Pt { x, y }; + // A long polyline, then a square: two curves. + let segments = (1..MAX_CURVE_POINTS).map(|i| Segment::Line(p(i as f64 * 0.01, 5.0))).collect(); + let long = SubPath { start: p(0.0, 0.0), segments, closed: false }; + let Geometry::Path(sq) = square(2.0, 2.0, 5.0) else { panic!() }; + for behind_fill in [false, true] { + let geometry = Geometry::Path(Path { subpaths: vec![long.clone(), sq.subpaths[0].clone()] }); + let o = Outline { behind_fill, ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.2)), Some(o)))); + let Object::Group { objects, .. } = &back.pages[0].layers[0].objects[0] else { panic!("not a group") }; + // Each curve carries the fill or the outline, the outlines all on one side of the fills. + let outlines: Vec = objects.iter().map(|o| shape(o).outline.is_some()).collect(); + assert!(objects.iter().all(|o| shape(o).fill.is_some() != shape(o).outline.is_some()), "{outlines:?}"); + assert!(outlines.windows(2).all(|w| w[0] >= w[1]) || outlines.windows(2).all(|w| w[0] <= w[1]), "{outlines:?}"); + // Front to back: the outline is in front unless it is drawn behind the fill. + assert_eq!(outlines[0], !behind_fill, "{outlines:?}"); + } +} + +#[test] +fn a_dash_pattern_past_one_table_entry_is_refused() { + let file = |n: usize| { + let o = Outline { dashes: vec![1.0; n], ..outline(Color::Gray(1.0)) }; + write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))) + }; + assert!(file(32_765).is_ok()); + assert_eq!(file(32_766), Err(Error::Limit("table entry size"))); +} + +#[test] +fn a_contour_whose_area_sums_to_nothing_counts_as_either_turn() { + let p = |x, y| Pt { x, y }; + let tri = |pts: [Pt; 3]| SubPath { start: pts[0], segments: vec![Segment::Line(pts[1]), Segment::Line(pts[2])], closed: true }; + let (a, b, c) = (p(0.0, 0.0), p(100_000_000.0, 99_999_999.0), p(100_000_001.0, 100_000_000.0)); + let geometry = Geometry::Path(Path { subpaths: vec![tri([a, b, c]), tri([b, c, a])] }); + let m = Matrix([16.0, -299_999_997.0, -16.0, 300_000_000.0, 0.0, 0.0]); + let s = Shape { nonzero: true, ..Shape::new(geometry, m, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_cubic_looping_from_its_start_is_reported() { + let p = |x, y| Pt { x, y }; + let mut segments = vec![Segment::Cubic(p(-10.0, 0.0), p(150.0, -10.0), p(480.0, 480.0))]; + segments.extend([p(-1.0, 480.0), p(-1.0, -1.0)].map(Segment::Line)); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start: p(0.0, 0.0), segments, closed: true }] }); + let s = Shape { nonzero: true, ..Shape::new(geometry, Matrix::IDENTITY, Some(Color::Gray(0.5)), None) }; + assert!(write_cmx(&one_shape(s)).unwrap().nonzero_fills); +} + +#[test] +fn a_blank_layer_name_before_a_nul_opens_with_no_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("\u{2003}\0", vec![plain])] }])).unwrap().bytes; + let back = read_cmx(&bytes, Limits::default()).unwrap(); + assert!(!back.pages[0].layers[0].name.contains('?'), "{:?}", back.pages[0].layers[0].name); +} + +#[test] +fn marks_too_short_to_store_stay_visible() { + let o = Outline { dashes: vec![0.4, 2.0], ..outline(Color::Gray(1.0)) }; + let back = round_trip(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))); + assert_eq!(shape(&back.pages[0].layers[0].objects[0]).outline.as_ref().unwrap().dashes, vec![1.0, 2.0]); +} + +#[test] +fn a_spot_color_without_a_look_takes_the_look_of_its_ink() { + let ink = |look| Color::Spot { name: "Ink".into(), tint: 1.0, look }; + let shapes = + [ink(None), ink(Some([1.0, 0.0, 0.0]))].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let back = round_trip(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])); + for o in &back.pages[0].layers[0].objects { + assert!(near_color(shape(o).fill.as_ref().unwrap(), &ink(Some([1.0, 0.0, 0.0]))), "{:?}", shape(o).fill); + } +} + +#[test] +fn art_on_a_desktop_layer_is_reported() { + let art = vec![Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None)))]; + let desktop = Layer { kind: LayerKind::Desktop, ..layer("Desktop", art) }; + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![desktop] }])).unwrap(); + assert!(w.left_out); + assert_eq!(read_cmx(&w.bytes, Limits::default()).unwrap().pages[0].layers[0].objects.len(), 1, "the art is kept"); +} + +#[test] +fn dashes_too_short_to_store_are_reported() { + let o = Outline { dashes: vec![0.0, 0.000_000_5], ..outline(Color::Gray(1.0)) }; + assert!(write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, None, Some(o)))).unwrap().rounded_dashes); +} + +#[test] +fn a_spot_color_with_no_name_is_reported() { + let unnamed = Color::Spot { name: String::new(), tint: 0.5, look: Some([0.0, 0.0, 1.0]) }; + let w = write_cmx(&one_shape(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(unnamed), None))).unwrap(); + assert!(w.unnamed_spots && !w.zero_tints); + let back = read_cmx(&w.bytes, Limits::default()).unwrap(); + let fill = shape(&back.pages[0].layers[0].objects[0]).fill.clone().unwrap(); + assert!(near_color(&fill, &Color::Rgb([0.5, 0.5, 1.0])), "{fill:?}"); +} + +#[test] +fn a_layer_name_keeps_its_windows_1252_characters_in_the_8_bit_name() { + let plain = Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let bytes = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("€ ‰ 中", vec![plain])] }])).unwrap().bytes; + // The 8-bit name: a u16 count, then the bytes. + let narrow = [5u8, 0, 0x80, b' ', 0x89, b' ', b'?']; + assert!(bytes.windows(narrow.len()).any(|w| w == narrow), "the euro and per-mille signs have bytes; the last character has none"); +} + +#[test] +fn more_layers_than_the_layer_number_holds_are_refused() { + let layers = (0..=usize::from(u16::MAX)).map(|_| layer("", Vec::new())).collect(); + assert_eq!(write_cmx(&drawing(vec![Page { size: None, layers }])), Err(Error::Limit("layers"))); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + /// Paths of lines and curves read back with every point within a coordinate unit. + #[test] + fn paths_read_back_point_for_point( + pts in prop::collection::vec((-1.0e5f64..1.0e5, -1.0e5f64..1.0e5), 4..60), + closed in any::(), + curves in any::(), + ) { + let p = |(x, y): (f64, f64)| Pt { x, y }; + let start = p(pts[0]); + let segments: Vec = if curves { + pts[1..].as_chunks::<3>().0.iter().map(|[a, b, c]| Segment::Cubic(p(*a), p(*b), p(*c))).collect() + } else { + pts[1..].iter().map(|q| Segment::Line(p(*q))).collect() + }; + prop_assume!(!segments.is_empty()); + let geometry = Geometry::Path(Path { subpaths: vec![SubPath { start, segments, closed }] }); + let s = Shape::new(geometry.clone(), Matrix::IDENTITY, Some(Color::Rgb([0.5, 0.5, 0.5])), None); + let d = drawing(vec![Page { size: Some((612.0, 792.0)), layers: vec![layer("L", vec![Object::Shape(Box::new(s))])] }]); + let back = round_trip(&d); + let read = &shape(&back.pages[0].layers[0].objects[0]).geometry; + let Geometry::Path(path) = read else { panic!() }; + prop_assert_eq!(path.subpaths[0].closed, closed); + let (want, got) = (points(&geometry), points(read)); + prop_assert_eq!(got.len(), want.len()); + for (a, b) in want.iter().zip(&got) { + prop_assert!(near(a.x, b.x) && near(a.y, b.y), "{:?} {:?}", a, b); + } + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs index 4fc7dcbdc9..df1f34c97d 100644 --- a/crates/cdr/tests/it/main.rs +++ b/crates/cdr/tests/it/main.rs @@ -4,5 +4,6 @@ mod bench; mod cmx; +mod cmx_write; mod provenance; mod read; From b436aa1cf83709398bd878ef57931a2ddca49534 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:46:50 -0800 Subject: [PATCH 026/235] craft-cdr: write .cmx files that a read within the given limits takes whole write_cmx now takes the Limits the file is written for. It refuses a drawing with Error::Limit when a read within those limits would refuse the file or leave part of it out: more chunks, objects, coordinates or dashes than the read takes, groups nested deeper than its depth, or a file longer than its input size. The counts follow what read_cmx charges. The writer checks them as it goes and stops at the first shape, group, table entry or page that does not fit. A dash pattern with no positive length, NaN included, is written solid and takes no dashes, and a NaN length sets rounded_dashes. The README, the write_cmx doc and the Error::Limit doc now give the same list of refusals and reports. They also say that a rounded rectangle scaled differently along its sides gets round corners, and which page, layer and group fields are not written. PROVENANCE.md defines the "own" and "the writer's choice" statuses of its Written fields table. --- crates/cdr/PROVENANCE.md | 13 +- crates/cdr/README.md | 41 +++--- crates/cdr/src/cmx_write.rs | 217 ++++++++++++++++++++++++++----- crates/cdr/src/lib.rs | 36 +++-- crates/cdr/tests/it/cmx_write.rs | 49 ++++++- 5 files changed, 292 insertions(+), 64 deletions(-) diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index fd9044cdb4..8c98c9c3f8 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -1,6 +1,7 @@ # Where each layout comes from -The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and +The reader relies on the record layouts below, and the `.cmx` writer writes in them ("Written +fields" lists each field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here. Sources: @@ -52,7 +53,10 @@ Sources: Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; -listed so it can be checked against a file, with what the reader does when it is wrong). +listed so it can be checked against a file, with what the reader does when it is wrong). The +"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test +files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and +the synthetic test files do not set, chosen by the writer). Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the @@ -132,8 +136,9 @@ file is committed. `src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table lists every field it sets. `own` marks a value the reader does not read, which the writer sets as the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the -index chunks (`LIST indx`), and the instruction counts, file offsets and bounds that the CX files -also keep in their page, layer and group records are not written: no public source describes +index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in +their page, layer and group records, and the bounds they keep in layer and group records are not +written: no public source describes them, and the reader finds every chunk by its id and walks the instructions in order. | Field written | Rows | Status | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index 5759c11109..ff38ff8683 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -78,21 +78,32 @@ path is left out and the objects it clips are read without it. Files in big-endi files with 16-bit coordinates are refused. `write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx` -reads: pages with their sizes, layers with their names, groups, and curves with uniform fills and -outlines. Rectangles and ellipses are written as curves, and a clipping container as a group of its -fill, the objects it clips (unclipped) and its outline. Hidden layers, groups and shapes, guide and -grid layers, guidelines and master layers are left out; opacity, blend modes, fill rules and locked -states are not written, desktop layers are written as drawing layers, and a spot color with no -name opens as a process color; every use of a named spot color takes the look of its use at the -strongest tint. A coordinate -past the 32-bit range, or more than 65,535 pages, layers on a page or different colors, pens or -outlines, is an error. The returned `Written` reports paths split or cut into several curves, -dashes rounded to whole outline widths, nonzero fills that may fill differently, names that open -shortened, spot colors at a 0% tint, with no name or with no known look (written black), and what -was left out or written opaque, -unclipped or unlocked. The header's index offsets and the index chunks (`LIST indx`) are not -written, so a reader must find the chunks by their ids, as `read_cmx` does. `PROVENANCE.md`'s -"Written fields" table lists every field it sets. +reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their +sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file +holds differently from the drawing is reported, as below. Rectangles and ellipses are +written as curves, and a clipping container as a group of its fill, the objects it clips +(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round +corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines +and master layers are left out; opacity, blend modes, fill rules and locked states are not +written, desktop layers are written as drawing layers, and a spot color with no name opens as a +process color; every use of a named spot color takes the look of its use at the strongest tint. + +`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width +past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than +65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a +dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks, +objects, coordinates or dashes than a read within the limits takes, a file longer than their input +size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes +rounded to whole outline widths, nonzero fills that may fill differently, names that open +shortened, spot colors at a tint too low to keep their look, with no name or with no known look +(written black), and what was left out or written opaque, unclipped or unlocked. + +The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets +inside page, layer and group records, and the bounds inside layer and group records are not +written, so a reader must find the chunks by their ids and walk the instructions in order, as +`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page +when it has none. `PROVENANCE.md`'s "Written +fields" table lists every field the writer sets. ## Provenance diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index cc662ce3ea..ae44d5d239 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -1,8 +1,9 @@ //! Writer for `.cmx` exchange files with 32-bit coordinates, in the layouts [`crate::read_cmx`] //! reads: the RIFF form `CMX1` (R53), its header (R54), the color, pen, line type, dash, outline and -//! arrowhead tables (R55 to R59) and one `page` chunk of instructions for each page (R60): pages, -//! layers, groups and curves (R61, R62) with uniform fills and outlines (R63). `PROVENANCE.md`'s -//! "Written fields" lists every field the writer sets and where its layout comes from. +//! arrowhead tables (R55 to R59), the screen table (R74) and one `page` chunk of instructions for +//! each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills and outlines +//! (R63). `PROVENANCE.md`'s "Written fields" lists every field the writer sets and where its layout +//! comes from. //! //! Rectangles and ellipses are written as curves. A clipping container is written as a group of //! its fill, the objects it clips, unclipped, and its outline. Hidden layers, groups and shapes, @@ -56,6 +57,7 @@ const CLOSES: u8 = 0x08; /// A written file and what it changed. #[derive(Clone, Debug, Default, PartialEq)] pub struct Written { + /// The file. pub bytes: Vec, /// A path held more than [`MAX_CURVE_POINTS`] points and was written as several curves in a /// group, so overlapping parts of its fill may draw differently. @@ -65,7 +67,8 @@ pub struct Written { /// its dashes again, where the pieces meet. pub cut_subpaths: bool, /// A dash or gap length was rounded to a whole number of outline widths, the unit the dash - /// table stores (R57), or held to the 65,535 widths a length there holds. + /// table stores (R57), held to the 65,535 widths a length there holds, or, when it is not a + /// number, stored as 0. pub rounded_dashes: bool, /// A layer or spot color name is longer than the 256 UTF-16 units the reader keeps whole, or /// ends in NUL characters, which the reader drops, so it opens shortened. Past 4,096 units it @@ -80,8 +83,8 @@ pub struct Written { /// A shape filled with the nonzero rule may fill differently with the even-odd rule every /// curve is written with: one of its cubics loops, one of its subpaths crosses or touches /// itself or loops over itself, or two turn the same way and their boxes overlap, measured - /// with each cubic flattened to 16 lines. Past 50,000,000 comparisons of edges and boxes in one file, a shape is taken to fill - /// differently. + /// with each cubic flattened to 16 lines. Past 50,000,000 comparisons of edges and boxes in one + /// file, a shape is taken to fill differently. pub nonzero_fills: bool, /// A spot color has no name, so it opens as a process color, its look at its tint: the reader /// takes a color without a name as a process color. @@ -98,15 +101,14 @@ pub struct Written { pub left_out: bool, } -/// Write `drawing` as a `.cmx` file. Coordinates are rounded to 0.1 µm. A page without its own -/// size takes the drawing's; with neither, it opens with no size. A point, page -/// size or outline width past what 32-bit coordinates hold is an [`Error::Limit`], as are a -/// negative or NaN outline width, a page side that rounds to 0, more than 65,535 pages, layers on -/// a page or different colors, pens or outlines, a stored dash pattern (an all-zero one is solid -/// and stores none) of more than 32,765 lengths (one table entry), groups nested deeper than the reader reads, and a file past what its 32-bit -/// chunk size holds; nothing is written then. -pub fn write(drawing: &Drawing) -> Result { +/// Write `drawing` as a `.cmx` file that a read within `limits` takes all of, as +/// [`crate::write_cmx`] describes. Coordinates are rounded to 0.1 µm. A page without its own size takes the drawing's; +/// with neither, it opens with no size. An all-zero dash pattern is solid and stores no lengths. +pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result { let mut w = Writer { + limits, + // The RIFF header, the form type and the `cont` chunk. + file_bytes: 12 + 8 + 180, looks: spot_looks(drawing), crossing_budget: CROSSING_BUDGET, left_out: !drawing.master.is_empty() || !drawing.guides.is_empty(), @@ -129,10 +131,20 @@ pub fn write(drawing: &Drawing) -> Result { if drawing.pages.is_empty() && drawing.page_size.is_some() { add(w.page(0, drawing.page_size, &[])?)?; } - for c in w.tables.chunks()? { + // The reader also counts every chunk (`cont`, the pages and the seven tables), every table entry + // and the one arrowhead pair. + let pages = if drawing.pages.is_empty() { usize::from(drawing.page_size.is_some()) } else { drawing.pages.len() }; + let t = &w.tables; + let entries = t.colors.entries.len() + t.pens.entries.len() + t.line_types.entries.len() + t.dashes.entries.len() + t.outlines.entries.len() + 1; + w.read_cost.chunks = w.read_cost.chunks.saturating_add(1 + pages + 7 + entries); + w.read_cost.check(&w.limits)?; + for c in w.tables.chunks(w.limits.input.saturating_sub(w.file_bytes))? { add(c)?; } let total = usize::try_from(size).ok().and_then(|n| n.checked_add(8)).ok_or(Error::Limit("chunk size"))?; + if total > w.limits.input { + return Err(Error::Limit("input size")); + } let mut bytes = Vec::new(); bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; bytes.extend(b"RIFF"); @@ -277,14 +289,36 @@ struct Tables { } impl Tables { - fn chunks(&self) -> Result>, Error> { + /// The table chunks, or an [`Error::Limit`] once they take more than `left` bytes. + fn chunks(&self, left: usize) -> Result>, Error> { + // The bytes taken so far, charged as each entry is made and then for each table's header. + let used = std::cell::Cell::new(0usize); + let charge = |n: usize| { + used.set(used.get().saturating_add(n)); + if used.get() > left { Err(Error::Limit("input size")) } else { Ok(()) } + }; let table = |id: &[u8; 4], entries: Vec>| -> Result, Error> { let mut d = (entries.len() as u16).to_le_bytes().to_vec(); d.extend(entries.concat()); - chunk(id, &d) + let c = chunk(id, &d)?; + charge(c.len() + 2 - d.len())?; + Ok(c) }; - let one = |tag: u8, data: &[u8]| field(tag, data).map(|f| fields(&[f])).ok_or(Error::Limit("table entry size")); - let colors = self.colors.entries.iter().map(color_entry).collect::, _>>()?; + let one = |tag: u8, data: &[u8]| -> Result, Error> { + let e = field(tag, data).map(|f| fields(&[f])).ok_or(Error::Limit("table entry size"))?; + charge(e.len())?; + Ok(e) + }; + let colors = self + .colors + .entries + .iter() + .map(|k| -> Result, Error> { + let e = color_entry(k)?; + charge(e.len())?; + Ok(e) + }) + .collect::, _>>()?; // A pen: the width, an aspect of 100 percent, an angle of 0 and a matrix of type 1 // (R57). let pens = self @@ -377,8 +411,44 @@ fn color_entry(k: &ColorKey) -> Result, Error> { Ok(fields(&[field(10, &rec).ok_or(Error::Limit("table entry size"))?])) } +/// The counts [`crate::read_cmx`] holds to [`crate::Limits`] while it reads a file. +#[derive(Default)] +struct ReadCost { + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, +} + +impl ReadCost { + /// An [`Error::Limit`] when a read within `limits` would refuse the file or leave out part of + /// it. + fn check(&self, limits: &crate::Limits) -> Result<(), Error> { + if self.chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + if self.objects > limits.objects { + return Err(Error::Limit("objects")); + } + if self.coordinates > limits.coordinates { + return Err(Error::Limit("coordinates")); + } + if self.dashes > limits.dashes { + return Err(Error::Limit("dashes")); + } + Ok(()) + } +} + #[derive(Default)] struct Writer { + /// What the file must open within. + limits: crate::Limits, + /// The bytes of the chunks written so far, with the RIFF header. + file_bytes: usize, + /// At least the bytes the table entries added so far take in the tables written at the end: + /// a dash pattern's lengths and a color's name. + table_bytes: usize, tables: Tables, /// The look of each named spot color, from [`spot_looks`]. looks: HashMap, @@ -389,6 +459,10 @@ struct Writer { /// The smallest and largest x and y the curves written on the current page reach, in /// coordinate units. bounds: Option<[i32; 4]>, + /// What [`crate::read_cmx`] counts against [`crate::Limits`] in the instructions written so + /// far: instructions (chunks), groups and curves (objects), curve points (coordinates) and the + /// dash lengths of every curve's outline (dashes). + read_cost: ReadCost, split_paths: bool, cut_subpaths: bool, rounded_dashes: bool, @@ -478,6 +552,10 @@ impl Writer { self.zero_tints |= key.values[3] == 0 || back.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0); self.unknown_looks |= look.is_none() && !self.looks.contains_key(name); } + if let Some(name) = key.name.as_ref().filter(|_| !self.tables.colors.index.contains_key(&key)) { + self.table_bytes = self.table_bytes.saturating_add(2 * utf16_prefix(name).len()); + self.check_bytes(0)?; + } self.tables.colors.index(key) } @@ -504,15 +582,34 @@ impl Writer { written += 1; self.objects(&layer.objects, &mut out)?; out.extend(instr(END_LAYER, &[])); + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; + self.check_bytes(out.len())?; } out.extend(instr(END_PAGE, &[])); + // The begin and end page instructions. + self.read_cost.chunks += 2; + self.read_cost.check(&self.limits)?; let begin = begin_page(n, size, self.bounds.take())?; if u32::try_from(begin.len() + out.len()).is_err() { return Err(Error::Limit("chunk size")); } let mut page = begin; page.extend(out); - chunk(b"page", &page) + let c = chunk(b"page", &page)?; + self.check_bytes(c.len())?; + self.file_bytes += c.len(); + Ok(c) + } + + /// An [`Error::Limit`] when the file would be longer than the input size of the limits with + /// `pending` more bytes. + fn check_bytes(&self, pending: usize) -> Result<(), Error> { + if self.file_bytes.saturating_add(self.table_bytes).saturating_add(pending) > self.limits.input { + Err(Error::Limit("input size")) + } else { + Ok(()) + } } /// The shown `objects` (front to back) in the order they are drawn. Groups are walked with a @@ -527,6 +624,7 @@ impl Writer { if u32::try_from(out.len()).is_err() { return Err(Error::Limit("chunk size")); } + self.check_bytes(out.len())?; let Some(o) = iter.next() else { if let Some((_, ends, over)) = stack.pop() { if let Some(s) = over { @@ -571,26 +669,49 @@ impl Writer { Ok(()) } - /// Begin a group. A group inside as many groups as the reader opens ([`crate::Limits`]'s - /// default depth) is an [`Error::Limit`]: the reader leaves out what it holds. + /// Begin a group. A group inside as many groups as the reader opens (the depth of the + /// [`crate::Limits`] written for) is an [`Error::Limit`]: the reader leaves out what it holds. fn begin_group(&mut self, out: &mut Vec) -> Result<(), Error> { - if self.open_groups >= crate::Limits::default().depth { + if self.open_groups >= self.limits.depth { return Err(Error::Limit("nesting depth")); } self.open_groups += 1; out.extend(group()); - Ok(()) + self.read_cost.chunks += 1; + self.read_cost.objects += 1; + self.read_cost.check(&self.limits) } fn end_group(&mut self, out: &mut Vec) { self.open_groups = self.open_groups.saturating_sub(1); out.extend(instr(END_GROUP, &[])); + self.read_cost.chunks += 1; } /// A shape as one curve, or as a group of curves when its path holds more than /// [`MAX_CURVE_POINTS`] points. fn shape(&mut self, s: &Shape, out: &mut Vec) -> Result<(), Error> { self.left_out |= s.opacity < 1.0 || s.blend != Blend::Normal || s.flags.locked; + // A path's nodes are at least as many as its segments and starts; a path past what the + // limits leave is refused before its points are made. + if let Geometry::Path(p) = &s.geometry { + let nodes = p.subpaths.iter().filter(|sp| !sp.segments.is_empty()).fold(0usize, |n, sp| { + sp.segments.iter().fold(n.saturating_add(1), |n, seg| n.saturating_add(if matches!(seg, Segment::Line(_)) { 1 } else { 3 })) + }); + // A path split into several curves is written once for its fill and once for its + // outline. + let passes = if s.fill.is_some() && s.outline.is_some() && nodes > MAX_CURVE_POINTS { 2 } else { 1 }; + let nodes = nodes.saturating_mul(passes); + if self.read_cost.coordinates.saturating_add(nodes) > self.limits.coordinates { + return Err(Error::Limit("coordinates")); + } + // A path with segments takes at least one object and one instruction. + if nodes > 0 { + let cost = ReadCost { chunks: self.read_cost.chunks + 1, objects: self.read_cost.objects + 1, ..ReadCost::default() }; + cost.check(&self.limits)?; + } + self.check_bytes(out.len().saturating_add(nodes.saturating_mul(9)))?; + } let points = points_of(&s.geometry, &s.matrix)?; let curves = split(&points); // A path with no segments draws nothing, and the file has no curve for it. @@ -621,6 +742,19 @@ impl Writer { self.split_paths = true; self.begin_group(out)?; } + // Each pass writes every curve, and the reader takes the outline's dashes again for every + // curve that names it. + let points_count = curves.iter().fold(0usize, |n, c| n.saturating_add(c.len())); + for (_, dashes) in &attrs { + let cost = &mut self.read_cost; + cost.chunks = cost.chunks.saturating_add(curves.len()); + cost.objects = cost.objects.saturating_add(curves.len()); + cost.coordinates = cost.coordinates.saturating_add(points_count); + cost.dashes = cost.dashes.saturating_add(dashes.saturating_mul(curves.len())); + } + self.read_cost.check(&self.limits)?; + // Each curve instruction holds at least 9 bytes for each point. + self.check_bytes(out.len().saturating_add(points_count.saturating_mul(9).saturating_mul(attrs.len())))?; let mut bodies = Vec::with_capacity(curves.len()); for c in &curves { let mut g = (c.len() as u16).to_le_bytes().to_vec(); @@ -648,10 +782,12 @@ impl Writer { g.extend(c.iter().map(|(_, t)| *t)); bodies.push(field(2, &g).ok_or(Error::Limit("curve size"))?); } - for a in &attrs { + for (a, _) in &attrs { let f1 = field(1, a).ok_or(Error::Limit("rendering attributes size"))?; for f2 in &bodies { - out.extend(instr(CURVE, &fields(&[f1.clone(), f2.clone()]))); + let i = instr(CURVE, &fields(&[f1.clone(), f2.clone()])); + self.check_bytes(out.len().saturating_add(i.len()))?; + out.extend(i); } } if curves.len() > 1 { @@ -661,10 +797,12 @@ impl Writer { } /// Rendering attributes (R63): the mask, then the uniform fill's field list (fill type 1 and a - /// field 1 of the color entry and screen entry 1, R74) and the outline's (its `rotl` entry). - fn attributes(&mut self, fill: Option<&Color>, outline: Option<&Outline>, matrix: &Matrix) -> Result, Error> { + /// field 1 of the color entry and screen entry 1, R74) and the outline's (its `rotl` entry), + /// with the number of dash lengths the outline names. + fn attributes(&mut self, fill: Option<&Color>, outline: Option<&Outline>, matrix: &Matrix) -> Result<(Vec, usize), Error> { let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1); let mut a = vec![mask]; + let mut dashes = 0; if let Some(c) = fill { let index = self.color(c)?; let mut v = 1u16.to_le_bytes().to_vec(); @@ -676,18 +814,22 @@ impl Writer { // shape takes the matrix's scale into its width, as the engine applies it (R50). let [m0, m1, m2, m3, _, _] = matrix.0; let scale = if o.scale_with { (m0 * m3 - m1 * m2).abs().sqrt() } else { 1.0 }; - let index = self.outline(o, scale)?; + let (index, n) = self.outline(o, scale)?; + dashes = n; a.extend(fields(&[field(1, &index.to_le_bytes()).ok_or(Error::Limit("outline size"))?])); } - Ok(a) + Ok((a, dashes)) } /// The `rotl` entry of an outline (R57, R58): its line type (2 solid, 4 dashed, 8 behind the /// fill, 16 scaled with the object; the caps in the low 4 bits and the join in the high 4 - /// bits), color, pen and dash pattern. `scale` multiplies the width. - fn outline(&mut self, o: &Outline, scale: f64) -> Result { - // A pattern of zero lengths draws a solid line (R57). - let lengths: &[f64] = if o.dashes.iter().all(|d| *d <= 0.0) { &[] } else { &o.dashes }; + /// bits), color, pen and dash pattern, and the number of dash lengths stored. `scale` + /// multiplies the width. + fn outline(&mut self, o: &Outline, scale: f64) -> Result<(u16, usize), Error> { + // A pattern with no positive length draws a solid line (R57). + let lengths: &[f64] = if !o.dashes.iter().any(|d| *d > 0.0) { &[] } else { &o.dashes }; + // A length that is not a number is stored as 0. + self.rounded_dashes |= o.dashes.iter().any(|d| d.is_nan()); // One table entry holds a u16 count and the lengths in a field of at most 65,535 bytes. if lengths.len() > (usize::from(u16::MAX) - 3 - 2) / 2 { return Err(Error::Limit("table entry size")); @@ -733,8 +875,13 @@ impl Writer { } let pen = self.tables.pens.index(if width > 0.0 { width_units(width)?.max(1) } else { 0 })?; // A solid outline names an empty pattern, as the sample files' solid outlines do (R58). + let stored = dashes.len(); + if !self.tables.dashes.index.contains_key(&dashes) { + self.table_bytes = self.table_bytes.saturating_add(2 * stored); + self.check_bytes(0)?; + } let dash = self.tables.dashes.index(dashes)?; - self.tables.outlines.index([line, color, pen, dash]) + Ok((self.tables.outlines.index([line, color, pen, dash])?, stored)) } } diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 91afe52367..402fdaddad 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -61,7 +61,8 @@ pub enum Error { Version(u16), /// A container structure that doesn't parse. Damaged(&'static str), - /// Past one of the [`Limits`]. + /// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an + /// outline width that is negative or NaN. Limit(&'static str), /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates. @@ -114,12 +115,29 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts /// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and -/// outlines. A coordinate past the 32-bit range, a page side that rounds to 0, more than 65,535 -/// pages, layers on a page or different colors, pens or outlines, a dash pattern of more than -/// 32,765 lengths, groups nested deeper than [`Limits`]' default depth, or a chunk past its 32-bit -/// size, is an [`Error::Limit`]. [`Written`] reports what the file could not hold as it was. The -/// header's index offsets and the index chunks are not written, so a reader must find the chunks -/// by their ids, as [`read_cmx`] does. -pub fn write_cmx(drawing: &Drawing) -> Result { - cmx_write::write(drawing) +/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them; +/// what the file holds differently from the drawing, such as a name the reader shortens, is +/// reported in [`Written`]. +/// +/// It fails with [`Error::Limit`], and writes nothing, for: +/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline +/// width, or a page side that rounds to 0; +/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash +/// patterns or outlines, or a dash pattern of more than 32,765 lengths; +/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or +/// dashes than a read within `limits` takes; +/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds. +/// +/// [`Written`] reports what the file holds differently from the drawing; its fields name each +/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is +/// written with round corners of its radii times the square root of the scales' product, not with +/// stretched corners, and is not reported. +/// +/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets +/// inside page, layer and group records, and the bounds inside layer and group records are not +/// written, so a reader must find the chunks by their ids and walk the instructions in order, as +/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the +/// page when it has none. +pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { + cmx_write::write(drawing, limits) } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index af85ce0a79..cbde1d4076 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -4,9 +4,14 @@ use craft_cdr::model::{ Cap, Color, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Path, Pt, Segment, Shape, SubPath, }; -use craft_cdr::{Error, Limits, MAX_CURVE_POINTS, is_cmx, read_cmx, write_cmx}; +use craft_cdr::{Error, Limits, MAX_CURVE_POINTS, Written, is_cmx, read_cmx}; use proptest::prelude::*; +/// [`craft_cdr::write_cmx`] within the default limits. +fn write_cmx(d: &Drawing) -> Result { + craft_cdr::write_cmx(d, Limits::default()) +} + fn layer(name: &str, objects: Vec) -> Layer { Layer { name: name.into(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() } } @@ -921,6 +926,48 @@ fn groups_nested_deeper_than_the_reader_reads_are_refused() { assert_eq!(write_cmx(&nest(deepest + 1)), Err(Error::Limit("nesting depth"))); } +#[test] +fn a_file_the_reader_would_not_take_whole_within_the_limits_is_refused() { + let dashed = Outline { dashes: vec![2.0, 1.0, 3.0], ..outline(Color::Gray(0.0)) }; + let art = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), Some(dashed.clone())))); + let group = Object::Group { objects: vec![art(0.0), art(20.0)], flags: Flags::default() }; + let d = drawing(vec![Page { size: None, layers: vec![layer("L", vec![group, art(40.0)])] }]); + let whole = write_cmx(&d).unwrap().bytes; + let fields: [fn(&mut Limits) -> &mut usize; 5] = + [|l| &mut l.chunks, |l| &mut l.objects, |l| &mut l.coordinates, |l| &mut l.dashes, |l| &mut l.depth]; + for (i, field) in fields.into_iter().enumerate() { + let (mut written, mut refused) = (false, false); + for v in 0..=80 { + let mut limits = Limits::default(); + *field(&mut limits) = v; + // What the reader takes from the file written within the default limits. + let opens_whole = read_cmx(&whole, limits).is_ok_and(|back| back.warnings.is_empty()); + match craft_cdr::write_cmx(&d, limits) { + Ok(w) => { + written = true; + assert!(opens_whole, "field {i} at {v}: written but not read whole"); + assert_eq!(w.bytes, whole, "field {i} at {v}"); + } + Err(e) => { + refused = true; + assert!(matches!(e, Error::Limit(_)), "field {i} at {v}: {e:?}"); + assert!(!opens_whole, "field {i} at {v}: refused but read whole"); + } + } + } + assert!(written && refused, "field {i}: both outcomes within 0 to 80"); + } + let input = |n: usize| craft_cdr::write_cmx(&d, Limits { input: n, ..Limits::default() }); + assert!(input(whole.len()).is_ok()); + assert_eq!(input(whole.len() - 1), Err(Error::Limit("input size"))); + // A pattern with no positive length is solid, and the reader takes no dashes for it. + let solid = Outline { dashes: vec![f64::NAN, 0.0], ..outline(Color::Gray(0.0)) }; + let one = one_shape(Shape::new(square(0.0, 0.0, 10.0), Matrix::IDENTITY, None, Some(solid))); + let w = craft_cdr::write_cmx(&one, Limits { dashes: 0, ..Limits::default() }).unwrap(); + assert!(w.rounded_dashes, "the length that is not a number"); + assert!(read_cmx(&w.bytes, Limits { dashes: 0, ..Limits::default() }).unwrap().warnings.is_empty()); +} + #[test] fn a_negative_radius_leaves_its_corner_square() { let rect = Shape::new(Geometry::Rect { w: 100.0, h: 100.0, radii: [-20.0, 0.0, 0.0, 0.0] }, Matrix::IDENTITY, Some(Color::Gray(0.5)), None); From 393107b31ea7215784ff5fd585e7aa6bbe188867 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:04:40 -0800 Subject: [PATCH 027/235] craft-cdr: report uses of one ink that open with another use's look Every use of a named spot color is written with the look of its use at the strongest tint. Written::merged_looks now reports a use that opens more than 2/255 off what its own look would open as, or off its own look where its own look would not. When the use opens the same as its own look would, a loss at its tint sets zero_tints as before. --- crates/cdr/README.md | 3 ++- crates/cdr/src/cmx_write.rs | 30 ++++++++++++++++++++++++++---- crates/cdr/tests/it/cmx_write.rs | 18 ++++++++++++++++++ 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/cdr/README.md b/crates/cdr/README.md index ff38ff8683..0fd2533c64 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -96,7 +96,8 @@ objects, coordinates or dashes than a read within the limits takes, a file longe size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes rounded to whole outline widths, nonzero fills that may fill differently, names that open shortened, spot colors at a tint too low to keep their look, with no name or with no known look -(written black), and what was left out or written opaque, unclipped or unlocked. +(written black), uses of one ink with different looks, and what was left out or written opaque, +unclipped or unlocked. The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets inside page, layer and group records, and the bounds inside layer and group records are not diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index ae44d5d239..22b8873e1b 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -92,6 +92,10 @@ pub struct Written { /// A spot color's look is unknown in every use of its name (or, for a spot color with no name, /// in that use), so it is written, and opens, as black at its tint. pub unknown_looks: bool, + /// A spot color name was used with different looks, and a use was written with the look of + /// the use at the strongest tint, so that it opens more than 2/255 off what its own look would + /// open as, or off its own look where its own look would not. + pub merged_looks: bool, /// The drawing held what the file does not hold: hidden layers, groups or shapes, guide and /// grid layers, guidelines and master layers (left out), opacity below 1 or a blend mode /// (written opaque and normal), clipping (written unclipped), locked layers, groups or shapes @@ -163,6 +167,7 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result nonzero_fills: w.nonzero_fills, unnamed_spots: w.unnamed_spots, unknown_looks: w.unknown_looks, + merged_looks: w.merged_looks, left_out: w.left_out, }) } @@ -471,6 +476,7 @@ struct Writer { nonzero_fills: bool, unnamed_spots: bool, unknown_looks: bool, + merged_looks: bool, left_out: bool, } @@ -546,11 +552,27 @@ impl Writer { self.long_names |= shortened(name); // The reader takes the tint back out of the stored color; at a low tint the 8-bit // values do not hold enough of the look for that. - let [b, g, r] = [key.values[0], key.values[1], key.values[2]].map(|v| f32::from(v) / 255.0); - let back = crate::records::untinted([r, g, b], f32::from(key.values[3]) / 100.0); - let want = self.looks.get(name).copied().or(*look).unwrap_or([0.0; 3]); - self.zero_tints |= key.values[3] == 0 || back.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0); + let opens = |k: &ColorKey| { + let [b, g, r] = [k.values[0], k.values[1], k.values[2]].map(|v| f32::from(v) / 255.0); + crate::records::untinted([r, g, b], f32::from(k.values[3]) / 100.0) + }; + // More than 2/255 apart in some value, with room for the reader's rounding. + let lost = |opened: &[f32; 3], want: [f32; 3]| opened.iter().zip(want).any(|(a, w)| (a - w.clamp(0.0, 1.0)).abs() > 2.0 / 255.0 + 1e-6); + let back = opens(&key); + let ink = self.looks.get(name).copied().or(*look).unwrap_or([0.0; 3]); + self.zero_tints |= key.values[3] == 0 || lost(&back, ink); self.unknown_looks |= look.is_none() && !self.looks.contains_key(name); + // A use with a look of its own: the ink's look written in its place changed it when the + // use opens off what its own look would open as, or off its own look where its own + // look would not. Otherwise the tint alone keeps its own look from opening again. + if let Some(own) = look { + let back_own = if self.looks.get(name) == Some(own) { back } else { opens(&color_key(c)) }; + if lost(&back, back_own) || (lost(&back, *own) && !lost(&back_own, *own)) { + self.merged_looks = true; + } else { + self.zero_tints |= lost(&back_own, *own); + } + } } if let Some(name) = key.name.as_ref().filter(|_| !self.tables.colors.index.contains_key(&key)) { self.table_bytes = self.table_bytes.saturating_add(2 * utf16_prefix(name).len()); diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index cbde1d4076..aa07e8609f 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -634,6 +634,24 @@ fn spot_colors_with_no_name_share_no_look() { assert!(near_color(&fill, &Color::Rgb([0.0, 0.0, 0.0])), "{fill:?}"); } +#[test] +fn an_ink_used_with_different_looks_is_reported() { + let ink = |tint, look| Color::Spot { name: "Ink".into(), tint, look: Some(look) }; + let written = |second| { + let shapes = + [ink(1.0, [1.0, 0.0, 0.0]), second].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap().merged_looks + }; + assert!(!written(ink(0.5, [1.0, 0.0, 0.0])), "one look"); + assert!(written(ink(0.5, [0.0, 1.0, 0.0])), "a second look"); + // At 1 % both looks store the same color, and only the tint changes it. + let gray = |tint, v| Color::Spot { name: "Gray".into(), tint, look: Some([v; 3]) }; + let shapes = + [gray(1.0, 0.5), gray(0.01, 0.501)].map(|c| Object::Shape(Box::new(Shape::new(square(0.0, 0.0, 1.0), Matrix::IDENTITY, Some(c), None)))); + let w = write_cmx(&drawing(vec![Page { size: None, layers: vec![layer("L", shapes.to_vec())] }])).unwrap(); + assert!(w.zero_tints && !w.merged_looks); +} + #[test] fn a_cubic_looping_between_its_samples_is_reported() { let p = |x, y| Pt { x, y }; From 9e1c5f75e43c84d973815bcfcaca8632d10cd03d Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Sat, 21 Nov 2026 12:20:36 +0000 Subject: [PATCH 028/235] #7171: scroll bodies offer fill-width children the view, not the bar lane Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/contract/body/hooks.rs | 9 +++++++- .../tests/it/layout/stack_widths.rs | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c6..6c96686a88 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1524,7 +1524,14 @@ impl BodyHooks<'_> { if lays_out { crate::runtime::lazy::begin(ctx, view, self.anchor.map(|anchor| anchor.child), self.glide.map(|glide| glide.child)); } - let env = run.env.derive_local(|scoped| scoped.lazy = Some(view)); + // The children fill what the view shows: the width the body was offered counts the bar's lane, so a child that + // fills the offered width would lie under the bar. + let env = run.env.derive_local(|scoped| { + scoped.lazy = Some(view); + if let Some(offered) = scoped.offered.as_mut() { + *offered = (*offered - inset.x).max(0.0); + } + }); let installed = Env::install_for(®ion_ui, env.clone()); ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out, laid_for: (inset, shows) } } diff --git a/crates/ui-widgets/tests/it/layout/stack_widths.rs b/crates/ui-widgets/tests/it/layout/stack_widths.rs index 2d6ba4bcfb..f3dd67968f 100644 --- a/crates/ui-widgets/tests/it/layout/stack_widths.rs +++ b/crates/ui-widgets/tests/it/layout/stack_widths.rs @@ -190,3 +190,26 @@ fn labelled_radios_in_a_wrapping_row_break_onto_a_new_line() { let starts = KINDS.iter().filter(|kind| (rect(kind).left() - first.left()).abs() < 0.5).count(); assert!(starts >= 2, "a radio that wraps starts its line at the row's start edge: {starts} radios do"); } + +/// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it +/// (a Print page's buttons ran under the settings column's bar). +#[trial] +fn a_fill_width_child_of_a_scrolling_stack_leaves_the_bars_lane() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let child = Cell::new(Rect::NOTHING); + let shown = Stack::new().sizing(Sizing::FillHeight).least_width(LeastWidth::Dialog).scroll(Scroll::vertical()).show(ui, |ui, _| { + for _ in 0..30 { + child.set(Button::new("Save these pages as PDF…").sizing(Sizing::FillWidth).show(ui).rect); + } + }); + if !ui.is_sizing_pass() { + out.set((shown.output.rect, child.get())); + } + }); + fixture.room(Vec2::new(1440.0, 300.0)).settle(); + let (stack, button) = seen.get(); + assert!(stack != Rect::NOTHING && button != Rect::NOTHING, "the stack showed"); + assert!(button.max.x <= stack.max.x - 4.0, "the button leaves the bar's lane: {button:?} in {stack:?}"); +} From 2cde919852d239ac996621d8037a5e8645c6fdde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:44:12 -0800 Subject: [PATCH 029/235] craft-docx: read and write the hide spelling and grammar errors settings Settings gains hide_spelling_errors and hide_grammar_errors, the per-document Hide spelling errors and Hide grammar errors options. craft-docx reads w:hideSpellingErrors and w:hideGrammaticalErrors from settings.xml, writes them after w:mirrorMargins and before w:proofState, and lists them as owned in the settings merge, so a saved file carries each one once and drops it when it is turned off. --- crates/docx/src/read/meta.rs | 2 ++ crates/docx/src/write/settings.rs | 7 ++++ crates/docx/src/write/settings_merge.rs | 2 ++ crates/docx/tests/it/settings_merge.rs | 47 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 9 +++++ 5 files changed, 67 insertions(+) diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index b9debe1fa0..a6e3c51bcb 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -24,6 +24,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a098174056..afd7d6a389 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.gutter_at_top { w.empty("w:gutterAtTop", &[]); } + // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. + if s.hide_spelling_errors { + w.empty("w:hideSpellingErrors", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index a72046e831..2e064f05ac 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -19,6 +19,8 @@ const OWNED: &[&str] = &[ "w:displayBackgroundShape", "w:mirrorMargins", "w:gutterAtTop", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index c07986795e..312564626c 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -163,3 +163,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 46faf16c36..d7689fa66d 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -170,6 +170,13 @@ pub struct Settings { /// comments and tracked changes are saved without `w:date`. #[serde(skip_serializing_if = "std::ops::Not::not")] pub remove_date_time: bool, + /// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under + /// misspelled words. Spelling & Grammar (F7) still finds them. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_spelling_errors: bool, + /// Hide grammar errors in this document only (`w:hideGrammaticalErrors`). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_grammar_errors: bool, /// The document was opened from ODF: the standard's rules that differ from Word's apply as /// it is laid out. #[serde(skip_serializing_if = "Option::is_none")] @@ -333,6 +340,8 @@ impl Default for Settings { zoom: None, remove_personal_info: false, remove_date_time: false, + hide_spelling_errors: false, + hide_grammar_errors: false, odf: None, } } From 97b202c281875d53a4dee080a394c125cbaa3aaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:22:43 -0800 Subject: [PATCH 030/235] Fit: items rank their short forms, and late ones shorten after the free items leave fit_items took every short form, last item first, before any free item left the strip. A host could not choose which items shorten first, or keep a label until the other items had gone to the overflow menu. FitItem gains two builder options: - short_order(order: u16) ranks the item's short form. Lower ranks shorten first; items of one rank shorten last item first. Every item ranks 0 by default. - short_late() keeps the item's full form until no more free items can leave. Late items then shorten in the same rank order. Items that left do not come back. Items that set neither option fit exactly as before. --- crates/behavior/src/fit.rs | 58 ++++++++++++++++++++++++++---------- crates/behavior/tests/fit.rs | 31 +++++++++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..ee52c7e4a7 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,12 +230,16 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } /// The item with a shorter form `extent` long, which it takes before any free item leaves. @@ -243,6 +247,20 @@ impl FitItem { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: short forms of a lower rank are taken first, and items of + /// one rank take theirs last item first. Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left, so the other items go to + /// the overflow menu before this one shortens. A free item with a late short form leaves in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +295,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +322,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; From 00acaa7081d759eadf830bd40b5280a81695d649 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:28:12 -0800 Subject: [PATCH 031/235] Icons: volume, mic, mic_off and radio meanings in all four sets Adds four icon meanings to the catalog: volume (a speaker with sound waves, the unmuted partner of track_mute), mic, mic_off and radio (a broadcast mark: a dot between sound arcs). Lucide, Phosphor, Carbon and Tabler each draw all four, except Carbon, which has no broadcast glyph and falls back to Phosphor for radio. The files are copied unchanged from the pinned releases that ATTRIBUTION.md names. --- .../icons/carbon/microphone--off.svg | 1 + .../ui-contract/icons/carbon/microphone.svg | 1 + .../ui-contract/icons/carbon/volume--up.svg | 1 + crates/ui-contract/icons/icons.toml | 31 +++++++++++++++++++ crates/ui-contract/icons/lucide/mic-off.svg | 18 +++++++++++ crates/ui-contract/icons/lucide/mic.svg | 15 +++++++++ crates/ui-contract/icons/lucide/radio.svg | 17 ++++++++++ crates/ui-contract/icons/lucide/volume-2.svg | 15 +++++++++ .../ui-contract/icons/phosphor/broadcast.svg | 1 + .../icons/phosphor/microphone-slash.svg | 1 + .../ui-contract/icons/phosphor/microphone.svg | 1 + .../icons/phosphor/speaker-simple-high.svg | 1 + crates/ui-contract/icons/tabler/broadcast.svg | 21 +++++++++++++ .../icons/tabler/microphone-off.svg | 23 ++++++++++++++ .../ui-contract/icons/tabler/microphone.svg | 22 +++++++++++++ crates/ui-contract/icons/tabler/volume.svg | 21 +++++++++++++ crates/ui-contract/src/testing/icon_trials.rs | 29 +++++++++++++++-- 17 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 crates/ui-contract/icons/carbon/microphone--off.svg create mode 100644 crates/ui-contract/icons/carbon/microphone.svg create mode 100644 crates/ui-contract/icons/carbon/volume--up.svg create mode 100644 crates/ui-contract/icons/lucide/mic-off.svg create mode 100644 crates/ui-contract/icons/lucide/mic.svg create mode 100644 crates/ui-contract/icons/lucide/radio.svg create mode 100644 crates/ui-contract/icons/lucide/volume-2.svg create mode 100644 crates/ui-contract/icons/phosphor/broadcast.svg create mode 100644 crates/ui-contract/icons/phosphor/microphone-slash.svg create mode 100644 crates/ui-contract/icons/phosphor/microphone.svg create mode 100644 crates/ui-contract/icons/phosphor/speaker-simple-high.svg create mode 100644 crates/ui-contract/icons/tabler/broadcast.svg create mode 100644 crates/ui-contract/icons/tabler/microphone-off.svg create mode 100644 crates/ui-contract/icons/tabler/microphone.svg create mode 100644 crates/ui-contract/icons/tabler/volume.svg diff --git a/crates/ui-contract/icons/carbon/microphone--off.svg b/crates/ui-contract/icons/carbon/microphone--off.svg new file mode 100644 index 0000000000..977de5f87b --- /dev/null +++ b/crates/ui-contract/icons/carbon/microphone--off.svg @@ -0,0 +1 @@ +microphone--off \ No newline at end of file diff --git a/crates/ui-contract/icons/carbon/microphone.svg b/crates/ui-contract/icons/carbon/microphone.svg new file mode 100644 index 0000000000..bc17c17a5d --- /dev/null +++ b/crates/ui-contract/icons/carbon/microphone.svg @@ -0,0 +1 @@ +microphone \ No newline at end of file diff --git a/crates/ui-contract/icons/carbon/volume--up.svg b/crates/ui-contract/icons/carbon/volume--up.svg new file mode 100644 index 0000000000..e5ac240a9e --- /dev/null +++ b/crates/ui-contract/icons/carbon/volume--up.svg @@ -0,0 +1 @@ +volume--up \ No newline at end of file diff --git a/crates/ui-contract/icons/icons.toml b/crates/ui-contract/icons/icons.toml index a0ea7d5e8f..22914700b5 100644 --- a/crates/ui-contract/icons/icons.toml +++ b/crates/ui-contract/icons/icons.toml @@ -1714,6 +1714,37 @@ phosphor = "speaker-simple-slash" carbon = "volume--mute" tabler = "volume-off" +[[icon]] +name = "volume" +directional = false +lucide = "volume-2" +phosphor = "speaker-simple-high" +carbon = "volume--up" +tabler = "volume" + +[[icon]] +name = "mic" +directional = false +lucide = "mic" +phosphor = "microphone" +carbon = "microphone" +tabler = "microphone" + +[[icon]] +name = "mic_off" +directional = false +lucide = "mic-off" +phosphor = "microphone-slash" +carbon = "microphone--off" +tabler = "microphone-off" + +[[icon]] +name = "radio" +directional = false +lucide = "radio" +phosphor = "broadcast" +tabler = "broadcast" # near: arcs above the dot only + [[icon]] name = "solo" directional = false diff --git a/crates/ui-contract/icons/lucide/mic-off.svg b/crates/ui-contract/icons/lucide/mic-off.svg new file mode 100644 index 0000000000..9fadf25b18 --- /dev/null +++ b/crates/ui-contract/icons/lucide/mic-off.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/ui-contract/icons/lucide/mic.svg b/crates/ui-contract/icons/lucide/mic.svg new file mode 100644 index 0000000000..2a1698d75f --- /dev/null +++ b/crates/ui-contract/icons/lucide/mic.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui-contract/icons/lucide/radio.svg b/crates/ui-contract/icons/lucide/radio.svg new file mode 100644 index 0000000000..b59855c411 --- /dev/null +++ b/crates/ui-contract/icons/lucide/radio.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/crates/ui-contract/icons/lucide/volume-2.svg b/crates/ui-contract/icons/lucide/volume-2.svg new file mode 100644 index 0000000000..519e6cbd4d --- /dev/null +++ b/crates/ui-contract/icons/lucide/volume-2.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui-contract/icons/phosphor/broadcast.svg b/crates/ui-contract/icons/phosphor/broadcast.svg new file mode 100644 index 0000000000..cb0522838f --- /dev/null +++ b/crates/ui-contract/icons/phosphor/broadcast.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/ui-contract/icons/phosphor/microphone-slash.svg b/crates/ui-contract/icons/phosphor/microphone-slash.svg new file mode 100644 index 0000000000..efeff63c33 --- /dev/null +++ b/crates/ui-contract/icons/phosphor/microphone-slash.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/ui-contract/icons/phosphor/microphone.svg b/crates/ui-contract/icons/phosphor/microphone.svg new file mode 100644 index 0000000000..d774a0c72b --- /dev/null +++ b/crates/ui-contract/icons/phosphor/microphone.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/ui-contract/icons/phosphor/speaker-simple-high.svg b/crates/ui-contract/icons/phosphor/speaker-simple-high.svg new file mode 100644 index 0000000000..195af63632 --- /dev/null +++ b/crates/ui-contract/icons/phosphor/speaker-simple-high.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/crates/ui-contract/icons/tabler/broadcast.svg b/crates/ui-contract/icons/tabler/broadcast.svg new file mode 100644 index 0000000000..9b9575e7c1 --- /dev/null +++ b/crates/ui-contract/icons/tabler/broadcast.svg @@ -0,0 +1,21 @@ + + + + + + diff --git a/crates/ui-contract/icons/tabler/microphone-off.svg b/crates/ui-contract/icons/tabler/microphone-off.svg new file mode 100644 index 0000000000..5a709880fd --- /dev/null +++ b/crates/ui-contract/icons/tabler/microphone-off.svg @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/crates/ui-contract/icons/tabler/microphone.svg b/crates/ui-contract/icons/tabler/microphone.svg new file mode 100644 index 0000000000..7d3b830ba2 --- /dev/null +++ b/crates/ui-contract/icons/tabler/microphone.svg @@ -0,0 +1,22 @@ + + + + + + + diff --git a/crates/ui-contract/icons/tabler/volume.svg b/crates/ui-contract/icons/tabler/volume.svg new file mode 100644 index 0000000000..056022b9ab --- /dev/null +++ b/crates/ui-contract/icons/tabler/volume.svg @@ -0,0 +1,21 @@ + + + + + + diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index 19c73c0555..85abae7c47 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -1,7 +1,8 @@ //! Trials of the icon lookup: the app icon registry (the catalog wins a clashing name, the first set keeps a name two -//! sets share), the set a theme's icon pack picks, and an app icon's layers by class. +//! sets share), the set a theme's icon pack picks, the audio and broadcast icons in every set, and an app icon's layers +//! by class. -use crate::primitives::{AppIcons, DataMode, Draw, DrawEnv, IconSpec, Layer, Mirror, PaintRecord, SvgIcon, icon_names, register_app_icons}; +use crate::primitives::{AppIcons, DataMode, Draw, DrawEnv, IconSet, IconSpec, Layer, Mirror, PaintRecord, SvgIcon, icon_names, register_app_icons}; use crate::style::{Ink, StyleColor, UiTokens, ink_color, rgba_color}; use crate::testing::{Frames, style, trial}; use craft_behavior::IconId; @@ -83,6 +84,30 @@ fn a_theme_icon_pack_picks_the_set_and_an_unknown_pack_draws_the_default() { assert_eq!(mask_under_pack(Some("user.missing"), CATALOG_NAME), default, "a pack that is not installed draws the default"); } +#[trial] +fn the_audio_and_broadcast_icons_draw_in_every_set_and_read_apart() { + const NAMES: [&str; 5] = ["volume", "track_mute", "mic", "mic_off", "radio"]; + for set in IconSet::ALL { + let pack = format!("{}{}", craft_theme::RESERVED_PREFIX, set.id()); + let masks: Vec = NAMES + .iter() + .map(|&name| { + let mask = mask_under_pack(Some(&pack), name); + assert!(mask.is_some(), "{name} is in the catalog"); + mask.unwrap_or_default() + }) + .collect(); + for (name, mask) in NAMES.iter().zip(&masks) { + assert!(mask.pixels.iter().any(|texel| texel.a() > 0), "{pack} draws {name}"); + } + for (i, (a, first)) in NAMES.iter().zip(&masks).enumerate() { + for (b, second) in NAMES.iter().zip(&masks).skip(i + 1) { + assert_ne!(first, second, "{pack} draws {a} and {b} apart"); + } + } + } +} + const LAYERED_NAME: &str = concat!("zz_t19_", "pen"); /// A plain body, an accent nib (a group, so the class reaches its children) and a fixed red cap. const LAYERED: &[u8] = b"\ From 45515d18b536184b357ffdd1cce3eb84bf97525d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:29:19 -0800 Subject: [PATCH 032/235] craft-automation: ui.drag presses, moves in even steps and releases as one request A host app that serves the control channel can now run a whole drag from one request instead of composing ui.click with hold, ui.move steps and ui.release itself. - synthetic::Drag reads {from, to, button?, steps?, modifiers}. from and to are point objects {x?, y?, coordinates?, page?}, each in its own space; errors inside one name it (from.x ...). steps runs from 1 to MAX_DRAG_STEPS (200), default DRAG_STEPS (12). - Drag::inject resolves both points before it queues anything, then queues the press at from, the moves to to in even steps (the last one lands on to) and the release at to. The modifiers stay held through the release and are let go afterwards unless other input stays held, as after ui.click. - input_method dispatches ui.drag, so its reply waits for the release. - The crate README, docs/craft-framework.md and docs/porting.md list it. Tests: a drag with a document-point end presses at from, makes one move per step towards to, releases at to and leaves nothing held; a drag keeps its modifiers while a held key stays down; a drag whose end cannot be placed queues no press; bad drag params join the refused-input table. --- crates/automation/README.md | 2 +- crates/automation/src/synthetic.rs | 79 ++++++++++++++++++++++++- crates/automation/tests/it/synthetic.rs | 70 +++++++++++++++++++++- docs/craft-framework.md | 2 +- docs/porting.md | 2 +- 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..be6496ceb0 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `KeyPress`, `move_from_params` and `Drag`: the validated parameters of `ui.click`, `ui.move`, `ui.key` and `ui.drag` (a press, moves in even steps and the release, from one request), and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958c..8a2bdb184b 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, +//! `ui.release`, `ui.type`, `ui.ime` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -11,7 +11,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -33,6 +34,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -192,6 +199,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are resolved before anything is queued, so a point that cannot be placed leaves no press down. + /// When the host withdraws the rest of the gesture after its press ran, the button stays down until `ui.release`, + /// as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.resolve(map)?, self.to.resolve(map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -304,6 +376,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848dd..aa70cb1439 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,11 +1,11 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -122,6 +122,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -291,6 +337,19 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -356,6 +415,13 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "coordinates": "page"})), ("ui.move", json!({"y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 5e24eaacdc..0c87b65c8a 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1124,7 +1124,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | | `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | -| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | +| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.drag`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists | | `profiler` | Frame profiler | exists | | `screenshot` | Screenshot request queue | exists | diff --git a/docs/porting.md b/docs/porting.md index f7a03e41bd..fdd9301051 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -130,7 +130,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | | Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | -| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | +| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`, `Drag`: the checked parameters of `ui.click`, `ui.key`, `ui.move`, `ui.drag` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | | Screenshots | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer | | View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` | From 6c33621a06715619e8a82d1bc6e01ccfdbaa32fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:30:38 -0800 Subject: [PATCH 033/235] Menu bar: the output reports the width every title takes side by side craft_ui::menu::MenuBarOutput and craft_menu::MenuBarOutput gain a `natural: f32` field: the width of every title side by side with none in the "..." menu, whatever room the bar had. `titles` stays the rect of the titles drawn. A host that puts controls after the titles on the same row compares `natural` with the room it leaves the bar, and can narrow its own controls before titles fold. The field is zero while the bar shows nothing (ScreenTop), and a memoized replay keeps it. Trials: a bar in a wide and a narrow rect (craft-ui-widgets) and MenuBarUi in a wide and a narrow Stack (craft-menu) report the same natural width, equal to the titles' width when all fit and larger than the drawn titles when some fold. --- crates/menu/README.md | 4 ++- crates/menu/src/bar.rs | 12 ++++++--- crates/menu/tests/it/title_bar.rs | 30 ++++++++++++++++++++- crates/ui-widgets/src/menu/bar.rs | 14 +++++++--- crates/ui-widgets/tests/it/menu/bar.rs | 36 +++++++++++++++++++++++++- 5 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index cb82dc8f9e..307cd092ad 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by +side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that +width with the room it leaves the bar. Show it inside a `Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 4b2c81e742..9ea75cec33 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform { /// A replay at another place moves the titles' rect with the bar. impl craft_ui::runtime::Shift for MenuBarOutput { fn shifted(&self, by: &egui::RecordShift) -> Self { - MenuBarOutput { titles: by.rect(self.titles) } + MenuBarOutput { titles: by.rect(self.titles), natural: self.natural } } fn snapped(&self, to: &Self, within: f32) -> Self { - MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within) } + MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural } } } @@ -63,6 +63,9 @@ pub struct MenuBarOutput { /// The menu titles alone, without the room the bar leaves after them /// ([`craft_ui::menu::MenuBarOutput::titles`]). pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had + /// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing. + pub natural: f32, } /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top @@ -145,7 +148,7 @@ impl<'a> MenuBarUi<'a> { help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0 }) } } @@ -182,7 +185,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); } - MenuBarOutput { titles: bar.show(ui).titles } + let shown = bar.show(ui); + MenuBarOutput { titles: shown.titles, natural: shown.natural } } /// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 1e79bf5c18..15543e8d97 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,6 +1,7 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title //! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` -//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. In any room the bar +//! reports the width its titles take side by side. use std::cell::Cell; use std::rc::Rc; @@ -131,3 +132,30 @@ fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_i fixture.click(&more).settle(); assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); } + +/// The bar reports the width every title takes side by side: in a stack that holds them all it is the titles' width, +/// and in a stack too narrow for them it is the same width while the drawn titles are narrower. +#[trial] +fn the_bar_reports_the_width_every_title_takes_in_a_wide_and_a_narrow_stack() { + let mut reports = Vec::new(); + for width in [1520.0, 240.0] { + let bar = Rc::new(model()); + let seen = Rc::new(Cell::new((0.0, 0.0))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let out = Rc::clone(&out); + Stack::new().show(ui, move |ui, _| { + let shown = MenuBarUi::new(&bar).target(Target::Windows).show(ui); + out.set((shown.natural, shown.titles.width())); + }); + }); + fixture.os(Os::Windows).room(vec2(width, 600.0)).settle(); + reports.push(seen.get()); + } + let [(wide, wide_titles), (narrow, narrow_titles)] = [reports[0], reports[1]]; + assert!(wide > 0.0, "the bar reports a width"); + assert!((wide - wide_titles).abs() < 0.5, "with room for every title the natural width {wide} is the titles' width {wide_titles}"); + assert!((narrow - wide).abs() < 0.5, "a narrow bar reports the same natural width {narrow} as a wide one {wide}"); + assert!(narrow_titles < narrow, "a narrow bar draws titles {narrow_titles} narrower than its natural width {narrow}"); +} diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index c74ef97b5c..dced87415a 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -209,6 +209,10 @@ pub struct MenuBarOutput { pub open: bool, /// The titles alone (with "…" when it shows), from the first title's reading start to the last title's end. pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had: a host that places + /// controls after the titles on the same row compares it with the room it leaves the bar. Zero when the bar + /// shows nothing (`MenuPlacement::ScreenTop`). + pub natural: f32, } impl Outcome for MenuBarOutput { @@ -304,12 +308,14 @@ pub struct MenuBar<'a> { #[prop] keyboard: bool, open: bool, + /// The width of every title side by side, from this pass's measure or parts step. + natural: f32, } impl<'a> MenuBar<'a> { /// A bar named `label` with one title per menu, in reading order. pub fn new(label: impl Into

{ /// goes back. #[serde(default)] hidden: Vec<(P, Location

)>, - /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the - /// workspace. + /// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that + /// floats records the place it would reopen at. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -264,6 +264,16 @@ impl Workspace

{ Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?, _ => false, }; + // Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel + // that would reopen in a floating window has no docked place. + let hidden_place = match &action { + Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed + .restored(panel, &policy) + .filter(|restored| !floats(&restored.layout, panel)) + .and_then(|restored| restored.layout.location(panel).ok()) + .map(|location| (panel.clone(), location)), + _ => None, + }; if !reopened { // SetNative records where the window system has a floating window, so a lock // does not refuse it. @@ -278,6 +288,12 @@ impl Workspace

{ proposed.hidden.push((panel, location)); } proposed.track_floated(&before); + if let Some((panel, location)) = hidden_place + && floats(&proposed.layout, &panel) + && !proposed.floated.iter().any(|(p, _)| p == &panel) + { + proposed.floated.push((panel, location)); + } all_closed.extend(closed); } let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 1d25354fdc..b6eea87da1 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert!(workspace.floated().is_empty(), "closing drops the record"); } +/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old +/// group keeps its front tab; docking it then returns it to that group at its old index. +#[test] +fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() { + let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0)); + let mut opened = Workspace::new(docked()); + opened.apply(Action::close(2), false, allow).unwrap(); + opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap(); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(float, false, allow).unwrap(); + let layout = workspace.layout(); + assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. }))); + assert_eq!(group_members(layout, 3), [3]); + assert_eq!(front(layout, 3), 3, "the old group keeps its front tab"); + assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives"); + + let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) }; + let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone()); + workspace.apply(back, false, allow).unwrap(); + assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index"); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(6), false, allow).unwrap(); + workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place"); +} + /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); From 52a090c6428fe235896f2f051c02102833684ddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:48:05 -0800 Subject: [PATCH 069/235] behavior: a Fill column raised to its least takes the difference from the other Fill columns, so a grid whose least widths fit no longer overflows GridCursor::new raised each Fill column's share to the column's least width but left the other Fill columns at their shares, so the row was wider than the grid by the difference even when the least widths fit. The Fill columns now share their room again: a column whose share by weight is below its least takes its least, and the other Fill columns share what is left by weight, down to their own least widths. The row is wider than the grid only when the least widths together do not fit. A grid whose shares already cover every least width is unchanged. --- crates/behavior/src/grid.rs | 86 ++++++++++++++++++++++++++++++++++--- 1 file changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index bd782a0e9c..103a97fcf0 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -85,15 +85,12 @@ pub struct GridCursor { impl GridCursor { /// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A /// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share - /// does not go below it. + /// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns. pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self { let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0); let content: Vec = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect(); - let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x) - .into_iter() - .enumerate() - .map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width }) - .collect(); + let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x); + keep_fill_least(columns, &mut widths, least); let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect(); GridCursor { flow, @@ -266,6 +263,44 @@ impl GridCursor { } } +/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a +/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight. +/// The fill columns together take more than their room only when their least widths do not fit in it. +fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) { + let fills: Vec<(usize, f32)> = columns + .iter() + .enumerate() + .filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None }) + .collect(); + let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum(); + if !room.is_finite() { + // Room with no bound leaves every share above its least. + for (i, _) in &fills { + widths[*i] = widths[*i].max(least(*i)); + } + return; + } + let mut raised = vec![false; columns.len()]; + loop { + let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::(); + let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum(); + let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 }; + let mut more = false; + for (i, weight) in &fills { + if !raised[*i] && share(*weight) < least(*i) { + raised[*i] = true; + more = true; + } + } + if !more { + for (i, weight) in &fills { + widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) }; + } + return; + } + } +} + /// `columns` with each `Fill` column as a `Content` column. fn as_content(columns: &[ColumnWidth]) -> Vec { columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect() @@ -288,4 +323,43 @@ mod tests { cursor.cell(Vec2::new(150.0, 100.0)); assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds"); } + + /// The widths of one row of `columns` placed by `last`, read from the cells. + fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec { + let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last); + columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect() + } + + #[test] + fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &fitting); + let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0])); + assert!(shares[0] < 120.0, "the first column's share is below its least"); + assert!(raised[0] >= 120.0, "the first column keeps its least"); + assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow"); + assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights"); + assert_eq!(raised[3], shares[3], "the content column keeps its width"); + assert_eq!(raised.iter().sum::(), 300.0, "the row fills the grid and no more"); + } + + #[test] + fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]); + let widths = row_widths(&columns, &last); + assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least"); + assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room"); + assert_eq!(widths.iter().sum::(), 330.0, "the row is as wide as the least widths and no wider"); + } + + #[test] + fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &last); + let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0])); + assert_eq!(kept, shares); + } } From 55756099eefff805eb000a3101f1340a23d56776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:34:50 -0800 Subject: [PATCH 070/235] ui-contract: every row of a label group that stacks takes the stacked height When a FieldGroup's shared label column grows too wide for its room, each field puts its control under its label. The rows measured before the widest label read a narrower column in the measuring run, sat beside it and kept that height. The real run stacked them at the final column, so their controls overlapped the next row and their values were clipped to a 1 pt band. The label step now notes, in a measuring run, the widest column at which a row that placed its label beside the group's column (or indented a row after it, or left a hidden label's column empty) keeps that placement. When the group's final column is wider, the group reports its widths as unsettled and its rows run once more at them, as for a sized row that read a narrower column. A group whose rows all keep their placement runs as before. --- .../ui-contract/src/contract/label/place.rs | 22 ++++++-- crates/ui-contract/src/layout/column_group.rs | 31 +++++++++-- crates/ui-contract/src/layout/mod.rs | 2 +- crates/ui-widgets/tests/it/label/mod.rs | 1 + crates/ui-widgets/tests/it/label/stacked.rs | 55 +++++++++++++++++++ 5 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/stacked.rs diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 47f510ece6..256e480322 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -59,6 +59,7 @@ pub(super) fn hidden_control(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flo } match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { Some(column) if input.room >= column + gap + input.control_min => { + crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); let (_, rest) = flow.take_start(column); rest.take_start(gap).1.rect() } @@ -75,7 +76,10 @@ fn after_indent(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, gap: f32) - return 0.0; } match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { - Some(column) if input.room >= column + gap + input.control_min => column + gap, + Some(column) if input.room >= column + gap + input.control_min => { + crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); + column + gap + } _ => 0.0, } } @@ -107,15 +111,17 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop)); return Placed { label, control: cell, trailing: Rect::NOTHING, caption: 0.0 }; } + let key = if glyph { crate::layout::GLYPHS } else { crate::layout::LABELS }; + let mut read = false; let (column, stack_below) = match input.side.layout { FieldLayout::Beside => { let own = natural.x; // An inline form shares no label column unless it asks for one ([`CaptionColumn`]): each caption is as wide // as its own text. let shared = env.values.get::() != LabelScheme::Inline || env.values.get::().shared(); - let width = crate::layout::ambient_width(ctx, &if glyph { crate::layout::GLYPHS } else { crate::layout::LABELS }, own) - .filter(|width| shared && *width > 0.0) - .unwrap_or(own); + let width = crate::layout::ambient_width(ctx, &key, own).filter(|width| shared && *width > 0.0); + read = width.is_some(); + let width = width.unwrap_or(own); (width, width + gap + input.control_min) } FieldLayout::Above => (natural.x, f32::INFINITY), @@ -132,8 +138,12 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let caption = if matches!(input.side.layout, FieldLayout::Above | FieldLayout::Caption(_)) { column } else { 0.0 }; // The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label // that never sits beside stacks in an unbounded room as well. - let stacks = (input.room < stack_below || stack_below == f32::INFINITY) - && !((input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside); + let pinned = (input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside; + let stacks = (input.room < stack_below || stack_below == f32::INFINITY) && !pinned; + // A label that sits beside the group's column measured so far stacks once the column passes this. + if read && !stacks && !pinned { + crate::layout::note_beside(ctx, &key, input.room - gap - input.control_min); + } // A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own. let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column }; // A beside label that does not stack takes its column, the gap and the control's least, past the row's end where diff --git a/crates/ui-contract/src/layout/column_group.rs b/crates/ui-contract/src/layout/column_group.rs index 105f6af610..7f5fefb513 100644 --- a/crates/ui-contract/src/layout/column_group.rs +++ b/crates/ui-contract/src/layout/column_group.rs @@ -114,8 +114,10 @@ enum Frame { /// sits after (in order from the start edge), the widest the row reaches past them (see [`report_beyond`]). /// `early`: per column, the narrowest width a row that shows at its measured width read in a measuring run: a /// label column read by a row of a `sized` Through frame inside, any other column read by any row. + /// `stays`: per label column, the widest the column could be for every row that placed its label beside it in a + /// measuring run to keep it there (`note_beside`). /// `depth`: the measuring runs open when the group opened (`layout_memory::depth`). - Group { id: Id, widest: Columns, beyond: HashMap, f32>, early: Columns, room: Option, depth: usize }, + Group { id: Id, widest: Columns, beyond: HashMap, f32>, early: Columns, stays: Columns, room: Option, depth: usize }, /// A plain container's body in the group around it: its rows read and report that group's widths, as the rows /// directly in the group do. Their reaches past the columns stay here, and the container hands them on to the /// frame around it (`Reached`). `room`: the width the container was offered. `sized`: the container shows at the @@ -198,7 +200,7 @@ fn column_group(grid: Id, column: usize) -> Id { /// Closes `frame`, a group a measuring run opened: records its widest width per column for the rows of the real run, /// and returns what its rows found. Any other frame found nothing. fn close(ctx: &Context, frame: Frame) -> Scoped { - let Frame::Group { id, widest, beyond, early, .. } = frame else { return Scoped::default() }; + let Frame::Group { id, widest, beyond, early, stays, .. } = frame else { return Scoped::default() }; let mut widths = HashMap::new(); for (column, width) in widest { // A row whose record a later sweep reused reports nothing there, so the widest of the pass stands. @@ -210,7 +212,10 @@ fn close(ctx: &Context, frame: Frame) -> Scoped { .iter() .filter_map(|(columns, past)| columns.iter().map(|column| widths.get(column).copied()).sum::>().map(|sum| sum + past)) .reduce(f32::max); - let early = early.iter().any(|(column, read)| widths.get(column).is_some_and(|width| width > read)); + // A row measured beside a label column narrower than the group's final one stacks under the final column, and + // its measure is of the other placement. + let wider = |columns: &Columns| columns.iter().any(|(column, most)| widths.get(column).is_some_and(|width| width > most)); + let early = wider(&early) || wider(&stays); Scoped { extent, unsettled: early.then(|| widths.clone()), widths } } @@ -251,7 +256,7 @@ impl ColumnGroup { let depth = layout_memory::depth(ctx); let widest = seed.unwrap_or_default(); pass_state::with::(ctx, |open| { - open.0.push(Frame::Group { id, widest, beyond: HashMap::new(), early: HashMap::new(), room: None, depth }); + open.0.push(Frame::Group { id, widest, beyond: HashMap::new(), early: HashMap::new(), stays: HashMap::new(), room: None, depth }); }); ColumnGroup { id, ctx: ctx.clone() } } @@ -289,6 +294,7 @@ impl ColumnGroup { widest, beyond: HashMap::new(), early: HashMap::new(), + stays: HashMap::new(), room: None, depth, }); @@ -404,6 +410,23 @@ pub fn ambient_width(ctx: &Context, column: &ColumnKey, content: f32) -> Option< Some(width) } +/// Notes, in a measuring run, that a row of the group the innermost open frame reads placed its label beside column +/// `column`, and would stack its control under the label once the column is wider than `most`. When the group's final +/// width passes it, the row's measure is of the beside placement the real run does not give it, and the group's scope +/// returns its widths as unsettled. Nothing happens outside a measuring run or a group. +pub(crate) fn note_beside(ctx: &Context, column: &ColumnKey, most: f32) { + if !crate::runtime::measure::active(ctx) { + return; + } + let Some((group, _)) = pass_state::with::(ctx, |open| open.innermost(std::slice::from_ref(column))) else { return }; + pass_state::with::(ctx, |open| { + if let Some(Frame::Group { stays, .. }) = open.0.iter_mut().rev().find(|frame| matches!(frame, Frame::Group { id, .. } if *id == group)) { + let stays = stays.entry(column.clone()).or_insert(most); + *stays = stays.min(most); + } + }); +} + /// The width the innermost open frame's container was offered, `None` when no label group is open, a barrier or a /// field's body is, or the container recorded none. pub(crate) fn ambient_room(ctx: &Context) -> Option { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 2895b9f4da..a11ff15e8f 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -13,7 +13,7 @@ pub use column_group::ColumnGroup; pub use column_group::ambient_width; #[doc(hidden)] pub use column_group::report_beyond; -pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room}; +pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room, note_beside}; pub use label::{control_baseline, place_label, record_control_baseline}; pub use slot::measure_slot; diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 37af7d23db..0ab8b3540e 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod reset; pub(crate) mod scheme; pub(crate) mod scrub_drags; pub(crate) mod short; +pub(crate) mod stacked; pub(crate) mod tooltip; use self::kit::{Dial, Field, Seen, Wide}; diff --git a/crates/ui-widgets/tests/it/label/stacked.rs b/crates/ui-widgets/tests/it/label/stacked.rs new file mode 100644 index 0000000000..dbace1561b --- /dev/null +++ b/crates/ui-widgets/tests/it/label/stacked.rs @@ -0,0 +1,55 @@ +//! A group whose label column is too wide for its room puts every row's control under its label: the rows measured +//! before the widest label take the stacked height too. + +use craft_theme::Size; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::{Rect, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; + +/// The rows of the group, with the widest label last, and the value each field shows. +const ROWS: [(&str, f64); 3] = [("Width", 11.0), ("Corner radius", 22.0), ("Maximum number of layers", 33.0)]; + +fn control(fixture: &Fixture, name: &str) -> Rect { + fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect +} + +fn caption(fixture: &Fixture, text: &str) -> Rect { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text:?} is painted")) +} + +/// In a group 240 pt wide, the last row's label is too wide to sit beside a control, so every row stacks. Each field +/// shows under its label and above the next row, and its value shows whole, not clipped to the row it measured +/// beside a narrower column. +#[trial] +fn every_row_of_a_group_that_stacks_takes_the_stacked_height() { + let mut fixture = Fixture::new(|ui| { + FieldGroup::new("Shape").show(ui, |ui, _| { + for (name, value) in ROWS { + Field::new(name).show(ui, |ui, _| NumberField::new(name, Bind::given(Some(value))).show(ui)); + } + }); + }); + fixture.room(Vec2::new(240.0, 600.0)).density(Size::Comfortable); + fixture.settle(); + let mut above = f32::NEG_INFINITY; + for (name, value) in ROWS { + let (label, field) = (caption(&fixture, name), control(&fixture, name)); + assert!(label.max.y <= field.min.y + SLACK, "{name}'s field shows under its label: {label:?} {field:?}"); + assert!(label.min.y >= above - SLACK, "{name}'s row starts under the field before: {label:?} {above}"); + above = field.max.y; + let digits = format!("{value}"); + let texts = fixture.texts(); + let run = texts.iter().find(|run| run.text.starts_with(&digits)).unwrap_or_else(|| panic!("{digits:?} is painted: {texts:?}")); + assert!( + run.clip.min.y <= run.rect.min.y + SLACK && run.clip.max.y >= run.rect.max.y - SLACK, + "{name}'s value shows whole: {:?} under the clip {:?}", + run.rect, + run.clip + ); + } +} From 7f8fec0e549a3cb4cd07e4600c22754ae4472e4c Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:49:06 +0000 Subject: [PATCH 071/235] menu gallery: the current tile is outlined in the accent, with no fill The current tile of a gallery was a state.selected fill inside a line.control_edge edge, which on the Styles gallery read as a grey tile. It is now a thin outline in accent.border, the colour a selected icon button's outline takes, and the tile keeps its own background. The outline is still a shape, so the current tile is not marked by colour alone. Reference: storytold/wordcraft#7678. Co-Authored-By: Claude Sonnet 5.5 --- crates/menu/src/ribbon/gallery.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 4375f7053b..33515f33b4 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -366,11 +366,7 @@ struct GalleryTileStyle { focus: FocusLook, /// Between the tile's edge and its picture. pad: f32, - /// The selection edge's width. - stroke: f32, - /// The current tile's fill. - fill: StyleColor, - /// The current tile's edge. + /// The current tile's outline: accent, unfilled, so the picture keeps its own background. edge: StyleColor, /// The ink of the item's name under the picture, in a captioned gallery. caption: StyleColor, @@ -443,9 +439,7 @@ impl Component for GalleryTile<'_> { metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)), focus: cx.focus_look(), pad, - stroke: cx.tokens.stroke.thin, - fill: cx.color(colors.state.selected), - edge: cx.color(colors.line.control_edge), + edge: cx.color(colors.accent.border), caption: cx.color(colors.text.normal), gap: cx.tokens.space.gap.tight, thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg], @@ -472,9 +466,7 @@ impl Component for GalleryTile<'_> { } if self.selected { let outer = area.expand(cx.style.pad); - let draw = ui.draw(); - draw.fill(&PaintShape::Rect(outer, CornerRadius::ZERO), cx.style.edge); - draw.fill(&PaintShape::Rect(outer.shrink(cx.style.stroke), CornerRadius::ZERO), cx.style.fill); + ui.draw().stroke(&PaintShape::Rect(outer, CornerRadius::ZERO), craft_ui::primitives::StrokeWidth::Thin, cx.style.edge); } // A captioned tile keeps the picture's height at the top and shows the name in the rest under it. let (area, caption) = match self.caption { From f7ddd9957a5de5b5af7d90bb82711caf6149b367 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:50:25 +0000 Subject: [PATCH 072/235] ui-canvas rulers: a centimetre document ruler labels every whole centimetre TickRule::of_unit gave centimetres the generic metric rule, whose least label step is 60 points, so at 100% (1 cm is about 28 points) the page and text rulers labelled every 2 cm. Add TickRule::Centimetres for document rulers: labels every centimetre down to 24 points apart, thinning to 2, 5, 10 and so on when zoomed out, with quarter-centimetre ticks (halves when tighter), as WordCraft v0.18.1 drew. Canvas and image rulers keep TickRule::Metric. Fixes storytold/wordcraft#7686. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-canvas/src/canvas/mod.rs | 3 ++- crates/ui-canvas/src/canvas/rulers/mod.rs | 2 +- crates/ui-canvas/src/canvas/rulers/ticks.rs | 30 +++++++++++++++++++-- crates/ui-canvas/tests/it/canvas/rulers.rs | 22 +++++++++++++-- 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 88a0dd64db..bf6c136d8a 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -82,7 +82,8 @@ pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view}; pub(crate) mod rulers; pub(crate) mod scrollbars; pub use rulers::{ - INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, RulersOutput, StepLadder, TickRule, + CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, + RulersOutput, StepLadder, TickRule, }; pub use scrollbars::{CanvasScrollbars, CanvasScrollbarsOutput}; diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index 96acf884f3..811a86d813 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -6,7 +6,7 @@ pub(crate) mod stories; mod ticks; -pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; +pub use ticks::{CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; use super::words::CanvasWords; use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, context_menu, readout}; diff --git a/crates/ui-canvas/src/canvas/rulers/ticks.rs b/crates/ui-canvas/src/canvas/rulers/ticks.rs index 2d0355edb5..1566afd8a4 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks.rs +++ b/crates/ui-canvas/src/canvas/rulers/ticks.rs @@ -13,6 +13,14 @@ pub const INCH_EIGHTHS: [u32; 3] = [8, 4, 2]; /// The least distance between labelled ticks, in points. pub const LABEL_STEP_MIN: f32 = 60.0; +/// The least distance between labelled ticks of a centimetre document ruler, in points: a whole centimetre at 100% +/// (about 28 points) is labelled, as Word's ruler does. +pub const CENTIMETRE_LABEL_STEP_MIN: f32 = 24.0; +/// The least distance between ticks of a centimetre document ruler, in points. +const CENTIMETRE_TICK_STEP_MIN: f64 = 4.0; +/// Labelled centimetre steps: 1, 2, 5, 10 times the base. +const CENTIMETRE_STEPS: [f64; 9] = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0]; + /// The metric rule's subdivisions of a labelled step. const METRIC_SUBDIVISIONS: f32 = 10.0; /// Labelled inch steps in inches: 1, 2, 5, 10 times the base. @@ -71,6 +79,9 @@ impl StepLadder { pub enum TickRule<'a> { /// The units' own table ([`RulerUnits::step`]): decimal steps and ten subdivisions, or the host's custom table. Metric, + /// Centimetres of a document ruler: a label every centimetre (every 2, 5, 10 and so on when smaller), with quarter + /// centimetre ticks while they stay [`CENTIMETRE_TICK_STEP_MIN`] apart, then halves. + Centimetres, /// Inches: a label every inch (every 2, 5, 10 and so on when smaller), subdivided by the first of these counts, /// finest first, that keeps the ticks a tenth of the least label step apart ([`INCH_SIXTEENTHS`], /// [`INCH_EIGHTHS`]). @@ -81,9 +92,14 @@ pub enum TickRule<'a> { } impl TickRule<'static> { - /// The rule for a ruler counting `kind`: Word's sixteenths for inches, `Metric` otherwise. + /// The rule for a document ruler counting `kind`: Word's sixteenths for inches, whole labelled centimetres for + /// centimetres, `Metric` otherwise. pub fn of_unit(kind: UnitKind) -> TickRule<'static> { - if kind == UnitKind::Inches { TickRule::Inches(&INCH_SIXTEENTHS) } else { TickRule::Metric } + match kind { + UnitKind::Inches => TickRule::Inches(&INCH_SIXTEENTHS), + UnitKind::Centimetres => TickRule::Centimetres, + _ => TickRule::Metric, + } } } @@ -112,6 +128,15 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { (step, subdivisions) } +/// The labelled centimetre step and its subdivisions at `points_per_cm` screen points per centimetre. +fn centimetre_step(points_per_cm: f64) -> (f64, u32) { + let step_min = f64::from(CENTIMETRE_LABEL_STEP_MIN); + let step = CENTIMETRE_STEPS.into_iter().find(|step| step * points_per_cm >= step_min).unwrap_or(1000.0); + let subdivisions = + if step > 1.0 { 2 } else { [4_u32, 2].into_iter().find(|n| points_per_cm / f64::from(*n) >= CENTIMETRE_TICK_STEP_MIN).unwrap_or(1) }; + (step, subdivisions) +} + /// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a /// text ruler or a page view's ruler shows the same ticks as the canvas's. One labelled step beyond each end is /// included, since a label starts right of its tick. `zoom` is screen points per document unit along the axis, as @@ -119,6 +144,7 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { pub fn ticks(units: &RulerUnits, rule: TickRule<'_>, zoom: f64, values: RangeInclusive) -> Vec { let (step, subdivisions) = match rule { TickRule::Metric => units.step(zoom, LABEL_STEP_MIN), + TickRule::Centimetres => centimetre_step(zoom / units.per_doc), TickRule::Inches(finest) => inch_step(zoom / units.per_doc, finest), TickRule::Steps(ladder) => { let (tick, label) = ladder.steps(zoom / units.per_doc); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 16aa582880..5fe156210e 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -4,8 +4,8 @@ use craft_behavior::geometry::{SnapOptions, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_behavior::{CancelReason, CanvasView, RulerUnits, TickLabels, Ticks}; use craft_ui::canvas::{ - Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, StepLadder, TickRule, - ToolAction, ToolContext, ToolPath, ToolPointer, + CENTIMETRE_LABEL_STEP_MIN, Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, + StepLadder, TickRule, ToolAction, ToolContext, ToolPath, ToolPointer, }; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::TickRank; @@ -60,6 +60,24 @@ fn labelled_ticks_never_touch_at_any_zoom() { } } +/// A document ruler labels every whole centimetre at 100% (28.35 points each), and thins the labels out when zoomed +/// out so they never touch. +#[trial] +fn a_centimetre_document_ruler_labels_each_centimetre_and_thins_out_zoomed_out() { + let centimetres = RulerUnits::new(2.54 / 72.0, Ticks::decimal(false)); + let rule = TickRule::of_unit(UnitKind::Centimetres); + let at_full = least_label_gap(¢imetres, rule, 1.0); + assert!(at_full < f64::from(LABEL_STEP_MIN), "labels at 100% are closer than the generic metric step: {at_full}"); + let one_cm = 72.0 / 2.54; + assert!((at_full - one_cm).abs() < 1e-6, "labels at 100% are one centimetre apart: {at_full}"); + let least = f64::from(CENTIMETRE_LABEL_STEP_MIN) - 1e-9; + for zoom in ZOOMS { + let gap = least_label_gap(¢imetres, rule, zoom); + assert!(gap >= least, "centimetre labels at zoom {zoom}: {gap} points apart"); + } + assert!(least_label_gap(¢imetres, rule, 0.25) > at_full, "labels thin out when zoomed out"); +} + /// A vertical label stacks its characters one label-role size apart; the longest label the metric rule gives at the /// least step (five characters) and its gap to the tick stay inside that step, so neighbouring labels never touch. #[trial] From 4c6c3bb6e18f65c6492f2da02a104202d688e2ff Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:57:07 +0000 Subject: [PATCH 073/235] menu gallery: scroll and more arrows show the small glyph, not the ribbon's icon side The Styles gallery's up, down and more buttons are icon buttons, and in a ribbon an icon-only button's glyph takes the ribbon's small icon side (17), which made the arrows far larger than the old ribbon's. A new GlyphRole::Compact shows the glyph at size.icon.glyph_sm whatever the control size and skips that ribbon side; the gallery sets it on its three buttons, and on the one it measures. Other icon buttons are unchanged. Reference: storytold/wordcraft#7679. Co-Authored-By: Claude Sonnet 5.5 --- crates/menu/src/ribbon/gallery.rs | 10 +++++----- crates/ui-contract/src/style/cx.rs | 3 +++ crates/ui-widgets/src/buttons/face.rs | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 4375f7053b..f026ac82a0 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -19,7 +19,7 @@ use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails}; use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun}; use craft_ui::runtime::env::Label; use craft_ui::runtime::focus::KeyUse; -use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole}; +use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, TypeRole}; use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid}; use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2}; @@ -189,7 +189,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes { let words = cx.env.words::(); - let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone())); + let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact)); Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.thumb_size, self.captioned())), button, gap: cx.gap() } } } @@ -723,9 +723,9 @@ impl Component for Gallery<'_, K> draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1)); draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2)); } - ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0)); - ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last)); - ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone())); + ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0).glyphs(GlyphRole::Compact)); + ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last).glyphs(GlyphRole::Compact)); + ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact)); } /// The context request is recorded after `update`, so `finish` reads it: a secondary click on a tile, or the Menu diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index d5ab7c55ea..021e3249d9 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -38,6 +38,9 @@ pub enum GlyphRole { ToolRail, /// A list row's trailing icon button: the control glyph, resting in `text.faint` and in the variant's ink under the pointer. PanelRail, + /// A stack of small arrow buttons (a gallery's scroll arrows): `size.icon.glyph_sm` whatever the control size, and + /// a ribbon's small icon side does not widen it. + Compact, } /// What `fn style` gets. Tokens are read here and nowhere else. diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs index d1070aa957..b27b517c08 100644 --- a/crates/ui-widgets/src/buttons/face.rs +++ b/crates/ui-widgets/src/buttons/face.rs @@ -407,9 +407,10 @@ pub(crate) fn icon_face(cx: &StyleCx<'_>) -> IconFace { GlyphRole::Tool => (icon.md, None), GlyphRole::ToolRail => (icon.lg, Some(text.muted)), GlyphRole::PanelRail => (cx.glyph(), Some(text.faint)), + GlyphRole::Compact => (icon.glyph_sm, None), _ => (cx.glyph(), None), }; - let side = super::small_icon(cx, side); + let side = if cx.glyph_role() == GlyphRole::Compact { side } else { super::small_icon(cx, side) }; let mut ink = off.text.clone(); if let Some(rest) = rest { ink.off.rest = cx.color(rest); From f2656d986137ceb0ed89c8bd0d79255cb1861d10 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:57:22 +0000 Subject: [PATCH 074/235] ui-widgets: icon button reads in a side menu's ink IconButton ignored ControlPlace::SideMenu: only Button took the menu's on-strong ink and brand-surface bands, so WordCraft's File rail Back arrow drew in the dark ghost ink on the blue rail and was almost invisible. Move the ink and band fills into side_menu_ink and use it from both. The glyph keeps tinted(), so a multi-colour icon keeps its own colours as in Button. Disabled stays the ink at the menu's disabled alpha. Refs storytold/wordcraft#7707 Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-widgets/src/buttons/button.rs | 31 +++++++++++------- crates/ui-widgets/src/buttons/icon_button.rs | 12 +++++-- crates/ui-widgets/tests/it/buttons.rs | 34 ++++++++++++++++++++ 3 files changed, 63 insertions(+), 14 deletions(-) diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 10060b7bc1..9609fa8e19 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -289,6 +289,23 @@ impl<'a> Button<'a> { } } +/// A side menu stands on the brand surface: its names and icons read in the ink of strong fills, a disabled page's +/// dimmed, and its bands are that ink laid thinly over the brand colour (hover lighter than the page shown), not the +/// panel's state fills, which painted a light band with dark text over the rail. The row of the page shown (`on`) +/// keeps its band, so the menu marks where the page is. Returns the ink and the band fill, for every control of the +/// place (`Button`, `IconButton`). +pub(super) fn side_menu_ink(cx: &StyleCx<'_>) -> (craft_theme::Stateful, craft_theme::Stateful) { + let ink = cx.tokens.color.text.on_strong; + let (rest, dim) = (cx.color(ink), cx.color(ink.with_alpha(SIDE_MENU_DISABLED_ALPHA))); + let text = craft_theme::Stateful::new(rest).off(craft_theme::States::new(rest, rest, rest, dim)); + let (clear, hover, shown) = + (cx.color(Rgba::TRANSPARENT), cx.color(ink.with_alpha(SIDE_MENU_HOVER_ALPHA)), cx.color(ink.with_alpha(SIDE_MENU_SHOWN_ALPHA))); + let fill = craft_theme::Stateful::new(clear) + .off(craft_theme::States::new(clear, hover, shown, clear)) + .on(craft_theme::States::new(shown, shown, shown, shown)); + (text, fill) +} + impl Component for Button<'_> { const ROLE: Role = Role::BUTTON; const OVERLAYS: bool = false; @@ -330,13 +347,7 @@ impl Component for Button<'_> { let pad = &cx.tokens.space.pad; style.text.role = TypeRole::BodyLarge; style.metrics.padding = Insets::new(pad.roomy, pad.roomy, pad.segment, pad.segment); - // A side menu stands on the brand surface: its names and icons read in the ink of strong fills, a disabled - // page's dimmed, and its bands are that ink laid thinly over the brand colour (hover lighter than the page - // shown), not the panel's state fills, which painted a light band with dark text over the rail. The row of - // the page shown (`selected`) keeps its band, so the menu marks where the page is. - let ink = cx.tokens.color.text.on_strong; - let (rest, dim) = (cx.color(ink), cx.color(ink.with_alpha(SIDE_MENU_DISABLED_ALPHA))); - let text = craft_theme::Stateful::new(rest).off(craft_theme::States::new(rest, rest, rest, dim)); + let (text, fill) = side_menu_ink(cx); style.text.color = text.clone(); // A place's icon is the large icon, not a control's standard one, set off from its name by a section gap: a // list of places reads by its icons (WordCraft's File rail: 18 pt icons, nearest token 20 pt, 12 pt before 14 pt names). @@ -344,11 +355,7 @@ impl Component for Button<'_> { // The face paints by its gap and the measure by the metrics', so the two stay one. style.face.gap = style.face.gap.max(cx.tokens.space.gap.section); style.metrics.gap = style.face.gap; - let (clear, hover, shown) = - (cx.color(Rgba::TRANSPARENT), cx.color(ink.with_alpha(SIDE_MENU_HOVER_ALPHA)), cx.color(ink.with_alpha(SIDE_MENU_SHOWN_ALPHA))); - style.surface.fill = craft_theme::Stateful::new(clear) - .off(craft_theme::States::new(clear, hover, shown, clear)) - .on(craft_theme::States::new(shown, shown, shown, shown)); + style.surface.fill = fill; } style } diff --git a/crates/ui-widgets/src/buttons/icon_button.rs b/crates/ui-widgets/src/buttons/icon_button.rs index 0dec4ab37f..cbf0e0fe5b 100644 --- a/crates/ui-widgets/src/buttons/icon_button.rs +++ b/crates/ui-widgets/src/buttons/icon_button.rs @@ -172,11 +172,19 @@ impl Component for IconButton<'_> { fn style(cx: &StyleCx<'_>, _: IconButtonStyleKey) -> IconButtonStyle { let face = face::icon_face(cx); let marker = MarkerStyle::of(cx); + let (mut surface, mut glyph) = (face.surface, face.glyph); + // On a side menu's brand surface the glyph reads in the menu's ink and its bands lie over the brand colour, as a + // `Button` row's do. + if cx.env::() == super::ControlPlace::SideMenu { + let (ink, fill) = super::button::side_menu_ink(cx); + glyph.color = ink; + surface.fill = fill; + } IconButtonStyle { - surface: face.surface, + surface, metrics: face.metrics, focus: face::focus(cx), - glyph: face.glyph, + glyph, marker: marker.side, marker_color: marker.color, marker_edge: marker.edge, diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 144252af84..dcba8e7fb8 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -647,6 +647,40 @@ fn a_side_menus_row_shows_the_standard_icon() { assert!(menu > plain, "a side menu's icon is the standard one: {menu} against {plain}"); } +/// An icon-only button in a side menu (WordCraft's Back arrow on the File rail) reads in the menu's ink, as a `Button` +/// row's icon does, not in the dark ghost ink that vanished on the brand surface; elsewhere it keeps its own ink. +#[trial] +fn a_side_menus_icon_button_reads_in_the_menus_ink() { + let rest = |side: bool, icon_only: bool| { + let mut fixture = Fixture::new(move |ui| { + let show = |ui: &mut Ui| { + if icon_only { + let _ = IconButton::new(IconId::new("print")).label("Back").show(ui); + } else { + let _ = Button::new("Print").icon(IconId::new("print")).variant(Variant::GHOST).show(ui); + } + }; + if side { + with_env( + ui, + |overrides| { + overrides.values.set(ControlPlace::SideMenu); + }, + show, + ); + } else { + show(ui); + } + }); + fixture.settle(); + let kind = if icon_only { std::any::type_name::>() } else { std::any::type_name::>() }; + let style = fixture.styles_of(kind).into_iter().next().expect("the button resolved its style"); + style.looks.icons.first().expect("the button has an icon look").color.off.rest.egui() + }; + assert_eq!(rest(true, true), rest(true, false), "the icon button takes the ink of the menu's rows"); + assert_ne!(rest(true, true), rest(false, true), "outside a side menu it keeps its own ink"); +} + /// A split button's body that closes itself (a colour palette's swatch pick) closes the split's menu layer: before, /// the close reached only the inline menu inside the layer, which stayed open around an empty body. Opened again, the /// body shows its rows. From 9a2615d2d97874a9844a6def9d366cec3e85921a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:06:27 -0800 Subject: [PATCH 075/235] ui-widgets, ui-panels: a focused disclosure or tool rail button shows the focus ring A Disclosure and a FlyoutButton (a tool rail slot) take keyboard focus, but neither style held a focus look. The paint step draws the focus ring only for a style that has one, so after Tab neither control showed where focus was. Both styles now take the theme's focus look, as Link and the breadcrumb bar do, and the paint step draws the ring around each control's rect. A disclosure painted as part of a list row, tree row, title row or grid header is a face, which draws no ring, so those rows look as before. FlyoutButtonStyle no longer derives Default, since the focus look has no default. --- crates/ui-panels/src/rails/flyout.rs | 17 +++++++++++---- crates/ui-panels/tests/it/rails/mod.rs | 23 ++++++++++++++++++++ crates/ui-widgets/src/controls/disclosure.rs | 6 +++-- crates/ui-widgets/tests/it/focus_ring.rs | 22 +++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index b96af1e160..619abb756f 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -14,7 +14,7 @@ use crate::menu::{self, Menu, MenuItem}; use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; @@ -30,12 +30,16 @@ const MARK: PartKey = PartKey::new("mark"); const BAR: PartKey = PartKey::new("bar"); /// The style of a flyout button: it paints through its face, so it holds no look of its own besides its side, the rail -/// button's, and the size of the corner mark's press area, which is the size and the inset of the mark the face paints. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// button's, its focus ring, and the size of the corner mark's press area, which is the size and the inset of the mark +/// the face paints. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct FlyoutButtonStyle { #[style(metrics)] metrics: Metrics, + /// The ring the button shows while it has keyboard focus: a face paints none. + #[style(focus)] + focus: FocusLook, /// The side of the corner mark, which is also its inset from the face's corner. mark: f32, /// The button's glyph role, which its face shows the icon in. @@ -235,7 +239,12 @@ impl Component for FlyoutButton<'_, T> { fn style(cx: &StyleCx<'_>, _: FlyoutButtonStyleKey) -> FlyoutButtonStyle { let side = cx.env::().button(cx.tokens); - FlyoutButtonStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), mark: cx.tokens.space.gap.tight, glyphs: cx.glyph_role() } + FlyoutButtonStyle { + metrics: Metrics::new().min_size(Vec2::splat(side)), + focus: cx.focus_look(), + mark: cx.tokens.space.gap.tight, + glyphs: cx.glyph_role(), + } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 24d4dcca32..9494807aeb 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -149,6 +149,29 @@ fn the_current_tools_button_reports_pressed_and_the_others_not() { assert_eq!(pressed("Cut"), Some(Mixed::Same(false)), "another tool's button reports that it is not"); } +/// A rail button with keyboard focus is ringed as a button is: a focus stroke of two points around its own rect. +#[trial] +fn a_focused_rail_button_shows_the_focus_ring_around_it() { + let all = tools(&[UNDO, REDO]); + let mut fixture = Fixture::new(move |ui| { + FlyoutButton::new(&all, &UNDO).show(ui); + }); + fixture.settle(); + let ring = |fixture: &mut Fixture| { + fixture.frame_shapes().iter().find_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + _ => None, + }) + }; + assert!(ring(&mut fixture).is_none(), "an unfocused rail button has no ring"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.focused().is_some(), "Tab focused the rail button"); + let target = fixture.by_role(Role::BUTTON).into_iter().next().expect("the rail button shows"); + let ring = ring(&mut fixture).expect("the focused rail button paints a focus ring"); + assert!(ring.expand(1.0).contains_rect(target.rect), "the ring {ring:?} goes around the button {:?}", target.rect); +} + /// With a click command a click, Enter or Space fires it and selects nothing; a hold, a drag away and a right click /// list the tools, and the release that ends a hold fires nothing. #[trial] diff --git a/crates/ui-widgets/src/controls/disclosure.rs b/crates/ui-widgets/src/controls/disclosure.rs index 6785bf03a1..16ff31972c 100644 --- a/crates/ui-widgets/src/controls/disclosure.rs +++ b/crates/ui-widgets/src/controls/disclosure.rs @@ -5,7 +5,7 @@ use crate::contract::{ Animate as _, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Pointer as _, Role, Styled as _, spec, }; use crate::primitives::{Glyph, PaintShape, StrokeWidth}; -use crate::style::{ComponentStyle, IconLook, StyleCx, UiTokens, ink_color, rgba_color}; +use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, UiTokens, ink_color, rgba_color}; use craft_behavior::{Metrics, Sense}; use craft_i18n::Direction; use egui::emath::GuiRounding as _; @@ -190,6 +190,8 @@ impl Glyph for DisclosureGlyph { pub struct DisclosureStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The triangle. #[style(icon)] glyph: IconLook, @@ -223,7 +225,7 @@ impl Component for Disclosure<'_> { fn style(cx: &StyleCx<'_>, _: DisclosureStyleKey) -> DisclosureStyle { let side = cx.control().icon; - DisclosureStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), glyph: IconLook::new(side, cx.quiet_ink()) } + DisclosureStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), focus: cx.focus_look(), glyph: IconLook::new(side, cx.quiet_ink()) } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { diff --git a/crates/ui-widgets/tests/it/focus_ring.rs b/crates/ui-widgets/tests/it/focus_ring.rs index 0c45a55142..c09225d910 100644 --- a/crates/ui-widgets/tests/it/focus_ring.rs +++ b/crates/ui-widgets/tests/it/focus_ring.rs @@ -31,3 +31,25 @@ fn the_focus_ring_is_two_points_thick() { let width = widest_stroke(&mut fixture); assert!((width - 2.0).abs() < 0.01, "the ring is the theme's focus stroke of two points: {width}"); } + +/// A disclosure with keyboard focus is ringed as a button is: a focus stroke around its own rect. +#[trial] +fn a_focused_disclosure_shows_the_focus_ring_around_it() { + use craft_ui::contract::{Bind, Props as _, Role}; + use craft_ui::controls::disclosure::Disclosure; + let mut fixture = Fixture::new(|ui| { + let _ = Disclosure::new(Bind::given(false)).label("Details").show(ui); + }); + fixture.settle(); + assert!(widest_stroke(&mut fixture) < 2.0, "an unfocused disclosure has no thick line"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.focused().is_some(), "Tab focused the disclosure"); + let target = fixture.by_role(Role::BUTTON).into_iter().next().expect("the disclosure shows"); + let ring = fixture.frame_shapes().iter().find_map(|shape| match shape { + Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + _ => None, + }); + let ring = ring.expect("the focused disclosure paints a focus ring"); + assert!(ring.expand(1.0).contains_rect(target.rect), "the ring {ring:?} goes around the disclosure {:?}", target.rect); +} From 9dfaf04f0275a000ae5c0408ed8ce6ae219fb7a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:16:48 -0800 Subject: [PATCH 076/235] draw: the Bezier overlay counts other paths' selected anchors instead of copying them for each path other_handles runs once per path when the overlay paints. For each path it built a new PathSelection by cloning every other path's anchor list and adding it with PathSelection::also, which searches the list it is building. With n paths in `others` one frame made about n^2 calls of also and n^2 vector clones, and also's search made the frame cubic in n. The rebuilt selection was only used to count the selected anchors for HandlesShown::OneAnchor. other_handles now sums the anchor counts of the other paths and passes the count to shown_handles_of, which shown_handles also calls with the selection's own count. The handles drawn do not change. With 1,500 selected rectangles in VectorCraft (every path but the first is in `others`), 28% of a profile's samples were in also, and about 120 hover frames after select all made 404,730,000 calls of it. Trial one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths checks the count with anchors listed in two other paths. --- crates/draw/src/ui/pen/bezier/hit_test.rs | 25 ++++++++++++++--------- crates/draw/tests/it/bezier.rs | 24 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/hit_test.rs b/crates/draw/src/ui/pen/bezier/hit_test.rs index 79bf7d2634..5c947df2d3 100644 --- a/crates/draw/src/ui/pen/bezier/hit_test.rs +++ b/crates/draw/src/ui/pen/bezier/hit_test.rs @@ -55,6 +55,11 @@ impl BezierOverlay<'_> { /// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection /// does not show. pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { + shown_handles_of(paths, sel, sel.selected_len(), handles, view) +} + +/// [`shown_handles`] with `selected` as the number of selected anchors that `OneAnchor` counts. +fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, handles: HandlesShown, view: &CanvasView) -> Vec { let mut shown = Vec::new(); for (index, path) in paths.iter().enumerate() { let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { @@ -71,7 +76,7 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha }; let wanted = match handles { HandlesShown::All => true, - HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(), + HandlesShown::OneAnchor => selected == 1 && of_selection(), HandlesShown::Selected => of_selection(), }; if wanted && !knot.retracted(side) { @@ -85,19 +90,19 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha /// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not /// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted. -/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. +/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per +/// path, so it reads the other paths' anchor counts from `sel` and copies none of their anchors. pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { let Some(path) = paths.get(at) else { return Vec::new() }; let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key)); let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() }; - let mut own = PathSelection::new(Some(path.key), anchors.clone(), None); - for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) { - own = own.also(*key, rest.clone()); - } - if let Some(edited) = sel.path.filter(|edited| *edited != path.key) { - own = own.also(edited, sel.anchors.clone()); - } - shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect() + let rest: usize = sel.others.iter().filter(|(key, _)| *key != path.key).map(|(_, rest)| rest.len()).sum(); + let edited = sel.path.filter(|edited| *edited != path.key).map_or(0, |_| sel.anchors.len()); + let own = PathSelection::new(Some(path.key), anchors.clone(), None); + shown_handles_of(std::slice::from_ref(path), &own, anchors.len() + rest + edited, handles, view) + .into_iter() + .map(|shown| Shown { path: at, ..shown }) + .collect() } /// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index aa17f19146..994fdcbeaf 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -465,6 +465,30 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() { assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}"); } +// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all +// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw. +#[trial] +fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() { + let painted_with = |selection: PathSelection, handles: HandlesShown| { + let mut other = path_b(); + other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0)); + let third = + EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]); + let mut h = harness(vec![path_a(), other, third]); + h.update(|st| (st.selection, st.handles) = (selection, handles)); + format!("{:?}", h.fixture.frame_shapes()) + }; + let one = || sel(1, &[]).also(2, vec![kr(0)]); + assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected)); + let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]); + assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected)); + assert_eq!( + painted_with(two(), HandlesShown::OneAnchor), + painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor), + "painting is the same from frame to frame" + ); +} + // Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at. // `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object. From 36f3188816ba48b9fc441825acb3c03ae8f327e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:22:39 -0800 Subject: [PATCH 077/235] ui-patterns: a FileListPicker in a short room keeps its buttons whole and the rows after it under them The picker filled the room it was given. In a room shorter than its column of buttons the stack cut the column to that room: the buttons after Browse got clip rects with negative heights, and the rows after the picker started over its buttons. In the param_rows story at 400 x 300 with comfortable density, Remove, Add Open Files and Sort By Name were clipped away and the Size row started at 306 pt while Sort By Name ended at 426 pt. The picker now fills the width only and takes the height its content needs, the taller of its list and its column of buttons. In a room that holds it, the list and the buttons stand where they stood. --- .../src/patterns/form_dialogs/file_list.rs | 6 +++-- .../tests/it/form_dialogs/files.rs | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/file_list.rs b/crates/ui-patterns/src/patterns/form_dialogs/file_list.rs index 65b8a02215..a6eefe0986 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/file_list.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/file_list.rs @@ -137,7 +137,9 @@ impl Outcome for FileListPickerOutput { /// Keys: the list is one Tab stop; arrows move the selection; Delete and Backspace remove the selected file; Cmd+] and /// Cmd+[ move it up and down (Ctrl off macOS; Shift to the ends). Dropped files are added by the dialog with [`FileList::add`]. /// -/// The list shows six rows and scrolls the rest. +/// The list shows six rows and scrolls the rest. The picker takes the width it is given and the height its content +/// needs: in a room shorter than its column of buttons, the buttons keep their height and the rows after the picker +/// start under them. #[must_use = "show the picker with `show`"] #[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] pub struct FileListPicker<'a> { @@ -180,7 +182,7 @@ impl<'a> FileListPicker<'a> { let FileListPicker { label, list, request, folder_mode, open_files, folder_files, info } = self; let words = Env::of(ui).words::(); let pass = RefCell::new(Pass { held: Held::new(list), seen: None, browsing: None }); - let mut stack = Stack::new().fill(); + let mut stack = Stack::new().fill_width(); if folder_mode { stack = stack.header(|ui, cx| { let mut pass = pass.borrow_mut(); diff --git a/crates/ui-patterns/tests/it/form_dialogs/files.rs b/crates/ui-patterns/tests/it/form_dialogs/files.rs index 00da7cfd2b..493a405620 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/files.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/files.rs @@ -2,10 +2,12 @@ //! answers them. use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; +use craft_theme::Size; use craft_ui::contract::Bind; use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FileList, FileListPicker, Param, ParamRows}; use craft_ui::runtime::requests::ListingRequest; use craft_ui::testing::{Fixture, trial}; +use egui::Rect; use std::cell::{Cell, RefCell}; use std::path::PathBuf; use std::rc::Rc; @@ -89,3 +91,27 @@ fn a_folder_row_asks_for_its_listing_once_per_folder_and_shows_the_answer() { assert_eq!(asked.borrow().len(), 1, "later passes ask for nothing"); assert!(fixture.by_label("dawn.png").is_some() && fixture.by_label("dusk.png").is_some(), "the answered files are listed"); } + +/// In a room shorter than its column of buttons, the picker keeps its list a positive height and shows each button +/// whole, one under another, inside the picker. +#[trial] +fn a_short_room_keeps_the_list_and_buttons_inside_the_picker() { + let picker = Rc::new(Cell::new(Rect::NOTHING)); + let shown = Rc::clone(&picker); + let mut list = FileList::default(); + list.add(paths(&["a.png", "b.png"])); + let mut fixture = Fixture::new(move |ui| shown.set(FileListPicker::new("Files to load", Bind::bound(&mut list)).show(ui).response.rect)); + fixture.density(Size::Comfortable).room(egui::vec2(400.0, 60.0)).settle(); + + let picker = picker.get(); + let files = fixture.by_label("Files").expect("the file list").rect; + assert!(files.height() > 0.0, "the list keeps a positive height: {files:?}"); + assert!(picker.contains_rect(files), "the list stays inside the picker: {files:?} in {picker:?}"); + let mut above = f32::NEG_INFINITY; + for name in ["Browse…", "Remove", "Add Open Files", "Sort By Name"] { + let button = fixture.by_label(name).unwrap_or_else(|| panic!("the {name} button")).rect; + assert!(button.height() > 0.0 && picker.contains_rect(button), "{name} shows whole inside the picker: {button:?} in {picker:?}"); + assert!(button.min.y >= above, "{name} stands under the button before it: {button:?}"); + above = button.max.y; + } +} From a2692197cb007479e160646e7d94bfa3fc080e68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:22:58 -0800 Subject: [PATCH 078/235] ui-panels: focused title row parts, dock chevrons, grips and dividers show the focus ring The paint step draws the focus ring only for a style that has a focus look, and no style in ui-panels had one. After Tab, these stops showed no ring: - a title row's disclosure or check box lead, commands and actions - a group grip, and a docked group's drag band and panel menu button - a dock column's chevron and its dividers - a dock window's chevron - a collapsed column's chevron, icon cells and edge divider - a split area's handles and the dividers between stacked sections Each of these styles now takes the theme's focus look, as Link and the breadcrumb bar do, and the paint step rings the focused part's rect. FloatingGroupStyle no longer derives Default, since the focus look has no default. --- crates/ui-panels/src/docking/dock_column.rs | 7 +- crates/ui-panels/src/docking/floating.rs | 13 +- crates/ui-panels/src/docking/group.rs | 12 +- crates/ui-panels/src/docking/iconic.rs | 6 +- crates/ui-panels/src/docking/mod.rs | 7 +- crates/ui-panels/src/docking/stack.rs | 7 +- crates/ui-panels/src/sections/title_row.rs | 6 +- crates/ui-panels/tests/it/focus/mod.rs | 1 + crates/ui-panels/tests/it/focus/rings.rs | 160 ++++++++++++++++++++ 9 files changed, 203 insertions(+), 16 deletions(-) create mode 100644 crates/ui-panels/tests/it/focus/rings.rs diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 5747b69c5f..2629923a03 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -15,7 +15,7 @@ use crate::contract::{ use crate::menu::GroupItem; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceEdge, SurfaceKind, SurfaceStyle, UiTokens}; +use crate::style::{ComponentStyle, Corners, FocusLook, StyleCx, SurfaceEdge, SurfaceKind, SurfaceStyle, UiTokens}; use crate::tabs::PanelTabLook; use craft_behavior::divider::{self as push, Segment}; use craft_behavior::dock::{Column, DockEdge, Group}; @@ -160,6 +160,9 @@ impl

Outcome for DockColumnOutput

{ pub struct DockColumnStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the chevron or the divider that has keyboard focus. + #[style(focus)] + focus: FocusLook, sizes: DockSizes, /// The card of a column shown as one ([`card`](DockColumn::card)). card: SurfaceStyle, @@ -469,7 +472,7 @@ impl Component for DockColumn<'_, P> { } fn style(cx: &StyleCx<'_>, _: DockColumnStyleKey

) -> DockColumnStyle { - DockColumnStyle { metrics: Metrics::new(), sizes: DockSizes::style(cx), card: card_style(cx) } + DockColumnStyle { metrics: Metrics::new(), focus: cx.focus_look(), sizes: DockSizes::style(cx), card: card_style(cx) } } fn sense(&self) -> Sense { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 7377e39240..9279bdc6d2 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -25,7 +25,7 @@ use crate::runtime::env::{Env, Label}; use crate::runtime::overlay::CloseReason; use crate::runtime::windows::{ResizeEdge, WindowSpec}; use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow}; -use crate::style::{ComponentStyle, StyleCx, SurfaceKind, UiTokens}; +use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceKind, UiTokens}; use craft_behavior::dock::DockEdge; use craft_behavior::{GesturePhase, IconId, Metrics, Sense}; use craft_ui_widgets::popover::WholeWindow; @@ -45,12 +45,15 @@ pub(crate) fn title_row(tokens: &UiTokens) -> f32 { /// title bar has beside its double arrow; the menu opens from the band. const ACTIONS: [HeaderAction; 1] = [HeaderAction::Close]; -/// The style of a floating group: the surface and padding come from the container. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// The style of a floating group: the surface and padding come from the container, and the ring from the theme. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct FloatingGroupStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the chevron while it has keyboard focus. + #[style(focus)] + focus: FocusLook, } /// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's @@ -511,8 +514,8 @@ impl Component for FloatingGroup<'_> { type Style = FloatingGroupStyle; type Output = FloatingGroupOutput; - fn style(_: &StyleCx<'_>, _: FloatingGroupStyleKey) -> FloatingGroupStyle { - FloatingGroupStyle::default() + fn style(cx: &StyleCx<'_>, _: FloatingGroupStyleKey) -> FloatingGroupStyle { + FloatingGroupStyle { metrics: Metrics::new(), focus: cx.focus_look() } } fn sense(&self) -> Sense { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 29c277e8ac..1883782f46 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -21,7 +21,7 @@ use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusRequest, FocusTarget}; use crate::runtime::memory::sub; use crate::sections::FooterBar; -use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; +use crate::style::{ComponentStyle, Corners, FocusLook, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; use crate::tabs::{PanelTabLook, Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{CursorIcon, CursorPriority, DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, GripMark, GripShape, Tokens}; @@ -37,6 +37,9 @@ use std::sync::Arc; pub struct GroupGripStyle { #[style(metrics)] metrics: Metrics, + /// The ring the grip shows while it has keyboard focus. + #[style(focus)] + focus: FocusLook, /// The marks a grip with [`ticks`](GroupGrip::ticks) shows. marks: GripMarks, } @@ -166,7 +169,7 @@ impl Component for GroupGrip

{ type Output = GroupGripOutput; fn style(cx: &StyleCx<'_>, _: GroupGripStyleKey

) -> GroupGripStyle { - GroupGripStyle { metrics: Metrics::new(), marks: GripMarks::style(cx) } + GroupGripStyle { metrics: Metrics::new(), focus: cx.focus_look(), marks: GripMarks::style(cx) } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { @@ -320,6 +323,9 @@ impl Outcome for DockGroupOutput { pub struct DockGroupStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the drag band or the panel menu button while it has keyboard focus. + #[style(focus)] + focus: FocusLook, header: f32, sizes: DockSizes, } @@ -506,7 +512,7 @@ impl Component for fn style(cx: &StyleCx<'_>, _: DockGroupStyleKey

) -> DockGroupStyle { let sizes = DockSizes::style(cx); - DockGroupStyle { metrics: Metrics::new(), header: sizes.strip, sizes } + DockGroupStyle { metrics: Metrics::new(), focus: cx.focus_look(), header: sizes.strip, sizes } } fn sense(&self) -> Sense { diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index f33dc4557b..3dceece46a 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -18,7 +18,7 @@ use crate::menu::GroupItem; use crate::primitives::{IconSpec, TextRun}; use crate::runtime::env::{Env, EnvValue, Label, with_env}; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, RuleKind, StyleColor, StyleCx, SurfaceKind, SurfaceStyle}; +use crate::style::{ComponentStyle, Corners, FocusLook, GlyphRole, RuleKind, StyleColor, StyleCx, SurfaceKind, SurfaceStyle}; use crate::tabs::PanelTabLook; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::overlay::Side; @@ -177,6 +177,9 @@ impl Outcome for IconicColumnOutput

{ pub struct IconicColumnStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the chevron, the icon cell or the edge divider that has keyboard focus. + #[style(focus)] + focus: FocusLook, sizes: IconicSizes, /// The ink of a panel's name in a wide column. name: StyleColor, @@ -549,6 +552,7 @@ impl Component for IconicColumn<'_, P> { let colors = &cx.tokens.color; IconicColumnStyle { metrics: Metrics::new(), + focus: cx.focus_look(), sizes: IconicSizes::style(cx), name: cx.color(colors.text.normal), name_open: cx.color(colors.accent.text), diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index cf6341c92c..eb3e4cb42b 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -75,7 +75,7 @@ use crate::runtime::commands::CommandRef; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; use crate::runtime::memory::sub; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::dock::{DockEdge, Layout, Node, SplitSize}; use craft_behavior::{Axis, EditEvents, Flow, Metrics, PartKey, Sense}; use divider::{Divider, Drag}; @@ -247,6 +247,9 @@ pub struct PanelDrag { pub struct SplitAreaStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the handle that has keyboard focus. + #[style(focus)] + focus: FocusLook, /// The docking sizes: the dividers' gap, reach and key steps, and the groups' least extent and strip. sizes: DockSizes, } @@ -416,7 +419,7 @@ impl Component for SplitAr type Output = SplitAreaOutput

; fn style(cx: &StyleCx<'_>, _: SplitAreaStyleKey

) -> SplitAreaStyle { - SplitAreaStyle { metrics: Metrics::new(), sizes: DockSizes::style(cx) } + SplitAreaStyle { metrics: Metrics::new(), focus: cx.focus_look(), sizes: DockSizes::style(cx) } } fn sense(&self) -> Sense { diff --git a/crates/ui-panels/src/docking/stack.rs b/crates/ui-panels/src/docking/stack.rs index 7837c814ca..5be2dfa929 100644 --- a/crates/ui-panels/src/docking/stack.rs +++ b/crates/ui-panels/src/docking/stack.rs @@ -7,7 +7,7 @@ use crate::contract::{ Access, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Pad, PaintUi, PartsCx, Role, Sizing, WordSetCx as _, }; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::divider::{self as push, Segment}; use craft_behavior::{Axis, Metrics, PartKey, Sense}; use egui::{Rect, Response}; @@ -99,6 +99,9 @@ pub fn section_heights(sections: &[StackSection], total: f32, header: f32) -> Ve pub struct StackSectionsStyle { #[style(metrics)] metrics: Metrics, + /// The ring around the divider that has keyboard focus. + #[style(focus)] + focus: FocusLook, sizes: DockSizes, } @@ -189,7 +192,7 @@ impl Component for StackSections { type Output = StackSectionsOutput; fn style(cx: &StyleCx<'_>, _: StackSectionsStyleKey) -> StackSectionsStyle { - StackSectionsStyle { metrics: Metrics::new(), sizes: DockSizes::style(cx) } + StackSectionsStyle { metrics: Metrics::new(), focus: cx.focus_look(), sizes: DockSizes::style(cx) } } fn sense(&self) -> Sense { diff --git a/crates/ui-panels/src/sections/title_row.rs b/crates/ui-panels/src/sections/title_row.rs index 4ec7e6297c..855da1723a 100644 --- a/crates/ui-panels/src/sections/title_row.rs +++ b/crates/ui-panels/src/sections/title_row.rs @@ -14,7 +14,7 @@ use crate::menu::Menu; use crate::primitives::{IconSpec, Span, TextRun}; use crate::runtime::commands::CommandRef; use crate::runtime::env::{EnvValue, Label}; -use crate::style::{ComponentStyle, IconLook, Ink, StyleCx, TextLook, TypeRole}; +use crate::style::{ComponentStyle, FocusLook, IconLook, Ink, StyleCx, TextLook, TypeRole}; use craft_behavior::{CursorIcon, Flow, IconId, Metrics, Mixed, NavShape, PartKey, Roving, Sense}; use craft_theme::variant::Tone; use craft_theme::{ControlSize, Stateful, States}; @@ -186,6 +186,9 @@ pub struct TitleRowStyle { icon: IconLook, /// The kind at the band's end: caption text in the faint text colour. subtitle: TextLook, + /// The ring around the lead, command or action part that has keyboard focus. + #[style(focus)] + focus: FocusLook, /// The side of an action part: the control height, which is below a tall header's height. action: f32, /// Whether the row is a quiet title's text row (`QuietTitleRow::Text`), as tall as it must be to hold its title @@ -397,6 +400,7 @@ impl Component for TitleRow<'_> { let faint = cx.color(text.faint); TextLook::new(TypeRole::Caption, Stateful::new(faint).off(States::new(faint, faint, faint, disabled))) }, + focus: cx.focus_look(), action: cx.control().height, text_row, } diff --git a/crates/ui-panels/tests/it/focus/mod.rs b/crates/ui-panels/tests/it/focus/mod.rs index fd2552ac98..01b1ae5b24 100644 --- a/crates/ui-panels/tests/it/focus/mod.rs +++ b/crates/ui-panels/tests/it/focus/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod dialog_tab; pub(crate) mod keys; pub(crate) mod press; +pub(crate) mod rings; pub(crate) mod roving; pub(crate) mod scopes; diff --git a/crates/ui-panels/tests/it/focus/rings.rs b/crates/ui-panels/tests/it/focus/rings.rs new file mode 100644 index 0000000000..ab8d4b073b --- /dev/null +++ b/crates/ui-panels/tests/it/focus/rings.rs @@ -0,0 +1,160 @@ +//! The focus ring of the panel family's focusable parts: Tab to each one and the paint step rings it, as it rings a +//! button. + +use craft_behavior::dock::{Column, DockEdge, Group}; +use craft_behavior::{Axis, PartKey}; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::docking::stack::{StackSection, StackSections}; +use craft_ui::docking::{ + DockColumn, DockGroup, DragUnit, FloatingGroup, GroupGrip, IconicColumn, PanelKey, PanelSpec, PanelTitle, SplitArea, Titles, WindowColumn, +}; +use craft_ui::menu::PanelRow; +use craft_ui::sections::{HeaderAction, Panel, TitleRow}; +use craft_ui::testing::memory::global; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Pos2, Rect, Shape, Vec2}; + +/// Presses Tab until a stop that `wanted` accepts holds the focus, and returns the rect of the focused part, or of +/// the focused component when the stop is a whole component. Panics when Tab never reaches one. +fn tab_to(fixture: &mut Fixture, wanted: impl Fn(Option) -> bool) -> Rect { + for _ in 0..16 { + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let Some((owner, part)) = fixture.focused_stop() else { continue }; + if !wanted(part.map(|part| part.key)) { + continue; + } + let rect = match part { + Some(part) => fixture.part_rect(owner, part), + None => fixture.node_of(owner).map(|target| target.rect), + }; + return rect.unwrap_or_else(|| panic!("the focused stop {owner:?} {part:?} has a rect")); + } + panic!("Tab never reached the wanted stop"); +} + +/// Tab to the part `key`. +fn tab_to_part(fixture: &mut Fixture, key: &'static str) -> Rect { + tab_to(fixture, |part| part == Some(PartKey::new(key))) +} + +/// Whether the latest frame paints a focus ring (a rectangle stroke at least two points wide) around `target`. +fn ringed(fixture: &mut Fixture, target: Rect) -> bool { + fixture.frame_shapes().iter().any(|shape| match shape { + Shape::Rect(rect) if rect.stroke.width >= 2.0 => rect.rect.expand(1.0).contains_rect(target), + _ => false, + }) +} + +fn spec(panel: &u8) -> PanelSpec { + PanelSpec::new(["Brushes", "Swatches", "History"].get(usize::from(*panel)).copied().unwrap_or("Panel")) +} + +/// A title row's disclosure lead and its action buttons are rung when Tab reaches them. +#[trial] +fn a_title_rows_focused_lead_and_action_show_the_focus_ring() { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + TitleRow::new("Layers").disclosure(Bind::bound(&mut open)).show(ui); + }); + fixture.settle(); + let lead = tab_to_part(&mut fixture, "lead"); + assert!(ringed(&mut fixture, lead), "the focused disclosure lead {lead:?} is ringed"); + let mut fixture = Fixture::new(|ui| { + TitleRow::new("Layers").actions([HeaderAction::Close]).show(ui); + }); + fixture.settle(); + let action = tab_to_part(&mut fixture, "action"); + assert!(ringed(&mut fixture, action), "the focused action {action:?} is ringed"); +} + +/// A group grip and a docked group's drag band and panel menu button are rung when Tab reaches them. +#[trial] +fn a_focused_group_grip_drag_band_and_panel_menu_button_show_the_focus_ring() { + let mut fixture = Fixture::new(|ui| { + let strip = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(60.0, 16.0)); + GroupGrip::new(DragUnit::Group(1usize), PanelKey::new(1)).label("Move tab group").show_at(ui, strip); + }); + fixture.settle(); + let grip = tab_to(&mut fixture, |part| part.is_none()); + assert!(ringed(&mut fixture, grip), "the focused grip {grip:?} is ringed"); + let group = || { + let panels = vec![PanelTitle::new(PanelKey::new(1), "Layers")]; + Fixture::new(move |ui| { + let group = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).menu(Vec::::new); + let _ = group.show_at(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 240.0)), |_, _| ()); + }) + }; + for part in ["grip", "panel_menu"] { + let mut fixture = group(); + fixture.settle(); + let rect = tab_to_part(&mut fixture, part); + assert!(ringed(&mut fixture, rect), "the group's focused {part} part {rect:?} is ringed"); + } +} + +/// A docked column's chevron and the divider between its groups are rung when Tab reaches them. +#[trial] +fn a_dock_columns_focused_chevron_and_divider_show_the_focus_ring() { + for part in ["chevron", "divider"] { + let mut fixture = Fixture::new(|ui| { + let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); + DockColumn::new("Panels", global("dock column", "focus ring trial"), &column, &spec).show_groups(ui, |_, rect, ui, _| { + Panel::new("Panel").show_at(ui, rect, |_, _| ()); + }); + }); + fixture.room(Vec2::new(240.0, 400.0)).settle(); + let rect = tab_to_part(&mut fixture, part); + assert!(ringed(&mut fixture, rect), "the column's focused {part} part {rect:?} is ringed"); + } +} + +/// A dock window's chevron is rung when Tab reaches it. +#[trial] +fn a_dock_windows_focused_chevron_shows_the_focus_ring() { + let mut fixture = Fixture::new(|ui| { + let rect = Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(240.0, 180.0)); + FloatingGroup::new("Layers", rect).column(WindowColumn::expanded(DockEdge::Start)).show_group(ui, |_, _| ()); + }); + fixture.settle(); + let chevron = tab_to_part(&mut fixture, "chevron"); + assert!(ringed(&mut fixture, chevron), "the window's focused chevron {chevron:?} is ringed"); +} + +/// A collapsed column's chevron and icon cells are rung when Tab reaches them. +#[trial] +fn an_iconic_columns_focused_chevron_and_cell_show_the_focus_ring() { + for part in ["chevron", "cell"] { + let mut fixture = Fixture::new(|ui| { + let column = Column::new(vec![Group::new(vec![0, 1], 0)]); + let mut open = None; + IconicColumn::new("Panels", global("iconic column", "focus ring trial"), &column, Bind::bound(&mut open), &spec) + .show_flyouts(ui, |_, _, _, _| None); + }); + fixture.room(Vec2::new(48.0, 300.0)).settle(); + let rect = tab_to_part(&mut fixture, part); + assert!(ringed(&mut fixture, rect), "the column's focused {part} part {rect:?} is ringed"); + } +} + +/// The handle between two docked areas and the divider between two stacked sections are rung when Tab reaches them. +#[trial] +fn a_focused_split_handle_and_stack_divider_show_the_focus_ring() { + use craft_behavior::dock::{Layout, Node, SplitSize}; + use craft_ui::contract::SizeLimits; + use craft_ui::docking::tree::FrameRules; + let mut fixture = Fixture::new(|ui| { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0usize], 0), Node::tabs(vec![1usize], 0)); + let mut layout = Layout::new(Some(root), Vec::new()); + let limits = |_: &usize| SizeLimits::default(); + SplitArea::new("Panels", Bind::bound(&mut layout), FrameRules::new(&limits)).show(ui, |_, _| ()); + }); + fixture.room(Vec2::new(400.0, 300.0)).settle(); + let handle = tab_to_part(&mut fixture, "handle"); + assert!(ringed(&mut fixture, handle), "the focused split handle {handle:?} is ringed"); + let mut fixture = Fixture::new(|ui| { + StackSections::new(vec![StackSection::new(true), StackSection::new(true)]).label("Sections").show(ui, |_, _| ()); + }); + fixture.room(Vec2::new(240.0, 300.0)).settle(); + let divider = tab_to_part(&mut fixture, "divider"); + assert!(ringed(&mut fixture, divider), "the focused stack divider {divider:?} is ringed"); +} From d4552077e99d89e746846ac329cf0ded928e9012 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:31:08 +0000 Subject: [PATCH 079/235] ui-canvas rulers: drop the centimetre rule's unreachable halves fallback A whole labelled centimetre is at least 24 points wide, so its quarter ticks are always 6 points apart; the 4-point fallback to halves never ran and the doc promised it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/rulers/ticks.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/ui-canvas/src/canvas/rulers/ticks.rs b/crates/ui-canvas/src/canvas/rulers/ticks.rs index 1566afd8a4..8ed6dd2f93 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks.rs +++ b/crates/ui-canvas/src/canvas/rulers/ticks.rs @@ -16,8 +16,6 @@ pub const LABEL_STEP_MIN: f32 = 60.0; /// The least distance between labelled ticks of a centimetre document ruler, in points: a whole centimetre at 100% /// (about 28 points) is labelled, as Word's ruler does. pub const CENTIMETRE_LABEL_STEP_MIN: f32 = 24.0; -/// The least distance between ticks of a centimetre document ruler, in points. -const CENTIMETRE_TICK_STEP_MIN: f64 = 4.0; /// Labelled centimetre steps: 1, 2, 5, 10 times the base. const CENTIMETRE_STEPS: [f64; 9] = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0]; @@ -79,8 +77,8 @@ impl StepLadder { pub enum TickRule<'a> { /// The units' own table ([`RulerUnits::step`]): decimal steps and ten subdivisions, or the host's custom table. Metric, - /// Centimetres of a document ruler: a label every centimetre (every 2, 5, 10 and so on when smaller), with quarter - /// centimetre ticks while they stay [`CENTIMETRE_TICK_STEP_MIN`] apart, then halves. + /// Centimetres of a document ruler: a label every centimetre with quarter centimetre ticks, or every 2, 5, 10 and so + /// on centimetres with halves when a centimetre is narrower than [`CENTIMETRE_LABEL_STEP_MIN`]. Centimetres, /// Inches: a label every inch (every 2, 5, 10 and so on when smaller), subdivided by the first of these counts, /// finest first, that keeps the ticks a tenth of the least label step apart ([`INCH_SIXTEENTHS`], @@ -132,9 +130,8 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { fn centimetre_step(points_per_cm: f64) -> (f64, u32) { let step_min = f64::from(CENTIMETRE_LABEL_STEP_MIN); let step = CENTIMETRE_STEPS.into_iter().find(|step| step * points_per_cm >= step_min).unwrap_or(1000.0); - let subdivisions = - if step > 1.0 { 2 } else { [4_u32, 2].into_iter().find(|n| points_per_cm / f64::from(*n) >= CENTIMETRE_TICK_STEP_MIN).unwrap_or(1) }; - (step, subdivisions) + // A whole labelled centimetre is at least 24 points wide, so its quarters are 6 points apart. + (step, if step > 1.0 { 2 } else { 4 }) } /// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a From 3b36acc52bb005fd0b60e216ac3849af834a93f2 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:32:25 +0000 Subject: [PATCH 080/235] menu gallery: the current tile's outline is accent.solid, not the translucent accent.border Several themes pin accent.border translucent so it reads on a control's own fill (Adwaita, Breeze, Soft, Studio, Solarized Dark). The current tile has no fill now, so that outline sat at 1.6 to 2.6:1 on the ribbon, under the 3:1 a state mark needs. accent.solid is what the other selection outlines take (table cells, graph nodes, timeline clips). Also drops the tile style's stale note about a selection fill. Co-Authored-By: Claude Opus 5.5 --- crates/menu/src/ribbon/gallery.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 33515f33b4..51a4fde5b9 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -356,7 +356,7 @@ fn grid(ui: &mut Ui, label: &Label, items: &[GalleryItem<'_, K>], current: Op // --------------------------------------------------------------------------------------------------------------- // The tile. -/// The style of a gallery tile: the theme's selection fill and edge while it is the current one. +/// The style of a gallery tile: the accent outline while it is the current one. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] struct GalleryTileStyle { @@ -366,7 +366,9 @@ struct GalleryTileStyle { focus: FocusLook, /// Between the tile's edge and its picture. pad: f32, - /// The current tile's outline: accent, unfilled, so the picture keeps its own background. + /// The current tile's outline: `accent.solid`, unfilled, so the picture keeps its own background. Not + /// `accent.border`, which several themes pin translucent to read on a control's own fill: with no fill under it, + /// it falls under 3:1 on the ribbon. edge: StyleColor, /// The ink of the item's name under the picture, in a captioned gallery. caption: StyleColor, @@ -439,7 +441,7 @@ impl Component for GalleryTile<'_> { metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)), focus: cx.focus_look(), pad, - edge: cx.color(colors.accent.border), + edge: cx.color(colors.accent.solid), caption: cx.color(colors.text.normal), gap: cx.tokens.space.gap.tight, thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg], From 715cccfbb7a09d9d8563752ee98f33b7e494fc64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:32:25 -0800 Subject: [PATCH 081/235] ui-contract: a field puts a row of controls under its label when the row would fall below its least width A field decides whether its label sits beside its control from the control's least width. Its label scope kept the least width of the first control inside it, so a field whose control is a row of several controls, such as a path field and its Browse button, left only the path field's least beside the label. In a 240 pt room the label "Folder agents can open from" stayed beside the row, the path field got 28 pt and the button's text was cut. A row that is the first control under a label now records its own least width for the label: its fixed content, the least widths of its units, the least widths of the leaves that fill it, and the probed least of each body unit. The label then puts the row under itself when the row does not fit beside it at that width. A field whose controls fit beside its label stays as it was. --- crates/ui-contract/src/contract/run.rs | 7 +++ crates/ui-contract/src/layout/body.rs | 33 ++++++++++- crates/ui-contract/src/layout/mod.rs | 5 +- .../ui-contract/src/runtime/access/scope.rs | 33 ++++++++++- .../ui-contract/src/runtime/layout_memory.rs | 1 + crates/ui-contract/src/runtime/pass_state.rs | 1 + crates/ui-widgets/tests/it/label/mod.rs | 1 + crates/ui-widgets/tests/it/label/row_least.rs | 56 +++++++++++++++++++ 8 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/row_least.rs diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 942b93fd31..9765902768 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1798,6 +1798,13 @@ fn measure_step( Some(crate::layout::Shrink::Least(row)) if shape == ShapeKind::Body => crate::layout::report_least(ctx, row, id, size.x), _ => {} } + // A leaf that fills a shrinking row is no unit of it, but a row under a label counts its least among the controls'. + let fills_row = t.fills() == Some(craft_behavior::Axis::X) || begun.common.sizing == Some(super::Sizing::Fill); + if let (Some(least), Some(crate::layout::Shrink::Count(row))) = (min_took.filter(|_| fills_row), env.shrink) + && shrink.is_none() + { + crate::layout::report_fill_least(ctx, row, size.x, least.x); + } // A body that fills the rest of a shrinking row needs at least its content: the row counts it at that width, so // the units narrow to leave it, and it takes what they leave. if let Some(crate::layout::Shrink::Count(row)) = env.shrink.filter(|_| fill_body) { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 5c64e895ed..b9732e0fb3 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -3,6 +3,7 @@ use super::column_group::{ColumnGroup, Columns}; use crate::contract::InBar; +use crate::runtime::access::scope; use crate::runtime::egui::{alloc, child}; use crate::runtime::env::{ColumnSweep, Env, RowLine, Shrink}; use crate::runtime::layout_memory; @@ -546,6 +547,12 @@ pub(crate) struct ShrinkReports(IdMap>); #[derive(Default)] pub(crate) struct LeastReports(IdMap>); +/// How much the leaves that fill each `Row` body under a label need at their least beyond what they took in its first +/// sweep (less where they took more), by row id: the row adds it to its units' least widths as the least its label +/// leaves it. +#[derive(Default)] +pub(crate) struct FillLeasts(IdMap); + /// How far the units of each `Row` body asked for one this pass reach past the row's room at their ideal widths, by /// row id: `None` for a row whose units fit. #[derive(Default)] @@ -727,6 +734,16 @@ fn level_of(ctx: &egui::Context, row: Id, unit: Id) -> (usize, Option) { .map_or((0, None), |(found, _)| (found.took.y.max(0.0) as usize, Some(found.took.x).filter(|width| width.is_finite() && *width > 0.0))) } +/// Reports the least width `least` of the leaf `leaf` that fills the row `row`, which took `took` in the row's first +/// sweep, to a row that sums its controls' least widths for its label (`FillLeasts`). +pub(crate) fn report_fill_least(ctx: &egui::Context, row: Id, took: f32, least: f32) { + pass_state::with::(ctx, |reports| { + if let Some(sum) = reports.0.get_mut(&row) { + *sum += least - took; + } + }); +} + /// Reports the least width of the body unit `body` of the row `row` that asks for it. pub(crate) fn report_least(ctx: &egui::Context, row: Id, body: Id, least: f32) { pass_state::with::(ctx, |reports| { @@ -984,11 +1001,17 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> } again }; - let (inner, rect, mut leaves, fixed, probe, again) = crate::contract::keeping_ids(&ctx, || { + // A row that is the first control under a label holds every control the label's placement must leave room for. + let labelled = scope::label_awaiting_min(&ctx); + let (inner, rect, mut leaves, fixed, fills, probe, again) = crate::contract::keeping_ids(&ctx, || { let mut first = laid_out_child(ui, layout); pass_state::with::(&ctx, |reports| reports.0.insert(id, Vec::new())); + if labelled.is_some() { + pass_state::with::(&ctx, |reports| reports.0.insert(id, 0.0)); + } let inner = sweep(&mut first, Shrink::Count(id), &mut body); let leaves = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); + let fills = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); let rect = first.min_rect(); let fixed = rect.width() - leaves.iter().map(|leaf| leaf.took).sum::(); let shortfall = fixed + leaves.iter().map(|leaf| leaf.widths.ideal).sum::() - room; @@ -996,9 +1019,10 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> if short { pass_state::with::(&ctx, |asked| asked.0.get_mut(&id).map(|slot| *slot = Some(shortfall))); } - let probe = room.is_finite() && short && leaves.iter().any(|leaf| leaf.body); + // A row under a label asks its bodies for their least whatever its room: the label's placement needs it. + let probe = (labelled.is_some() || (room.is_finite() && short)) && leaves.iter().any(|leaf| leaf.body); let again = !probe && settle(&leaves, fixed); - ((inner, rect, leaves, fixed, probe, again), probe || again) + ((inner, rect, leaves, fixed, fills, probe, again), probe || again) }); let again = again || probe; if probe { @@ -1020,6 +1044,9 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> } settle(&leaves, fixed); } + if let Some(container) = labelled { + scope::record_row_min(&ctx, container, fixed + fills + leaves.iter().map(|leaf| leaf.widths.least).sum::()); + } if again { child::block(ui, None, layout, |ui| sweep(ui, Shrink::Apply(id), &mut body)).0 } else { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 2895b9f4da..b33afc7542 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,6 +26,7 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, - members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, - run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, view_room, + members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, + report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, + view_room, }; diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index bb2ae60f6a..fe785b0555 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -366,27 +366,54 @@ pub(crate) fn record_control_min(ctx: &Context, width: f32) { stack.0.iter().rev().find(|scope| matches!(scope.kind, Kind::Label(_))).map(|scope| scope.container) }); if let Some(container) = container { - layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width })); + layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width, whole: false })); } } +/// The innermost open label scope, when no control inside it has reported its narrowest width yet. +pub(crate) fn label_awaiting_min(ctx: &Context) -> Option { + pass_state::with::(ctx, |stack| { + stack + .0 + .iter() + .rev() + .find(|scope| matches!(scope.kind, Kind::Label(_))) + .filter(|scope| scope.control_min.is_none()) + .map(|scope| scope.container) + }) +} + +/// Records `width` as the narrowest width of the controls of `container`'s label scope, in place of what the first of +/// them reported: the least of a row that holds them side by side, the first control of the scope +/// (`label_awaiting_min`). Only a measuring run records it. +pub(crate) fn record_row_min(ctx: &Context, container: Id, width: f32) { + layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width, whole: true })); +} + /// A control's narrowest width reported to the label scope of `container`, as a measuring run hands it forward. struct ControlMin { container: Id, width: f32, + /// The width is the least of a row of controls (`record_row_min`): it replaces the first control's. + whole: bool, } impl layout_memory::Contribution for ControlMin { fn apply(&self, ctx: &Context) { pass_state::with::(ctx, |stack| { if let Some(scope) = stack.0.iter_mut().rev().find(|scope| scope.container == self.container && matches!(scope.kind, Kind::Label(_))) { - scope.control_min.get_or_insert(self.width); + if self.whole { + scope.control_min = Some(self.width); + } else { + scope.control_min.get_or_insert(self.width); + } } }); } fn report(&self) -> Option<(Id, f32)> { - Some((sub(self.container, "control_min"), self.width)) + // A row's shrink step sweeps only in a measuring run, so a real run has no row least to compare. + (!self.whole).then(|| (sub(self.container, "control_min"), self.width)) } fn undo(&self, ctx: &Context) -> layout_memory::TakeBack { diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index dbea6d3e98..2f35b81e50 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1266,6 +1266,7 @@ pub(crate) mod guard { ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), + ("layout::body::FillLeasts", "fill leasts: opened and closed by the row's own first sweep; the sum goes through contribute"), ("layout::body::RowShortfalls", "shortfalls: asked and taken by the container around the row in the same measuring sweep"), ("runtime::reads::Runs", "measuring runs of the read record: opened and closed by each run; reads go through contribute"), ("contract::steps::id::IdPass", "id registration: a measuring run keeps the ids it uses out of the pass (keeping_ids)"), diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 417b27d852..2ac5ad08b6 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -91,6 +91,7 @@ pass_state! { jumps: crate::contract::body::scroll::Jumps, shrink_reports: crate::layout::body::ShrinkReports, least_reports: crate::layout::body::LeastReports, + fill_leasts: crate::layout::body::FillLeasts, row_shortfalls: crate::layout::body::RowShortfalls, bar_rules: crate::contract::BarRules, surface_frames: crate::primitives::SurfaceFrames, diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 37af7d23db..caa2537022 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -11,6 +11,7 @@ pub mod kit; pub(crate) mod link; pub(crate) mod reach; pub(crate) mod reset; +pub(crate) mod row_least; pub(crate) mod scheme; pub(crate) mod scrub_drags; pub(crate) mod short; diff --git a/crates/ui-widgets/tests/it/label/row_least.rs b/crates/ui-widgets/tests/it/label/row_least.rs new file mode 100644 index 0000000000..9fd16fcdc3 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/row_least.rs @@ -0,0 +1,56 @@ +//! A field whose control is a row of several controls (a path field and its Browse button) puts the row under its +//! label when the label beside it would leave the row less than its least width. + +use craft_theme::Size; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::form::Field; +use craft_ui::layout_components::Row; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Rect, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; +const BROWSE: &str = "Browse…"; + +/// A field labelled `label` over a fill-width path field and a Browse button, in a room `width` wide. +fn path_field(label: &'static str, width: f32) -> Fixture { + let mut fixture = Fixture::new(move |ui| { + Field::new(label).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + TextField::new(label, Bind::given(String::from("/photos/agents"))).limit(None).sizing(Sizing::FillWidth).show(ui); + Button::new(BROWSE).show(ui); + }); + }); + }); + fixture.room(Vec2::new(width, 300.0)).density(Size::Compact); + fixture.settle(); + fixture +} + +fn caption(fixture: &Fixture, text: &str) -> Rect { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text:?} is painted")) +} + +/// In a room 240 pt wide, the long label beside the row would leave it less than the path field's and the button's +/// least widths together. The row shows under the label, and the button's text shows whole. +#[trial] +fn a_long_label_puts_a_row_of_controls_under_it_when_the_row_would_fall_below_its_least() { + const LABEL: &str = "Folder agents can open from"; + let fixture = path_field(LABEL, 240.0); + let (label, field) = (caption(&fixture, LABEL), fixture.by_label(LABEL).expect("the label names the path field").rect); + assert!(label.max.y <= field.min.y + SLACK, "the path field shows under its label: {label:?} {field:?}"); + let texts = fixture.texts(); + let browse = texts.iter().find(|run| run.text == BROWSE).unwrap_or_else(|| panic!("{BROWSE:?} shows whole: {texts:?}")); + assert!(browse.clip.min.x <= browse.rect.min.x + SLACK && browse.clip.max.x >= browse.rect.max.x - SLACK, "Browse shows whole: {browse:?}"); +} + +/// A short label leaves the row its least width beside it, so the label stays beside the row. +#[trial] +fn a_short_label_stays_beside_a_row_of_controls_that_fits() { + const LABEL: &str = "Folder"; + let fixture = path_field(LABEL, 240.0); + let (label, field) = (caption(&fixture, LABEL), fixture.by_label(LABEL).expect("the label names the path field").rect); + assert!(label.max.x <= field.min.x + SLACK && label.max.y > field.min.y, "the label stays beside the path field: {label:?} {field:?}"); +} From c9c90a5a72fe572f9b1daeaa09546fe66aef83b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:46:51 -0800 Subject: [PATCH 082/235] host: QueueOptions::default_lanes reads the core count once per process `QueueOptions::default_lanes` called `std::thread::available_parallelism` on every call. On Linux that call opens /proc/self/cgroup and the cpu.max file of every cgroup level, so each call costs several file opens and reads. `ThumbnailOptions::new` calls it, and the glyphs panel's `glyph_painter` builds a `ThumbnailOptions` for every visible cell in every pass, so the panel made about 5,000 such calls per frame. The lane count is now computed once and kept in a `OnceLock`. wasm32 still returns 0. --- crates/host/src/queue.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/host/src/queue.rs b/crates/host/src/queue.rs index 7197297ccb..8133d17e64 100644 --- a/crates/host/src/queue.rs +++ b/crates/host/src/queue.rs @@ -19,6 +19,8 @@ use std::cmp::Reverse; use std::collections::VecDeque; use std::hash::Hash; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread::{self, ThreadId}; @@ -94,14 +96,17 @@ pub enum QueueOrder { impl QueueOptions { /// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when - /// the core count is unknown); 0 on wasm32. + /// the core count is unknown); 0 on wasm32. The core count is read once per process. // lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8; // ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`). pub fn default_lanes() -> usize { #[cfg(target_arch = "wasm32")] return 0; #[cfg(not(target_arch = "wasm32"))] - thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)) + { + static LANES: OnceLock = OnceLock::new(); + *LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))) + } } } From 7e3945ec4e0face57a57afeb86867d0d8cfc2fde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:47:57 -0800 Subject: [PATCH 083/235] ui-widgets: a derived number field shows its reading whole inside the field A number field gives a value wider than its text area some of its padding back. It measured that value as the plain number, so a derived value, which reads in parentheses with its unit, kept the full padding and its closing parenthesis was cut. In the number_field_derived story at compact size, "(12.5 pt)" is 62.3 pt wide in a 60 pt clip. The field now measures a derived value as it shows at rest. Its reading takes the padding it needs, as a longer number does, and the field keeps its width. A field whose value fits is laid out as before. --- crates/ui-widgets/src/text/number.rs | 7 +++++- .../tests/it/text/number_derived.rs | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index c1bd4db826..3600b4a15b 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -763,8 +763,13 @@ impl Component for NumberField<'_, V> { self.leading = Self::before_text(cx, self.step_arrows); self.trailing = self.after_text(cx, &chevrons); let names = self.names(|row| cx.env.resolve(&row.label().clone())); + // A derived value is measured as it shows at rest, in parentheses with its unit, so its reading takes the + // padding it needs as a longer number does. self.value_width = cx.value().map_or(0.0, |value| { - let text = self.ruled(&cx.env, false, names).format(value); + let mut text = self.ruled(&cx.env, false, names).format(value); + if self.derives(Some(value)) { + text = self.derived_text(&text, &cx.env.units()); + } cx.field_text(&TextRun::new(&text).role(self.value_role())).x }); let placed = self.laid_out(cx.style, cx.content_rect, rtl); diff --git a/crates/ui-widgets/tests/it/text/number_derived.rs b/crates/ui-widgets/tests/it/text/number_derived.rs index a12e0f439a..a6dccbc22e 100644 --- a/crates/ui-widgets/tests/it/text/number_derived.rs +++ b/crates/ui-widgets/tests/it/text/number_derived.rs @@ -37,6 +37,29 @@ fn a_derived_number_shows_in_parentheses_and_edits_from_the_plain_number() { assert_eq!(fixture.tree().numeric(id.get()).and_then(|numeric| numeric.value), Some(12.0), "the field reports the committed number"); } +/// A derived reading that is wider than the field's text area with its padding, "(12.5 pt)" in a one-cell field, takes +/// room from the padding and shows whole inside the field, and the field is as wide as the same field showing the plain +/// number with its unit. Guards against sizing the text area by the plain number, which cut the closing parenthesis. +#[trial] +fn a_derived_number_shows_whole_inside_its_field() { + let boxes = Rc::new(Cell::new([egui::Rect::NOTHING; 2])); + let seen = boxes.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut derived = Some(12.5); + let mut plain = Some(12.5); + let at = NumberField::new("Leading", Bind::bound(&mut derived)).unit_kind(UnitKind::Points).derived(true).show(ui).response.rect; + let beside = NumberField::new("Size", Bind::bound(&mut plain)).unit_kind(UnitKind::Points).show(ui).response.rect; + seen.set([at, beside]); + }); + fixture.settle(); + fixture.idle(3); + let [field, plain] = boxes.get(); + let text = fixture.texts().iter().find(|text| text.text == "(12.5 pt)").expect("the derived reading is painted").clone(); + assert!(field.contains_rect(text.rect), "the reading {:?} lies inside the field {field:?}", text.rect); + assert!(text.clip.contains_rect(text.rect), "the reading {:?} is not cut by its clip {:?}", text.rect, text.clip); + assert_eq!(field.width(), plain.width(), "the derived field is as wide as the same field with the plain number"); +} + /// A blank value is no number to derive: the field shows it as it would without `derived`, never as empty /// parentheses, and an edit from the blank still starts from nothing. #[trial] From 84279466d43f3aee85ca9bdc1cd7a8ba3389651a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:50:15 -0800 Subject: [PATCH 084/235] ui-contract: a scroll bar whose track has no room paints nothing A scroll view shorter than its padding has a view whose top lies below its bottom, and its scroll bar track inherits those crossed ends. The bar painted a thumb in that track. A scroll body 6 pt tall with 6 pt of padding above and below painted a thumb of zero height, and a FileListPicker list given 12 pt with 8 pt of padding painted one with a negative height, at [254.8, 296] to [256.8, 292]. ScrollBar::shapes now returns no shapes when the track is not positive, as ScrollBar::fades already paints no fade over a view with no room. Every bar that goes through it, a scroll body's, a collection's, the canvas's and the timeline's, is covered. Bars in views that have room paint as before. --- .../ui-contract/src/primitives/scroll_bar.rs | 6 +++- crates/ui-contract/tests/it/layout/mod.rs | 1 + .../ui-contract/tests/it/layout/short_view.rs | 33 +++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 crates/ui-contract/tests/it/layout/short_view.rs diff --git a/crates/ui-contract/src/primitives/scroll_bar.rs b/crates/ui-contract/src/primitives/scroll_bar.rs index 8027b18d56..3ff0a08bd8 100644 --- a/crates/ui-contract/src/primitives/scroll_bar.rs +++ b/crates/ui-contract/src/primitives/scroll_bar.rs @@ -89,8 +89,12 @@ impl ScrollBar { /// The shapes of the bar in `track` along `axis` for `span`, in `state` (the bar's: hovered while the pointer is /// anywhere on it): the track and the fully round thumb, `look.thumb_width` thick along the track's outer edge (its - /// bottom, or its end side in the reading direction). + /// bottom, or its end side in the reading direction). No shapes when the track has no room: a view shorter or + /// narrower than its padding gives its bar a track of no length, or one whose ends cross. pub fn shapes(look: &ScrollBarLook, track: Rect, axis: Axis, rtl: bool, span: &ScrollSpan, state: &StateSet) -> Vec { + if !track.is_positive() { + return Vec::new(); + } let full = Self::thumb(look.min_thumb, track, axis, rtl, span); let thumb = Self::along_edge(full, state.resolve(&look.thumb_width), axis, rtl); let round = |rect: Rect| CornerRadius::from(rect.width().min(rect.height()) / 2.0); diff --git a/crates/ui-contract/tests/it/layout/mod.rs b/crates/ui-contract/tests/it/layout/mod.rs index 3c8d9f2c6b..7ccab8dc8c 100644 --- a/crates/ui-contract/tests/it/layout/mod.rs +++ b/crates/ui-contract/tests/it/layout/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod fill; pub(crate) mod line_fill; pub(crate) mod memory; pub(crate) mod overlay_bar; +pub(crate) mod short_view; diff --git a/crates/ui-contract/tests/it/layout/short_view.rs b/crates/ui-contract/tests/it/layout/short_view.rs new file mode 100644 index 0000000000..0264444f38 --- /dev/null +++ b/crates/ui-contract/tests/it/layout/short_view.rs @@ -0,0 +1,33 @@ +//! A scroll body whose rect is shorter than its padding: its view has no room, so its scroll bar paints nothing. + +use craft_ui::contract::{ContainerProps, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; +use craft_ui::testing::{Frames, pointer, trial}; +use craft_ui_test_kit::body::Slab; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Shape, Ui, Vec2}; +use std::cell::RefCell; + +/// The container's rect: shorter than the padding above and below its view. +const AT: Rect = Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(180.0, 26.0) }; + +/// The padded container that scrolls along y under `scroll`'s bar, holding a probe that paints nothing and is far +/// taller than the container. +fn short(ui: &mut Ui, seen: &RefCell, scroll: Scroll) { + let props = ContainerProps::new().pad(Pad::Control).sizing(Sizing::Fill).scroll(scroll); + Slab::new(props).id_salt("short").show_at(ui, AT, |ui, _| { + Probe::new(seen).size(Vec2::new(40.0, 400.0)).sizing(Sizing::FillWidth).id_salt("content").show(ui); + }); +} + +#[trial] +fn a_scroll_body_shorter_than_its_padding_paints_no_bar() { + for (name, scroll) in [("bar", Scroll::vertical()), ("overlay bar", Scroll::vertical().overlay())] { + let seen = RefCell::new(Seen::default()); + let mut show = |ui: &mut Ui| short(ui, &seen, scroll); + let mut frames = Frames::new(); + frames.frame(vec![pointer::moved(AT.center())], &mut show); + frames.idle(4, &mut show); + let painted: Vec = frames.frame_shapes(&mut show).iter().map(Shape::visual_bounding_rect).filter(|bounds| bounds.is_finite()).collect(); + assert!(painted.is_empty(), "{name}: the bar paints nothing: {painted:?}"); + } +} From 6169fc3032abf0f90ee1bae513cc640da3ce5794 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:54:15 +0000 Subject: [PATCH 085/235] ui-patterns preview zoom: opt-in whole-percent display PreviewZoom::whole_percent() caps the zoom field at whole percents ("94 %"), as a word processor's print preview shows. The default keeps the units zoom codec (up to two decimals), so image apps' 12.5% step is unchanged. Fixes storytold/wordcraft#7708. Co-Authored-By: Claude Sonnet 5.5 --- .../src/patterns/form_dialogs/preview.rs | 12 +++++++-- .../tests/it/form_dialogs/preview.rs | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs index 12ffd5a6e3..3bb60e82c3 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs @@ -675,13 +675,21 @@ impl Outcome for PreviewZoomOutput { #[derive(crate::contract::Pattern)] pub struct PreviewZoom { view: PreviewView, + whole_percent: bool, } impl PreviewZoom { /// A zoom row for `view`, the one the pane takes: the buttons stay inside its zoom range. While the pane fits, /// the caller has adopted the pane's `PreviewOutput::shown`, so the row steps from what is on screen. pub fn new(view: &PreviewView) -> Self { - PreviewZoom { view: view.clone() } + PreviewZoom { view: view.clone(), whole_percent: false } + } + + /// Shows the zoom as a whole percent ("94 %"), as a word processor's print preview does, instead of up to two + /// decimals. The view keeps its fractional zoom, and a typed fraction still applies; only the shown value is whole. + pub fn whole_percent(mut self) -> Self { + self.whole_percent = true; + self } /// Shows the row. @@ -694,7 +702,7 @@ impl PreviewZoom { let row = Row::new().show(ui, |ui, _| { let out = IconButton::new(IconId::new("minus")).label(words.zoom_out.clone()).enabled(self.view.can_zoom_out()).show(ui); let field = NumberField::new(words.zoom.clone(), Bind::given(Some(percent(self.view.transform.scale)))) - .codec(env.units().zoom_codec()) + .codec(if self.whole_percent { env.units().zoom_codec().at_most(0) } else { env.units().zoom_codec() }) .unit_kind(UnitKind::Percent) .range(range.clone()) .enabled(!self.view.fixed) diff --git a/crates/ui-patterns/tests/it/form_dialogs/preview.rs b/crates/ui-patterns/tests/it/form_dialogs/preview.rs index 093b9cc6d0..8672b922ec 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/preview.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/preview.rs @@ -83,3 +83,29 @@ fn a_click_reports_the_picture_point_under_it() { let (kept, moved) = click(8.0, false, vec2(16.0, 8.0)); assert!(near(kept, pos2(PICTURE.x / 2.0 + 2.0, PICTURE.y / 2.0 + 1.0)) && !moved, "{kept:?} {moved}"); } + +/// The zoom text the row shows for `scale`, with the option applied or not. +fn shown_zoom(scale: f32, whole: bool) -> Vec { + let view = PreviewView::new(CanvasTransform::new(scale, Vec2::ZERO)); + let mut fixture = Fixture::new(move |ui| { + let zoom = PreviewZoom::new(&view); + if whole { zoom.whole_percent() } else { zoom }.show(ui); + }); + fixture.settle(); + fixture.texts().iter().map(|run| run.text.clone()).collect() +} + +/// With `whole_percent`, a fractional zoom shows with no decimals. +#[trial] +fn a_whole_percent_preview_zoom_shows_no_decimals() { + let shown = shown_zoom(0.9415, true); + assert!(shown.iter().any(|text| text == "94"), "the zoom shows as 94: {shown:?}"); + assert!(!shown.iter().any(|text| text.contains('.') || text.contains(',')), "no decimals shown: {shown:?}"); +} + +/// Without it, a fractional zoom step keeps its decimals, as image apps need. +#[trial] +fn a_default_preview_zoom_keeps_a_fractional_step() { + let shown = shown_zoom(0.125, false); + assert!(shown.iter().any(|text| text.starts_with("12") && text.len() > 2), "the zoom keeps its decimals: {shown:?}"); +} From 49c27ec4149fbb90d9f4f91e8dc97beecd085097 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:04:47 -0800 Subject: [PATCH 086/235] ui-widgets: ring focused parts that showed no focus ring Tab reached focusable parts whose component style had no focus look, so the paint step drew no ring: a notice's actions and dismiss button, bar items, a list row's trailing items, status action and thumbnail link, a chip, the alt text field's decorative check, a tile's actions, a tile grid's insert gaps, the thumbnail slider's buttons, a tab strip's end items and a table's header cells. A list row and a tile that are their own stop showed no ring either. Each of those styles now carries the theme's focus look. A collection (table, tile grid, tab strip) rings its focused parts but not itself: paint_focus skips the whole-component ring for the items shape, so no collection gains a ring around itself. TableStyle and BarItemsStyle no longer derive Default, since the focus look comes from the theme. --- crates/ui-contract/src/contract/run.rs | 2 +- .../ui-contract/src/contract/steps/paint.rs | 6 +- crates/ui-widgets/src/bars/items.rs | 7 +- crates/ui-widgets/src/list/row/show.rs | 1 + crates/ui-widgets/src/list/row/style.rs | 4 +- crates/ui-widgets/src/notices/notice.rs | 5 +- crates/ui-widgets/src/table/view.rs | 12 +-- crates/ui-widgets/src/tabs/strip.rs | 7 +- crates/ui-widgets/src/text/alt_text.rs | 6 +- crates/ui-widgets/src/text/chips.rs | 11 ++- crates/ui-widgets/src/tile_grid/grid.rs | 5 +- crates/ui-widgets/src/tile_grid/slider.rs | 6 +- crates/ui-widgets/src/tile_grid/tile.rs | 6 +- crates/ui-widgets/tests/it/main.rs | 1 + crates/ui-widgets/tests/it/part_rings.rs | 87 +++++++++++++++++++ 15 files changed, 143 insertions(+), 23 deletions(-) create mode 100644 crates/ui-widgets/tests/it/part_rings.rs diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 942b93fd31..da56d6a847 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1266,7 +1266,7 @@ fn paint_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &mut HostStep e.content_env(&mut h.values); steps::unfade(ui, e.core(), fade); ui.set_clip_rect(h.outer_clip); - steps::paint_focus(ui, e.core_ref(), p.style); + steps::paint_focus(ui, e.core_ref(), p.style, e.shape() != ShapeKind::Item); // A rule a bar's view shows waits for the member after it. if let Some((line, from)) = rule_from { hold_rule(ui, line, from); diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 75f95948c8..0360b61534 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -114,8 +114,8 @@ pub(crate) fn paint_part_layers(ui: &Ui, env: &Env, core: &CxCore<'_>) { /// Step 13, paint, after `C::paint`: the focus ring of the focused component or its active part, when focus is /// keyboard-visible. An active part's ring takes the shape the part declared (`focus_shape`), else its rect; the /// component's own ring takes the shape it declared (`Cx::focus_shape`), else its rect with its surface's corners. Never -/// on `Well` surfaces. -pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) { +/// on `Well` surfaces, and never around a collection (`whole` false), whose lead item shows the focus. +pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView, whole: bool) { let Some(look) = style.focus() else { return }; let ppp = ui.ctx().pixels_per_point(); let flags = core.state.flags; @@ -125,7 +125,7 @@ pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) { let declared = core.focus_shapes.iter().find(|((key, index), _)| craft_behavior::PartRef { key: *key, index: *index } == part); let outline = declared.map_or(PaintShape::Rect(rect, egui::CornerRadius::ZERO), |(_, shape)| FocusRing::outline(shape, rect)); ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &outline, ppp)); - } else if FocusRing::visible(flags) && !well { + } else if whole && FocusRing::visible(flags) && !well { let outline = match &core.focus_shape { Some(shape) => FocusRing::outline(shape, core.rect), None => PaintShape::Rect(core.rect, style.surface().map_or(egui::CornerRadius::ZERO, |surface| surface.radius)), diff --git a/crates/ui-widgets/src/bars/items.rs b/crates/ui-widgets/src/bars/items.rs index fd524c8ebd..fd61817168 100644 --- a/crates/ui-widgets/src/bars/items.rs +++ b/crates/ui-widgets/src/bars/items.rs @@ -11,7 +11,7 @@ use crate::menu::{Menu, MenuItem}; use crate::primitives::IconSpec; use crate::runtime::commands::{CommandRef, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleCx}; use craft_behavior::fit::{FitItem, FitKeep, fit_items}; use craft_behavior::{Axis, IconId, Metrics, NavShape, PartKey, PartRef, Proposal, Roving, Sense}; use craft_theme::Variant; @@ -89,11 +89,13 @@ impl BarItem { /// The style of a bar item strip: the gap between items, the space around the rule of a section change and the /// space between the groups of a vertical strip. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct BarItemsStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// Between an item and the rule of a section change. joint: f32, /// The clear space of a section change, on both sides of its rule together. @@ -305,6 +307,7 @@ impl Component for BarItems { let gap = cx.tokens.space.gap.inline; BarItemsStyle { metrics: Metrics::new().gap(gap), + focus: cx.focus_look(), joint: gap, section_gap: gap * 2.0, stack_gap: gap + cx.tokens.space.gap.stack, diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 35ca35602f..7113222b91 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -90,6 +90,7 @@ impl Component for ListRow<'_> { surface, // A separator is as high as its rule and the room around it. metrics: Metrics::new().min_size(Vec2::new(0.0, if key.separator { 0.0 } else { sizes.row })).gap(sizes.gap), + focus: cx.focus_look(), text: TextLook::new(role, ink(base)), icon: IconLook::new( sizes.icon, diff --git a/crates/ui-widgets/src/list/row/style.rs b/crates/ui-widgets/src/list/row/style.rs index 3942613e78..b6e7381451 100644 --- a/crates/ui-widgets/src/list/row/style.rs +++ b/crates/ui-widgets/src/list/row/style.rs @@ -2,7 +2,7 @@ use super::placement::Sizes; use crate::display::divider::SeparatorRule; -use crate::style::{ComponentStyle, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook}; +use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook}; use craft_behavior::Metrics; use craft_theme::{Contrast, Rgba, Stateful, States, contrast_ratio, identifiable_outline, over}; @@ -17,6 +17,8 @@ pub struct ListRowStyle { pub(super) surface: SurfaceLook, #[style(metrics)] pub(super) metrics: Metrics, + #[style(focus)] + pub(super) focus: FocusLook, /// The label. #[style(text)] pub(super) text: TextLook, diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index bd710c09f1..a0a3ec72d4 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -11,7 +11,7 @@ use crate::contract::{ use crate::primitives::{HAlign, IconSpec, TextRun, Wrap}; use crate::runtime::commands::CommandRef; use crate::runtime::env::{EnvView, Label}; -use crate::style::{ComponentStyle, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens}; +use crate::style::{ComponentStyle, FocusLook, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens}; use craft_behavior::{Flow, IconId, Metrics, NavShape, PartKey, Proposal, Roving, Sense}; use craft_i18n::Format; use craft_theme::{Rgba, Stateful, States, Variant, variant::Tone}; @@ -135,6 +135,8 @@ pub struct NoticeStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The title's role and colour. #[style(text)] title: TextLook, @@ -581,6 +583,7 @@ impl Component for Notice<'_> { NoticeStyle { surface, metrics: Metrics::new().padding(padding).gap(control.gap), + focus: cx.focus_look(), title, brand, byline, diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index cdfc063625..4aeaecb6ac 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -13,7 +13,7 @@ use crate::display::Divider; use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText}; use crate::menu::{Menu, MenuItem}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::{ColumnKey, ItemSource, Metrics, Selection, SpanLayout}; use egui::{Rect, Ui}; use std::hash::Hash; @@ -21,12 +21,14 @@ use std::hash::Hash; /// The header menu's popup. const HEADER_MENU: &str = "header_menu"; -/// The style of the table: it has no look of its own beyond its container's surface. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// The style of the table: the focus ring of its header cells, and no other look beyond its container's surface. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct TableStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// A table: one Tab stop, a header row over the columns, the selection rules of the collection contract, type-ahead on @@ -134,8 +136,8 @@ impl Component for Table<'_, K> { type Style = TableStyle; type Output = CollectionResponse; - fn style(_: &StyleCx<'_>, _: TableStyleKey) -> TableStyle { - TableStyle::default() + fn style(cx: &StyleCx<'_>, _: TableStyleKey) -> TableStyle { + TableStyle { metrics: Metrics::default(), focus: cx.focus_look() } } fn update(&mut self, cx: &mut Cx<'_, Self>) { diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index e8379d2818..97dce4ce93 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -29,7 +29,7 @@ use crate::menu::Menu; use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx}; use craft_behavior::fit::{FitItem, fit_items}; use craft_behavior::{ Flow, HitLevel, HitPriority, IconId, Insets, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, @@ -122,12 +122,14 @@ fn strip_lead(kind: TabKind, tokens: &crate::style::UiTokens) -> f32 { if kind == TabKind::Ribbon { tokens.space.pad.regular } else { 0.0 } } -/// The look of a strip: it has none of its own; its row is as high as its tabs. +/// The look of a strip: the focus ring of its end items; its row is as high as its tabs. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct TabStripStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The text line a wheel notch given in lines counts. line: f32, /// The colour of the one underline a ribbon strip slides under its shown tab. @@ -827,6 +829,7 @@ impl Component f let (lead, side) = (strip_lead(key.kind, tokens), if ribbon { super::tab::ribbon_pad(tokens) - tokens.stroke.thick / 2.0 } else { 0.0 }); TabStripStyle { metrics: Metrics::new().padding(Insets::new(lead, 0.0, 0.0, 0.0)), + focus: cx.focus_look(), line: tokens.typography.body.line_height, underline: cx.color(tokens.color.accent.solid), underline_inset: tokens.stroke.thick / 2.0, diff --git a/crates/ui-widgets/src/text/alt_text.rs b/crates/ui-widgets/src/text/alt_text.rs index 644e2ce1cd..5ca927ce14 100644 --- a/crates/ui-widgets/src/text/alt_text.rs +++ b/crates/ui-widgets/src/text/alt_text.rs @@ -10,7 +10,7 @@ use crate::contract::{ }; use crate::primitives::{TextOptions, TextRun}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, Flags, StyleCx, SurfaceLook}; +use crate::style::{ComponentStyle, Flags, FocusLook, StyleCx, SurfaceLook}; use craft_behavior::{Codec, Metrics, Mixed, NotAValue, PartKey, Proposal, Sense}; use egui::{Rect, Vec2, pos2, vec2}; use std::borrow::Cow; @@ -104,6 +104,8 @@ pub struct AltTextFieldStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// An alt text editor: a multi-line description box and a Mark as decorative check. While the check is on, the box @@ -148,7 +150,7 @@ impl Component for AltTextField<'_> { fn style(cx: &StyleCx<'_>, _: AltTextFieldStyleKey) -> AltTextFieldStyle { let field = FieldStyle::at(cx); - AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap) } + AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), focus: cx.focus_look() } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/text/chips.rs b/crates/ui-widgets/src/text/chips.rs index 15cb0beb81..6ba34734af 100644 --- a/crates/ui-widgets/src/text/chips.rs +++ b/crates/ui-widgets/src/text/chips.rs @@ -14,7 +14,7 @@ use crate::display::Badge; use crate::menu::Menu; use crate::primitives::TextOptions; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx, SurfaceLook}; +use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook}; use craft_behavior::{Caret, Codec, Flow, Granularity, IconId, Intent, Metrics, NavShape, NotAValue, PartKey, Proposal, Roving, Sense}; use craft_theme::Variant; use egui::{Rect, Response, Vec2, pos2, vec2}; @@ -105,6 +105,8 @@ pub struct ChipFieldStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The least width of the draft, so a full line of chips still leaves room to type. draft_min: f32, } @@ -334,7 +336,12 @@ impl Component for ChipField<'_> { fn style(cx: &StyleCx<'_>, _: ChipFieldStyleKey) -> ChipFieldStyle { let field = FieldStyle::at(cx); - ChipFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), draft_min: cx.tokens.size.length.short } + ChipFieldStyle { + surface: field.surface, + metrics: field.metrics.gap(cx.control().gap), + focus: cx.focus_look(), + draft_min: cx.tokens.size.length.short, + } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index 07d0c57aab..d512ddbe30 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -24,7 +24,7 @@ use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth}; use crate::runtime::access::Name; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, RuleKind, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, RuleKind, StyleColor, StyleCx}; use craft_behavior::{ ColumnKey, ColumnWidth, EditEvent, HitLevel, HitPriority, Intent, ItemLayout as _, ItemSource, Metrics, Mixed, NavShape, PartKey, PointerButton, PressPhase, Roving, Selection, Sense, @@ -154,6 +154,8 @@ impl Outcome for TileGridOutput { pub struct TileGridStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// A header pinned over its group's tiles. pinned: StyleColor, /// The look of a group header: a heading row, which places the disclosure the grid declares. @@ -668,6 +670,7 @@ impl Component for TileGrid<'_, K> fn style(cx: &StyleCx<'_>, _: TileGridStyleKey) -> TileGridStyle { TileGridStyle { metrics: Metrics::new(), + focus: cx.focus_look(), pinned: cx.color(cx.tokens.color.surface.panel), header: ListRow::style(cx, ListRow::new(Label::default()).heading().style_key()), insert: cx.color(cx.tokens.color.accent.solid), diff --git a/crates/ui-widgets/src/tile_grid/slider.rs b/crates/ui-widgets/src/tile_grid/slider.rs index 3b9427b8db..6c7ebc8cad 100644 --- a/crates/ui-widgets/src/tile_grid/slider.rs +++ b/crates/ui-widgets/src/tile_grid/slider.rs @@ -6,7 +6,7 @@ use crate::contract::{ Access, Bind, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, PaintUi, PartsCx, Props as _, Role, WordSetCx as _, }; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::{IconId, Metrics, Mixed, NavShape, PartKey, Roving, Sense}; use egui::{Rect, Vec2}; use std::ops::RangeInclusive; @@ -106,6 +106,8 @@ const LARGER_ICON: &str = "grid"; pub struct ThumbnailSliderStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// Where the thumbnail slider's three controls lie. @@ -152,7 +154,7 @@ impl Component for ThumbnailSlider<'_> { type Output = EditResponse; fn style(cx: &StyleCx<'_>, _: ThumbnailSliderStyleKey) -> ThumbnailSliderStyle { - ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap) } + ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap), focus: cx.focus_look() } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/tile_grid/tile.rs b/crates/ui-widgets/src/tile_grid/tile.rs index 202fd4b8a7..734e225c4b 100644 --- a/crates/ui-widgets/src/tile_grid/tile.rs +++ b/crates/ui-widgets/src/tile_grid/tile.rs @@ -21,7 +21,8 @@ use crate::primitives::{ContentPainterCx, HAlign, IconSpec, PaintShape, StrokeWi use crate::runtime::commands::CommandRef; use crate::runtime::env::{Label, Units}; use crate::style::{ - ComponentStyle, Corners, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle, TextLook, UiTokens, + ComponentStyle, Corners, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle, + TextLook, UiTokens, }; use craft_behavior::{AccessAction, AccessData, Flow, IconId, Insets, Metrics, Mixed, NavShape, PartKey, PressPhase, Proposal, Roving, Sense}; use craft_keymap::Mods; @@ -243,6 +244,8 @@ pub struct TileStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The name. #[style(text)] name: TextLook, @@ -877,6 +880,7 @@ impl Component for Tile<'_> { sizes.inset, )) .gap(sizes.tight), + focus: cx.focus_look(), name: if key.card { TextLook::new(key.card_text.name_role(), ink(c(text.normal))) } else { diff --git a/crates/ui-widgets/tests/it/main.rs b/crates/ui-widgets/tests/it/main.rs index c9fd20c1dc..c54922f773 100644 --- a/crates/ui-widgets/tests/it/main.rs +++ b/crates/ui-widgets/tests/it/main.rs @@ -22,6 +22,7 @@ pub(crate) mod list; pub(crate) mod menu; pub(crate) mod notices; pub(crate) mod overlay; +pub(crate) mod part_rings; pub(crate) mod pickers; pub(crate) mod picture; pub(crate) mod popover; diff --git a/crates/ui-widgets/tests/it/part_rings.rs b/crates/ui-widgets/tests/it/part_rings.rs new file mode 100644 index 0000000000..ae940f0069 --- /dev/null +++ b/crates/ui-widgets/tests/it/part_rings.rs @@ -0,0 +1,87 @@ +//! The focus ring of focusable parts: Tab to each part of a story and the paint step rings it, as it rings a button. +//! A collection rings its focused parts but not itself, since its lead item shows the focus. + +use craft_behavior::PartKey; +use craft_ui::testing::{Fixture, Registry, trial}; +use egui::{Key, Modifiers, Rect, Shape}; + +/// The story named `name`, settled. +fn story(name: &str) -> Fixture { + let registry = Registry::of(&[crate::register, craft_ui::testing::register]); + let _ = registry.install_story_sets(); + let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("a story named {name}")); + let mut fixture = Fixture::story(&entry.story); + fixture.settle(); + fixture +} + +/// Presses Tab until the stop `part` (`None` for a component's own stop) holds the focus, and returns its rect. +fn tab_to(fixture: &mut Fixture, part: Option<&'static str>) -> Option { + let wanted = part.map(PartKey::new); + for _ in 0..24 { + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let Some((owner, focused)) = fixture.focused_stop() else { continue }; + if focused.map(|focused| focused.key) != wanted { + continue; + } + return match focused { + Some(focused) => fixture.part_rect(owner, focused), + None => fixture.node_of(owner).map(|target| target.rect), + }; + } + None +} + +/// Whether the latest frame paints a focus ring (a rectangle stroke at least two points wide) around `target`. +fn ringed(fixture: &mut Fixture, target: Rect) -> bool { + fixture.frame_shapes().iter().any(|shape| match shape { + Shape::Rect(rect) if rect.stroke.width >= 2.0 => rect.rect.expand(1.0).contains_rect(target), + _ => false, + }) +} + +/// Each focusable part, and each control that is its own stop, is ringed when Tab reaches it. +#[trial] +fn focused_parts_show_the_focus_ring() { + const STOPS: &[(&str, Option<&str>)] = &[ + ("notice", Some("action")), + ("toast_stack", Some("dismiss")), + ("bar_items", Some("item")), + ("list_row", None), + ("list_row_trailing_items", Some("trailing")), + ("list_row_status_cell", Some("status-action")), + ("list_row_thumbnails_only", Some("link")), + ("chip_field", Some("chip")), + ("alt_text_field", Some("decorative")), + ("tile", None), + ("tile_actions", Some("action")), + ("tile_grid_insert_gaps", Some("insert_gap")), + ("thumbnail_slider", Some("out")), + ("tab_strip_ribbon_end_items", Some("end")), + ("table_one", Some("header")), + ("table_editable_grid", Some("header_remove")), + ]; + let mut unringed = Vec::new(); + for &(name, part) in STOPS { + let mut fixture = story(name); + let rect = tab_to(&mut fixture, part).unwrap_or_else(|| panic!("Tab reaches {part:?} in {name}")); + if !ringed(&mut fixture, rect) { + unringed.push(format!("{name} {part:?}")); + } + } + assert!(unringed.is_empty(), "these focused stops show no ring: {unringed:?}"); +} + +/// A focused collection draws no ring around itself: its lead item shows the focus. +#[trial] +fn a_focused_collection_draws_no_ring_around_itself() { + let mut ringed_whole = Vec::new(); + for name in ["tab_strip_ribbon_end_items", "table_one", "tile_grid_insert_gaps"] { + let mut fixture = story(name); + let rect = tab_to(&mut fixture, None).unwrap_or_else(|| panic!("Tab reaches the collection in {name}")); + if ringed(&mut fixture, rect) { + ringed_whole.push(name); + } + } + assert!(ringed_whole.is_empty(), "these collections ring themselves: {ringed_whole:?}"); +} From c0ed8a3e12a9fc20e5c4e94c2ced569da117816e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:06:37 -0800 Subject: [PATCH 087/235] ui-contract: Fixture::frame_clipped_shapes clears the texture changes it does not render frame_clipped_shapes dropped the frame's paint output with its texture changes still in it, so in a debug build a frame that uploaded a texture panicked with "Dropped TexturesDelta with 7 unapplied deltas". It now clears the texture changes before it reads the shapes, as frame_shapes_with already does. The test calls frame_clipped_shapes on the first frame of six menu, rail and tile stories; without the change it panics on the first of them. --- crates/ui-contract/src/testing/fixture.rs | 4 +++- crates/ui-panels/tests/it/main.rs | 1 + crates/ui-panels/tests/it/story_shapes.rs | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 crates/ui-panels/tests/it/story_shapes.rs diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 47c093e029..4b407b1277 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -525,7 +525,9 @@ impl Fixture { self.frames.record_paint(); self.frame(Vec::new()); let mut out = Vec::new(); - let Some(paint) = self.frames.take_paint() else { return out }; + let Some(mut paint) = self.frames.take_paint() else { return out }; + // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. + paint.textures_delta.clear(); for clipped in paint.shapes { let mut shapes = Vec::new(); fixture::flatten(clipped.shape, &mut shapes); diff --git a/crates/ui-panels/tests/it/main.rs b/crates/ui-panels/tests/it/main.rs index 83aaa72406..1c11662b45 100644 --- a/crates/ui-panels/tests/it/main.rs +++ b/crates/ui-panels/tests/it/main.rs @@ -18,6 +18,7 @@ pub(crate) mod popup_surface; pub(crate) mod rails; pub(crate) mod sections; +pub(crate) mod story_shapes; craft_ui::registry!(); diff --git a/crates/ui-panels/tests/it/story_shapes.rs b/crates/ui-panels/tests/it/story_shapes.rs new file mode 100644 index 0000000000..ef8f94c747 --- /dev/null +++ b/crates/ui-panels/tests/it/story_shapes.rs @@ -0,0 +1,17 @@ +//! A fixture returns the clipped shapes of a frame that uploads textures. + +use craft_ui::testing::{Fixture, Registry, trial}; + +/// Menu, rail and tile stories; the first frame of each uploads textures, the font atlas among them. +const STORIES: [&str; 6] = + ["tool_rail_marked_in_a_closed_group", "edit_menu", "menu", "menu_taller_than_the_window", "menu_with_companion", "tile_actions"]; + +#[trial] +fn the_first_frame_of_a_story_returns_its_clipped_shapes() { + let registry = Registry::of(&[craft_ui::testing::register, craft_ui_widgets::testing::register]); + for name in STORIES { + let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("story {name}")); + let shapes = Fixture::story(&entry.story).frame_clipped_shapes(); + assert!(!shapes.is_empty(), "{name}: the frame paints the story"); + } +} From cb1b2301ad615df8b3592b70218ef74b333a53c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:01:02 -0800 Subject: [PATCH 088/235] ui-widgets: InspectOverlay's Tab-order badges show whole inside the drawing Each badge was centered on its stop's leading top corner with nothing keeping it inside the drawing, so a stop at the region's edge got a badge cut in half. In the inspect_overlay story at 400 x 300, badges 1 and 2 sat across the left edge and badge 1 across the top. The badge, ring included, is now moved the least distance that puts it inside the drawing, with keep_inside, the rule a layer's bounds use. On an axis where it already fits it stays on the corner. keep_inside is now public in craft-ui-contract's contract module. --- crates/ui-contract/src/contract/body.rs | 2 +- .../ui-contract/src/contract/body/window.rs | 2 +- crates/ui-contract/src/contract/mod.rs | 1 + .../ui-widgets/src/display/inspect_overlay.rs | 10 ++- crates/ui-widgets/tests/it/runtime/inspect.rs | 65 +++++++++++++++++++ 5 files changed, 76 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 34dc4a8640..76f1c9c2aa 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -36,7 +36,7 @@ pub use scroll::{STRIP_BACK, STRIP_FORWARD}; pub(crate) use window::MOVE_BAND; use window::WindowMode; pub use window::grip_band; -pub(crate) use window::keep_inside; +pub use window::keep_inside; /// The scroll region's view in the last pass that showed it. #[derive(Clone, Default)] diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 79eb032b4d..518f756173 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -215,7 +215,7 @@ fn resized_edge(before: Rect, after: Rect) -> Option { /// `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's /// bounds, whether the user moves the layer or the host places it. On an axis where it is longer than the bounds, its /// low edge sits on theirs. -pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { +pub fn keep_inside(rect: Rect, bounds: Rect) -> Rect { let keep = |low: f32, high: f32, bounds_low: f32, bounds_high: f32| low.min(bounds_high - (high - low)).max(bounds_low) - low; rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y))) } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 60c7bfd0c1..c92e4accef 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -54,6 +54,7 @@ pub use crate::runtime::pending::{Job, Pending, Progress}; pub use body::REORDER_BAND; #[doc(hidden)] pub use body::grip_band; +pub use body::keep_inside; pub use body::pad_of; #[doc(hidden)] pub use body::{STRIP_BACK, STRIP_FORWARD}; diff --git a/crates/ui-widgets/src/display/inspect_overlay.rs b/crates/ui-widgets/src/display/inspect_overlay.rs index 73f9e24ab7..fd259d3399 100644 --- a/crates/ui-widgets/src/display/inspect_overlay.rs +++ b/crates/ui-widgets/src/display/inspect_overlay.rs @@ -1,7 +1,7 @@ //! `InspectOverlay`: the debug inspector's drawing over an inspected region ([`inspect::record`]): each element's //! padding, the hit areas and the focus stops numbered in Tab order, as the record of the region says. -use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Role}; +use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Role, keep_inside}; use crate::primitives::{Draw, PaintShape, StrokeWidth, TextRun}; use crate::runtime::inspect::Recorded; use crate::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; @@ -46,6 +46,8 @@ pub struct InspectOverlayStyle { marquee_fill: StyleColor, badge: StyleColor, badge_text: StyleColor, + /// The width of the ring round a badge: `stroke.thin`. + badge_ring: f32, /// Hit areas under this size across are flagged. pub min_target: f32, } @@ -120,6 +122,7 @@ impl Component for InspectOverlay { marquee_fill: cx.color(color.overlay.marquee.faded(Opacity::TINT)), badge: cx.color(color.status.info.solid), badge_text: cx.color(color.text.on_status), + badge_ring: cx.tokens.stroke.thin, min_target: cx.tokens.size.control.sm, } } @@ -177,10 +180,13 @@ impl InspectOverlay { stops.sort_unstable(); for (number, index) in stops { let Some(bounds) = recorded.stop_rect(index) else { continue }; - let centre = if rtl { bounds.right_top() } else { bounds.left_top() }; + let corner = if rtl { bounds.right_top() } else { bounds.left_top() }; let run = TextRun::new(number.to_string()).role(TypeRole::Caption).color(style.badge_text); let layout = draw.layout(&run, f32::INFINITY); let radius = (layout.size().max_elem() / 2.0 + 2.0).max(7.0); + // Centred on the stop's leading top corner, moved in where that would put the badge past the drawing's edge. + let reach = Vec2::splat(2.0 * (radius + style.badge_ring)); + let centre = keep_inside(Rect::from_center_size(corner, reach), cx.content_rect).center(); draw.fill(&PaintShape::Circle(centre, radius), style.badge); draw.stroke(&PaintShape::Circle(centre, radius), StrokeWidth::Thin, style.halo); draw.galley(centre - layout.size() / 2.0, &layout); diff --git a/crates/ui-widgets/tests/it/runtime/inspect.rs b/crates/ui-widgets/tests/it/runtime/inspect.rs index b4ef417476..3f24e90960 100644 --- a/crates/ui-widgets/tests/it/runtime/inspect.rs +++ b/crates/ui-widgets/tests/it/runtime/inspect.rs @@ -88,6 +88,71 @@ fn a_region_records_its_own_elements_and_numbers_every_stop() { } } +/// The inspected region's rect and its record, as the latest real pass showed them. +type Drawn = (Rect, Arc); + +/// Each Tab-order badge shows whole inside the drawing, in both directions: a badge on a stop at the region's edge +/// moves in until it fits, and on an axis where it already fits it stays on its stop's leading top corner. +#[trial] +fn every_badge_shows_whole_inside_the_region() { + use craft_ui::runtime::env::Direction; + use egui::{Shape, vec2}; + + for direction in [Direction::Ltr, Direction::Rtl] { + let key = Id::NULL.with("trial.inspect.badges"); + let seen: Rc>> = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let mut snap = true; + let mut fixture = Fixture::new(move |ui| { + let (shown, recorded) = inspect::record(ui, key, |ui| { + Stack::new().show(ui, |ui, _| { + Button::new("Apply").show(ui); + Checkbox::new(Bind::bound(&mut snap)).label("Snap to grid").show(ui); + }) + }); + if let Some(recorded) = recorded { + InspectOverlay::new(Arc::clone(&recorded)).show_at(ui, shown.output.rect); + *out.borrow_mut() = Some((shown.output.rect, recorded)); + } + }); + fixture.room(vec2(400.0, 300.0)).direction(direction); + fixture.ctx().disable_accesskit(); + fixture.settle(); + let shapes = fixture.frame_shapes(); + let seen = seen.borrow(); + let (region, recorded) = seen.as_ref().expect("the region ran"); + let mut stops: Vec<(usize, usize)> = + recorded.elements.iter().enumerate().filter_map(|(index, element)| Some((element.stop?, index))).collect(); + stops.sort_unstable(); + assert!(stops.len() >= 2, "{direction:?}: the region has stops: {stops:?}"); + for (number, index) in stops { + let text = fixture.texts().iter().find(|text| text.text == number.to_string()).cloned().expect("the badge's number is painted"); + // The badge's disc and ring, centred on its number; a circle's stroke lies outside its radius. + let reach = shapes + .iter() + .filter_map(|shape| match shape { + Shape::Circle(circle) if circle.center.distance(text.rect.center()) < 1.0 => Some(circle.radius + circle.stroke.width), + _ => None, + }) + .fold(0.0_f32, f32::max); + assert!(reach > 0.0, "{direction:?}: badge {number} has a disc round its number"); + let badge = Rect::from_center_size(text.rect.center(), vec2(2.0 * reach, 2.0 * reach)); + assert!(region.expand(0.05).contains_rect(badge), "{direction:?}: badge {number} at {badge:?} shows whole in the region {region:?}"); + assert!(region.expand(0.5).contains_rect(text.rect), "{direction:?}: badge {number}'s number at {:?} shows whole", text.rect); + // Where the stop's corner leaves room for the whole badge, the badge stays on it. + let stop = recorded.stop_rect(index).expect("the stop is recorded"); + let corner = if direction == Direction::Rtl { stop.right_top() } else { stop.left_top() }; + let room = region.shrink(reach); + if (room.min.x..=room.max.x).contains(&corner.x) { + assert!((badge.center().x - corner.x).abs() < 1.0, "{direction:?}: badge {number} stays on its stop across"); + } + if (room.min.y..=room.max.y).contains(&corner.y) { + assert!((badge.center().y - corner.y).abs() < 1.0, "{direction:?}: badge {number} stays on its stop down"); + } + } + } +} + /// The commands the command trial's buttons are bound to. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] #[command(prefix = "inspectTrial")] From 4bb8e364291a0686833613acfdd8d8cfe1d83082 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:22:08 -0800 Subject: [PATCH 089/235] ui-widgets: a focused menu bar title shows the focus ring Tab, F10 and the arrow keys move the keyboard to a menu bar title, a part of the bar, but no ring marked it. The paint step rings a focused part with its component's focus look, and MenuBarStyle had none; the focus look on TitleFaceStyle belongs to the face, which never takes focus. MenuBarStyle now carries the theme's focus look. --- crates/ui-widgets/src/menu/bar.rs | 9 ++++--- crates/ui-widgets/tests/it/menu/bar.rs | 34 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 99e4e86c20..d583f51d85 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -179,12 +179,15 @@ impl Component for TitleFace { } } -/// The style of a menu bar: the titles wear row faces, which underline their mnemonics. +/// The style of a menu bar: the titles wear row faces, which underline their mnemonics, and the title the keyboard is +/// on is ringed with the focus look. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct MenuBarStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// A title's text without its marker, and its mnemonic: the letter and its character index in the text, none for a @@ -475,8 +478,8 @@ impl Component for MenuBar<'_> { type Style = MenuBarStyle; type Output = MenuBarOutput; - fn style(_: &StyleCx<'_>, _: MenuBarStyleKey) -> MenuBarStyle { - MenuBarStyle { metrics: Metrics::new() } + fn style(cx: &StyleCx<'_>, _: MenuBarStyleKey) -> MenuBarStyle { + MenuBarStyle { metrics: Metrics::new(), focus: cx.focus_look() } } /// Every title's width; at its least (`Proposal::Min`) the width of the "…" title alone. A row that has less room diff --git a/crates/ui-widgets/tests/it/menu/bar.rs b/crates/ui-widgets/tests/it/menu/bar.rs index 0c5f90c5d0..f16fde3cd9 100644 --- a/crates/ui-widgets/tests/it/menu/bar.rs +++ b/crates/ui-widgets/tests/it/menu/bar.rs @@ -601,3 +601,37 @@ fn a_fields_selection_holds_while_the_menu_bar_has_the_keyboard() { let copy = fixture.by_label("Copy").expect("the Edit menu is open"); assert!(!fixture.tree().is_disabled_key(copy.node), "Copy applies to the field's selection"); } + +/// Whether the latest frame paints a focus ring (a stroke at least two points wide) close around `target`, not around +/// the whole bar. +fn ringed(fixture: &mut Fixture, target: egui::Rect) -> bool { + let around = |ring: egui::Rect| ring.expand(1.0).contains_rect(target) && target.expand(4.0).contains_rect(ring); + fixture.frame_shapes().iter().any(|shape| match shape { + egui::Shape::Rect(rect) if rect.stroke.width >= 2.0 => around(rect.rect), + egui::Shape::Path(path) if path.stroke.width >= 2.0 => around(egui::Rect::from_points(&path.points)), + _ => false, + }) +} + +/// The title that Tab, F10 or an arrow key moves the keyboard to is ringed, as a focused button is, and the title the +/// keyboard left is not. +#[trial] +fn the_focused_title_shows_the_focus_ring() { + let mut rig = rig(Direction::Ltr); + let fixture = &mut rig.fixture; + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let (bar, file) = fixture.focused_stop().and_then(|(bar, part)| Some((bar, part?))).expect("Tab focuses a title"); + let file_rect = fixture.part_rect(bar, file).expect("the focused title's rect"); + assert!(ringed(fixture, file_rect), "Tab rings the title it focuses"); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + let edit = fixture.focused_stop().and_then(|(_, part)| part).expect("Right focuses the next title"); + assert_ne!(edit, file, "Right moves to another title"); + let edit_rect = fixture.part_rect(bar, edit).expect("the next title's rect"); + assert!(ringed(fixture, edit_rect), "Right rings the title it moves to"); + assert!(!ringed(fixture, file_rect), "the title the keyboard left loses its ring"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + fixture.key(Key::F10, Modifiers::NONE).settle(); + let first = fixture.focused_stop().and_then(|(_, part)| part).expect("F10 focuses the first title"); + let first_rect = fixture.part_rect(bar, first).expect("the first title's rect"); + assert!(ringed(fixture, first_rect), "F10 rings the title it focuses"); +} From ec140dd7695ccdb461d41742ea67543f6233a53d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:37:28 -0800 Subject: [PATCH 090/235] ui-contract: a label after its control that wraps takes its row's height A field laid out After, or a check box or switch row, whose label wraps after its control kept the height of one line. The measuring run counted the label's height past the control's cell, which spans the whole offered row, so a wrapped label added nothing and its second line was cut. The row now counts the label's reach below the body the control took. A row measured before a wider label column of its form wrapped its label in more room than the real run gives it. The row now notes the widest column its measure holds for, as a beside row does, so the group runs its rows again at the final column. --- crates/ui-contract/src/contract/body/hooks.rs | 10 ++- .../ui-contract/src/contract/label/place.rs | 30 ++++--- .../ui-widgets/tests/it/label/after_wrap.rs | 90 +++++++++++++++++++ crates/ui-widgets/tests/it/label/mod.rs | 1 + 4 files changed, 120 insertions(+), 11 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/after_wrap.rs diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index a92e7820ed..2b12e0b554 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1679,7 +1679,15 @@ impl BodyHooks<'_> { let left = if plan.rtl { body.max.x - size.x } else { body.min.x }; layout::report_bracket_control(ctx, row, Rect::from_min_size(egui::pos2(left, body.min.y), *size), plan.rtl); } - let label_extra = plan.label_extra; + // A label after the control counts the height it reaches below the body the control took, not below the + // row: a measuring run's row can be taller than its body, and a label that wraps there is taller than it. + let after = plan.label_rect.is_positive() && props.label.as_ref().is_some_and(|side| side.layout == label::FieldLayout::After); + let label_extra = if after { + let control = Rect::from_min_size(plan.body_rect.min, Vec2::new(plan.body_rect.width(), size.y)); + label_extra_of(plan.regions.body, control, plan.label_rect, plan.rtl) + } else { + plan.label_extra + }; // A body beside its label in a content-sized column of rows reports how far it reaches past the label // column, so that column's container measures its rows at the widest label. let beside = |side: &&label::SideLabel| side.layout != label::FieldLayout::After && label_extra.x > 0.0 && label_extra.y <= 0.0; diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 256e480322..20b6169e14 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -67,20 +67,22 @@ pub(super) fn hidden_control(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flo } } -/// How far a control with its label after it (a check box row: a labelled check box, or a field whose label follows -/// its control) starts from its row's start. Under a form whose labelled rows share a label column, a row of the -/// column's flow starts past the column and the gap, so its control lines up with theirs, when the row has room for -/// the column, the gap and the control; 0 elsewhere. An inspector's check rows stay at the row's start. -fn after_indent(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, gap: f32) -> f32 { +/// The label column a control with its label after it (a check box row: a labelled check box, or a field whose label +/// follows its control) starts past. Under a form whose labelled rows share a label column, a row of the column's flow +/// starts past the column and the gap, so its control lines up with theirs, when the row has room for the column, the +/// gap and the control: that column, or 0 while the form has none. `None` where the row stays at its start whatever +/// the column: an inspector's check rows, a row outside the column's flow, and a row too narrow for the column. +fn after_column(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, gap: f32) -> Option { if input.side.layout != FieldLayout::After || !input.in_column || env.values.get::() != LabelScheme::Form { - return 0.0; + return None; } match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { Some(column) if input.room >= column + gap + input.control_min => { crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); - column + gap + Some(column) } - _ => 0.0, + Some(_) => None, + None => Some(0.0), } } @@ -89,12 +91,20 @@ fn after_indent(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, gap: f32) - pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: &Ui, leaf: &mut LabelLeaf, glyph: bool, flow: Flow) -> Placed { let rtl = env.direction.is_rtl(); let gap = label_gap(env); - let indent = after_indent(ctx, env, input, gap); + let after_column = after_column(ctx, env, input, gap); + let indent = after_column.filter(|column| *column > 0.0).map_or(0.0, |column| column + gap); let mut natural = leaf.measure_in(kids, craft_behavior::Proposal::Ideal); if input.side.layout == FieldLayout::After && !input.egui_cell { // The label takes the room the control and the gap leave, and its detail wraps there. let room = (input.row.width() - indent - input.control_min - gap).max(0.0); - if natural.x > room { + let wraps = natural.x > room; + // A wider label column leaves the label less room: the row's measure holds while the group's column stays + // within the column it read, or for a label on one line, within the widest column that keeps it there. + if let Some(column) = after_column { + let one_line = input.row.width() - input.control_min - gap - natural.x - gap; + crate::layout::note_beside(ctx, &crate::layout::LABELS, if wraps { column } else { one_line }); + } + if wraps { natural = leaf.measure_in(kids, craft_behavior::Proposal::Width(room)); } } diff --git a/crates/ui-widgets/tests/it/label/after_wrap.rs b/crates/ui-widgets/tests/it/label/after_wrap.rs new file mode 100644 index 0000000000..1adb698aa6 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/after_wrap.rs @@ -0,0 +1,90 @@ +//! A label that follows its control and wraps in a narrow room: the row takes the wrapped label's height. + +use craft_theme::Size; +use craft_ui::choice::{Checkbox, Switch}; +use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _}; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::{Ui, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; + +/// The widest beside label of the form: it sets the label column the row after its control starts past. +const WIDE: &str = "Spacing"; +const SNAP: &str = "Snap to grid"; +const NEXT: &str = "Name"; + +/// The control a row shows with `SNAP` after it. +#[derive(Clone, Copy, Debug)] +enum Row { + /// A field laid out `After` around a check box. + FieldCheckbox, + /// A field laid out `After` around a switch. + FieldSwitch, + /// A switch that carries its own label. + Switch, +} + +impl Row { + fn show(self, ui: &mut Ui) { + match self { + Row::FieldCheckbox => { + Field::new(SNAP).layout(FieldLayout::After).id_salt("snap").show(ui, |ui, _| { + Checkbox::new(Bind::given(true)).show(ui); + }); + } + Row::FieldSwitch => { + Field::new(SNAP).layout(FieldLayout::After).id_salt("snap").show(ui, |ui, _| { + Switch::new(Bind::given(true)).show(ui); + }); + } + Row::Switch => { + Switch::new(Bind::given(true)).label(SNAP).show(ui); + } + } + } +} + +fn number(ui: &mut Ui, name: &'static str, value: f64) { + Field::new(name).show(ui, |ui, _| NumberField::new(name, Bind::given(Some(value))).show(ui)); +} + +/// In a form 130 pt wide at comfortable density, the row's label wraps after its control in the room the label +/// column leaves, whether the form's widest label comes before the row or after it. Every line shows whole inside its +/// clip, and the row after starts under the wrapped label. +#[trial] +fn a_wrapped_label_after_its_control_takes_its_rows_height() { + for row in [Row::FieldCheckbox, Row::FieldSwitch, Row::Switch] { + for wide_first in [true, false] { + let mut fixture = Fixture::new(move |ui| { + FieldGroup::new("Canvas").show(ui, |ui, _| { + if wide_first { + number(ui, WIDE, 1.0); + } + row.show(ui); + number(ui, NEXT, 2.0); + if !wide_first { + number(ui, WIDE, 1.0); + } + }); + }); + fixture.room(Vec2::new(130.0, 600.0)).density(Size::Comfortable); + fixture.settle(); + let case = format!("{row:?}, widest label first: {wide_first}"); + let texts = fixture.texts(); + let snap = texts.iter().find(|run| run.text == SNAP).unwrap_or_else(|| panic!("{case}: {SNAP:?} is painted: {texts:?}")); + let line = texts.iter().find(|run| run.text == WIDE).map_or(0.0, |run| run.rect.height()); + assert!(snap.rect.height() > line + SLACK, "{case}: the label wraps in the room after its control: {:?}", snap.rect); + assert!( + snap.clip.min.y <= snap.rect.min.y + SLACK && snap.clip.max.y >= snap.rect.max.y - SLACK, + "{case}: every line of the label shows whole: {:?} under the clip {:?}", + snap.rect, + snap.clip + ); + let next = texts.iter().find(|run| run.text == NEXT).map(|run| run.rect).unwrap_or_else(|| panic!("{case}: {NEXT:?} is painted")); + assert!(next.min.y >= snap.rect.max.y - SLACK, "{case}: the row after starts under the wrapped label: {:?} {next:?}", snap.rect); + } + } +} diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 0ab8b3540e..3814cd199c 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -1,5 +1,6 @@ //! The label step: scrub across a pointer warp and the label beside or above a fill-width control. +pub(crate) mod after_wrap; pub(crate) mod align; pub(crate) mod baseline; pub(crate) mod bracket; From 52948ceaaf2518c95b2a66ba6274c610fbed4007 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:41:50 -0800 Subject: [PATCH 091/235] dock: a docked group's drag band narrows before the shown tab loses its first letters In a header too narrow for the drag band and the shown tab, the band took its whole width first and the tab strip got what was left. In the DockArea story's 40 pt Tools column the shown tab was 2 pt wide at compact density and missing at comfortable density, though TabStrip keeps the shown tab visible. - ui-contract: HeaderParts::end_narrows lets a container's end parts give up width, down to a least, so the header's children keep a given room. The header line applies it; headers that fit are unchanged. - ui-panels: DockGroup keeps room for the shown tab with its first three letters (with its icon, count, mark and close button, and the overflow button beside other tabs), and its band narrows to an icon's width before that room shrinks. Floating groups use the same header. Test: a_narrow_groups_drag_band_narrows_before_the_shown_tab --- .../ui-contract/src/contract/body/regions.rs | 11 +++- crates/ui-contract/src/contract/container.rs | 15 ++++- crates/ui-panels/src/docking/group.rs | 56 +++++++++++++++---- crates/ui-panels/tests/it/dock_group.rs | 49 ++++++++++++++++ docs/contract-api.md | 3 +- 5 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 5b4025a61e..2e39c20830 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -362,7 +362,8 @@ impl<'b> BodyHooks<'b> { } /// The header's line inside its inset, less the slots of the container's own header parts at its two edges: the - /// rect the header's children get, and the slots. + /// rect the header's children get, and the slots. An end edge that narrows (`HeaderParts::end_narrows`) gives up + /// room, down to its least, until the children keep their room. pub(super) fn header_line(&self, header: Rect, inset: f32, parts: HeaderParts, rtl: bool) -> (Rect, HeaderSlots) { let mut flow = craft_behavior::Flow::new(header.shrink2(Vec2::new(inset, 0.0)), rtl); let mut slots = HeaderSlots::default(); @@ -371,8 +372,12 @@ impl<'b> BodyHooks<'b> { slots.start = Some(slot); flow = rest.take_start(self.region_gap).1; } - if parts.end > 0.0 { - let (slot, rest) = flow.take_end(parts.end); + let end = match parts.end_least { + Some(least) => parts.end.min((flow.rect().width() - self.region_gap - parts.keep).max(least)), + None => parts.end, + }; + if end > 0.0 { + let (slot, rest) = flow.take_end(end); slots.end = Some(slot); flow = rest.take_end(self.region_gap).1; } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 942cdd8240..7866ce3a95 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -280,11 +280,16 @@ pub struct HeaderParts { pub start: f32, /// The width at the end edge. pub end: f32, + /// The least the end edge narrows to, when the line is too narrow for the header's children to keep `keep` + /// beside the end parts' whole width. `None`: the end edge keeps its width. + pub end_least: Option, + /// The room the header's children keep before the end edge narrows below `end` (to `end_least`). + pub keep: f32, } impl HeaderParts { /// No room for parts. - pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0 }; + pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0, end_least: None, keep: 0.0 }; /// `width` at the start edge. pub const fn start(mut self, width: f32) -> Self { @@ -297,6 +302,14 @@ impl HeaderParts { self.end = width; self } + + /// The end edge narrows, down to `least`, so the header's children keep `keep` of the line: on a line too narrow + /// for both, the children's least room comes before the end parts' whole width. + pub const fn end_narrows(mut self, least: f32, keep: f32) -> Self { + self.end_least = Some(least); + self.keep = keep; + self + } } /// An edge of a header's line, where a container's own header parts sit. diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 29c277e8ac..a4426dbcdb 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -221,6 +221,15 @@ const GRIP: PartKey = PartKey::new("grip"); fn grip_width(tokens: &Tokens) -> f32 { tokens.size.icon.lg + 2.0 * tokens.space.pad.regular } + +/// The least the drag band narrows to in a header too narrow for it and the shown tab: an icon's room. +fn grip_least(tokens: &Tokens) -> f32 { + tokens.size.icon.lg +} + +/// How many of the shown tab's first letters the header keeps room for before the drag band narrows, as many as a +/// shrunk panel tab shows. +const SHOWN_TAB_LETTERS: usize = 3; /// The panel menu button at the header's end edge. pub(super) const MENU: PartKey = PartKey::new("panel_menu"); /// Where the group menu hangs while a context request on a tab holds it open: the request's point. @@ -492,6 +501,34 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< IconButton::new(self.panel_menu_icon.clone()).size(ControlSize::Sm).popup(PopupKind::Menu).label(name) } + /// The room the panel menu button takes past the drag band, with the gap before it; none when it does not show. + fn menu_room(&self, cx: &MeasureCx<'_, Self>) -> f32 { + if self.shows_menu_button() { cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x } else { 0.0 } + } + + /// The least room the strip takes to show the shown tab's first letters: the tab as the strip builds it (icon, + /// count, mark and close button) with only those letters of its title, and beside other tabs the overflow + /// button, which is as wide as the tab is high. + fn shown_tab_least(&self, cx: &MeasureCx<'_, Self>) -> f32 { + let panels = self.panels.as_slice(); + let tabs = strip_tabs(panels, self.closable); + let shown = shown_tab(panels, self.active); + let Some(tab) = tabs.iter().find(|tab| tab.key == shown) else { return 0.0 }; + let letters: String = tab.title.as_str().chars().take(SHOWN_TAB_LETTERS).collect(); + let marked = tab_marks(cx.ui.ctx(), panels).iter().any(|(key, _)| *key == shown); + let mut face = Tab::new(letters).kind(TabKind::Panel).panel_look(self.tab_look).closable(tab.closes).marked(marked); + if let Some(count) = tab.count { + face = face.detail(cx.env.format().integer(u64::try_from(count).unwrap_or(u64::MAX))); + } + match tab.swatch { + Some(Some(color)) => face = face.icon(IconSpec::swatch(color)), + Some(None) => face = face.icon(IconSpec::empty_swatch()), + None => {} + } + let size = cx.face(face); + if tabs.len() > 1 { size.x + size.y } else { size.x } + } + /// Starts a drag of the whole group: its drop region shows the group's name. fn start_drag(&mut self, cx: &mut Cx<'_, Self>) { start_group_drag(cx, DragUnit::Group(self.anchor.clone()), self.active, Some(self.size), Some(cx.label())); @@ -520,12 +557,14 @@ impl Component for let Some(slot) = cx.header_slot(HeaderEdge::End) else { return }; let words = cx.words::(); let flow = craft_behavior::Flow::new(slot, cx.flow.is_rtl()); - let (band, rest) = flow.take_start(grip_width(cx.tokens)); + // The band takes what the slot leaves past the panel menu button, which a narrowed header takes from the band. + let width = (slot.width() - self.menu_room(cx)).clamp(0.0, grip_width(cx.tokens)); + let (band, rest) = flow.take_start(width); let sense = if self.movable { Sense::CLICK | Sense::DRAG | Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }; let _ = cx.header_part(HeaderEdge::End, GRIP, band).sense(sense).focusable(); if self.shows_menu_button() { // An icon button is square: its side is the slot's room past the band and the gap. - let side = (slot.width() - grip_width(cx.tokens) - cx.tokens.space.gap.item).max(0.0); + let side = (slot.width() - width - cx.tokens.space.gap.item).max(0.0); let end = rest.take_end(side).0; let height = side.min(slot.height()); let top = if self.tab_look == PanelTabLook::Plain { slot.top() } else { slot.center().y - height / 2.0 }; @@ -680,15 +719,12 @@ impl Container for Some(self.open.reborrow()) } - /// The drag band, then the panel menu button when it shows, at the header's end edge. + /// The drag band, then the panel menu button when it shows, at the header's end edge. In a header too narrow for + /// them and the shown tab's least room, the band narrows to an icon's room, so the shown tab stays visible. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { - let band = grip_width(cx.tokens); - let button = if self.shows_menu_button() { - cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x - } else { - 0.0 - }; - HeaderParts::NONE.end(band + button) + let button = self.menu_room(cx); + let parts = HeaderParts::NONE.end(grip_width(cx.tokens) + button); + if self.titled { parts } else { parts.end_narrows(grip_least(cx.tokens) + button, self.shown_tab_least(cx)) } } fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) { diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index b76f4b2753..70e4217822 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -296,6 +296,55 @@ fn a_press_on_an_app_drag_widget_in_the_body_is_no_surface_press() { assert!(surface.get(), "a press on the empty body is the group's surface press"); } +// As a group narrows, at both densities, the drag band narrows to its least before the shown tab goes below the width a +// shrunk tab keeps (its first letters), alone and beside a tab that goes to the overflow menu. The shown tab stays +// inside the group, and the band never covers it, down to a 40 pt column. +#[trial] +fn a_narrow_groups_drag_band_narrows_before_the_shown_tab() { + use craft_theme::Size; + let tab = |width: f32, density: Size, names: &'static [&'static str]| { + let panels: Vec = names.iter().enumerate().map(|(at, name)| PanelTitle::new(PanelKey::new(at as u64 + 1), *name)).collect(); + let group_rect = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + let grip = Rc::new(Cell::new(None::)); + let seen = Rc::clone(&grip); + let mut fixture = Fixture::new(move |ui| { + let out = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).show_at(ui, group_rect, |_, _| ()); + seen.set(out.output.grip.map(|(rect, _)| rect)); + }); + fixture.density(density).settle(); + (fixture.by_label("Tools").map(|node| node.rect), grip.get()) + }; + for density in [Size::Compact, Size::Comfortable] { + // The least a tab shows: the narrowest "Tools" gets beside a shown tab as the group narrows by 1 pt steps, before + // it overflows; so within 1 pt of the strip's least. + let least = (0..260) + .filter_map(|step| tab(300.0 - step as f32, density, &["Tools Options", "Tools"]).0) + .map(|rect| rect.width()) + .fold(f32::INFINITY, f32::min); + assert!(least.is_finite(), "the other tab shows shrunk in some group ({density:?})"); + for names in [&["Tools"][..], &["Tools", "Swatches"][..]] { + let (Some(natural), Some(whole)) = tab(300.0, density, names) else { panic!("a wide group shows the tab and the band ({density:?})") }; + let least = least.min(natural.width()); + // The band at its narrowest, in the narrowest group. + let (_, Some(narrowest)) = tab(40.0, density, names) else { panic!("a 40 pt group shows the band ({density:?}, {names:?})") }; + assert!(narrowest.width() < whole.width() - 0.5, "the band narrows in a 40 pt group ({density:?}, {names:?})"); + for width in (0..13).map(|step| 40.0 + 8.0 * step as f32) { + let (shown, grip) = tab(width, density, names); + let Some(shown) = shown else { panic!("the shown tab shows in a {width} pt group ({density:?}, {names:?})") }; + let Some(grip) = grip else { panic!("the band shows in a {width} pt group ({density:?}, {names:?})") }; + let group = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + assert!(group.contains_rect(shown), "the shown tab {shown:?} lies inside the {width} pt group ({density:?}, {names:?})"); + assert!(!grip.intersects(shown.shrink(0.5)), "the band {grip:?} does not cover the shown tab {shown:?} in {width} pt ({density:?})"); + assert!( + shown.width() >= least - 1.0 || grip.width() <= narrowest.width() + 0.5, + "the band {grip:?} narrows to {} pt before the shown tab {shown:?} goes below {least} pt in {width} pt ({density:?}, {names:?})", + narrowest.width() + ); + } + } + } +} + // Closable panel tabs stay panel tabs: in a group too narrow for their whole names every tab keeps its place in the // strip, the shown one its whole name, and each shows a close button. A middle click closes an inactive tab without // showing it first. diff --git a/docs/contract-api.md b/docs/contract-api.md index b186ce4737..2f49f3115d 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2279,10 +2279,11 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::GroupState`: `pub struct GroupState { pub selected: Option, pub members: Vec<(M, Id, bool)> }`. A group's registrations: the members shown in the last pass and the member the group picked. - `craft_ui::contract::HeaderEdge`: `pub enum HeaderEdge { Start, End }`. An edge of a header's line, where a container's own header parts sit. - `craft_ui::contract::HeaderMenuRequest`: `pub struct HeaderMenuRequest { pub column: Option, pub at: Pos2 }`. A request for the header menu: a secondary click on a header cell or on the empty header after the last one, or the -- `craft_ui::contract::HeaderParts`: `pub struct HeaderParts { pub start: f32, pub end: f32 }`. The room a container's own parts take on its header's line (`Container::header_parts`): a width at the start edge +- `craft_ui::contract::HeaderParts`: `pub struct HeaderParts { pub start: f32, pub end: f32, pub end_least: Option, pub keep: f32 }`. The room a container's own parts take on its header's line (`Container::header_parts`): a width at the start edge - `pub const NONE: HeaderParts`. No room for parts. - `pub const fn start(mut self, width: f32) -> Self`. `width` at the start edge. - `pub const fn end(mut self, width: f32) -> Self`. `width` at the end edge. + - `pub const fn end_narrows(mut self, least: f32, keep: f32) -> Self`. The end edge narrows, down to `least`, so the header's children keep `keep` of the line: on a line too narrow - `craft_ui::contract::HeaderRegion`: `pub struct HeaderRegion { pub band: DragBand, pub rule: bool, pub rule_above: bool, pub inline: bool, pub trailing: bool, pub fill: Option, pub inset: Pad, pub gap: Option }`. A header region, filled by `Container::header`. - `pub const fn new() -> Self`. A header with no drag band, no rule, on its own line, with no trailing region, no fill and no inset. - `pub const fn fill(mut self, kind: SurfaceKind) -> Self`. The surface of a band behind the header. From 3fb6e6794962fca78c86e16eb4e056f5efddc296 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:52:44 -0800 Subject: [PATCH 092/235] ui-widgets: a list row's cell nodes take their own cell's bounds ListRow::access added the label, toggle, text and status Cell nodes without bounds, so each took the row's rect: in a row with a toggle column, every Cell reported the whole row. The row now keeps each cell's placed rect from parts (the label band for the label cell) and gives it to the cell's node, as a link gives its line and piece nodes theirs. --- crates/ui-widgets/src/list/row.rs | 5 ++- crates/ui-widgets/src/list/row/show.rs | 28 ++++++++++++ crates/ui-widgets/tests/it/list.rs | 62 ++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index f3ac7af3eb..48ebe16a79 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -14,7 +14,7 @@ use crate::contract::{Common, OpenChange, RowHeight, RowPressed, RowState, Show} use crate::primitives::{ContentPainterCx, HAlign, IconSpec, Span, TextRun}; use crate::runtime::env::Label; use crate::style::DataColor; -use craft_behavior::{ColumnKey, Cursor}; +use craft_behavior::{ColumnKey, Cursor, PartRef}; use craft_i18n::Word; use craft_theme::variant::Tone; use craft_theme::{LabelColor, TypeRole}; @@ -467,6 +467,8 @@ pub struct ListRow<'a> { /// The row's menu button was clicked: its rect, where the menu hangs. pub(super) menu: Option, pub(super) label_rect: Rect, + /// The placed rect of each cell node, by the node's part: the access step reads them as the cells' bounds. + pub(super) cell_bounds: Vec<(PartRef, Rect)>, } impl<'a> ListRow<'a> { @@ -564,6 +566,7 @@ impl<'a> ListRow<'a> { open: None, menu: None, label_rect: Rect::NOTHING, + cell_bounds: Vec::new(), } .label(label) } diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 35ca35602f..1d8da0170d 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -211,6 +211,7 @@ impl Component for ListRow<'_> { self.measure_hosted(cx); let widths = self.widths(&cx.style.sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x); let placed = self.place(&cx.style.sizes, &widths, rect, cx.flow.is_rtl()); + self.record_cell_bounds(&placed); self.toggle_parts(&placed, cx); for (at, position, _) in &placed.texts { if self.cell_selects(*at) { @@ -475,12 +476,18 @@ impl Component for ListRow<'_> { let column_of = |key: &ColumnKey| self.cells.iter().position(|(column, _)| column == key); if let Some(column) = self.label_column(&self.cells) { let node = access.node(LABEL_CELL, Role::CELL); + if let Some(rect) = self.cell_rect(LABEL_CELL) { + node.bounds(rect); + } node.name = Name::Text(label.to_owned()); node.grid.column_index = column_of(column); node.flags.set(Flags::SELECTED, selected); } for (at, toggle) in self.toggles.iter().enumerate() { let cell = access.node(TOGGLE_CELL.at(at as u64), Role::CELL); + if let Some(rect) = self.cell_rect(TOGGLE_CELL.at(at as u64)) { + cell.bounds(rect); + } cell.name = Name::Text(label.to_owned()); cell.grid.column_index = column_of(&toggle.column); cell.flags.set(Flags::SELECTED, selected); @@ -492,6 +499,9 @@ impl Component for ListRow<'_> { for text in &self.texts { let Some(position) = self.cells.iter().position(|(column, _)| *column == text.column) else { continue }; let node = access.node(TEXT_CELL.at(position as u64), Role::CELL); + if let Some(rect) = self.cell_rect(TEXT_CELL.at(position as u64)) { + node.bounds(rect); + } node.name = Name::Text(text.text.as_str().to_owned()); node.description = self.tips.iter().find(|(column, _)| *column == text.column).map(|(_, tip)| tip.as_str().to_owned()); node.grid.column_index = Some(position); @@ -500,6 +510,9 @@ impl Component for ListRow<'_> { for (at, cell) in self.statuses.iter().enumerate() { let Some(position) = self.cells.iter().position(|(column, _)| *column == cell.column) else { continue }; let node = access.node(STATUS.at(position as u64), Role::CELL); + if let Some(rect) = self.cell_rect(STATUS.at(position as u64)) { + node.bounds(rect); + } node.name = Name::Text(cell.status.text.as_str().to_owned()); node.description = cell.status.tip.as_ref().map(|tip| tip.as_str().to_owned()); node.grid.column_index = Some(position); @@ -745,6 +758,21 @@ impl ListRow<'_> { if part == TrailingPart::MENU { Label::from(named(&words.more, row)) } else { name.clone() } } + /// Keeps the placed rect of each cell node for the access step: the label cell's is the label band, which spans + /// the label column and the empty toggle columns beside it. + fn record_cell_bounds(&mut self, placed: &Placed) { + let toggles = placed.toggles.iter().map(|(at, cell)| (TOGGLE_CELL.at(*at as u64), *cell)); + let texts = placed.texts.iter().map(|(_, position, cell)| (TEXT_CELL.at(*position as u64), *cell)); + let statuses = placed.statuses.iter().map(|(_, position, cell)| (STATUS.at(*position as u64), *cell)); + self.cell_bounds = std::iter::once((LABEL_CELL.into(), placed.band)).chain(toggles).chain(texts).chain(statuses).collect(); + } + + /// The placed rect of the cell node `part`, which `parts` recorded. + fn cell_rect(&self, part: impl Into) -> Option { + let part = part.into(); + self.cell_bounds.iter().find(|(key, _)| *key == part).map(|(_, rect)| *rect) + } + /// The parts of the row's toggle cells: their flags, held state and tooltip with the toggle's key. fn toggle_parts(&self, placed: &Placed, cx: &mut PartsCx<'_, Self>) { for (at, cell) in &placed.toggles { diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 8d451418de..1ebaa84ce6 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -916,6 +916,68 @@ fn a_toggle_column_holds_one_toggle_with_room_on_each_side() { assert!(cell.width() < 2.0 * cell.height(), "the toggle column holds one toggle: {cell:?}"); } +/// Each cell node of a row lies in its own column: a leading and a trailing toggle cell, the label cell, a text cell +/// and a status cell each take their column's span of the row, not the whole row. +#[trial] +fn each_cell_node_of_a_row_takes_its_columns_bounds() { + use craft_behavior::{ColumnKey, ColumnWidth}; + use craft_theme::variant::Tone; + use craft_ui::contract::{ColumnSpec, Role, ToggleColumn}; + use craft_ui::list::{CellStatus, ToggleCell}; + const EYE: ColumnKey = ColumnKey::new("eye"); + const NAME: ColumnKey = ColumnKey::new("name"); + const SIZE: ColumnKey = ColumnKey::new("size"); + const WARNINGS: ColumnKey = ColumnKey::new("warnings"); + const LOCK: ColumnKey = ColumnKey::new("lock"); + let cells = Rc::new(RefCell::new(Vec::new())); + let held = cells.clone(); + let mut fixture = Fixture::new(move |ui| { + let columns = vec![ + ColumnSpec::toggle(EYE, "", ToggleColumn::sweepable()), + ColumnSpec::new(NAME, "Name", ColumnWidth::fill(1.0)), + ColumnSpec::new(SIZE, "Size", ColumnWidth::fill(1.0)), + ColumnSpec::new(WARNINGS, "Warnings", ColumnWidth::fill(1.0)), + ColumnSpec::toggle(LOCK, "", ToggleColumn::sweepable()), + ]; + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + let _ = List::new("Layers").columns(columns).show_items(ui, &source, &mut |_, icx| { + held.replace(icx.cells().to_vec()); + ListRow::new("Layer 1") + .cells(icx.cells()) + .toggle(ToggleCell::eye(EYE, true)) + .cell(SIZE, "12 KB") + .cell_status(WARNINGS, CellStatus::new(Tone::Warn, "2 warnings")) + .toggle(ToggleCell::lock(LOCK, false)) + }); + }); + fixture.room(Vec2::new(600.0, 200.0)); + fixture.settle(); + let cells = cells.borrow(); + let column = |key: &ColumnKey| cells.iter().find(|(column, _)| column == key).map(|(_, rect)| *rect).expect("the row lists the column"); + let nodes = fixture.by_role(Role::CELL); + assert_eq!(nodes.len(), 5, "one cell node per column: {nodes:?}"); + for node in &nodes { + let tree = fixture.tree(); + let key = match tree.name_of(node.node) { + Some("12 KB") => SIZE, + Some("2 warnings") => WARNINGS, + Some("Layer 1") => match tree.children_of(node.node).first().and_then(|child| tree.name_of(*child)) { + Some(name) if name.contains("Lock") => LOCK, + Some(_) => EYE, + None => NAME, + }, + other => panic!("an unexpected cell node {other:?}"), + }; + let span = column(&key); + assert!( + (node.rect.left() - span.left()).abs() < 0.5 && (node.rect.right() - span.right()).abs() < 0.5, + "the {key:?} cell spans its column: {:?}, the column {span:?}", + node.rect + ); + } +} + /// A toggle cell's glyph rests in `text.muted` and reads in `text.normal` under the pointer. #[trial] fn a_toggle_glyph_rests_muted_and_reads_normal_under_the_pointer() { From 01ab6c5d1dc3b746e3d4f6156fdd5c30d1b98ce6 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 12:54:51 +0000 Subject: [PATCH 093/235] ui-patterns: CommandPalette quiet look for an in-place search in a bar The in-place palette face drew TextField::search at the field look: field fill and the control edge, so in a title bar it read as a heavy outlined white box. Add TextField::quiet (style key) and StyleCx::quiet_field: surface.chrome fill at rest, surface.sunken under the pointer and while focused, line.border edge at rest (line.divider disabled). Focus and invalid edges stay the field's own. CommandPalette::quiet(bool) passes it to both the closed and open in-place field; default false, so the dialog face and other users are unchanged. For storytold/wordcraft#7682. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-contract/src/style/cx.rs | 18 +++++++++++++++ .../tests/it/style/surface_look.rs | 19 ++++++++++++++++ .../src/patterns/panels/palette.rs | 22 +++++++++++++++---- crates/ui-widgets/src/text/text_field.rs | 8 +++++++ 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index d5ab7c55ea..d8aaf1fa49 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -487,6 +487,24 @@ impl<'a> StyleCx<'a> { look } + /// The look of a field that sits in a bar (a title bar's search box): [`field`](Self::field) filled with the bar's + /// `surface.chrome` at rest and with the field fill under the pointer and while it holds focus, and with the quieter + /// `line.border` edge at rest. The focus and invalid edges are the field's own. A bevelled well keeps its look. + pub fn quiet_field(&self) -> SurfaceLook { + let mut look = self.field(); + let (surface, line) = (&self.tokens.color.surface, &self.tokens.color.line); + let (chrome, sunken) = (self.color(surface.chrome), self.color(surface.sunken)); + let off = self.color(self.tokens.color.state.disabled_fill); + look.fill = Stateful::new(chrome).off(States::new(chrome, sunken, sunken, off)).when(Flags::FOCUSED, sunken); + if let Some(edge) = &mut look.border + && edge.off.rest != self.color(Rgba::TRANSPARENT) + { + let (rest, disabled) = (self.color(line.border), self.color(line.divider)); + edge.off = States::new(rest, rest, rest, disabled); + } + look + } + /// The look of the closed box of a dropdown picker: the field, filled with the hover fill under the pointer and /// while its list is open. pub fn dropdown(&self) -> SurfaceLook { diff --git a/crates/ui-contract/tests/it/style/surface_look.rs b/crates/ui-contract/tests/it/style/surface_look.rs index 9b012d4995..862452720d 100644 --- a/crates/ui-contract/tests/it/style/surface_look.rs +++ b/crates/ui-contract/tests/it/style/surface_look.rs @@ -53,3 +53,22 @@ fn a_dropdown_box_fills_under_the_pointer_and_while_open() { assert_eq!(open, hover, "an open box keeps the hover fill"); }); } + +#[trial] +fn a_quiet_field_takes_the_bar_fill_and_a_lighter_edge_at_rest_and_keeps_the_focus_edge() { + let ctx = egui::Context::default(); + let tokens = tokens(Mode::Light, Contrast::Standard); + with_cx(&ctx, &tokens, Variant::SECONDARY, ControlSize::Md, |cx| { + let (plain, quiet) = (cx.field(), cx.quiet_field()); + let (plain_edge, quiet_edge) = (plain.border.as_ref().expect("a field draws an edge"), quiet.border.as_ref().expect("so does a quiet one")); + let at = |state: State, flags: Flags| StateSet::new(state, flags, StateMix::REST); + let rest = at(State::Rest, Flags::empty()); + let hover = StateSet::new(State::Hover, Flags::empty(), StateMix::new(1.0, 0.0, 0.0)); + assert_ne!(rest.resolve(&quiet.fill), rest.resolve(&plain.fill), "at rest the field takes the bar's fill, not the field fill"); + assert_eq!(hover.resolve(&quiet.fill), rest.resolve(&plain.fill), "under the pointer it takes the field fill"); + assert_eq!(at(State::Rest, Flags::FOCUSED).resolve(&quiet.fill), rest.resolve(&plain.fill), "so does a focused one"); + assert_ne!(rest.resolve(quiet_edge), rest.resolve(plain_edge), "the rest edge is quieter than the control edge"); + let focused = at(State::Rest, Flags::FOCUSED); + assert_eq!(focused.resolve(quiet_edge), focused.resolve(plain_edge), "the focus edge is the field's own"); + }); +} diff --git a/crates/ui-patterns/src/patterns/panels/palette.rs b/crates/ui-patterns/src/patterns/panels/palette.rs index 2ac09e7201..9cd8bc08b9 100644 --- a/crates/ui-patterns/src/patterns/panels/palette.rs +++ b/crates/ui-patterns/src/patterns/panels/palette.rs @@ -153,6 +153,10 @@ pub struct CommandPalette<'a> { /// Where the search shows: a centred box or in place. #[prop] face: PaletteFace, + /// The in-place face in the look of a bar's own field: the bar's fill and a light edge at rest, the field fill + /// under the pointer and while open. The field is still named, and shows its search glyph and hint. + #[prop] + quiet: bool, /// The hint the in-place search box shows while it is closed. #[prop(into)] placeholder: Option

) -> Self { + self.drag = payload.map(|payload| Arc::new(payload) as Arc); + self + } } /// The marks of a swatch cell: each is painted from tokens. Other crates build them with the builders, as @@ -452,11 +467,17 @@ impl Component for Swatch { } fn sense(&self) -> Sense { - Sense::CLICK | Sense::FOCUS + if self.drag.is_some() { Sense::CLICK | Sense::FOCUS | Sense::DRAG } else { Sense::CLICK | Sense::FOCUS } } - /// Registers with the enclosing group when it is a member; reports the click. + /// Registers with the enclosing group when it is a member; reports the click; starts the drag of its payload. fn update(&mut self, cx: &mut Cx<'_, Self>) { + if let (PressPhase::DragStart { start, .. }, Some(payload)) = (cx.press().phase, &self.drag) + && start.button == PointerButton::Primary + && cx.resolved.enabled + { + crate::runtime::drag::start(&cx.ctx, cx.id, &cx.env, payload.clone(), Vec::new(), DragPreview::frame(cx.rect.size(), None)); + } if let Some(value) = &self.member { let group = cx.env.get::>>(); group.register(value.clone(), cx.id, cx.resolved.enabled); diff --git a/crates/ui-widgets/tests/it/pickers/swatch.rs b/crates/ui-widgets/tests/it/pickers/swatch.rs index 87f0104fc0..a3519c589a 100644 --- a/crates/ui-widgets/tests/it/pickers/swatch.rs +++ b/crates/ui-widgets/tests/it/pickers/swatch.rs @@ -1,12 +1,50 @@ -//! `Swatch`: the focus ring of a shaped well follows its outline. +//! `Swatch`: the focus ring of a shaped well follows its outline, and a swatch with a drag payload drags it. + +use std::cell::Cell; +use std::rc::Rc; use craft_theme::Srgba; use craft_ui::choice::{RadioGroup, Swatch, SwatchShape}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::layout_components::Row; +use craft_ui::runtime::drag; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Shape, vec2}; +/// A swatch given a payload with `drag` starts a drag session carrying it once the pointer passes the slop, and a +/// click on it still reports `clicked`; a swatch given `None` starts no drag. +#[trial] +fn a_swatch_with_a_payload_drags_it_and_keeps_its_click() { + let clicked = Rc::new(Cell::new(false)); + let seen = clicked.clone(); + let mut fixture = Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + if Swatch::new("Dragged", Srgba::rgb(0.2, 0.4, 0.8)).drag(Some(7u8)).show(ui).clicked { + seen.set(true); + } + Swatch::new("Still", Srgba::rgb(0.8, 0.4, 0.2)).drag(None::).show(ui); + }); + }); + fixture.room(vec2(300.0, 100.0)); + fixture.settle(); + let dragged = fixture.by_label("Dragged").expect("the swatch with a payload").rect; + let still = fixture.by_label("Still").expect("the swatch without one").rect; + + let held = Cell::new(None); + fixture.drag_at_pausing(dragged.center(), vec2(0.0, 40.0), |fixture| held.set(drag::active::(fixture.ctx()).map(|payload| *payload))); + assert_eq!(held.get(), Some(7), "the drag carries the swatch's payload"); + fixture.settle(); + + let held = Cell::new(true); + fixture.drag_at_pausing(still.center(), vec2(0.0, 40.0), |fixture| held.set(drag::active::(fixture.ctx()).is_some())); + assert!(!held.get(), "a swatch given no payload starts no drag"); + fixture.settle(); + + fixture.click_at(dragged.center()); + fixture.settle(); + assert!(clicked.get(), "a click on the swatch with a payload still reports clicked"); +} + /// Every shape of the frame, groups opened. fn flat(shapes: Vec) -> Vec { shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect() From 75be04acdb1f2962f1096f7ea048324dfc7a05df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:24:37 -0800 Subject: [PATCH 152/235] text: the styles panel can treat character style 0 as an editable base style TextStylesPanel always draws character style 0 as "No character style": Style Options, Duplicate and Redefine skip it, a double click does nothing, the row is dimmed and drags of it are refused. An app whose character style 0 is a real base style cannot open its options from the panel. `base_character_style(true)` makes character style 0 behave as paragraph style 0 does: Style Options, Duplicate and Redefine take it from the footer, the panel menu, the row menu and a double click, and the row is drawn like the others. Delete still skips it. The option is off by default, so apps with a "None" row see no change. --- crates/text/src/ui/style_panel.rs | 48 ++++++++++++---- crates/text/tests/it/style_panel.rs | 85 ++++++++++++++++++++++++++++- 2 files changed, 120 insertions(+), 13 deletions(-) diff --git a/crates/text/src/ui/style_panel.rs b/crates/text/src/ui/style_panel.rs index 71ad84b0d9..6491dff78d 100644 --- a/crates/text/src/ui/style_panel.rs +++ b/crates/text/src/ui/style_panel.rs @@ -59,7 +59,8 @@ pub enum TextStyleKind { } /// A style in the list. Id 0 is the base style: "None" for character styles (shown dimmed, never deleted, -/// redefined or edited) and "Basic Paragraph" for paragraph styles (editable, never deleted). +/// redefined or edited) and "Basic Paragraph" for paragraph styles (editable, never deleted). With +/// [`TextStylesPanel::base_character_style`], character style 0 is editable and never deleted as well. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct TextStyleRow { @@ -121,7 +122,8 @@ pub enum TextStyleAction { /// Clear Override, with a target whose style is overridden. ClearOverride, /// Redefine: the style of this id takes the target's attributes: the current style from the footer and the panel - /// menu, the row's from its menu. Not for character style 0. + /// menu, the row's from its menu. Not for character style 0 unless it is a base style + /// ([`TextStylesPanel::base_character_style`]). Redefine(u64), /// New: a style from the selected type when there is a target (`from_selection`), else a default one. The app /// opens its Style Options for the new id. @@ -136,7 +138,8 @@ pub enum TextStyleAction { Duplicate(u64), /// Delete the selected row's style (never id 0). Delete(u64), - /// Style Options for a style: a double click or Enter on a row, or the footer button (not for character style 0). + /// Style Options for a style: a double click or Enter on a row, or the footer button (not for character style 0 + /// unless it is a base style, [`TextStylesPanel::base_character_style`]). Options(u64), /// Duplicate with several rows highlighted: every highlighted style, in list order. DuplicateHighlighted, @@ -182,7 +185,9 @@ impl Outcome for TextStylesPanelOutput { /// What the panel knows of the last pass: the rules the footer, the panel menu and the keys share. #[derive(Clone, Debug, Default, PartialEq, Eq)] struct Facts { - paragraph: bool, + /// Whether style 0 is a base style the user edits: paragraph style 0, or character style 0 with + /// [`TextStylesPanel::base_character_style`]. + base: bool, target: bool, overridden: bool, current: Option, @@ -195,11 +200,11 @@ struct Facts { impl Facts { /// The action of a footer button or menu command, `None` when its condition doesn't hold. fn action(&self, command: TextStyleCommand) -> Option { - let editable = self.picked.filter(|id| *id != 0 || self.paragraph); + let editable = self.picked.filter(|id| *id != 0 || self.base); let several = self.selected.len() > 1; match command { TextStyleCommand::ClearOverride => (self.target && self.overridden).then_some(TextStyleAction::ClearOverride), - TextStyleCommand::Redefine => self.current.filter(|id| self.target && (*id != 0 || self.paragraph)).map(TextStyleAction::Redefine), + TextStyleCommand::Redefine => self.current.filter(|id| self.target && (*id != 0 || self.base)).map(TextStyleAction::Redefine), TextStyleCommand::New => Some(TextStyleAction::new_style(self.target, false)), TextStyleCommand::Duplicate if several => Some(TextStyleAction::DuplicateHighlighted), TextStyleCommand::Delete if several => Some(TextStyleAction::DeleteHighlighted), @@ -289,6 +294,10 @@ pub struct TextStylesPanel<'a> { /// Several rows select together: the footer's Duplicate and Delete act on all of them. #[prop] highlighting: bool, + /// Character style 0 is a base style the user edits instead of "No character style": it takes Style Options, + /// Duplicate and Redefine as paragraph style 0 does, is drawn like the other rows, and is still never deleted. + #[prop] + base_character_style: bool, /// The list's text with no rows, passed to the collection's `empty` prop. #[prop(into)] empty: Option

+ Sen #[derive(Clone, Copy)] struct Inputs<'a> { wells: Option<&'a [PairWell; 2]>, + buttons: Option<&'a [Label; 2]>, edited: Option<&'a Option>, shown: &'a ColorPanelShown, recent: &'a [Srgba], @@ -486,6 +488,7 @@ impl<'a> ColorPanel<'a> { dynamic: true, layout: ColorPanelLayout::default(), wells: None, + buttons: None, edited: None, shown: None, recent: &[], @@ -528,6 +531,14 @@ impl<'a> ColorPanel<'a> { self } + /// The names of the [`ColorPanelLayout::FillStroke`] layout's swap and default buttons, which are also their + /// tooltips: a host names the keys of its own commands there ("Swap Fill and Stroke (Shift+X)"). The panel's + /// words by default. + pub fn buttons(mut self, swap: impl Into

{ moving.column.groups.iter_mut().for_each(|group| group.height = height); } let index = place.group_index().ok_or(DockError::InvalidPlacement)?; - let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups; + let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?; + // Groups shown at a width of their own, in a floating window or an expanded column, keep it + // as the flyout width of the collapsed column they join. + if column.iconic + && !moving.column.iconic + && let Some(width) = moving.column.width + { + let flyout = (column.width != Some(width)).then_some(width); + moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout); + } + let groups = &mut column.groups; let index = (index + usize::from(below)).min(groups.len()); groups.splice(index..index, moving.column.groups); Ok(()) diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index b6eea87da1..e3dad084a9 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -313,6 +313,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect"); } +/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's +/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group +/// moved between collapsed columns keeps its own flyout width. +#[test] +fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() { + let flyout = |layout: &Layout, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width; + + let mut layout = columns(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic); + assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width"); + + layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap(); + layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap(); + layout.apply(Action::set_iconic(6, false)).unwrap(); + layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap(); + layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with"); + + let mut layout = columns(); + layout.apply(Action::resize_column(2, 260.0)).unwrap(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width"); + + let mut layout = columns(); + layout.apply(Action::resize_column(3, 300.0)).unwrap(); + layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column"); + + let mut layout = columns(); + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]); + let Some(root) = layout.root.take() else { panic!("no root") }; + layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root)); + layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); + layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own"); +} + /// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a /// column float in its state; groups joining a column, docked or floating, take that column's state. #[test] From a909963f28c51211e9ab18f0d1e5fcf2746a516c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:52:34 -0800 Subject: [PATCH 159/235] ui-shell: start page links stand on the panel surface The theme holds link text (accent.text) to the 4.5:1 text minimum on the panel, raised and sunken surfaces. The start page drew its links on surface.page (Column) or the canvas surround (Gallery, Greeting), where several light themes read below it. - The Column page's plain links, the rail's links, the links after the sections and the Greeting page's more-templates link stand on a panel surface. - The theme changes are reverted: the accent.text rule, the pinned link colors, the app overrides and Classic's high-contrast page are as on next, and the token dumps are unchanged. --- crates/theme/src/semantic_tests.rs | 4 +- crates/theme/src/values.rs | 5 +- crates/theme/tests/dumps.rs | 24 ----- .../tokens/adwaita-light-high-comfortable.txt | 2 +- .../tokens/adwaita-light-high-compact.txt | 2 +- .../artcraft-light-high-comfortable.txt | 2 +- .../tokens/artcraft-light-high-compact.txt | 2 +- .../artcraft-light-standard-comfortable.txt | 2 +- .../artcraft-light-standard-compact.txt | 2 +- .../tokens/breeze-light-high-comfortable.txt | 2 +- .../tokens/breeze-light-high-compact.txt | 2 +- .../tokens/classic-light-high-comfortable.txt | 2 +- .../tokens/classic-light-high-compact.txt | 2 +- .../classic-light-standard-comfortable.txt | 2 +- .../tokens/classic-light-standard-compact.txt | 2 +- .../graphite-light-high-comfortable.txt | 2 +- .../tokens/graphite-light-high-compact.txt | 2 +- .../pro-light-gray-light-high-comfortable.txt | 4 +- .../pro-light-gray-light-high-compact.txt | 4 +- ...-light-gray-light-standard-comfortable.txt | 4 +- .../pro-light-gray-light-standard-compact.txt | 4 +- .../tokens/pro-light-high-comfortable.txt | 2 +- .../dumps/tokens/pro-light-high-compact.txt | 2 +- .../tokens/pro-light-standard-comfortable.txt | 2 +- .../tokens/pro-light-standard-compact.txt | 2 +- .../tokens/soft-light-high-comfortable.txt | 2 +- .../dumps/tokens/soft-light-high-compact.txt | 2 +- .../tokens/studio-light-high-comfortable.txt | 2 +- .../tokens/studio-light-high-compact.txt | 2 +- ...torcraft-modern-light-high-comfortable.txt | 2 +- .../vectorcraft-modern-light-high-compact.txt | 2 +- ...t-modern-medium-light-high-comfortable.txt | 2 +- ...craft-modern-medium-light-high-compact.txt | 2 +- ...dern-medium-light-standard-comfortable.txt | 2 +- ...t-modern-medium-light-standard-compact.txt | 2 +- crates/theme/themes/artcraft.json | 6 +- crates/theme/themes/classic.json | 5 - crates/theme/themes/pro-light-gray.json | 2 +- crates/theme/themes/pro.json | 2 +- crates/ui-shell/src/shell/start.rs | 28 ++++-- crates/ui-shell/tests/it/shell/start.rs | 91 +++++++++++++++++++ 41 files changed, 155 insertions(+), 84 deletions(-) diff --git a/crates/theme/src/semantic_tests.rs b/crates/theme/src/semantic_tests.rs index 1e76ab627e..958f6eef98 100644 --- a/crates/theme/src/semantic_tests.rs +++ b/crates/theme/src/semantic_tests.rs @@ -117,7 +117,7 @@ pub(super) fn over(fg: Rgba, bg: Rgba) -> Rgba { const TEXT_BGS: [T; 7] = [T::SurfaceBackground, T::SurfacePanel, T::SurfaceChrome, T::SurfaceRaised, T::SurfaceSunken, T::StateHover, T::StatePressed]; -const LINK_BGS: [T; 5] = [T::SurfacePanel, T::SurfaceRaised, T::SurfaceSunken, T::SurfacePage, T::SurfaceBackground]; +const CONTROL_BGS: [T; 3] = [T::SurfacePanel, T::SurfaceRaised, T::SurfaceSunken]; /// The §3 pairs, written out independently of the pass's own table: (fg, bg, standard, high). fn spec_pairs() -> Vec<(T, T, f64, f64)> { @@ -127,7 +127,7 @@ fn spec_pairs() -> Vec<(T, T, f64, f64)> { } p.extend([T::StateSelected, T::StateSelectedHover].map(|bg| (T::TextOnSelected, bg, 4.5, 7.0))); p.push((T::TextOnInverse, T::SurfaceInverse, 4.5, 7.0)); - p.extend(LINK_BGS.map(|bg| (T::AccentText, bg, 4.5, 7.0))); + p.extend(CONTROL_BGS.map(|bg| (T::AccentText, bg, 4.5, 7.0))); p.push((T::AccentOnSoft, T::AccentSoft, 4.5, 7.0)); p.extend([T::AccentSolid, T::AccentHover, T::AccentPressed].map(|bg| (T::TextOnAccent, bg, 4.5, 7.0))); p.extend([T::AccentStrong, T::AccentStrongHover, T::AccentStrongPressed].map(|bg| (T::TextOnStrong, bg, 4.5, 7.0))); diff --git a/crates/theme/src/values.rs b/crates/theme/src/values.rs index 5be41771a9..dc77ea1382 100644 --- a/crates/theme/src/values.rs +++ b/crates/theme/src/values.rs @@ -395,9 +395,6 @@ const TEXT_BGS: &[Bg] = &[ ]; const SELECTED_BGS: &[Bg] = &[Token(T::StateSelected), Token(T::StateSelectedHover)]; const CONTROL_BGS: &[Bg] = &[Token(T::SurfacePanel), Token(T::SurfaceRaised), Token(T::SurfaceSunken)]; -/// Link text stands on the control surfaces, and on the page and the background where a start page draws its links. -const LINK_BGS: &[Bg] = - &[Token(T::SurfacePanel), Token(T::SurfaceRaised), Token(T::SurfaceSunken), Token(T::SurfacePage), Token(T::SurfaceBackground)]; /// The focus line also marks focus on the title bars and tab strips, which sit on the background. const FOCUS_BGS: &[Bg] = &[Token(T::SurfaceBackground), Token(T::SurfacePanel), Token(T::SurfaceChrome), Token(T::SurfaceRaised), Token(T::SurfaceSunken)]; @@ -421,7 +418,7 @@ pub(super) const RULES: &[PairRule] = &[ rule(&[T::TextFaint, T::TextMuted], &[Token(T::SurfaceChrome)], CONTROL_EDGE_MIN.0, CONTROL_EDGE_MIN.1), rule(&[T::TextOnSelected], SELECTED_BGS, TEXT_MIN.0, TEXT_MIN.1), rule(&[T::TextOnInverse], &[Token(T::SurfaceInverse)], TEXT_MIN.0, TEXT_MIN.1), - rule(&[T::AccentText], LINK_BGS, TEXT_MIN.0, TEXT_MIN.1), + rule(&[T::AccentText], CONTROL_BGS, TEXT_MIN.0, TEXT_MIN.1), // After `accent.text`, which it starts from. rule(&[T::AccentOnSoft], &[Token(T::AccentSoft)], TEXT_MIN.0, TEXT_MIN.1), // High contrast only: where the text reaches no further than white, the soft fill moves. diff --git a/crates/theme/tests/dumps.rs b/crates/theme/tests/dumps.rs index 33ccc7ff75..8c597ec6ca 100644 --- a/crates/theme/tests/dumps.rs +++ b/crates/theme/tests/dumps.rs @@ -170,30 +170,6 @@ fn diff(old: &str, new: &str) -> String { out.join("\n") } -/// Link text (`accent.text`) reads at the text minimum on the page and on the window background, where a start page -/// draws its links, in every built-in theme, app, mode and contrast, pinned link colors included. -#[test] -fn link_text_meets_the_text_minimum_on_the_page_and_the_background() { - let mut failures = Vec::new(); - for theme in builtins() { - for app in std::iter::once(None).chain(theme.apps.keys().map(Some)) { - for mode in modes(theme) { - for contrast in [Contrast::Standard, Contrast::High] { - let appearance = Appearance { mode, contrast, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; - let c = resolve(theme, appearance, app).tokens.color; - for (name, ground) in [("surface.page", c.surface.page), ("surface.background", c.surface.background)] { - let ratio = craft_theme::contrast_ratio(c.accent.text, ground); - if ratio < craft_theme::text_contrast_min(contrast) { - failures.push(format!("{} {app:?} {mode:?} {contrast:?}: accent.text on {name} is {ratio:.2}:1", theme.id.as_str())); - } - } - } - } - } - } - assert!(failures.is_empty(), "{}", failures.join("\n")); -} - /// L-310: at the comfortable density the page view keeps production's 70 pt side margins, 28 pt above the first page and /// 14 pt between pages. #[test] diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt index e26b9222bb..bfd4c2a4b7 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #00488fff accent.strong_pressed = #003d7cff accent.soft = #3584e428 accent.border = #486c99ff -accent.text = #00458cff +accent.text = #034d98ff accent.on_soft = #034c98ff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt index d26c27ff9e..428f4679ef 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #00488fff accent.strong_pressed = #003d7cff accent.soft = #3584e428 accent.border = #486c99ff -accent.text = #00458cff +accent.text = #034d98ff accent.on_soft = #034c98ff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt index 0d63ff97b6..7ae732239c 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #002c5bff accent.strong_pressed = #002147ff accent.soft = #d6d6d6ff accent.border = #0058abff -accent.text = #003f87ff +accent.text = #004ea4ff accent.on_soft = #003f87ff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt index 86c74662c6..f4055162b0 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #002c5bff accent.strong_pressed = #002147ff accent.soft = #d6d6d6ff accent.border = #0058abff -accent.text = #003f87ff +accent.text = #004ea4ff accent.on_soft = #003f87ff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt index 37c50f9c28..5de1b1d40b 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #00478aff accent.strong_pressed = #003b75ff accent.soft = #d6d6d6ff accent.border = #378ef0ff -accent.text = #025abcff +accent.text = #1062c4ff accent.on_soft = #025abcff status.good.fg = #297008ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt index 701f87b493..22c786c1bc 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #00478aff accent.strong_pressed = #003b75ff accent.soft = #d6d6d6ff accent.border = #378ef0ff -accent.text = #025abcff +accent.text = #1062c4ff accent.on_soft = #025abcff status.good.fg = #297008ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt index c06e58e9ae..89a38d3fe0 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #003758ff accent.strong_pressed = #002b47ff accent.soft = #3aace830 accent.border = #217399ff -accent.text = #004a72ff +accent.text = #10537dff accent.on_soft = #004a73ff status.good.fg = #1e5b00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt index 1b4164e3ef..1d3a65eee2 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #003758ff accent.strong_pressed = #002b47ff accent.soft = #3aace830 accent.border = #217399ff -accent.text = #004a72ff +accent.text = #10537dff accent.on_soft = #004a73ff status.good.fg = #1e5b00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt index d611d11ee7..61cb69af23 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt @@ -2,7 +2,7 @@ surface.background = #d4d0c8ff surface.canvas = #808080ff surface.canvas_pattern = #808080ff -surface.page = #d4d0c8ff +surface.page = #808080ff surface.panel = #d4d0c8ff surface.chrome = #d4d0c8ff surface.raised = #d4d0c8ff diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt index 0626f13b66..0ca15ed942 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt @@ -2,7 +2,7 @@ surface.background = #d4d0c8ff surface.canvas = #808080ff surface.canvas_pattern = #808080ff -surface.page = #d4d0c8ff +surface.page = #808080ff surface.panel = #d4d0c8ff surface.chrome = #d4d0c8ff surface.raised = #d4d0c8ff diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt index a293e3b041..5af6b006e3 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #d4d0c8ff accent.strong_pressed = #d4d0c8ff accent.soft = #0a246aff accent.border = #0a246aff -accent.text = #021149ff +accent.text = #0b225bff accent.on_soft = #7091d3ff status.good.fg = #45612bff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt index 36c54d3725..245919d79c 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #d4d0c8ff accent.strong_pressed = #d4d0c8ff accent.soft = #0a246aff accent.border = #0a246aff -accent.text = #021149ff +accent.text = #0b225bff accent.on_soft = #7091d3ff status.good.fg = #45612bff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt index decfcb5ff1..6cabc69b57 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #003ca0ff accent.strong_pressed = #003288ff accent.soft = #e5efffff accent.border = #014fcbff -accent.text = #1a4ea1ff +accent.text = #2356aaff accent.on_soft = #184c9fff status.good.fg = #005c4cff status.good.bg = #d4f8eeff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt index 592302a2bb..dec4dfff76 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #003ca0ff accent.strong_pressed = #003288ff accent.soft = #e5efffff accent.border = #014fcbff -accent.text = #1a4ea1ff +accent.text = #2356aaff accent.on_soft = #184c9fff status.good.fg = #005c4cff status.good.bg = #d4f8eeff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt index 1c0730a668..300b3802f1 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt @@ -38,8 +38,8 @@ accent.strong_hover = #00366cff accent.strong_pressed = #002b59ff accent.soft = #d0d0d0ff accent.border = #00498fff -accent.text = #00113bff -accent.on_soft = #003184ff +accent.text = #002964ff +accent.on_soft = #003a85ff status.good.fg = #1b3200ff status.good.bg = #e7f3deff status.good.border = #adcd95ff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt index 630edbe143..27db441dd3 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt @@ -38,8 +38,8 @@ accent.strong_hover = #00366cff accent.strong_pressed = #002b59ff accent.soft = #d0d0d0ff accent.border = #00498fff -accent.text = #00113bff -accent.on_soft = #003184ff +accent.text = #002964ff +accent.on_soft = #003a85ff status.good.fg = #1b3200ff status.good.bg = #e7f3deff status.good.border = #adcd95ff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt index cb27453f77..4e2d60d87b 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt @@ -38,8 +38,8 @@ accent.strong_hover = #0061b9ff accent.strong_pressed = #0055a3ff accent.soft = #d0d0d0ff accent.border = #378ef0ff -accent.text = #003184ff -accent.on_soft = #003184ff +accent.text = #004296ff +accent.on_soft = #004296ff status.good.fg = #36511aff status.good.bg = #e7f3deff status.good.border = #adcd95ff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt index b4b0cc5cd8..da83865dea 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt @@ -38,8 +38,8 @@ accent.strong_hover = #0061b9ff accent.strong_pressed = #0055a3ff accent.soft = #d0d0d0ff accent.border = #378ef0ff -accent.text = #003184ff -accent.on_soft = #003184ff +accent.text = #004296ff +accent.on_soft = #004296ff status.good.fg = #36511aff status.good.bg = #e7f3deff status.good.border = #adcd95ff diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt index 966d049ddd..6ffb292cbd 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #004487ff accent.strong_pressed = #003972ff accent.soft = #d6d6d6ff accent.border = #0058abff -accent.text = #003f87ff +accent.text = #004ea4ff accent.on_soft = #003f87ff status.good.fg = #3c5821ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt index 624d323afa..ca70e2b4c7 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #004487ff accent.strong_pressed = #003972ff accent.soft = #d6d6d6ff accent.border = #0058abff -accent.text = #003f87ff +accent.text = #004ea4ff accent.on_soft = #003f87ff status.good.fg = #3c5821ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt index 05de48efd2..4255d49a8f 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #0061b9ff accent.strong_pressed = #0055a3ff accent.soft = #d6d6d6ff accent.border = #378ef0ff -accent.text = #025abcff +accent.text = #1062c4ff accent.on_soft = #025abcff status.good.fg = #4b6831ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt index 25ecfd821d..35e3129d2d 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #0061b9ff accent.strong_pressed = #0055a3ff accent.soft = #d6d6d6ff accent.border = #378ef0ff -accent.text = #025abcff +accent.text = #1062c4ff accent.on_soft = #025abcff status.good.fg = #4b6831ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt index 5543b49ee4..586c299641 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #323f99ff accent.strong_pressed = #29338bff accent.soft = #6e80d82c accent.border = #6069a1ff -accent.text = #2e3991ff +accent.text = #2e3a92ff accent.on_soft = #2e3a92ff status.good.fg = #3b5821ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt index 5b81005fa7..1dd2cd15fc 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #323f99ff accent.strong_pressed = #29338bff accent.soft = #6e80d82c accent.border = #6069a1ff -accent.text = #2e3991ff +accent.text = #2e3a92ff accent.on_soft = #2e3a92ff status.good.fg = #3b5821ff status.good.bg = #e7f3deff diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt index 4fb92a6269..f786d932ac 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #040406ff accent.strong_pressed = #010101ff accent.soft = #6c5ce724 accent.border = #6f67a4ff -accent.text = #442eb7ff +accent.text = #4b3ac2ff accent.on_soft = #4632baff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt index bcffef3733..097cc1014a 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #040406ff accent.strong_pressed = #010101ff accent.soft = #6c5ce724 accent.border = #6f67a4ff -accent.text = #442eb7ff +accent.text = #4b3ac2ff accent.on_soft = #4632baff status.good.fg = #1f5d00ff status.good.bg = #def7d6ff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt index 3be9a72a1f..2909929b10 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #921600ff accent.strong_pressed = #801100ff accent.soft = #ffe9e4ff accent.border = #af1c00ff -accent.text = #951d09ff +accent.text = #9e2613ff accent.on_soft = #98210dff status.good.fg = #005d28ff status.good.bg = #daf7dfff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt index 663d38a918..deff824ff2 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #921600ff accent.strong_pressed = #801100ff accent.soft = #ffe9e4ff accent.border = #af1c00ff -accent.text = #951d09ff +accent.text = #9e2613ff accent.on_soft = #98210dff status.good.fg = #005d28ff status.good.bg = #daf7dfff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt index 225c67b63b..13c9020bf3 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #921500ff accent.strong_pressed = #801100ff accent.soft = #ffe9e4ff accent.border = #af1b00ff -accent.text = #750e00ff +accent.text = #851200ff accent.on_soft = #98210dff status.good.fg = #004d20ff status.good.bg = #daf7dfff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt index 6651453749..e6da117635 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #921500ff accent.strong_pressed = #801100ff accent.soft = #ffe9e4ff accent.border = #af1b00ff -accent.text = #750e00ff +accent.text = #851200ff accent.on_soft = #98210dff status.good.fg = #004d20ff status.good.bg = #daf7dfff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt index 46f01daf32..eb6164ff38 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt @@ -38,7 +38,7 @@ accent.strong_hover = #bf2d15ff accent.strong_pressed = #b01c00ff accent.soft = #ffe9e4ff accent.border = #d9472fff -accent.text = #a02916ff +accent.text = #a42d1aff accent.on_soft = #a42d1aff status.good.fg = #0b6d32ff status.good.bg = #daf7dfff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt index 4663c03c0f..9c39c4f922 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt @@ -38,7 +38,7 @@ accent.strong_hover = #bf2d15ff accent.strong_pressed = #b01c00ff accent.soft = #ffe9e4ff accent.border = #d9472fff -accent.text = #a02916ff +accent.text = #a42d1aff accent.on_soft = #a42d1aff status.good.fg = #0b6d32ff status.good.bg = #daf7dfff diff --git a/crates/theme/themes/artcraft.json b/crates/theme/themes/artcraft.json index 726d3f750e..aec135debe 100644 --- a/crates/theme/themes/artcraft.json +++ b/crates/theme/themes/artcraft.json @@ -20,7 +20,7 @@ "light": { "accent.soft": "#d6d6d6", "accent.solid": "#378ef0", - "accent.text": "#025abc", + "accent.text": "#1062c4", "caption.close_hover": "#c42b1c", "caption.close_text": "#ffffff", "line.border": "#d6d6d6", @@ -143,7 +143,7 @@ "deckcraft": { "light": { "accent.solid": "#d95a1a", - "accent.text": "#a43b00", + "accent.text": "#b54b16", "text.on_accent": "#ffffff" }, "dark": { @@ -155,7 +155,7 @@ "soundcraft": { "light": { "accent.solid": "#3e74b4", - "accent.text": "#2c5f9a", + "accent.text": "#3b6eab", "text.on_accent": "#ffffff" }, "dark": { diff --git a/crates/theme/themes/classic.json b/crates/theme/themes/classic.json index 8587311ce3..c56d46aa42 100644 --- a/crates/theme/themes/classic.json +++ b/crates/theme/themes/classic.json @@ -62,10 +62,5 @@ "text.normal": "#000000", "text.on_selected": "{text.on_accent}", "text.on_strong": "#000000" - }, - "high_contrast": { - "light": { - "surface.page": "{surface.background}" - } } } diff --git a/crates/theme/themes/pro-light-gray.json b/crates/theme/themes/pro-light-gray.json index 7be3ca729d..852e5b38ca 100644 --- a/crates/theme/themes/pro-light-gray.json +++ b/crates/theme/themes/pro-light-gray.json @@ -20,7 +20,7 @@ "light": { "accent.soft": "#d0d0d0", "accent.solid": "#378ef0", - "accent.text": "#003184", + "accent.text": "#004296", "caption.close_hover": "#c42b1c", "caption.close_text": "#ffffff", "line.border": "#a0a0a0", diff --git a/crates/theme/themes/pro.json b/crates/theme/themes/pro.json index 90d80b1792..0f721de17a 100644 --- a/crates/theme/themes/pro.json +++ b/crates/theme/themes/pro.json @@ -20,7 +20,7 @@ "light": { "accent.soft": "#d6d6d6", "accent.solid": "#378ef0", - "accent.text": "#025abc", + "accent.text": "#1062c4", "caption.close_hover": "#c42b1c", "caption.close_text": "#ffffff", "line.border": "#d6d6d6", diff --git a/crates/ui-shell/src/shell/start.rs b/crates/ui-shell/src/shell/start.rs index 4f0e53ff27..409847732a 100644 --- a/crates/ui-shell/src/shell/start.rs +++ b/crates/ui-shell/src/shell/start.rs @@ -1153,10 +1153,12 @@ fn greeting_body( if !templates.is_empty() { templates_grid(page, ui, templates); } - if let Some(label) = more_templates - && clicked(&Link::new(label.clone()).id_salt("more-templates").show(ui)) - { - page.push(StartAction::MoreTemplates); + if let Some(label) = more_templates { + // The theme holds link text to the text minimum on the panel surface, not on the surround. + let panel = Stack::new().id_salt("more-templates-panel").surface(SurfaceKind::Panel).pad(Pad::Control); + if panel.show(ui, |ui, _| clicked(&Link::new(label.clone()).id_salt("more-templates").show(ui))).inner == Some(true) { + page.push(StartAction::MoreTemplates); + } } let mut list = RecentList::new(recent).max_recent(max_recent).now(page.now); if let Some((thumbnails, source)) = page.thumbnails { @@ -1212,7 +1214,8 @@ fn column_heading(page: &Page<'_>, ui: &mut Ui, title: Option<&Label>, subtitle: /// The links of a Column page under their heading, each centred: the call to action ([`StartLink::primary`]) as a /// pill with its icon, the others as links without their icons, each run of them in rows `size.page.link` high a -/// page link gap apart. A URL opens in the browser (the URL is its tooltip); a command fires as a pointer activation. +/// page link gap apart, on the panel surface. A URL opens in the browser (the URL is its tooltip); a command fires as a +/// pointer activation. fn column_links(page: &Page<'_>, ui: &mut Ui, title: Option<&Label>, links: &[StartLink]) { if links.is_empty() { return; @@ -1227,7 +1230,9 @@ fn column_links(page: &Page<'_>, ui: &mut Ui, title: Option<&Label>, links: &[St if run[0].primary { column_link(ui, cx, at, &run[0]); } else { - let _ = Stack::new().gap(Gap::PageLink).fill_width().show(ui, |ui, cx| { + // The theme holds link text to the text minimum on the panel surface, not on the page. + let panel = Stack::new().id_salt(("start-link-panel", at)).surface(SurfaceKind::Panel).pad(Pad::Control).gap(Gap::PageLink); + let _ = panel.fill_width().show(ui, |ui, cx| { for (offset, link) in run.iter().enumerate() { column_link(ui, cx, at + offset, link); } @@ -1286,9 +1291,16 @@ fn new_and_open(page: &Page<'_>, ui: &mut Ui, sizing: Sizing) { } } -/// The links, one under another: a URL opens through its `Link` (the URL is its tooltip), a command fires as a -/// pointer activation. +/// The links, one under another on the panel surface: a URL opens through its `Link` (the URL is its tooltip), a +/// command fires as a pointer activation. fn link_items(ui: &mut Ui, links: &[StartLink], home: bool) { + // The theme holds link text to the text minimum on the panel surface, not on the surround. + let panel = Stack::new().id_salt("start-link-panel").surface(SurfaceKind::Panel).pad(Pad::Control).gap(Gap::Tight); + let _ = panel.show(ui, |ui, _| link_rows(ui, links, home)); +} + +/// The rows of `link_items`. +fn link_rows(ui: &mut Ui, links: &[StartLink], home: bool) { for (at, link) in links.iter().enumerate() { match &link.target { StartLinkTarget::Url(url) => { diff --git a/crates/ui-shell/tests/it/shell/start.rs b/crates/ui-shell/tests/it/shell/start.rs index 81ab752567..183e1c31a6 100644 --- a/crates/ui-shell/tests/it/shell/start.rs +++ b/crates/ui-shell/tests/it/shell/start.rs @@ -943,6 +943,97 @@ fn a_column_call_to_action_is_a_pill_that_opens_its_url() { assert!(fixture.opened().iter().any(|(url, _)| url == "https://example.com/chat"), "the pill opens its URL: {:?}", fixture.opened()); } +/// The fill under `link` in the painted frame of a start page in `layout` and a `room`, under `root`: the last filled +/// rectangle that holds the link. Returns that fill, the panel's colour, and `accent.text` with the text minimum. +fn ground_under_link(root: RootEnv, layout: StartLayout, room: egui::Vec2, link: &str) -> (egui::Color32, egui::Color32, f64, f64) { + use craft_ui::testing::Frames; + use egui::Color32; + + let color = |c: craft_theme::Rgba| Color32::from(craft_theme::Srgba::from(c)); + let links = vec![ + StartLink::url("Join the community", None, "https://example.com/chat").primary(), + StartLink::url("Website", None, "https://example.com"), + StartLink::url("Docs", None, "https://example.test/docs"), + ]; + let files = vec![RecentFile::new("/tmp/work/Poster.psd", "Poster.psd")]; + let contrast = craft_theme::text_contrast_min(root.appearance(&egui::Context::default()).contrast); + let mut frames = Frames::new(); + frames.root(root); + frames.screen(room); + let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened); + let (mut panel, mut ratio) = (Color32::TRANSPARENT, 0.0); + let mut show = |ui: &mut egui::Ui| { + let c = &Env::of(ui).tokens.color; + panel = color(c.surface.panel); + ratio = craft_theme::contrast_ratio(c.accent.text, c.surface.panel); + let _ = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &files) + .layout(layout) + .links(&links) + .more_templates("More templates") + .show(ui); + }; + frames.frame(Vec::new(), &mut show); + frames.record_paint(); + frames.frame(Vec::new(), &mut show); + let tree = frames.tree(); + let bounds = tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(link)).and_then(|key| tree.bounds_of(key)).expect("the link"); + let paint = frames.take_paint().expect("the frame drew the page"); + let mut fills = Vec::new(); + for shape in &paint.shapes { + filled_rects(&shape.shape, &mut fills); + } + let ground = fills.into_iter().rev().find_map(|(rect, fill)| rect.contains_rect(bounds).then_some(fill)).expect("a fill under the link"); + (ground, panel, ratio, contrast) +} + +/// The filled rectangles of `shape` in paint order, those inside a `Shape::Vec` included. +fn filled_rects(shape: &egui::Shape, out: &mut Vec<(egui::Rect, egui::Color32)>) { + match shape { + egui::Shape::Rect(rect) if rect.fill.a() != 0 => out.push((rect.rect, rect.fill)), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| filled_rects(shape, out)), + _ => {} + } +} + +/// The links a start page draws as `Link`s stand on the panel surface, where the theme holds link text to the text +/// minimum, in every built-in theme, mode and contrast: on a Column page, in the rail, after the sections, and the +/// Greeting page's more-templates link. +#[trial] +fn start_page_links_stand_on_the_panel_surface() { + use craft_theme::{Contrast, Mode, Variants}; + + let pages = [ + (StartLayout::Column, egui::vec2(1600.0, 900.0), "Website"), + (StartLayout::Gallery, egui::vec2(1600.0, 900.0), "Website"), + (StartLayout::Gallery, egui::vec2(420.0, 1600.0), "Website"), + (StartLayout::Greeting, egui::vec2(1600.0, 900.0), "More templates"), + ]; + let mut failures = Vec::new(); + for theme in craft_theme::builtins() { + let modes: &[Mode] = match theme.variants { + Variants::Both => &[Mode::Light, Mode::Dark], + Variants::LightOnly => &[Mode::Light], + Variants::DarkOnly => &[Mode::Dark], + }; + for &mode in modes { + for contrast in [Contrast::Standard, Contrast::High] { + for (layout, room, link) in pages { + let root = RootEnv::default().theme(theme.id.clone()).mode(mode).contrast(contrast); + let (ground, panel, ratio, min) = ground_under_link(root, layout, room, link); + let case = format!("{} {mode:?} {contrast:?} {layout:?} {room:?} {link}", theme.id.as_str()); + if ground != panel { + failures.push(format!("{case}: the link stands on {ground:?}, not the panel {panel:?}")); + } + if ratio < min { + failures.push(format!("{case}: accent.text on the panel is {ratio:.2}:1")); + } + } + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + /// A Column page takes its room above the column and its call to action's height from the page sizes, which an app /// sets (VectorCraft's 60-point margin and 36-point pill). #[trial] From db76f3742f407b87f6365775fb42559c9ac7faef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:55:36 -0800 Subject: [PATCH 160/235] ui-widgets: a segment on a one-line strip is cut at the strip's edges A strip kept on one line in a rect narrower than its segments cuts each part at the rect's edges, so no hit area or face reaches past the strip, and a cut segment shows its label as its tooltip. --- crates/ui-widgets/src/choice/segmented.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/ui-widgets/src/choice/segmented.rs b/crates/ui-widgets/src/choice/segmented.rs index 0ffd5a64ad..4b2d571c6b 100644 --- a/crates/ui-widgets/src/choice/segmented.rs +++ b/crates/ui-widgets/src/choice/segmented.rs @@ -125,14 +125,16 @@ impl Placement { } /// The rect of segment `at` in `rect`, its lines sharing the height `rect` leaves after the gaps between them, and - /// each line's start edge the reading start. + /// each line's start edge the reading start. A segment that reaches past `rect` is cut at its edges. fn rect(&self, at: usize, rect: Rect, gap: f32, rtl: bool) -> Rect { let (line, start) = self.cells[at]; let lines = self.lines.max(1) as f32; let height = ((rect.height() - (lines - 1.0) * gap) / lines).max(0.0); let top = rect.min.y + line as f32 * (height + gap); let line = Rect::from_min_size(pos2(rect.min.x, top), vec2(rect.width(), height)); - Flow::new(line, rtl).span(start, self.widths[at]) + let cell = Flow::new(line, rtl).span(start, self.widths[at]); + let clamp = |x: f32| x.clamp(line.min.x, line.max.x); + Rect::from_x_y_ranges(clamp(cell.min.x)..=clamp(cell.max.x), cell.y_range()) } } @@ -169,8 +171,9 @@ impl Component for Segmented<'_, T> { let placement = if one_line { place(&self.widths(cx), f32::INFINITY, gap) } else { self.arrange(cx, rect.width()) }; let current = self.position_of(cx.value()); for (at, entry) in self.entries.iter().enumerate() { - let mut part = cx.part(Self::part(at), placement.rect(at, rect, gap, rtl)); - if entry.icon_spec().is_some() || placement.widths[at] < placement.wants[at] { + let cell = placement.rect(at, rect, gap, rtl); + let mut part = cx.part(Self::part(at), cell); + if entry.icon_spec().is_some() || cell.width() < placement.wants[at] - 0.5 { part = part.tooltip(entry.label().clone()); } if !entry.is_enabled() { From a830ff539b7d2f311ca4f979411d40e16fb39d45 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:32:11 -0800 Subject: [PATCH 161/235] theme, ui-contract: overlay.cursor colors a painted pointer's marks and a tool's icon; VectorCraft's themes pin it white overlay.cursor follows overlay.stroke unless a theme pins it, so pointers in other themes keep the color they had. VectorCraft Modern and Modern Medium pin it to #ffffff in both variants, so their tool pointers no longer show in the #ffa492 overlay tint, and their hand, magnifier, rotate and badge marks match the icons. The shared pointer art no longer borrows overlay.handle_fill for tool icons. overlay.cursor joins overlay.stroke in the halo contrast rule, so a pin that misses the minimum is reported, and a user's accent keeps a theme's pinned cursor color. Trials; dumps gain the token. --- crates/theme/src/semantic_tests.rs | 24 ++++++++ crates/theme/src/tests.rs | 16 +++++ crates/theme/src/theme.rs | 6 +- crates/theme/src/tokens/color.rs | 8 ++- crates/theme/src/values.rs | 3 +- .../tokens/adwaita-dark-high-comfortable.txt | 1 + .../tokens/adwaita-dark-high-compact.txt | 1 + .../adwaita-dark-standard-comfortable.txt | 1 + .../tokens/adwaita-dark-standard-compact.txt | 1 + .../tokens/adwaita-light-high-comfortable.txt | 1 + .../tokens/adwaita-light-high-compact.txt | 1 + .../adwaita-light-standard-comfortable.txt | 1 + .../tokens/adwaita-light-standard-compact.txt | 1 + .../tokens/artcraft-dark-high-comfortable.txt | 1 + .../tokens/artcraft-dark-high-compact.txt | 1 + .../artcraft-dark-standard-comfortable.txt | 1 + .../tokens/artcraft-dark-standard-compact.txt | 1 + .../artcraft-light-high-comfortable.txt | 1 + .../tokens/artcraft-light-high-compact.txt | 1 + .../artcraft-light-standard-comfortable.txt | 1 + .../artcraft-light-standard-compact.txt | 1 + .../tokens/breeze-dark-high-comfortable.txt | 1 + .../dumps/tokens/breeze-dark-high-compact.txt | 1 + .../breeze-dark-standard-comfortable.txt | 1 + .../tokens/breeze-dark-standard-compact.txt | 1 + .../tokens/breeze-light-high-comfortable.txt | 1 + .../tokens/breeze-light-high-compact.txt | 1 + .../breeze-light-standard-comfortable.txt | 1 + .../tokens/breeze-light-standard-compact.txt | 1 + .../tokens/classic-light-high-comfortable.txt | 1 + .../tokens/classic-light-high-compact.txt | 1 + .../classic-light-standard-comfortable.txt | 1 + .../tokens/classic-light-standard-compact.txt | 1 + .../tokens/graphite-dark-high-comfortable.txt | 1 + .../tokens/graphite-dark-high-compact.txt | 1 + .../graphite-dark-standard-comfortable.txt | 1 + .../tokens/graphite-dark-standard-compact.txt | 1 + .../graphite-light-high-comfortable.txt | 1 + .../tokens/graphite-light-high-compact.txt | 1 + .../graphite-light-standard-comfortable.txt | 1 + .../graphite-light-standard-compact.txt | 1 + .../tokens/pro-dark-high-comfortable.txt | 1 + .../dumps/tokens/pro-dark-high-compact.txt | 1 + ...ro-dark-standard-comfortable-app-sizes.txt | 1 + .../tokens/pro-dark-standard-comfortable.txt | 1 + .../tokens/pro-dark-standard-compact.txt | 1 + .../pro-light-gray-light-high-comfortable.txt | 1 + .../pro-light-gray-light-high-compact.txt | 1 + ...-light-gray-light-standard-comfortable.txt | 1 + .../pro-light-gray-light-standard-compact.txt | 1 + .../tokens/pro-light-high-comfortable.txt | 1 + .../dumps/tokens/pro-light-high-compact.txt | 1 + .../tokens/pro-light-standard-comfortable.txt | 1 + .../tokens/pro-light-standard-compact.txt | 1 + .../tokens/soft-dark-high-comfortable.txt | 1 + .../dumps/tokens/soft-dark-high-compact.txt | 1 + .../tokens/soft-dark-standard-comfortable.txt | 1 + .../tokens/soft-dark-standard-compact.txt | 1 + .../tokens/soft-light-high-comfortable.txt | 1 + .../dumps/tokens/soft-light-high-compact.txt | 1 + .../soft-light-standard-comfortable.txt | 1 + .../tokens/soft-light-standard-compact.txt | 1 + .../solarized-dark-dark-high-comfortable.txt | 1 + .../solarized-dark-dark-high-compact.txt | 1 + ...larized-dark-dark-standard-comfortable.txt | 1 + .../solarized-dark-dark-standard-compact.txt | 1 + .../tokens/studio-dark-high-comfortable.txt | 1 + .../dumps/tokens/studio-dark-high-compact.txt | 1 + .../studio-dark-standard-comfortable.txt | 1 + .../tokens/studio-dark-standard-compact.txt | 1 + .../tokens/studio-light-high-comfortable.txt | 1 + .../tokens/studio-light-high-compact.txt | 1 + .../studio-light-standard-comfortable.txt | 1 + .../tokens/studio-light-standard-compact.txt | 1 + ...ctorcraft-modern-dark-high-comfortable.txt | 1 + .../vectorcraft-modern-dark-high-compact.txt | 1 + ...craft-modern-dark-standard-comfortable.txt | 1 + ...ctorcraft-modern-dark-standard-compact.txt | 1 + ...torcraft-modern-light-high-comfortable.txt | 1 + .../vectorcraft-modern-light-high-compact.txt | 1 + ...raft-modern-light-standard-comfortable.txt | 1 + ...torcraft-modern-light-standard-compact.txt | 1 + ...ft-modern-medium-dark-high-comfortable.txt | 1 + ...rcraft-modern-medium-dark-high-compact.txt | 1 + ...odern-medium-dark-standard-comfortable.txt | 1 + ...ft-modern-medium-dark-standard-compact.txt | 1 + ...t-modern-medium-light-high-comfortable.txt | 1 + ...craft-modern-medium-light-high-compact.txt | 1 + ...dern-medium-light-standard-comfortable.txt | 1 + ...t-modern-medium-light-standard-compact.txt | 1 + .../themes/vectorcraft-modern-medium.json | 2 + crates/theme/themes/vectorcraft-modern.json | 2 + .../ui-contract/src/primitives/pointer_art.rs | 24 +++----- crates/ui-contract/tests/it/runtime/cursor.rs | 58 ++++++++++++++----- docs/suite-themes.md | 2 +- 95 files changed, 193 insertions(+), 37 deletions(-) diff --git a/crates/theme/src/semantic_tests.rs b/crates/theme/src/semantic_tests.rs index 958f6eef98..73fcadd3ea 100644 --- a/crates/theme/src/semantic_tests.rs +++ b/crates/theme/src/semantic_tests.rs @@ -228,3 +228,27 @@ fn the_grip_ink_lies_a_little_apart_from_the_panel_and_a_theme_can_pin_it() { let r = resolve(&pinned, standard(Mode::Dark), None); assert_eq!(r.tokens.color.line.grip, hex("#5a6b7c"), "a theme's pinned line.grip is used"); } + +/// A painted pointer's colour is `overlay.stroke` in a theme that does not pin `overlay.cursor`, in every appearance; +/// a theme that pins it gets its pin with `overlay.stroke` unchanged, and a pin that misses the halo minimum is +/// reported. +#[test] +fn the_cursor_colour_follows_the_overlay_stroke_and_a_theme_can_pin_it() { + for def in [grey_blue(), violet()] { + for a in appearances() { + let c = &resolve(&def, a, None).tokens.color; + assert_eq!(c.overlay.cursor, c.overlay.stroke, "{} {a:?}: overlay.cursor follows overlay.stroke", def.name); + } + } + let reported = |r: &Resolved| r.warnings.iter().any(|w| w.fg == T::OverlayCursor && w.bg == T::OverlayHalo); + let unpinned = resolve(&grey_blue(), app(Mode::Dark, Contrast::Standard), None).tokens.color.overlay.stroke; + let mut pinned = grey_blue(); + pinned.pins.dark = Pins::from_iter([(T::OverlayCursor, Rgba::WHITE)]); + let r = resolve(&pinned, app(Mode::Dark, Contrast::Standard), None); + assert_eq!(r.tokens.color.overlay.cursor, Rgba::WHITE, "a theme's pinned overlay.cursor is used"); + assert_eq!(r.tokens.color.overlay.stroke, unpinned, "the pin leaves overlay.stroke as it was"); + assert!(!reported(&r), "white reads on the halo: {:?}", r.warnings); + pinned.pins.dark = Pins::from_iter([(T::OverlayCursor, hex("#404040"))]); + let r = resolve(&pinned, app(Mode::Dark, Contrast::Standard), None); + assert!(reported(&r), "a dark grey on the dark halo is reported: {:?}", r.warnings); +} diff --git a/crates/theme/src/tests.rs b/crates/theme/src/tests.rs index 47b21c1b56..1d1740b42a 100644 --- a/crates/theme/src/tests.rs +++ b/crates/theme/src/tests.rs @@ -53,3 +53,19 @@ fn an_accent_over_a_theme_takes_its_fill_and_fails_no_pair_the_theme_passes() { } } } + +/// A user's accent leaves a theme's pinned pointer colour as it is, and an unpinned one follows `overlay.stroke` to the +/// new accent. +#[test] +fn an_accent_over_a_theme_keeps_its_pinned_cursor_colour() { + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::default(), text_size: TextSize::default(), reduced_motion: false }; + let seed = Rgba::rgb(0x12, 0x80, 0x30); + let vectorcraft = builtins().iter().find(|t| t.id.as_str() == "craft.vectorcraft-modern").unwrap(); + let pinned = resolve(&vectorcraft.with_accent(seed), appearance, None).tokens; + assert_eq!(pinned.color(ColorToken::OverlayCursor), Rgba::WHITE, "the theme's pin stays"); + let pro = builtins().iter().find(|t| t.id.as_str() == "craft.pro").unwrap(); + let (before, after) = (resolve(pro, appearance, None).tokens, resolve(&pro.with_accent(seed), appearance, None).tokens); + assert_eq!(after.color(ColorToken::OverlayCursor), after.color(ColorToken::OverlayStroke), "an unpinned cursor follows the stroke"); + assert_ne!(after.color(ColorToken::OverlayCursor), before.color(ColorToken::OverlayCursor), "and with it the new accent"); +} diff --git a/crates/theme/src/theme.rs b/crates/theme/src/theme.rs index 36235decfe..4982c6854c 100644 --- a/crates/theme/src/theme.rs +++ b/crates/theme/src/theme.rs @@ -71,7 +71,8 @@ impl ThemeDef { /// colours (the tokens the accent ramp gives, and the ones derived from them) and the text of every contrast pair /// drawn on an accent colour drop their pins and references in every layer, the high-contrast and per-app ones /// included, so they derive from the seed and the contrast pass fits them as it fits an unpinned theme. A token - /// the theme refers to an accent colour keeps its reference, and so follows the seed. + /// the theme refers to an accent colour keeps its reference, and so follows the seed. A pinned `overlay.cursor` + /// keeps its pin, although its default follows the accent through `overlay.stroke`. #[must_use] pub fn with_accent(&self, seed: Rgba) -> ThemeDef { let mut theme = self.clone(); @@ -97,7 +98,8 @@ impl ThemeDef { /// and the text of each contrast pair drawn on an accent colour, counting the tokens a layer refers to one. fn accent_derived(&self, mode: Mode) -> BTreeSet { use crate::values::{Bg, RULES, follows_accent}; - let own: BTreeSet = ColorToken::ALL.iter().copied().filter(|&token| follows_accent(token, mode)).collect(); + let own: BTreeSet = + ColorToken::ALL.iter().copied().filter(|&token| token != ColorToken::OverlayCursor && follows_accent(token, mode)).collect(); let layers = [&self.pins, &self.high_contrast].into_iter().chain(self.apps.values().flat_map(|app| [&app.pins, &app.high_contrast])); let refs: Vec<(ColorToken, ColorToken)> = layers.flat_map(|layer| layer.get(mode).refs.iter().map(|(&token, &to)| (token, to))).collect(); let mut shown = own.clone(); diff --git a/crates/theme/src/tokens/color.rs b/crates/theme/src/tokens/color.rs index 601d964651..e4b5596165 100644 --- a/crates/theme/src/tokens/color.rs +++ b/crates/theme/src/tokens/color.rs @@ -212,8 +212,11 @@ pub struct StateColors { /// Canvas overlays: selection paths, handles, guides. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct OverlayColors { - /// Marks drawn over `halo` (the rotate cursor); handle outlines follow it. + /// Marks drawn over `halo`; handle outlines follow it. pub stroke: Rgba, + /// A painted pointer's marks over `halo`, a tool's icon included (the circle and crosshair keep their own ink); + /// follows `stroke` unless pinned. + pub cursor: Rgba, /// Bare lines on the canvas: a transform box, path outlines, a pen draft, warp boundaries. /// The accent itself, with no halo and no contrast pair, as guides are. pub line: Rgba, @@ -363,6 +366,7 @@ impl ColorTokens { }, overlay: OverlayColors { stroke: c, + cursor: c, line: c, halo: c, handle_fill: c, @@ -583,6 +587,8 @@ color_tokens! { StateStripe = "state.stripe" => state.stripe; /// `overlay.stroke` OverlayStroke = "overlay.stroke" => overlay.stroke; + /// `overlay.cursor` + OverlayCursor = "overlay.cursor" => overlay.cursor; /// `overlay.line` OverlayLine = "overlay.line" => overlay.line; /// `overlay.halo` diff --git a/crates/theme/src/values.rs b/crates/theme/src/values.rs index dc77ea1382..50aaa31707 100644 --- a/crates/theme/src/values.rs +++ b/crates/theme/src/values.rs @@ -300,6 +300,7 @@ pub(super) fn source(token: ColorToken, mode: Mode) -> ColorSource { T::StateMatchCurrent => Faded(T::StatusWarnSolid, 0x6e), T::StateStripe => Faded(T::StateHover, 0x40), T::OverlayStroke => Accent(9), + T::OverlayCursor => Same(T::OverlayStroke), T::OverlayLine => Same(T::AccentSolid), T::OverlayHalo => Fixed(Rgba::BLACK.with_alpha(alpha(0.6))), T::OverlayHandleFill => Fixed(Rgba::WHITE), @@ -457,7 +458,7 @@ pub(super) const RULES: &[PairRule] = &[ TEXT_MIN.1, ) }, - rule(&[T::OverlayStroke], HALO_BGS, NON_TEXT_MIN.0, NON_TEXT_MIN.1), + rule(&[T::OverlayStroke, T::OverlayCursor], HALO_BGS, NON_TEXT_MIN.0, NON_TEXT_MIN.1), // A selected anchor is a handle filled with its outline colour: the outline on the fill is the // only mark of the selection. Standard keeps the accent PhotoCraft outlines its handles in. rule(&[T::OverlayHandleStroke], &[Token(T::OverlayHandleFill)], STATE_CUE_MIN.0, STATE_CUE_MIN.1), diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt index 8e5eec51b5..471ba73dca 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #48484c40 overlay.stroke = #d2e6ffff +overlay.cursor = #d2e6ffff overlay.line = #6eaeffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt index 9616b41a3e..b4dd4841d6 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #48484c40 overlay.stroke = #d2e6ffff +overlay.cursor = #d2e6ffff overlay.line = #6eaeffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt index 99d598503e..93c76d692e 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #48484c40 overlay.stroke = #8dbfffff +overlay.cursor = #8dbfffff overlay.line = #3584e4ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt index bb3adeb54f..6000aa3a17 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #48484c40 overlay.stroke = #8dbfffff +overlay.cursor = #8dbfffff overlay.line = #3584e4ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt index bfd4c2a4b7..d2284d112e 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #766c005a state.match_current = #f8e45c6e state.stripe = #e2e2e540 overlay.stroke = #d2e6ffff +overlay.cursor = #d2e6ffff overlay.line = #0058adff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt index 428f4679ef..8a6319a802 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #766c005a state.match_current = #f8e45c6e state.stripe = #e2e2e540 overlay.stroke = #d2e6ffff +overlay.cursor = #d2e6ffff overlay.line = #0058adff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt index bd0d5c8362..93b8d66d7e 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #e2e2e540 overlay.stroke = #8dbfffff +overlay.cursor = #8dbfffff overlay.line = #3584e4ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt index 63cc0e1092..cf704431c2 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f8e45c6e state.stripe = #e2e2e540 overlay.stroke = #8dbfffff +overlay.cursor = #8dbfffff overlay.line = #3584e4ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt index 8e05869def..fb7173df2f 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #59595940 overlay.stroke = #d3e6ffff +overlay.cursor = #d3e6ffff overlay.line = #bbdaffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt index c5164ff6f3..eabef7ef19 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #59595940 overlay.stroke = #d3e6ffff +overlay.cursor = #d3e6ffff overlay.line = #bbdaffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt index 83cde1b4d3..90fbca176a 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #62626240 overlay.stroke = #8fbeffff +overlay.cursor = #8fbeffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt index bf6f479d76..db5e86ccf5 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #62626240 overlay.stroke = #8fbeffff +overlay.cursor = #8fbeffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt index 7ae732239c..72ab53ca85 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #d3e6ffff +overlay.cursor = #d3e6ffff overlay.line = #0058abff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt index f4055162b0..685df649f3 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #d3e6ffff +overlay.cursor = #d3e6ffff overlay.line = #0058abff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt index 5de1b1d40b..1b13454963 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #8fbeffff +overlay.cursor = #8fbeffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt index 22c786c1bc..53b9c2fb87 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #8fbeffff +overlay.cursor = #8fbeffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt index da8de6122e..2654983b89 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #32363b40 overlay.stroke = #c6e9ffff +overlay.cursor = #c6e9ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt index 4dbde9f9df..06e1b2d4c7 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #32363b40 overlay.stroke = #c6e9ffff +overlay.cursor = #c6e9ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt index d48eaefff7..d4028729ec 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #32363b40 overlay.stroke = #61c6ffff +overlay.cursor = #61c6ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt index 6250cbd212..9cd58df742 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #32363b40 overlay.stroke = #61c6ffff +overlay.cursor = #61c6ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt index 89a38d3fe0..493e039934 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8075005a state.match_current = #f478066e state.stripe = #e2e6eb40 overlay.stroke = #c6e9ffff +overlay.cursor = #c6e9ffff overlay.line = #005f89ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt index 1d3a65eee2..6f72ada43d 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8075005a state.match_current = #f478066e state.stripe = #e2e6eb40 overlay.stroke = #c6e9ffff +overlay.cursor = #c6e9ffff overlay.line = #005f89ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt index d6ca71d5f9..4d179cb802 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #e2e6eb40 overlay.stroke = #61c6ffff +overlay.cursor = #61c6ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt index ebc7d71b49..a312fc415b 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f478066e state.stripe = #e2e6eb40 overlay.stroke = #61c6ffff +overlay.cursor = #61c6ffff overlay.line = #3aace8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt index 61cb69af23..f26daec991 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #7154006e state.stripe = #e2ded640 overlay.stroke = #d7e5ffff +overlay.cursor = #d7e5ffff overlay.line = #0a246aff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt index 0ca15ed942..c2a59173c8 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #7154006e state.stripe = #e2ded640 overlay.stroke = #d7e5ffff +overlay.cursor = #d7e5ffff overlay.line = #0a246aff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt index 5af6b006e3..4d521c1ef9 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #8060006e state.stripe = #e2ded640 overlay.stroke = #ffffffff +overlay.cursor = #ffffffff overlay.line = #0a246aff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt index 245919d79c..54cb7b50f3 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #8060006e state.stripe = #e2ded640 overlay.stroke = #ffffffff +overlay.cursor = #ffffffff overlay.line = #0a246aff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt index 460784c315..79d824f8a6 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #30303440 overlay.stroke = #d5e5ffff +overlay.cursor = #d5e5ffff overlay.line = #5394feff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt index a623008439..5255dfd3f6 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #30303440 overlay.stroke = #d5e5ffff +overlay.cursor = #d5e5ffff overlay.line = #5394feff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt index d7843dc149..70eec503a5 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #30303440 overlay.stroke = #94bdffff +overlay.cursor = #94bdffff overlay.line = #4b8bf5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt index cd4a1b9db4..df033a0c27 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #30303440 overlay.stroke = #94bdffff +overlay.cursor = #94bdffff overlay.line = #4b8bf5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt index 6cabc69b57..f109674bdc 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #ffc14d6e state.stripe = #f7f7f740 overlay.stroke = #d5e5ffff +overlay.cursor = #d5e5ffff overlay.line = #014fcbff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt index dec4dfff76..bd317791d0 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #ffc14d6e state.stripe = #f7f7f740 overlay.stroke = #d5e5ffff +overlay.cursor = #d5e5ffff overlay.line = #014fcbff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt index fbddb2096e..b0de1631f0 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #f7f7f740 overlay.stroke = #94bdffff +overlay.cursor = #94bdffff overlay.line = #1b63e0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt index 7fcbd0bef1..1a4acc7682 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #ffc14d6e state.stripe = #f7f7f740 overlay.stroke = #94bdffff +overlay.cursor = #94bdffff overlay.line = #1b63e0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt index ad3eab959b..e0d24683e6 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #42424240 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #60a9ffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt index ff40e11024..be9fe911d9 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #42424240 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #60a9ffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt index 1b8d7c24de..30091e48a1 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #42424240 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt index b3ddcedb95..4f9c0356e2 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #42424240 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt index ee02262150..0ea0ea7a52 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #42424240 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt index 300b3802f1..d560520aef 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #685e005a state.match_current = #e8b0466e state.stripe = #c6c6c640 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #00498fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt index 27db441dd3..46935ba017 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #685e005a state.match_current = #e8b0466e state.stripe = #c6c6c640 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #00498fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt index 4e2d60d87b..4b74a52be6 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #c6c6c640 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt index da83865dea..1784b8000d 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #c6c6c640 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt index 6ffb292cbd..4c2a5f8382 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #0058abff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt index ca70e2b4c7..22d2076a5e 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #d1e6ffff +overlay.cursor = #d1e6ffff overlay.line = #0058abff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt index 4255d49a8f..ff6a3f49d1 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt index 35e3129d2d..4698cca531 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #e8b0466e state.stripe = #e2e2e240 overlay.stroke = #8abfffff +overlay.cursor = #8abfffff overlay.line = #378ef0ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt index a20c41bb74..fe72f1f53b 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0c8826e state.stripe = #44445040 overlay.stroke = #dce3ffff +overlay.cursor = #dce3ffff overlay.line = #97a8f7ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt index 2f8c94d2d8..22b9581bbd 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0c8826e state.stripe = #44445040 overlay.stroke = #dce3ffff +overlay.cursor = #dce3ffff overlay.line = #97a8f7ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt index 190a24b654..c94bc2b3f5 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0c8826e state.stripe = #44445040 overlay.stroke = #a9b8ffff +overlay.cursor = #a9b8ffff overlay.line = #8a9ae8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt index f0f435aef1..363c1ae46a 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0c8826e state.stripe = #44445040 overlay.stroke = #a9b8ffff +overlay.cursor = #a9b8ffff overlay.line = #8a9ae8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt index 586c299641..08115b0023 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8074005a state.match_current = #8b47006e state.stripe = #e4e2ea40 overlay.stroke = #dce3ffff +overlay.cursor = #dce3ffff overlay.line = #4551a5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt index 1dd2cd15fc..5fde2e32e6 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8074005a state.match_current = #8b47006e state.stripe = #e4e2ea40 overlay.stroke = #dce3ffff +overlay.cursor = #dce3ffff overlay.line = #4551a5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt index 55eb9f36d9..7d1a744956 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #8c48006e state.stripe = #e4e2ea40 overlay.stroke = #a7b9ffff +overlay.cursor = #a7b9ffff overlay.line = #6e80d8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt index eb99cd7c7f..8e826bbaf6 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #8c48006e state.stripe = #e4e2ea40 overlay.stroke = #a7b9ffff +overlay.cursor = #a7b9ffff overlay.line = #6e80d8ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt index f50ae9a4dd..826fe97e5a 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #bb8f116e state.stripe = #0e4a5a40 overlay.stroke = #cde7ffff +overlay.cursor = #cde7ffff overlay.line = #4dacf5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt index 53eca4a616..6b17682d53 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #bb8f116e state.stripe = #0e4a5a40 overlay.stroke = #cde7ffff +overlay.cursor = #cde7ffff overlay.line = #4dacf5ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt index 4bf8a58b61..147b7fe269 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #b589006e state.stripe = #0e4a5a40 overlay.stroke = #79c2ffff +overlay.cursor = #79c2ffff overlay.line = #268bd2ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt index c150d533e0..6cc46fef3b 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #b589006e state.stripe = #0e4a5a40 overlay.stroke = #79c2ffff +overlay.cursor = #79c2ffff overlay.line = #268bd2ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt index bddceef55a..04d9d033d1 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #2c2c3040 overlay.stroke = #e2e2ffff +overlay.cursor = #e2e2ffff overlay.line = #9385ffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt index 3e147fa7eb..6aac24cfa9 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #2c2c3040 overlay.stroke = #e2e2ffff +overlay.cursor = #e2e2ffff overlay.line = #9385ffff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt index a692592aaf..27713e15f7 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #2c2c3040 overlay.stroke = #b7b4ffff +overlay.cursor = #b7b4ffff overlay.line = #8b7cf6ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt index 6a3459b130..0a3c0dc41e 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #2c2c3040 overlay.stroke = #b7b4ffff +overlay.cursor = #b7b4ffff overlay.line = #8b7cf6ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt index f786d932ac..4d4be2a057 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #7b70005a state.match_current = #f0be5a6e state.stripe = #e8e8ed40 overlay.stroke = #e2e2ffff +overlay.cursor = #e2e2ffff overlay.line = #5740caff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt index 097cc1014a..bb2893f308 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #7b70005a state.match_current = #f0be5a6e state.stripe = #e8e8ed40 overlay.stroke = #e2e2ffff +overlay.cursor = #e2e2ffff overlay.line = #5740caff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt index 495a587635..261ef16fb3 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #e8e8ed40 overlay.stroke = #b7b4ffff +overlay.cursor = #b7b4ffff overlay.line = #6c5ce7ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt index 37cefe8908..6d99e6de53 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0be5a6e state.stripe = #e8e8ed40 overlay.stroke = #b7b4ffff +overlay.cursor = #b7b4ffff overlay.line = #6c5ce7ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt index f6cc4664aa..fda37b0371 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #262b3540 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #f26b53ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt index 0d4bc1a574..87e055765a 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #262b3540 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #f26b53ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt index 4f34ee8570..e6d51029c0 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #262b3540 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #f06a52ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt index 0016d3b8f5..68507ff8c1 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #262b3540 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #f06a52ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt index 2909929b10..48d39a6d60 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #f0a3306e state.stripe = #e3e7ed40 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #af1c00ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt index deff824ff2..164d92fb74 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #8378005a state.match_current = #f0a3306e state.stripe = #e3e7ed40 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #af1c00ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt index 66e454fbe6..12a28219c6 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #e3e7ed40 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #d9472fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt index 3eaea40da3..883715ab39 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #e3e7ed40 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #d9472fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt index 1535dfa222..b937848694 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #353c4940 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #fc755cff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt index f58bb3abc0..0138dcf574 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-high-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #353c4940 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #fc755cff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt index 66dad0b281..dbd7056849 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #353c4940 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #f06a52ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt index 55361654ae..ca988719f0 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-dark-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #353c4940 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #f06a52ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt index 13c9020bf3..e340740024 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-comfortable.txt @@ -74,6 +74,7 @@ state.match = #776c005a state.match_current = #f0a3306e state.stripe = #c5ccd640 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #af1b00ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt index e6da117635..c7454463ab 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-high-compact.txt @@ -74,6 +74,7 @@ state.match = #776c005a state.match_current = #f0a3306e state.stripe = #c5ccd640 overlay.stroke = #ffddd5ff +overlay.cursor = #ffffffff overlay.line = #af1b00ff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt index eb6164ff38..554f88b12c 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-comfortable.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #c5ccd640 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #d9472fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt index 9c39c4f922..7d24efddea 100644 --- a/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/vectorcraft-modern-medium-light-standard-compact.txt @@ -74,6 +74,7 @@ state.match = #f0dc005a state.match_current = #f0a3306e state.stripe = #c5ccd640 overlay.stroke = #ffa492ff +overlay.cursor = #ffffffff overlay.line = #d9472fff overlay.halo = #00000099 overlay.handle_fill = #ffffffff diff --git a/crates/theme/themes/vectorcraft-modern-medium.json b/crates/theme/themes/vectorcraft-modern-medium.json index 45029c879f..3fd043a440 100644 --- a/crates/theme/themes/vectorcraft-modern-medium.json +++ b/crates/theme/themes/vectorcraft-modern-medium.json @@ -36,6 +36,7 @@ "line.divider": "#bcc3ce", "line.grip": "#7d8594", "line.outline": "#8a93a2", + "overlay.cursor": "#ffffff", "seeds": { "accent": "#d9472f", "neutral": "#d3d8e0" @@ -64,6 +65,7 @@ "line.divider": "#323946", "line.grip": "#626b7a", "line.outline": "#5a6476", + "overlay.cursor": "#ffffff", "state.hover": "#353c49", "state.pressed": "#633f3e", "state.selected": "#573b3d", diff --git a/crates/theme/themes/vectorcraft-modern.json b/crates/theme/themes/vectorcraft-modern.json index c33372ae3e..f583ab4560 100644 --- a/crates/theme/themes/vectorcraft-modern.json +++ b/crates/theme/themes/vectorcraft-modern.json @@ -36,6 +36,7 @@ "line.divider": "#dde1e8", "line.grip": "#9aa1ad", "line.outline": "#a4abb8", + "overlay.cursor": "#ffffff", "seeds": { "accent": "#d9472f", "neutral": "#f3f5f8" @@ -64,6 +65,7 @@ "line.divider": "#232832", "line.grip": "#5a6271", "line.outline": "#4a5363", + "overlay.cursor": "#ffffff", "state.hover": "#262b35", "state.pressed": "#593330", "state.selected": "#4c2e2e", diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index e9aaa7122f..97e3a29909 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -32,9 +32,8 @@ pub(crate) fn pointer_art(env: &Env, cursor: &PaintedCursor, closed: bool, marks let overlay = &env.tokens.color.overlay; let pen = Pen { art: RefCell::new(Art::default()), - fill: crate::style::rgba_color(overlay.stroke), + fill: crate::style::rgba_color(overlay.cursor), halo: crate::style::rgba_color(overlay.halo), - icon: crate::style::rgba_color(overlay.handle_fill), thin: env.tokens.stroke.thin, rtl: env.direction.is_rtl(), }; @@ -187,14 +186,12 @@ fn v(point: [f32; 2]) -> Vec2 { Vec2::new(point[0], point[1]) } -/// What the pointers draw with: the art they add marks to, the mark colour, its halo, the colour of a tool's icon over -/// that halo, the hairline width, and whether the reading direction is right to left (marks that point along it -/// mirror). +/// What the pointers draw with: the art they add marks to, the mark colour, its halo, the hairline width, and whether +/// the reading direction is right to left (marks that point along it mirror). pub(crate) struct Pen { pub art: RefCell, pub fill: Color32, pub halo: Color32, - pub icon: Color32, pub thin: f32, pub rtl: bool, } @@ -345,7 +342,7 @@ pub(crate) fn zoom(pen: &Pen, out: bool) { } } -/// A tool's `icon` of `side` points with `hotspot` (a point of the icon's 24-unit box) on the pointer, in the icon +/// A tool's `icon` of `side` points with `hotspot` (a point of the icon's 24-unit box) on the pointer, in the mark /// colour over a halo of the icon drawn a hairline off in every direction, and its badge at the icon's lower right. An /// icon the catalog lacks leaves only the badge. pub(crate) fn tool(pen: &Pen, icon: Option, hotspot: Vec2, badge: Option, side: f32) { @@ -358,7 +355,7 @@ pub(crate) fn tool(pen: &Pen, icon: Option, hotspot: Vec2, badge: Optio } } -/// `icon` in `rect` in the icon colour, over copies of it a hairline off in each of eight directions in the halo. +/// `icon` in `rect` in the mark colour, over copies of it a hairline off in each of eight directions in the halo. fn icon_on_halo(pen: &Pen, rect: Rect, icon: SvgIcon) { for dx in [-1.0, 0.0, 1.0] { for dy in [-1.0, 0.0, 1.0] { @@ -367,7 +364,7 @@ fn icon_on_halo(pen: &Pen, rect: Rect, icon: SvgIcon) { } } } - pen.push(Mark::Icon(rect, icon, pen.icon)); + pen.push(Mark::Icon(rect, icon, pen.fill)); } /// The I-beam centred on the pointer: its stem and two serifs, as rules so each lies on whole device pixels and the @@ -499,14 +496,7 @@ fn minus(center: Vec2, half: f32) -> Line { /// badges use, for interface icons that show the same mark. The hairline and the reading direction are those of the /// component that paints the icon: `tokens` and `direction`. pub(crate) fn paint_badge(painter: &egui::Painter, tokens: &UiTokens, direction: Direction, rect: Rect, badge: CursorBadge, ink: Color32) { - let pen = Pen { - art: RefCell::new(Art::default()), - fill: ink, - halo: Color32::TRANSPARENT, - icon: ink, - thin: tokens.stroke.thin, - rtl: direction.is_rtl(), - }; + let pen = Pen { art: RefCell::new(Art::default()), fill: ink, halo: Color32::TRANSPARENT, thin: tokens.stroke.thin, rtl: direction.is_rtl() }; self::badge(&pen, Vec2::ZERO, badge); pen.art.into_inner().paint(painter, rect.center()); } diff --git a/crates/ui-contract/tests/it/runtime/cursor.rs b/crates/ui-contract/tests/it/runtime/cursor.rs index 1772787f91..47a072c8c1 100644 --- a/crates/ui-contract/tests/it/runtime/cursor.rs +++ b/crates/ui-contract/tests/it/runtime/cursor.rs @@ -3,6 +3,7 @@ use craft_behavior::{CountMark, Cursor, CursorBadge, CursorIcon, CursorPriority, IconId, PaintedCursor, PointerGlyph}; use craft_host::target::{Backend, Caps, Os, Runtime, ShellInfo}; +use craft_theme::{Appearance, ColorToken, Contrast, Mode, ModeChoice, Rgba, Size, TextSize, ThemeDef, format, resolve}; use craft_ui::runtime::cursor; use craft_ui::runtime::env::{RootEnv, Scale}; use craft_ui::testing::pointer::moved; @@ -245,22 +246,49 @@ fn a_badged_tool_pointer_keeps_its_tip_on_the_hotspot_and_the_badge_below_right( } } -/// A tool's icon on the pointer is a neutral light silhouette over its dark halo, whatever colour the theme gives the -/// canvas overlay marks: every pixel of the image is grey, with no tint from the overlay colour. +/// A library theme whose overlay marks take a blue tint from its accent, with `overlay.cursor` pinned to white in dark +/// mode when `pinned`. +fn tinted_theme(pinned: bool) -> Arc { + let pin = if pinned { r##", "dark": { "overlay.cursor": "#ffffff" }"## } else { "" }; + let json = format!( + r##"{{ + "schema": "craft-design-theme", "schema_version": 1, + "id": "trial.cursor-ink", "name": "Cursor ink", + "seeds": {{ + "neutral": "#535353", "accent": "#78ADF6", + "status": {{ "good": "#85DC6A", "warn": "#E8B046", "bad": "#FF8080", "info": "#78ADF6" }} + }}{pin} + }}"## + ); + Arc::new(format::parse(json.as_bytes()).expect("the trial's theme parses").theme) +} + +/// A painted pointer is drawn in `overlay.cursor`: a theme that pins it gets a tool's icon and the pointer's own marks +/// in the pin, with no pixel in `overlay.stroke`, and a theme that does not gets them in `overlay.stroke`, which the +/// cursor colour follows. #[trial] -fn a_tool_icon_on_the_pointer_takes_no_overlay_tint() { - let mut frames = frames(linux(), 1.0); - for cursor in [ - PaintedCursor::tool(IconId::new("brush"), Vec2::new(4.0, 20.0), None), - PaintedCursor::pointer_tool(PointerGlyph::Crosshair, IconId::new("crop")), - ] { - let image = painted(&mut frames, cursor.clone()).image.unwrap(); - let tinted = image.rgba.chunks(4).filter(|p| p[3] > 0).find(|p| { - let (high, low) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2])); - high - low > 2 - }); - assert_eq!(tinted, None, "{cursor:?}: a tinted pixel"); - assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] > 200), "{cursor:?}: the icon is drawn light"); +fn a_painted_pointer_is_drawn_in_the_cursor_colour() { + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::default(), text_size: TextSize::default(), reduced_motion: false }; + for pinned in [false, true] { + let def = tinted_theme(pinned); + let tokens = resolve(&def, appearance, None).tokens; + let (ink, stroke) = (tokens.color(ColorToken::OverlayCursor), tokens.color(ColorToken::OverlayStroke)); + assert_eq!(ink == stroke, !pinned, "pinned {pinned}: the cursor colour follows overlay.stroke unless pinned"); + let mut frames = frames(linux(), 1.0); + frames.root(RootEnv::new().library_theme(def).mode(ModeChoice::Dark)); + for cursor in [ + PaintedCursor::tool(IconId::new("brush"), Vec2::new(4.0, 20.0), None), + PaintedCursor::pointer_tool(PointerGlyph::Arrow, IconId::new("lasso")), + PaintedCursor::Hand, + ] { + let image = painted(&mut frames, cursor.clone()).image.unwrap(); + let drawn_in = |colour: Rgba| image.rgba.chunks(4).any(|p| p[3] == 255 && (0..3).all(|i| p[i].abs_diff(colour.0[i]) <= 2)); + assert!(drawn_in(ink), "pinned {pinned}, {cursor:?}: drawn in overlay.cursor"); + if pinned { + assert!(!drawn_in(stroke), "{cursor:?}: no pixel in overlay.stroke"); + } + } } } diff --git a/docs/suite-themes.md b/docs/suite-themes.md index 9d7936b41e..eaf15d5683 100644 --- a/docs/suite-themes.md +++ b/docs/suite-themes.md @@ -98,7 +98,7 @@ High contrast meets every minimum below: it moves pinned values that miss one. S | `accent.text` on `surface.panel`, `surface.raised` and `surface.sunken`; `accent.on_soft` on `accent.soft` | 4.5 | 7 | | Status text (`status.good.fg` ...) on `surface.panel`, `surface.raised` and its own `status.*.bg` | 4.5 | 7 | | `text.on_accent` on `accent.solid`, `accent.hover` and `accent.pressed`; `text.on_strong` on `accent.strong`, `accent.strong_hover` and `accent.strong_pressed`; `text.on_status` on the status solids and their hover and pressed steps | 4.5 | 7 | -| `line.focus` on the surfaces; `accent.solid` on the control surfaces (panel, raised, sunken: checked and selected marks); `line.mark` (slider marks and ticks, the badge ring) on the control surfaces, `state.hover` and `state.pressed`; `overlay.stroke` on `overlay.halo` over black and over white | 3 | 4.5 | +| `line.focus` on the surfaces; `accent.solid` on the control surfaces (panel, raised, sunken: checked and selected marks); `line.mark` (slider marks and ticks, the badge ring) on the control surfaces, `state.hover` and `state.pressed`; `overlay.stroke` and `overlay.cursor` on `overlay.halo` over black and over white | 3 | 4.5 | | State cues: `accent.border` (the outline of a selected or on control) on the control surfaces; `overlay.handle_stroke` on `overlay.handle_fill` (a selected anchor against a hollow one); the data channel colours (`data.red` ... `data.yellow`) on `surface.sunken` (a curve editor's plot) | 0 (listed, never warned) | 4.5 | | The thumb of a canvas scroll bar (`text.faint`, `text.muted`) on its track (`surface.chrome`) | 0 (listed, never warned) | 3 | From 3af616be852c438e5fe06b234e9ece4d64ac0dc0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:34:51 -0800 Subject: [PATCH 162/235] ui-widgets: a toggle cell the list does not flip paints disabled A collection already refuses a press, a sweep and the Space key on a toggle cell whose source says it does not flip (`ItemSource::toggle_enabled` false, or a section row), and reports its node disabled. The row still painted that cell with the normal toggle ink, brightened it under the pointer and showed the off glyph on hover, so a locked cell looked clickable. - `ItemFacts` carries `closed_toggles`, the toggle columns whose cell in the item does not flip, filled from `toggle_open`. - `ListRow` reads them with the other facts and declares such a cell's part inactive, so its glyph or check box paints in the Disabled state at rest, under the pointer and under a press. - An off cell there shows no off glyph under the pointer. --- crates/ui-contract/src/contract/items.rs | 1 + .../ui-contract/src/contract/items/hooks.rs | 2 + .../ui-contract/src/contract/items/measure.rs | 1 + crates/ui-contract/src/runtime/env.rs | 4 + crates/ui-widgets/src/list/row.rs | 4 + crates/ui-widgets/src/list/row/paint.rs | 2 +- crates/ui-widgets/src/list/row/placement.rs | 3 +- crates/ui-widgets/src/list/row/show.rs | 12 ++- crates/ui-widgets/tests/it/list.rs | 100 ++++++++++++++++++ 9 files changed, 124 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 0d2e7d28ac..cabba801f8 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -24,6 +24,7 @@ fn with_item_facts(ui: &mut Ui, at: crate::runtime::access::SetPosition, body columns: Vec::new(), toggles: Vec::new(), toggle_keys: Vec::new(), + closed_toggles: Vec::new(), aligns: Vec::new(), pressed: None, menu_open: false, diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index a274babf17..f4613b13c6 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -499,6 +499,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let column_keys: Vec = cells.iter().map(|(key, _)| key.clone()).collect(); let shown_cells = cells.clone(); let toggle_keys: Vec = self.header.toggle_columns().map(|(key, _)| key).collect(); + let closed_toggles: Vec = toggle_keys.iter().filter(|key| !self.toggle_open(at, key)).cloned().collect(); let mut icx = ItemCx { key: &key, at, @@ -551,6 +552,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { columns: column_keys, toggles: toggle_keys, toggle_keys: self.header.toggle_keys(), + closed_toggles, aligns: aligns.clone(), pressed: state.pressed.clone(), menu_open: state.menu_open, diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 2a546e8921..3a752f9589 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -220,6 +220,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { columns, toggles: self.header.toggle_columns().map(|(key, _)| key).collect(), toggle_keys: Vec::new(), + closed_toggles: Vec::new(), aligns: self.header.aligns(), pressed: None, menu_open: false, diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 64494b8af4..6b03e835b5 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -377,6 +377,10 @@ pub struct ItemFacts { /// The keys of the toggle columns that have one (`ToggleColumn::key`), which their cells show in the tooltip. #[doc(hidden)] pub toggle_keys: Vec<(craft_behavior::ColumnKey, craft_keymap::Chord)>, + /// The toggle columns whose cell in this item does not flip (`ItemSource::toggle_enabled` is false, or the item is + /// a section): the row paints such a cell inactive. + #[doc(hidden)] + pub closed_toggles: Vec, /// Each column's alignment and whether its figures are tabular, from its `ColumnSpec`: a row places its cells' /// text by them. #[doc(hidden)] diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index 48ebe16a79..f17f070791 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -399,6 +399,9 @@ pub struct ListRow<'a> { pub(super) toggle_columns: Vec, /// The keys of those toggle columns that have one, from the same facts: their cells show the key in the tooltip. pub(super) toggle_keys: Vec<(ColumnKey, craft_keymap::Chord)>, + /// The toggle columns whose cell in this row does not flip, from the same facts: their cells paint inactive and + /// show no hover. + pub(super) closed_toggles: Vec, pub(super) toggles: Vec, pub(super) texts: Vec, /// The status cells (`cell_status`), in the order added. @@ -538,6 +541,7 @@ impl<'a> ListRow<'a> { selectable: Vec::new(), toggle_columns: Vec::new(), toggle_keys: Vec::new(), + closed_toggles: Vec::new(), toggles: Vec::new(), texts: Vec::new(), statuses: Vec::new(), diff --git a/crates/ui-widgets/src/list/row/paint.rs b/crates/ui-widgets/src/list/row/paint.rs index 20412f017e..b88e9649d9 100644 --- a/crates/ui-widgets/src/list/row/paint.rs +++ b/crates/ui-widgets/src/list/row/paint.rs @@ -97,7 +97,7 @@ impl ListRow<'_> { ToggleFace::Icons { on, off } => { let shown = match toggle.state { ToggleState::On | ToggleState::Mixed => Some(on), - ToggleState::Off if toggle.shows_off(cx.part(part).hovered) => Some(off), + ToggleState::Off if toggle.shows_off(cx.part(part).hovered && !self.toggle_closed(toggle)) => Some(off), ToggleState::Off => None, }; if let Some(id) = shown { diff --git a/crates/ui-widgets/src/list/row/placement.rs b/crates/ui-widgets/src/list/row/placement.rs index 171cb5d9d0..c7d9671bbd 100644 --- a/crates/ui-widgets/src/list/row/placement.rs +++ b/crates/ui-widgets/src/list/row/placement.rs @@ -228,13 +228,14 @@ impl ListRow<'_> { } } - /// Takes the toggle columns, their keys, the columns' alignments and the press the collection holds on the row from + /// Takes the toggle columns, their keys, the ones that do not flip in this row, the columns' alignments and the press the collection holds on the row from /// the facts it recorded for this row: an end-aligned column's text ends at the cell's end (mirrored in a /// right-to-left interface) and a numeric column's figures are tabular. pub(super) fn adopt_facts(&mut self, env: &EnvView<'_>, id: egui::Id) { if let Some(facts) = env.facts_of(id) { self.toggle_columns.clone_from(&facts.toggles); self.toggle_keys.clone_from(&facts.toggle_keys); + self.closed_toggles.clone_from(&facts.closed_toggles); self.aligns = facts.aligns.iter().map(|(key, align, tabular)| (key.clone(), halign(*align), *tabular)).collect(); if self.pressed.is_none() { self.pressed.clone_from(&facts.pressed); diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 4b403ce195..ff3705d148 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -14,7 +14,7 @@ use crate::contract::{ }; use crate::controls::disclosure::Disclosure; use crate::display::Progress; -use crate::list::toggle::{ToggleFace, ToggleState}; +use crate::list::toggle::{ToggleCell, ToggleFace, ToggleState}; use crate::list::words::ListWords; use crate::primitives::{DocRun, DocText, RectSide, RuleKind, StrokeWidth, TextRun, Wrap, glyph}; use crate::runtime::commands::FireSource; @@ -779,7 +779,13 @@ impl ListRow<'_> { self.cell_bounds.iter().find(|(key, _)| *key == part).map(|(_, rect)| *rect) } - /// The parts of the row's toggle cells: their flags, held state and tooltip with the toggle's key. + /// The collection does not flip `toggle` in this row (`ItemSource::toggle_enabled`): its cell paints in the + /// Disabled state and shows no hover. + pub(super) fn toggle_closed(&self, toggle: &ToggleCell) -> bool { + self.closed_toggles.contains(&toggle.column) + } + + /// The parts of the row's toggle cells: their flags, held state, inactive state and tooltip with the toggle's key. fn toggle_parts(&self, placed: &Placed, cx: &mut PartsCx<'_, Self>) { for (at, cell) in &placed.toggles { let toggle = &self.toggles[*at]; @@ -808,7 +814,7 @@ impl ListRow<'_> { Some(RowPressed::Row) => toggle.row_press, _ => false, }; - let part = cx.part(TOGGLE.at(*at as u64), shape).flags(flags).held(held); + let part = cx.part(TOGGLE.at(*at as u64), shape).flags(flags).held(held).inactive(self.toggle_closed(toggle)); let _ = match tip { Some(tip) => part.tooltip(tip), None => part, diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 822fc22898..81cbcb6f84 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -1078,6 +1078,106 @@ fn a_toggle_glyph_rests_muted_and_reads_normal_under_the_pointer() { ); } +/// Two rows whose eye cell is on and whose lock cell is off; the source does not flip the first row's cells. +struct LockedFirst; + +const LOCKED_EYE: craft_behavior::ColumnKey = craft_behavior::ColumnKey::new("eye"); + +impl craft_behavior::DisplayOrder for LockedFirst { + fn len(&self) -> usize { + 2 + } + + fn key(&self, at: usize) -> usize { + at + } +} + +impl craft_behavior::ItemSource for LockedFirst { + fn toggled(&self, _: usize, column: &craft_behavior::ColumnKey) -> bool { + *column == LOCKED_EYE + } + + fn toggle_enabled(&self, at: usize, _: &craft_behavior::ColumnKey) -> bool { + at != 0 + } +} + +/// A toggle cell the source does not flip paints its glyph in `text.disabled` at rest, under the pointer and under a +/// press, shows no off glyph under the pointer, and its node reads disabled; the cells of a row that flips keep +/// `text.muted`, their off glyph under the pointer and enabled nodes. +#[trial] +fn a_toggle_cell_that_does_not_flip_paints_disabled_and_ignores_the_pointer() { + use craft_behavior::{ColumnKey, ColumnWidth}; + use craft_ui::contract::{ColumnSpec, Role, ToggleColumn}; + use craft_ui::list::ToggleCell; + use craft_ui::runtime::env::Env; + use craft_ui::testing::pointer; + use egui::Color32; + use std::cell::Cell; + const LOCK: ColumnKey = ColumnKey::new("lock"); + const NAME: ColumnKey = ColumnKey::new("name"); + // The eye and lock cells of each row. + let seen = Rc::new(Cell::new(([[egui::Rect::NOTHING; 2]; 2], Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let text = Env::of(ui).tokens.tokens().color.text; + let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a); + let columns = vec![ + ColumnSpec::toggle(LOCKED_EYE, "", ToggleColumn::sweepable()), + ColumnSpec::toggle(LOCK, "", ToggleColumn::sweepable()), + ColumnSpec::new(NAME, "", ColumnWidth::fill(1.0)), + ]; + let _ = List::new("Layers").columns(columns).show_items(ui, &LockedFirst, &mut |key, icx| { + let (mut cells, ..) = held.get(); + cells[*key] = [LOCKED_EYE, LOCK].map(|column| icx.cell(&column).unwrap_or(egui::Rect::NOTHING)); + held.set((cells, color(text.disabled.0), color(text.muted.0))); + ListRow::new(NAMES[*key]).cells(icx.cells()).toggle(ToggleCell::eye(LOCKED_EYE, true)).toggle(ToggleCell::lock(LOCK, false)) + }); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let tints = |shapes: &[egui::Shape], cell: egui::Rect| -> Vec { + let mut tints: Vec = shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::Mesh(mesh) if cell.contains(mesh.calc_bounds().center()) => Some(mesh.vertices.iter().map(|vertex| vertex.color)), + _ => None, + }) + .flatten() + .filter(|color| color.a() > 0) + .collect(); + tints.dedup(); + tints + }; + let ([[locked, locked_lock], [open, open_lock]], disabled, muted) = seen.get(); + let shapes = fixture.frame_shapes(); + let (rest, open_rest) = (tints(&shapes, locked), tints(&shapes, open)); + let mut hover = |cell: egui::Rect| { + fixture.frame(vec![pointer::moved(cell.center())]); + fixture.frame(Vec::new()); + tints(&fixture.frame_shapes(), cell) + }; + let (locked_off, open_off) = (hover(locked_lock), hover(open_lock)); + let hovered = hover(locked); + fixture.frame(vec![pointer::press(locked.center())]); + let pressed = tints(&fixture.frame_shapes(), locked); + fixture.frame(vec![pointer::release(locked.center())]); + for (when, found) in [("at rest", &rest), ("under the pointer", &hovered), ("under a press", &pressed)] { + assert!(!found.is_empty() && found.iter().all(|tint| *tint == disabled), "the locked eye reads text.disabled {disabled:?} {when}: {found:?}"); + } + assert!(!open_rest.is_empty() && open_rest.iter().all(|tint| *tint == muted), "the open eye rests in text.muted {muted:?}: {open_rest:?}"); + assert!(locked_off.is_empty(), "the locked row's off lock shows no glyph under the pointer: {locked_off:?}"); + assert!(!open_off.is_empty(), "the open row's off lock shows its glyph under the pointer"); + let tree = fixture.tree(); + let switches: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::SWITCH)).collect(); + let states = |row: &str| -> Vec { + switches.iter().filter(|key| tree.name_of(**key).is_some_and(|name| name.contains(row))).map(|key| tree.is_disabled_key(*key)).collect() + }; + assert_eq!(states(NAMES[0]), [true, true], "the locked row's toggle nodes read disabled"); + assert_eq!(states(NAMES[1]), [false, false], "the open row's toggle nodes read enabled"); +} + /// Every filled rect among `shapes`, nested lists included. fn fills(shapes: &[egui::Shape], out: &mut Vec<(egui::Rect, egui::Color32)>) { for shape in shapes { From ed7b213d5142aa4b299c60b437944dcc9f951037 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 26 Nov 2026 11:39:35 +0700 Subject: [PATCH 163/235] design-lint: clear the four findings on next from #3534, #3541 and #3431 craft-design-lint's workspace test fails on next with four findings in code that landed before the lint became a hard test: - draw (#3534): the Bezier overlay's read counter is a thread_local in a module gated cfg(all(test, feature)); the global-state rule skips cfg(test) modules only, so the gate is split into #[cfg(test)] and #[cfg(feature)], which compiles the same code. - menu (#3541): the macOS menu rebuild retry reads the runtime's clock (runtime::motion::now) and asks for its frame through runtime::frame::request_repaint_after instead of Instant::now and Context::request_repaint_after. - ui-panels (#3431): Prompt::layer_role was a hand-written setter; the field is now #[prop(vis = "pub(super)")]. --- crates/draw/src/ui/pen/bezier/model.rs | 3 ++- crates/menu/src/mac.rs | 5 ++--- crates/ui-panels/src/dialog/prompt.rs | 10 ++-------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index d95f1d0532..f35dc157b8 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -328,7 +328,8 @@ impl SelectedAnchors { } /// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work. -#[cfg(all(test, feature = "screen-testing"))] +#[cfg(test)] +#[cfg(feature = "screen-testing")] pub(crate) mod reads { use std::cell::Cell; diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index ea200bd452..098e09b216 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -33,7 +33,6 @@ use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::Instant; use craft_keymap::{Chord, CommandRef, Key, Mods}; use craft_ui::menu::Alternate; @@ -154,7 +153,7 @@ impl Native { fn update(&mut self, bar: &MenuBar) { let (spec, targets) = lower(bar); let (native, live) = (&mut self.bar, &self.targets); - let attempt = self.retry.attempt(&spec, Instant::now, || { + let attempt = self.retry.attempt(&spec, craft_ui::runtime::motion::now, || { let rebuilt = native.apply(&spec); if rebuilt { *lock(live) = targets; @@ -165,7 +164,7 @@ impl Native { // due asks again. if let Attempt::Retry(wait) = attempt { self.pending = Some(bar.clone()); - self.ctx.request_repaint_after(wait); + craft_ui::runtime::frame::request_repaint_after(&self.ctx, wait.as_secs_f64()); } } } diff --git a/crates/ui-panels/src/dialog/prompt.rs b/crates/ui-panels/src/dialog/prompt.rs index 9ae51f8143..7e4c1a05bc 100644 --- a/crates/ui-panels/src/dialog/prompt.rs +++ b/crates/ui-panels/src/dialog/prompt.rs @@ -227,7 +227,8 @@ pub struct Prompt<'a> { escape: Option, /// Whether the dialog reports the alert-dialog role, described by the message and any tone. alert: bool, - /// What the dialog's layer is for. + /// What the dialog's layer is for: `LayerRole::Progress` for a job's progress window. + #[prop(vis = "pub(super)")] layer_role: LayerRole, } @@ -255,13 +256,6 @@ impl<'a> Prompt<'a> { self } - /// What the dialog's layer is for: `LayerRole::Progress` for a job's progress window. - #[must_use] - pub(super) fn layer_role(mut self, role: LayerRole) -> Self { - self.layer_role = role; - self - } - /// The answers, one footer button each. #[must_use] pub fn answers(mut self, answers: impl IntoIterator) -> Self { From 49c56041ca0cfbb2dad9c4b518813181c6e12e92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:55:50 -0800 Subject: [PATCH 164/235] i18n: catalog::Entry documents @msgplural rows main added the @msgplural context to the catalog parser. The Entry docs now name it, and the catalog tests read a valid and an unmatchable @msgplural row through the public parse_row. --- crates/i18n/src/catalog.rs | 7 ++++--- crates/i18n/tests/catalog.rs | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/i18n/src/catalog.rs b/crates/i18n/src/catalog.rs index 4c1a6996f4..448d8bdfb4 100644 --- a/crates/i18n/src/catalog.rs +++ b/crates/i18n/src/catalog.rs @@ -14,11 +14,12 @@ use crate::message::Template; /// A row that passed, with its columns unescaped. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Entry { - /// The context column: empty, a context such as `menu`, or `@plural`, `@id` or `@msg`. + /// The context column: empty, a context such as `menu`, or `@plural`, `@id`, `@msg` or + /// `@msgplural`. pub context: String, - /// The English source text. + /// The English source text; for `@plural` and `@msgplural`, its two forms joined by `|`. pub source: String, - /// The translation; for `@plural`, its forms joined by `|`. + /// The translation; for `@plural` and `@msgplural`, its forms joined by `|`. pub translation: String, } diff --git a/crates/i18n/tests/catalog.rs b/crates/i18n/tests/catalog.rs index ea4512b8e6..eb31ce9c72 100644 --- a/crates/i18n/tests/catalog.rs +++ b/crates/i18n/tests/catalog.rs @@ -39,6 +39,11 @@ fn parse_row_checks_one_row() { assert_eq!(parse_row("@id\tlanguage.name\tDeutsch", 2), Ok(entry("@id", "language.name", "Deutsch"))); assert_eq!(parse_row("\t{n} left\t{m} übrig", 2), Err("placeholders differ from the source text".into())); assert_eq!(parse_row("@plural\t{n} file|{n} files\t{n} файл|{n} файла", plural_forms("ru")), Err("expected 3 nonempty plural forms".into())); + assert_eq!( + parse_row("@msgplural\t{n} file|{n} files\t{n} Datei|{n} Dateien", plural_forms("de")), + Ok(entry("@msgplural", "{n} file|{n} files", "{n} Datei|{n} Dateien")) + ); + assert_eq!(parse_row("@msgplural\t{n}|{n}\t{n}|{n}", plural_forms("de")), Err("unmatchable message template".into())); } #[test] From e172271774892a56142fb14b38821082719237b6 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:56:27 +0000 Subject: [PATCH 165/235] ui-contract: keep an app's own text curve for each mode (#3516) (#3615) The mode sync from #3259 wrote egui's default curve for the resolved mode into both theme styles every pass, so an app's own curve (WordCraft's dark Gamma(0.8)) was lost. Each style's curve is now remembered as the app's own whenever it differs from the one the sync last wrote, and the resolved mode's own curve is written into both styles. (cherry picked from commit 0f7450e5788397e4d587272841b579b9e7a4bd67) Co-authored-by: acebear17 <121527825+acebear17@users.noreply.github.com> --- crates/ui-contract/src/runtime/egui/style.rs | 31 ++++++++++++++++---- crates/ui-contract/tests/it/style/cache.rs | 30 +++++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index 9c28942e75..4960c63513 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -1,5 +1,6 @@ //! The theme styles' `right_to_left` and font coverage transfer function. +use super::memory; use craft_theme::Mode; use egui::epaint::FontColorTransferFunction; use egui::{Context, Theme, Ui}; @@ -78,18 +79,36 @@ pub(crate) fn set_style(ui: &mut Ui, style: &Arc) { ui.set_style(Arc::clone(style)); } +/// Each egui theme style's own font coverage transfer function, and the one [`set_text_color_transfer`] last wrote. +#[derive(Clone, Copy)] +struct TextCurves { + light: FontColorTransferFunction, + dark: FontColorTransferFunction, + written: FontColorTransferFunction, +} + /// Matches egui's font coverage transfer function to `mode` across both egui theme styles, so dark-on-light text /// never renders with the dark-mode curve (or vice versa) when the app's mode differs from the OS's. +/// +/// The curve for `mode` is the one the app set on that mode's egui style (egui's default until it sets one): a +/// style whose curve is not the one written here last has been set by the app since, and that curve becomes the +/// style's own. pub(crate) fn set_text_color_transfer(ctx: &Context, mode: Mode) { - let transfer = match mode { - Mode::Light => FontColorTransferFunction::LIGHT_MODE_DEFAULT, - Mode::Dark => FontColorTransferFunction::DARK_MODE_DEFAULT, + let id = memory::unique("craft-ui-contract text color transfer"); + let held = |theme: Theme| ctx.style_of(theme).visuals.text_options.color_transfer_function; + let (light, dark) = (held(Theme::Light), held(Theme::Dark)); + let (own_light, own_dark) = match memory::peek_copy::(ctx, id) { + Some(last) => (if light == last.written { last.light } else { light }, if dark == last.written { last.dark } else { dark }), + None => (light, dark), }; - let matches = ctx.style_of(Theme::Dark).visuals.text_options.color_transfer_function == transfer - && ctx.style_of(Theme::Light).visuals.text_options.color_transfer_function == transfer; - if !matches { + let transfer = match mode { + Mode::Light => own_light, + Mode::Dark => own_dark, + }; + if light != transfer || dark != transfer { ctx.all_styles_mut(|style| { style.visuals.text_options.color_transfer_function = transfer; }); } + memory::put(ctx, id, TextCurves { light: own_light, dark: own_dark, written: transfer }); } diff --git a/crates/ui-contract/tests/it/style/cache.rs b/crates/ui-contract/tests/it/style/cache.rs index e2d86f03e3..e7f8129b8f 100644 --- a/crates/ui-contract/tests/it/style/cache.rs +++ b/crates/ui-contract/tests/it/style/cache.rs @@ -141,3 +141,33 @@ fn egui_font_transfer_function_follows_the_resolved_theme_mode() { }); assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT)); } + +/// An app's own curve for a mode (#3516): the dark curve it sets on egui's dark style is the one dark passes use, +/// while light passes still get the light curve, and the app's dark curve comes back on the next dark pass. +#[trial] +fn an_app_s_own_dark_text_curve_survives_the_mode_sync() { + use egui::epaint::FontColorTransferFunction; + + let mut frames = Frames::new(); + let own = FontColorTransferFunction::Gamma(0.8); + frames.ctx.style_mut_of(egui::Theme::Dark, |style| style.visuals.text_options.color_transfer_function = own); + let mut transfer = None; + + frames.root(RootEnv::new().mode(ModeChoice::Dark)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Light)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(own), "a dark pass keeps the app's dark curve"); + + frames.root(RootEnv::new().mode(ModeChoice::Light)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(FontColorTransferFunction::LIGHT_MODE_DEFAULT), "a light pass gets the light curve"); + + frames.root(RootEnv::new().mode(ModeChoice::Dark)); + frames.frame(vec![egui::Event::SystemTheme(egui::Theme::Dark)], |ui| { + transfer = Some(ui.visuals().text_options.color_transfer_function); + }); + assert_eq!(transfer, Some(own), "the app's dark curve comes back with dark mode"); +} From c94a5f795d1d07868baa9d495a6763a56cfeb289 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:06:26 -0800 Subject: [PATCH 166/235] craft-settings: expect the dotted key path in the section error test SectionError::section holds the dotted key path of the value, so an invalid theme under [appearance] reports [appearance.theme]. --- crates/settings/tests/recovery.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index 5c6c336d2b..23af5c05cd 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -30,7 +30,7 @@ fn section_error_displays_its_section_and_message() { let (_, report) = open_in(tmp.path()); let error = &report.section_errors[0]; let text = error.to_string(); - assert!(text.starts_with("settings section [appearance] was reset to defaults: "), "{text}"); + assert!(text.starts_with("settings section [appearance.theme] was reset to defaults: "), "{text}"); assert!(text.ends_with(&error.message), "{text}"); let source: &dyn std::error::Error = error; assert!(source.source().is_none()); From 4114cb807050d0b8e87f4db6ee5fdcc17f1ba35e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:13:15 -0800 Subject: [PATCH 167/235] draw: TransformBox draws its handles at a side the host passes `TransformBox::handle_side(points)` sets the side of the corner and side handles, for a host whose handle size follows a preference. Without it the handles keep the theme's `size.handle.md`. The handle squares, a live line's end and side squares, and the overflow handle use the side. A handle's hit circle grows with a larger side and never falls below the theme's reach, so a press anywhere on a large square takes it. --- crates/draw/src/ui/transform/transform_box.rs | 26 ++++++++-- crates/draw/tests/it/transform_box.rs | 49 +++++++++++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 837fe4dee1..6b6594715b 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -492,6 +492,10 @@ pub struct TransformBox<'a> { /// Whether the corner and side handles are circles (a rounded document editor's look) instead of squares. #[prop] round_handles: bool, + /// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the + /// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's. + #[prop] + handle_side: Option, /// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends /// take a press and the keys, each as the box handle it points to ([`LineLook`]), so an end drag scales the box as /// that handle does; while it is dragged, the box shows as it scales. No other part is declared. @@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> { session_arrows: true, centre_mark: false, round_handles: false, + handle_side: None, line: None, reach: TransformReach::Box, color: None, @@ -580,6 +585,16 @@ impl<'a> TransformBox<'a> { self.color.map_or(StrokeColor::from(theme), StrokeColor::from) } + /// The side of a corner or side handle: the host's, else the theme's. + fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 { + self.handle_side.unwrap_or(style.handle.side) + } + + /// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle. + fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 { + self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES)) + } + /// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place. fn declares_centre(&self) -> bool { self.takes_input() && self.move_only().is_none() && !self.reference_point && self.inside_moves && self.rules.allows(BoxPart::Inside) @@ -1032,7 +1047,8 @@ impl TransformBox<'_> { /// press; `enlarged` with the overflow plus. fn paint_handle(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, part: BoxPart, at: Pos2, enlarged: bool) { let look = &cx.style.handle; - let side = if enlarged { look.side * OVERFLOW_IN_HANDLES } else { look.side }; + let side = self.side_of_handles(cx.style); + let side = if enlarged { side * OVERFLOW_IN_HANDLES } else { side }; self.paint_handle_shape(draw, cx, self.handle_shape(at, side), self.rules.allows(part).then(|| BOX.at(part.index()))); if enlarged { Handle::plus(draw, look, at, side); @@ -1048,14 +1064,14 @@ impl TransformBox<'_> { paint_frame(draw, style, self.ink(style.line), corners); for k in 0..4 { let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5); - self.paint_handle_shape(draw, cx, self.handle_shape(middle, style.handle.side), None); + self.paint_handle_shape(draw, cx, self.handle_shape(middle, self.side_of_handles(style)), None); } } for (part, end) in line.end_parts() { self.paint_handle(draw, cx, part, view.to_screen(end), false); } for (end, at) in line.free_ends() { - self.paint_handle_shape(draw, cx, self.handle_shape(view.to_screen(at), style.handle.side), Some(LINE_END.at(end.index()))); + self.paint_handle_shape(draw, cx, self.handle_shape(view.to_screen(at), self.side_of_handles(style)), Some(LINE_END.at(end.index()))); } paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget, None); } @@ -1278,7 +1294,7 @@ impl Component for TransformBox<'_> { handle => { let at = self.part_point(&state, handle).map_or(Pos2::ZERO, |at| space.view.to_screen(at)); ( - HitShape::circle(at, style.handle_reach), + HitShape::circle(at, self.reach_of_handles(style)), Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS, HitPriority::new(HitLevel::Handle, HANDLE_SUB), FocusShape::Circle, @@ -1290,7 +1306,7 @@ impl Component for TransformBox<'_> { } if let Some(line) = self.line { for (end, at) in line.free_ends() { - cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) + cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), self.reach_of_handles(style))) .sense(Sense::DRAG | Sense::CLICK | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(LINE_END_BY_KEY); diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index e8b32bb82e..90c8f0568e 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -60,6 +60,8 @@ struct Config { f32_host: bool, centre_mark: bool, round_handles: bool, + /// The host's handle side, `None` for the theme's. + handle_side: Option, line: Option, /// Snap targets beside the guides at [`SNAP_XS`]. targets: Vec, @@ -119,6 +121,7 @@ fn defaults() -> Config { f32_host: false, centre_mark: false, round_handles: false, + handle_side: None, line: None, targets: Vec::new(), suspend: SnapSuspend::Control, @@ -218,6 +221,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { if let Some(line) = config.line { control = control.line(line); } + if let Some(side) = config.handle_side { + control = control.handle_side(side); + } control = control.reach(config.reach).session_commit(config.session_commit); if config.hover_frame { control = control.id(frame_id); @@ -1649,3 +1655,46 @@ fn round_handles_are_circles() { // Each handle is a filled circle and its stroke. assert_eq!(circles(true), circles(false) + 16, "the four corners and four sides are circles"); } + +/// A host's handle side draws the corner and side handles at that side: a larger side draws a larger square. +#[trial] +fn a_host_handle_side_sets_the_drawn_handle_square() { + let corner_side = |side: Option| { + let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side); + let corner = h.screen(Point::new(RECT.x1, RECT.y1)); + let sides: Vec = h + .fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()), + _ => None, + }) + .collect(); + sides.into_iter().fold(0.0, f32::max) + }; + let (small, large) = (corner_side(Some(4.0)), corner_side(Some(12.0))); + assert!(small > 0.0, "the corner handle is drawn as a square"); + assert!(large > small, "a larger side draws a larger square: {large} against {small}"); +} + +/// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it. +#[trial] +fn a_press_just_inside_a_large_handles_edge_grabs_it() { + // 7 points in from the bottom right corner on both axes: inside a 16 point square, about 9.9 from its centre. + let near_edge = Point::new(RECT.x1 - 7.0, RECT.y1 - 7.0); + let mut theme = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules()); + hover(&mut theme, near_edge); + assert_ne!(theme.host.borrow().hovered, Some(BoxPart::Corner(2)), "past the theme's handle reach"); + + let mut h = harness(BoxState::from_rect(RECT), |config| { + config.rules = free_rules(); + config.handle_side = Some(16.0); + }); + hover(&mut h, near_edge); + assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "on the large handle's square"); + drag(&mut h, near_edge, Point::new(RECT.x1 + 13.0, RECT.y1 + 13.0)); + let quad = h.state().quad; + assert!(quad[2].x > RECT.x1 + 1.0 && quad[2].y > RECT.y1 + 1.0, "the corner moved with the drag: {quad:?}"); + assert_eq!(quad[0], Point::new(RECT.x0, RECT.y0), "the opposite corner stayed: {quad:?}"); +} From e8730f38258f9bd7f535851aec8a4ce142b9afa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:28:03 -0800 Subject: [PATCH 168/235] ui-patterns: the preset browser's Find also matches a row's search name PresetRow::search_name is documented as the name Find also matches, but shown_rows compared the query with the label only. A host that shows a translated label and sets the stored name as search_name could not find the item by its stored name. Find now keeps a preset whose label or search_name matches. --- .../src/patterns/presets/browser.rs | 5 +-- .../ui-patterns/tests/it/presets/browser.rs | 35 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index 06ff89253e..33edb61c31 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -510,14 +510,15 @@ impl DisplayOrder> for Shown<'_, K> { impl ItemSource> for Shown<'_, K> {} /// The positions of the rows to show: without a search, the rows outside closed groups; with one, the presets whose -/// name matches and their groups. +/// label or `search_name` matches and their groups. fn shown_rows(rows: &[PresetRow], open: &[bool], matcher: Option<&Matcher>) -> Vec { if let Some(matcher) = matcher { + let found = |text: &str| matcher.score(text).is_some(); let mut keep = vec![false; rows.len()]; let mut path: Vec = Vec::new(); for (at, row) in rows.iter().enumerate() { path.truncate(row.depth); - if !row.is_group() && matcher.score(&row.label).is_some() { + if !row.is_group() && (found(&row.label) || row.search_name.as_deref().is_some_and(found)) { keep[at] = true; for &ancestor in &path { keep[ancestor] = true; diff --git a/crates/ui-patterns/tests/it/presets/browser.rs b/crates/ui-patterns/tests/it/presets/browser.rs index 889de8713c..d15d4805d2 100644 --- a/crates/ui-patterns/tests/it/presets/browser.rs +++ b/crates/ui-patterns/tests/it/presets/browser.rs @@ -65,6 +65,41 @@ fn a_preset_released_over_the_zone_reports_drop_at_and_nothing_else_does() { } } +/// Find matches a row's `search_name` beside its label: in both views, a preset shown as "Rot" with the search name +/// "Red" is found by either name, and a preset without a search name is still found by its label. +#[trial] +fn find_matches_a_preset_by_its_search_name_or_its_label() { + // (query, the presets shown, the presets hidden) + type Case = (&'static str, &'static [&'static str], &'static [&'static str]); + let cases: [Case; 3] = [("Red", &["Rot"], &["Blau"]), ("Rot", &["Rot"], &["Blau"]), ("Blau", &["Blau"], &["Rot"])]; + for view in [PresetView::List, PresetView::Grid] { + for (query, shown, hidden) in cases { + let rows = PresetSource::new( + (), + PresetFns::new(|_, _| { + let mut red = PresetRow::item(ALPHA, "Rot", 1); + red.search_name = Some(String::from("Red")); + vec![PresetRow::group(GROUP, "Group", 0), red, PresetRow::item(2, "Blau", 1)] + }), + ); + let mut state = PresetState::::new(); + state.filter = String::from(query); + let mut fixture = Fixture::new(move |ui| { + ui.scope_builder(UiBuilder::new().max_rect(BROWSER), |ui| { + let _ = PresetBrowser::new("Patterns", Bind::bound(&mut state), &rows).view_lock(view).show(ui); + }); + }); + fixture.room(vec2(480.0, 320.0)).settle(); + for name in shown { + assert!(fixture.by_label(name).is_some(), "{view:?}: Find \"{query}\" shows {name}"); + } + for name in hidden { + assert!(fixture.by_label(name).is_none(), "{view:?}: Find \"{query}\" hides {name}"); + } + } + } +} + /// A browser over `presets` presets in a room as narrow as a docked panel and 300 high, with a footer and /// `room_height` set when given, and where its New Group button and its last preset are. fn footer_rig(presets: u32, room_height: Option) -> (Rect, Option) { From 930fcb4baefe7e74777964afd26bc794c6bab8e5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 26 Nov 2026 05:40:09 +0000 Subject: [PATCH 169/235] CI: next is retired; workflows trigger on main only next's work goes into main and the branch is retired, so its triggers, the nightly job that started the Workspace and full-test runs on next, and the cache and concurrency rules for next's runs are removed. The Workspace concurrency test checks the policy for main alone. --- .github/workflows/ai-core.yml | 2 +- .github/workflows/atomic.yml | 2 +- .github/workflows/audio.yml | 2 +- .github/workflows/cms.yml | 2 +- .github/workflows/crw.yml | 4 +- .github/workflows/dialogs.yml | 2 +- .github/workflows/doc.yml | 2 +- .github/workflows/docs.yml | 2 +- .github/workflows/ecproj-format.yml | 2 +- .github/workflows/font-store.yml | 2 +- .github/workflows/formats.yml | 2 +- .github/workflows/house-rules.yml | 2 +- .github/workflows/jpeg.yml | 2 +- .github/workflows/keymap.yml | 2 +- .github/workflows/media.yml | 2 +- .github/workflows/menu.yml | 2 +- .github/workflows/nightly.yml | 27 ------------- .github/workflows/pcraft-format.yml | 2 +- .github/workflows/pdf.yml | 2 +- .github/workflows/proof.yml | 2 +- .github/workflows/theme.yml | 2 +- .github/workflows/update.yml | 2 +- .github/workflows/vectorcraft-format.yml | 2 +- .github/workflows/video.yml | 2 +- .github/workflows/web-api.yml | 2 +- .github/workflows/web-host.yml | 2 +- .github/workflows/window.yml | 2 +- .github/workflows/workspace.yml | 49 ++++++++++-------------- scripts/test-workspace-concurrency.py | 16 +++----- scripts/test-workspace-tests.py | 2 +- 30 files changed, 54 insertions(+), 94 deletions(-) diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 6f5b34e892..2be123b233 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -3,7 +3,7 @@ name: AI model on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] pull_request: paths: ['crates/ai-core/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ai-core.yml'] diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index b8bcc8b8ea..6afdafc290 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -3,7 +3,7 @@ name: Atomic file writes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] pull_request: paths: ['crates/atomic/**', 'crates/settings/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/atomic.yml'] diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index 6063c4e4dc..5fd971c629 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -2,7 +2,7 @@ name: Shared audio on: push: - branches: [main, next] + branches: [main] paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] pull_request: paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"] diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index b13dd82d14..c1737392da 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -3,7 +3,7 @@ name: Colour management on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] pull_request: paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 3e9b430d67..10e5b7ccf7 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -2,7 +2,7 @@ name: Shared CRW on: push: - branches: [main, next] + branches: [main] paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] pull_request: paths: ["crates/crw/**", "scripts/fetch-crw-samples.py", "Cargo.toml", "Cargo.lock", ".github/workflows/crw.yml"] @@ -52,7 +52,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - # Pull requests restore the entry main or next saved and never write their own: the same + # Pull requests restore the entry main saved and never write their own: the same # files saved once per pull request took a share of the 10 GB cache budget. - name: Restore the CC0 sample files id: samples diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index f9ab8fe56e..23def9feb0 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -3,7 +3,7 @@ name: Dialogs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] pull_request: paths: ['crates/dialogs/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/dialogs.yml'] diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index 00b8336db1..6275433817 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -3,7 +3,7 @@ name: Craft documents on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] pull_request: paths: ['crates/doc/**', 'crates/pcraft-format/**', 'crates/vectorcraft-format/**', 'crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/doc.yml'] diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fc51a0da51..cb54dbf119 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -6,7 +6,7 @@ name: Docs on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] pull_request: paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml'] diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index bec96fed5c..048c897b3c 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -3,7 +3,7 @@ name: EffectCraft project format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] pull_request: paths: ['crates/ecproj-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/ecproj-format.yml'] diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index fd599d207c..e655697b3d 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -3,7 +3,7 @@ name: Font store on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] pull_request: paths: ['crates/font-store/**', 'crates/font-catalog/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/font-store.yml'] diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 22d90712e8..2ee6fc6281 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -2,7 +2,7 @@ name: Shared format crates on: push: - branches: [main, next] + branches: [main] paths: - "crates/xml/**" - "crates/mime/**" diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml index 7ee967c65b..de64ad3ee4 100644 --- a/.github/workflows/house-rules.yml +++ b/.github/workflows/house-rules.yml @@ -2,7 +2,7 @@ name: House rules on: push: - branches: [main, next] + branches: [main] paths: - AGENTS.md - CLAUDE.md diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index ebb27bafde..495af8b232 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -2,7 +2,7 @@ name: Shared JPEG on: push: - branches: [main, next] + branches: [main] paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] pull_request: paths: ["crates/jpeg/**", "Cargo.toml", "Cargo.lock", ".github/workflows/jpeg.yml"] diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index bfce473788..47a5576499 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -2,7 +2,7 @@ name: Keymap on: push: - branches: [main, next] + branches: [main] paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] pull_request: paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 090ad84da9..f4c4e6689b 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -2,7 +2,7 @@ name: Shared media on: push: - branches: [main, next] + branches: [main] paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] pull_request: paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"] diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 80b6678cd3..b12c8bcc6a 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -2,7 +2,7 @@ name: Menu on: push: - branches: [main, next] + branches: [main] paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] pull_request: paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5cc8032668..89d6344bc2 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -33,30 +33,3 @@ jobs: cache-key-files: scripts/ci-test-inputs.sh # The gate's build (the same targets and profile overrides), with every test at its full count. command: bash scripts/ci-workspace-tests.sh full - - # The scheduled run is main's; this starts the full tests above on next too, where the gate - # runs the same fractions. It also starts one Workspace run on next a day that nothing cancels - # (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's - # macOS and Windows legs then run in full at least once a day, and its Linux leg builds from - # source and saves next's own workspace-crates cache entry, which pull requests into next - # restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with - # `actions: write`; it checks out and runs nothing from the repository. - workspace-next: - name: Workspace on next - if: github.event_name == 'schedule' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - actions: write - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - name: Start the Workspace workflow and these full tests on next - env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - run: | - gh workflow run workspace.yml --repo "$REPO" --ref next - gh workflow run nightly.yml --repo "$REPO" --ref next diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index cefa5360c4..0e4feabc92 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -3,7 +3,7 @@ name: PhotoCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] pull_request: paths: ['crates/pcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pcraft-format.yml'] diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index 1550512ac5..0269fdc7ea 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -2,7 +2,7 @@ name: Shared PDF on: push: - branches: [main, next] + branches: [main] paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] pull_request: paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**", "vendor/vello_common/**", "vendor/vello_cpu/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 0f5b869a4a..ea5edb8a56 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -2,7 +2,7 @@ name: Proofing on: push: - branches: [main, next] + branches: [main] paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] pull_request: paths: ["crates/proof/**", "Cargo.toml", "Cargo.lock", ".github/workflows/proof.yml"] diff --git a/.github/workflows/theme.yml b/.github/workflows/theme.yml index 213a74b147..f0bb32a466 100644 --- a/.github/workflows/theme.yml +++ b/.github/workflows/theme.yml @@ -3,7 +3,7 @@ name: Suite themes on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] pull_request: paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml'] diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 0ea3b8c1bb..e5e3e71d15 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -3,7 +3,7 @@ name: App updates on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] pull_request: paths: ['crates/update/**', 'Cargo.toml', 'Cargo.lock', 'rustfmt.toml', 'clippy.toml', '.github/workflows/update.yml'] diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index 0ca15636df..cd66615a50 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -3,7 +3,7 @@ name: VectorCraft format on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] pull_request: paths: ['crates/vectorcraft-format/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/vectorcraft-format.yml'] diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index 03b59cc427..20afe0d700 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -2,7 +2,7 @@ name: Shared video on: push: - branches: [main, next] + branches: [main] paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] pull_request: paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"] diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 0ad01e28fd..f0f8e22da7 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -3,7 +3,7 @@ name: Web API (page command API) on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] pull_request: paths: ['crates/web-api/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/web-api.yml'] diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index 055303bc26..dc0254850a 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -2,7 +2,7 @@ name: Shared web host on: push: - branches: [main, next] + branches: [main] paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] pull_request: paths: ["crates/web-host/**", "Cargo.toml", "Cargo.lock", ".github/workflows/web-host.yml"] diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index a534393fdc..5f05883d14 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -3,7 +3,7 @@ name: Window decorations on: workflow_dispatch: push: - branches: [main, next] + branches: [main] paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] pull_request: paths: ['crates/window/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/window.yml'] diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 5c802e799e..b1a0ee2ffd 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -2,7 +2,7 @@ name: Workspace on: push: - branches: [main, next] + branches: [main] tags: ["v*"] pull_request: workflow_dispatch: @@ -16,13 +16,12 @@ permissions: contents: read concurrency: - # A pull request, main and next each have one group, so a newer push cancels the run it - # supersedes; the newest push's run still tests everything before it. Every other run (a release - # tag, a manual run, the scheduled run, nightly.yml's run on next) gets a group of its own and is - # neither cancelled nor replaced while queued: a release run always finishes, the scheduled run - # saves the caches, and next gets one complete macOS and Windows run a day. - group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next') && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'push' && github.ref == 'refs/heads/next' }} + # A pull request and main each have one group, so a newer push cancels the run it supersedes; the + # newest push's run still tests everything before it. Every other run (a release tag, a manual + # run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while + # queued: a release run always finishes, and the scheduled run saves the caches. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} jobs: # Whether this run needs the macOS and Windows legs, and which tests every leg runs @@ -71,7 +70,7 @@ jobs: # The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the # settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every # other override names a workspace crate (scripts/test-workspace-tests.py), so changing one - # keeps those entries, and next's runs restore main's. + # keeps those entries. - uses: actions/checkout@v7.0.1 if: github.event_name != 'pull_request' with: @@ -104,13 +103,10 @@ jobs: # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight - # scheduled run builds from source (`cold-build`) and starts the entry afresh. next has an entry - # of its own, since main's is built from different code and lockfile and a pull request into next - # rebuilt nearly everything from it (15.5 minutes): nightly.yml's daily manual run on next builds - # from source and saves it (`cache-save-on-dispatch`), and pull requests into next restore it - # before main's. The macOS and Windows legs keep a dependency-only entry: their workspace crates - # would not fit the 10 GB cache budget beside Linux's. The lint legs keep no cache - # (`lint-cache: false`) for the same reason; a cold lint leg is still shorter than its gate leg. + # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and + # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache + # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a + # cold lint leg is still shorter than its gate leg. native: name: Workspace needs: platforms @@ -118,9 +114,8 @@ jobs: with: os: '["ubuntu-latest"]' cache-workspace-crates: true - cache-save-on-dispatch: true cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} - cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} + cold-build: ${{ github.event.schedule == '17 0 * * *' }} lint-cache: false # The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a # workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them. @@ -182,7 +177,7 @@ jobs: # The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux # leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on - # every push to main and next, on main's scheduled runs and on nightly.yml's daily run on next. + # every push to main and on main's scheduled runs. # A pull request that needs them before it merges gets the full-ci label. native-platforms: name: Workspace @@ -192,7 +187,7 @@ jobs: with: os: '["windows-latest","macos-latest"]' lint-cache: false - # Named by the dependency settings alone (`deps-profile`), so next restores main's entries. + # Named by the dependency settings alone (`deps-profile`). cache-version: v2-${{ needs.platforms.outputs.deps-profile }} timeout-minutes: *timeout tools: *tools @@ -212,15 +207,14 @@ jobs: lint-command: *lint command: *command - # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as - # does the daily manual run on next, and every run restores only the newest. This deletes the - # older ones of the run's branch as soon as the Linux leg is done, instead of leaving them to the - # 10 GB budget's eviction, which would evict other entries too. The only job with - # `actions: write`; it checks out and runs nothing from the repository. + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and + # every run restores only the newest. This deletes the older ones as soon as the Linux leg is + # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries + # too. The only job with `actions: write`; it checks out and runs nothing from the repository. cache-prune: name: cache prune needs: native - if: ${{ !cancelled() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/next') }} + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -234,11 +228,10 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} - REF: ${{ github.ref }} run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --ref "$REF" --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do diff --git a/scripts/test-workspace-concurrency.py b/scripts/test-workspace-concurrency.py index b8324eb0a2..dd5a29dd1c 100644 --- a/scripts/test-workspace-concurrency.py +++ b/scripts/test-workspace-concurrency.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -"""Check the Workspace workflow's cancellation policy: pull requests and pushes to main or next -cancel the run they supersede; release tags, manual runs and scheduled runs are never cancelled. +"""Check the Workspace workflow's cancellation policy: pull requests and pushes to main cancel +the run they supersede; release tags, manual runs and scheduled runs are never cancelled. The policy is the top-level `concurrency` block of .github/workflows/workspace.yml. This script reads those fields, requires the documented expression shapes, and checks which group each event @@ -32,7 +32,6 @@ PULL_REQUEST, PUSH, DISPATCH, SCHEDULE = "pull_request", "push", "workflow_dispa SUPERSEDED = ( "github.event_name == 'pull_request'" " || github.event_name == 'push' && github.ref == 'refs/heads/main'" - " || github.event_name == 'push' && github.ref == 'refs/heads/next'" ) GROUP_SHAPE = re.compile( r"(?P[A-Za-z0-9._-]+)-\$\{\{\s*\(\s*(?P[^()]+?)\s*\)\s*" @@ -47,7 +46,7 @@ def normal(expression): def superseded(event_name, ref): """SUPERSEDED, evaluated.""" - return event_name == PULL_REQUEST or (event_name == PUSH and ref in ("refs/heads/main", "refs/heads/next")) + return event_name == PULL_REQUEST or (event_name == PUSH and ref == "refs/heads/main") def read_concurrency(text): @@ -86,11 +85,10 @@ def other_run(event_name, ref, run_id): return (event_name, ref, run_id) -MAIN, NEXT, TAG = ("refs/heads/main", "refs/heads/next", "refs/tags/v1.2.3") +MAIN, TAG = ("refs/heads/main", "refs/tags/v1.2.3") SAME_GROUP = [ ("a newer commit on the same pull request", pull_request(1316, 43599251877), pull_request(1316, 43600899878)), ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), - ("two pushes to next", other_run(PUSH, NEXT, 20), other_run(PUSH, NEXT, 21)), ] DIFFERENT_GROUPS = [ ("two pull requests", pull_request(1316, 1), pull_request(1317, 1)), @@ -101,15 +99,11 @@ DIFFERENT_GROUPS = [ ("a main push and a scheduled run", other_run(PUSH, MAIN, 17), other_run(SCHEDULE, MAIN, 17)), ("a main push and a manual run of main", other_run(PUSH, MAIN, 18), other_run(DISPATCH, MAIN, 18)), ("a main push and a pull request", other_run(PUSH, MAIN, 9), pull_request(1316, 9)), - ("a main push and a next push", other_run(PUSH, MAIN, 22), other_run(PUSH, NEXT, 22)), - ("a next push and the nightly manual run of next", other_run(PUSH, NEXT, 23), other_run(DISPATCH, NEXT, 23)), ("a release tag and a pull request", other_run(PUSH, TAG, 10), pull_request(1316, 10)), ] CANCELLATION = [ ("a push supersedes the previous run of its pull request", pull_request(1316, 11), True), ("a push to main supersedes the previous main run", other_run(PUSH, MAIN, 12), True), - ("a push to next supersedes the previous next run", other_run(PUSH, NEXT, 24), True), - ("the nightly manual run of next is never cancelled", other_run(DISPATCH, NEXT, 25), False), ("a release tag run is never cancelled", other_run(PUSH, TAG, 13), False), ("a manual run is never cancelled", other_run(DISPATCH, MAIN, 14), False), ("the scheduled run that saves the caches is never cancelled", other_run(SCHEDULE, MAIN, 19), False), @@ -158,7 +152,7 @@ class ConcurrencyTests(unittest.TestCase): with self.subTest(description): self.assertNotEqual(self.group(*first), self.group(*second), description) - def test_only_pull_requests_and_main_and_next_pushes_cancel(self): + def test_only_pull_requests_and_main_pushes_cancel(self): for description, context, expected in CANCELLATION: with self.subTest(description): self.assertEqual(self.cancels(context[0], context[1]), expected, description) diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index 5cceeddc1b..9a926eb5a6 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -318,7 +318,7 @@ class WorkspaceTests(unittest.TestCase): self.assertIn("test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }}", source) # The Linux leg's entry, which keeps workspace crates, is named after every profile override; # the macOS and Windows legs' dependency-only entries after the settings that reach a - # dependency, so next restores main's (test_profile_overrides_name_only_workspace_members). + # dependency (test_profile_overrides_name_only_workspace_members). self.assertIn("cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}\n", source) self.assertIn(" cache-version: v2-${{ needs.platforms.outputs.deps-profile }}\n", source) self.assertIn(" deps-profile: ${{ steps.audit.outputs.deps-profile }}\n", source) From 6cdbd0af0655671e1cb26233421c8d87c2f5494b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:38:53 -0800 Subject: [PATCH 170/235] ui-canvas rulers: the zero point's cross hairs draw over a halo A corner drag drew the zero point's cross hairs as a thin line in the text color, the same color as the strips' pointer marker. Over the paper, which fills the canvas when artboards are hidden, a light line in a dark theme had almost no contrast, and a dark line in a light theme had almost none over dark art. The cross hairs now draw as a thin overlay.stroke line over a thick overlay.halo, the pair the clone source marker and the straight-line preview use. The theme holds that pair to 3:1 over black and white (4.5:1 in high contrast). --- crates/ui-canvas/src/canvas/rulers/mod.rs | 10 +++- crates/ui-canvas/tests/it/canvas/rulers.rs | 59 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index 811a86d813..50e8ef6bb6 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -147,6 +147,10 @@ pub struct RulersStyle { shade: StyleColor, label: TextLook, marker: StyleColor, + /// The zero point's cross hairs over the view. + cross: StyleColor, + /// The halo under the cross hairs, so they read on the paper, the pasteboard and any art. + halo: StyleColor, } /// The type role of the tick labels. @@ -382,6 +386,8 @@ impl Component for Rulers<'_> { shade: cx.color(c.surface.canvas), label: TextLook::new(LABEL_ROLE, Stateful::new(cx.color(c.text.muted))), marker: cx.color(c.text.normal), + cross: cx.color(c.overlay.stroke), + halo: cx.color(c.overlay.halo), } } @@ -526,7 +532,9 @@ impl Component for Rulers<'_> { for (from, to) in [(Point::new(zero.x, visible.y0), Point::new(zero.x, visible.y1)), (Point::new(visible.x0, zero.y), Point::new(visible.x1, zero.y))] { - draw.stroke(&PaintShape::Path(vec![space.view.to_screen(from), space.view.to_screen(to)]), StrokeWidth::Thin, style.marker); + let path = PaintShape::Path(vec![space.view.to_screen(from), space.view.to_screen(to)]); + draw.stroke(&path, StrokeWidth::Thick, style.halo); + draw.stroke(&path, StrokeWidth::Thin, style.cross); } if let Some(at) = crate::runtime::pointer::frame(&cx.core.ctx).pos { let numbers = cx.env.units(); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 5fe156210e..7deb5fb8ee 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -284,6 +284,65 @@ fn a_corner_drag_the_host_cancelled_lands_nothing_at_its_release() { assert_eq!(*zero.borrow(), host, "the release after the host's change leaves the zero point where the host put it"); } +/// The strokes of the vertical cross hair that a corner drag shows in `mode` and `contrast`, in paint order, and the +/// colour of the pasteboard under them. +fn cross_hair_strokes(mode: craft_theme::Mode, contrast: craft_theme::Contrast) -> (Vec, craft_theme::Rgba) { + let zero = Rc::new(RefCell::new(Point::ZERO)); + let view = |room: Rect| CanvasView::new(room, Point::new(f64::from(room.center().x), f64::from(room.center().y)), 1.0); + let snap = Snap::new(std::sync::Arc::new(SnapTargets::new()), SnapOptions::default()); + let mut fixture = ToolFixture::with_rulers("Document", Overpaint, view, snap, zero, |_, _| {}); + fixture.fixture().theme(mode, contrast).room(Vec2::new(500.0, 400.0)).settle(); + let canvas = fixture.canvas().rect; + let (from, to) = (canvas.min + Vec2::splat(4.0), canvas.center()); + let fixture = fixture.fixture(); + fixture.frame(vec![craft_ui::testing::pointer::moved(from)]); + fixture.frame(vec![craft_ui::testing::pointer::press(from)]); + fixture.frame(vec![craft_ui::testing::pointer::moved(to)]); + let shapes = fixture.frame_shapes(); + let vertical = |points: &[Pos2]| { + points.len() == 2 + && (points[0].x - to.x).abs() < 1.0 + && (points[1].x - to.x).abs() < 1.0 + && (points[0].y - points[1].y).abs() > canvas.height() / 2.0 + }; + let strokes = shapes + .iter() + .filter_map(|shape| match shape { + Shape::LineSegment { points, stroke } if vertical(points) => Some(stroke.color), + Shape::Path(path) if vertical(&path.points) => match path.stroke.color { + egui::epaint::ColorMode::Solid(color) => Some(color), + _ => None, + }, + _ => None, + }) + .collect(); + let pasteboard = craft_ui::testing::style::tokens(mode, contrast).color.surface.canvas; + (strokes, pasteboard) +} + +/// With artboards hidden the paper fills the canvas, so the zero point's cross hairs cross the paper as well as the +/// pasteboard and dark art. Over each, the top line contrasts with what lies under it (the strokes below it over the +/// backdrop) by the minimum the theme sets for overlay strokes on their halo: 3 to 1, and 4.5 to 1 in high contrast. +#[trial] +fn the_zero_point_cross_hairs_contrast_with_the_paper_and_the_pasteboard() { + use craft_theme::{Contrast, Mode, Rgba, contrast_ratio, over}; + let rgba = |color: Color32| Rgba(color.to_srgba_unmultiplied()); + for mode in [Mode::Light, Mode::Dark] { + for contrast in [Contrast::Standard, Contrast::High] { + let (strokes, pasteboard) = cross_hair_strokes(mode, contrast); + let Some((line, under)) = strokes.split_last() else { + panic!("{mode:?} {contrast:?}: a corner drag shows a vertical cross hair"); + }; + let min = if contrast == Contrast::High { 4.5 } else { 3.0 }; + for (name, backdrop) in [("the paper", Rgba::WHITE), ("dark art", Rgba::BLACK), ("the pasteboard", pasteboard)] { + let below = under.iter().fold(backdrop, |bg, stroke| over(rgba(*stroke), bg)); + let ratio = contrast_ratio(over(rgba(*line), below), below); + assert!(ratio >= min, "{mode:?} {contrast:?}: the cross hair over {name} contrasts {ratio:.2} to 1, needs {min}"); + } + } + } +} + /// A right-click on a ruler strip or on the corner is the rulers': they report the part, for their units menu, and /// the tool host under them asks for no menu of its own. #[trial] From 915bbe59d17709f44c06bbffdc3d7892f116549d Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 26 Nov 2026 05:47:11 +0000 Subject: [PATCH 171/235] Clear the design-lint findings next brought - craft-draw: the Bezier overlay's read counter is a test-only module the lint recognises (cfg(test) and the screen-testing feature as two attributes). It stays per thread, so parallel trials do not add to each other's counts. - craft-menu: the macOS menu retry reads the runtime's motion clock and asks for its repaint through runtime::frame. - craft-ui-panels: Prompt's layer_role setter is derived (#[prop]). --- crates/draw/src/ui/pen/bezier/model.rs | 3 ++- crates/menu/src/mac.rs | 6 +++--- crates/ui-panels/src/dialog/prompt.rs | 10 ++-------- 3 files changed, 7 insertions(+), 12 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index d95f1d0532..f35dc157b8 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -328,7 +328,8 @@ impl SelectedAnchors { } /// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work. -#[cfg(all(test, feature = "screen-testing"))] +#[cfg(test)] +#[cfg(feature = "screen-testing")] pub(crate) mod reads { use std::cell::Cell; diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index ea200bd452..ae30fb801d 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -33,10 +33,10 @@ use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::Instant; use craft_keymap::{Chord, CommandRef, Key, Mods}; use craft_ui::menu::Alternate; +use craft_ui::runtime::{frame, motion}; use craft_window::native_menu as native; use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok}; @@ -154,7 +154,7 @@ impl Native { fn update(&mut self, bar: &MenuBar) { let (spec, targets) = lower(bar); let (native, live) = (&mut self.bar, &self.targets); - let attempt = self.retry.attempt(&spec, Instant::now, || { + let attempt = self.retry.attempt(&spec, motion::now, || { let rebuilt = native.apply(&spec); if rebuilt { *lock(live) = targets; @@ -165,7 +165,7 @@ impl Native { // due asks again. if let Attempt::Retry(wait) = attempt { self.pending = Some(bar.clone()); - self.ctx.request_repaint_after(wait); + frame::request_repaint_after(&self.ctx, wait.as_secs_f64()); } } } diff --git a/crates/ui-panels/src/dialog/prompt.rs b/crates/ui-panels/src/dialog/prompt.rs index 9ae51f8143..7e4c1a05bc 100644 --- a/crates/ui-panels/src/dialog/prompt.rs +++ b/crates/ui-panels/src/dialog/prompt.rs @@ -227,7 +227,8 @@ pub struct Prompt<'a> { escape: Option, /// Whether the dialog reports the alert-dialog role, described by the message and any tone. alert: bool, - /// What the dialog's layer is for. + /// What the dialog's layer is for: `LayerRole::Progress` for a job's progress window. + #[prop(vis = "pub(super)")] layer_role: LayerRole, } @@ -255,13 +256,6 @@ impl<'a> Prompt<'a> { self } - /// What the dialog's layer is for: `LayerRole::Progress` for a job's progress window. - #[must_use] - pub(super) fn layer_role(mut self, role: LayerRole) -> Self { - self.layer_role = role; - self - } - /// The answers, one footer button each. #[must_use] pub fn answers(mut self, answers: impl IntoIterator) -> Self { From dd19e4bf9f9461804493cf65b1fd94ffc669e5db Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 26 Nov 2026 05:49:58 +0000 Subject: [PATCH 172/235] design-lint: a module under cfg(all(test, ..)) is test code is_cfg_test found `test` only at the top level of a cfg, so a test-only module gated on test and a feature together was linted as UI code. It now reads the predicate: `test`, or an `all(..)` holding such a predicate; `any` and `not` do not count. craft-draw's Bezier read counter goes back to one cfg(all(test, feature = "screen-testing")) attribute. --- crates/design-lint/src/contract/global_state.rs | 16 ++++++++++++---- .../contract-rules/accept/global-state.rs | 7 +++++++ crates/draw/src/ui/pen/bezier/model.rs | 3 +-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index 75208f2ecd..35ef8ffd3c 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -62,10 +62,18 @@ fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec bool { - attrs.iter().any(|a| { - a.path().is_ident("cfg") - && matches!(&a.meta, syn::Meta::List(list) if list.tokens.clone().into_iter().any(|t| matches!(t, proc_macro2::TokenTree::Ident(i) if i == "test"))) - }) + attrs.iter().any(|a| a.path().is_ident("cfg") && a.parse_args::().is_ok_and(|m| implies_test(&m))) +} + +/// Whether the cfg predicate holds only under `test`: `test` itself, or an `all(..)` with such a predicate in it. +fn implies_test(meta: &syn::Meta) -> bool { + match meta { + syn::Meta::Path(path) => path.is_ident("test"), + syn::Meta::List(list) if list.path.is_ident("all") => list + .parse_args_with(syn::punctuated::Punctuated::::parse_terminated) + .is_ok_and(|all| all.iter().any(implies_test)), + _ => false, + } } fn names_fs(segments: &[String]) -> bool { diff --git a/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs index 11d96951cd..6a895e20c5 100644 --- a/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs +++ b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs @@ -15,3 +15,10 @@ fn exists(path: &Path) -> bool { mod tests { static SEEN: std::sync::Mutex = std::sync::Mutex::new(0); } + +#[cfg(all(test, feature = "screen-testing"))] +mod counted { + thread_local! { + static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } +} diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index f35dc157b8..d95f1d0532 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -328,8 +328,7 @@ impl SelectedAnchors { } /// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work. -#[cfg(test)] -#[cfg(feature = "screen-testing")] +#[cfg(all(test, feature = "screen-testing"))] pub(crate) mod reads { use std::cell::Cell; From 2ac1123a2c8bbb34ead4b240bb826e79b2dfcb5d Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 26 Nov 2026 05:58:25 +0000 Subject: [PATCH 173/235] craft-menu: the rebuild retry reads the framework's Instant, which is the browser clock on wasm --- crates/menu/src/driver.rs | 3 ++- crates/ui-contract/src/runtime/motion.rs | 8 ++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/menu/src/driver.rs b/crates/menu/src/driver.rs index e12f7f2c7c..53e6aa54ca 100644 --- a/crates/menu/src/driver.rs +++ b/crates/menu/src/driver.rs @@ -3,11 +3,12 @@ use std::borrow::Cow; use std::collections::HashSet; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::{Duration, Instant}; +use std::time::Duration; use craft_keymap::{Chord, CommandRef, Key, Mods}; use craft_ui::contract::{MemoKey, MemoProps}; use craft_ui::menu::Alternate; +use craft_ui::runtime::motion::Instant; use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost}; use crate::layout::{Clash, Layout}; diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index 5fb7df0beb..b7fad9cce2 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -243,10 +243,14 @@ pub(crate) struct Wanted { wake: Option, } +/// The instant type [`now`] returns: `std::time::Instant` on native targets, a clock that works in the browser on +/// wasm. +pub use web_time::Instant; + /// The wall clock's reading, for a host that drives a store on real time (`ShellApp::tick`). It is the one place /// outside a pass that reads the clock. -pub fn now() -> web_time::Instant { - web_time::Instant::now() +pub fn now() -> Instant { + Instant::now() } /// Marks the running viewport as having an animation that is not at its end value. From c90fb7343cb8d843c37e0673a50c99a9561d99e7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 26 Nov 2026 06:02:38 +0000 Subject: [PATCH 174/235] actions.lock: nightly.yml pins no actions --- .github/workflows/actions.lock | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 01b258e23c..66897e207a 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -69,8 +69,7 @@ workflows: '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - '.github/workflows/nightly.yml': - - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' From 76322b729c2580d3b0546397359ed0e455e7b7dd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 26 Nov 2026 13:03:37 +0700 Subject: [PATCH 175/235] menu: the macOS rebuild retry keeps std Instant, allowed and listed runtime::motion::now returns a web_time Instant, which is not std's on wasm, so the menu macOS and WASM lint job failed to compile mac.rs. The AppKit rebuild retry is a native timer outside any pass, so it keeps Instant::now with a contract/motion marker and its entry in design/exceptions/craft-menu/crate.toml. --- crates/menu/src/mac.rs | 4 +++- design/exceptions/craft-menu/crate.toml | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index 098e09b216..f295e6fa74 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -33,6 +33,7 @@ use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Instant; use craft_keymap::{Chord, CommandRef, Key, Mods}; use craft_ui::menu::Alternate; @@ -153,7 +154,8 @@ impl Native { fn update(&mut self, bar: &MenuBar) { let (spec, targets) = lower(bar); let (native, live) = (&mut self.bar, &self.targets); - let attempt = self.retry.attempt(&spec, craft_ui::runtime::motion::now, || { + // design: allow[contract/motion](the AppKit menu rebuild retry is a native timer outside any pass, not a motion clock; the runtime clock is a web_time Instant, not std, on wasm) + let attempt = self.retry.attempt(&spec, Instant::now, || { let rebuilt = native.apply(&spec); if rebuilt { *lock(live) = targets; diff --git a/design/exceptions/craft-menu/crate.toml b/design/exceptions/craft-menu/crate.toml index 88f56e78b1..97d6521666 100644 --- a/design/exceptions/craft-menu/crate.toml +++ b/design/exceptions/craft-menu/crate.toml @@ -1 +1,8 @@ config_version = 1 + +[[exception]] +name = "mac-menu-rebuild-retry-clock" +kind = "marker" +rule = "contract/motion" +path = "crates/menu/src/mac.rs" +reason = "The AppKit menu rebuild retry is a native timer that runs outside any pass, not a motion clock; RebuildRetry takes a std Instant, which the runtime clock (a web_time Instant on wasm) is not." From 09d11fef0a6076de8e00da2c225d4b615aa3b90f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:12:52 -0800 Subject: [PATCH 176/235] atomic: document the Windows minimum age for sweep_temp_files On Windows, a write may not update a file's last write time until the writing handle closes, so the sweep can see an active staging file as old. The doc comment and README now say to pass a minimum age longer than the longest whole save on Windows. --- crates/atomic/README.md | 4 +++- crates/atomic/src/lib.rs | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/atomic/README.md b/crates/atomic/README.md index 7c178a6dc2..6ef4429a89 100644 --- a/crates/atomic/README.md +++ b/crates/atomic/README.md @@ -80,7 +80,9 @@ a symbolic link, and does not search subfolders. A save updates its staging file time only while it writes bytes, not while it flushes or renames, and removing the staging file makes that save fail. Choose a minimum age longer than the longest time any save into the folder, by any process including the calling one, may go without writing, counting the final flush and -rename. Entries that cannot be removed are left in place. +rename. On Windows, a write may not update the modification time until the staging file's handle +closes, so choose a minimum age longer than the longest whole save, from the staging file's +creation through the rename. Entries that cannot be removed are left in place. ### Document Permissions and Private Data diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 340fd25073..104f859368 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -826,8 +826,10 @@ pub fn temp_name(file: &str) -> String { /// staging file's modification time only while it writes bytes, not while it flushes or renames, /// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest /// time any save into `dir`, by any process including the calling one, may go without writing, -/// counting the final flush and rename. Entries that cannot be read or removed are left in place. -/// Subfolders are not searched. +/// counting the final flush and rename. On Windows, a write may not update the modification time +/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save, +/// from the staging file's creation through the rename. Entries that cannot be read or removed are +/// left in place. Subfolders are not searched. /// On `wasm32` this returns an `Unsupported` error. pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result { #[cfg(target_arch = "wasm32")] From 82c484b52d753a4a8f2a9833b674cd3e4d4be01a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:20:44 -0800 Subject: [PATCH 177/235] craft-settings: keep the document unchanged when a save fails The save now merges the settings into a copy of the document and keeps the copy only after the file is written. Before, a save rejected as too large, or one whose write failed, had already removed dropped keys from the document together with their comments, so putting a key back later wrote it without its comment. --- crates/settings/src/store.rs | 12 +++++++----- crates/settings/tests/recovery.rs | 26 +++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 76c10d1429..45917e2b6d 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -466,15 +466,16 @@ impl SettingsStore { // writing over the changes this save merges in. An early return releases it. let lock = self.files.lock(&path); let (on_disk, theirs) = self.check_disk(&path)?; - merge_into(&mut self.doc, &self.value).map_err(|e| SettingsError::Serialize(e.to_string()))?; - set_schema_version(&mut self.doc, T::SCHEMA_VERSION); - // The merge is staged and only kept once the file is written, so a save that fails leaves the + // The merge is staged on a copy and only kept once the file is written, so a save that fails leaves the // document, the value and the baseline as they were, and the next save merges the disk again. + let mut doc = self.doc.clone(); + merge_into(&mut doc, &self.value).map_err(|e| SettingsError::Serialize(e.to_string()))?; + set_schema_version(&mut doc, T::SCHEMA_VERSION); let theirs = theirs.map(|mut theirs| { - merge_changes::(&self.base, &self.doc, &mut theirs); + merge_changes::(&self.base, &doc, &mut theirs); theirs }); - let text = document::render(theirs.as_ref().unwrap_or(&self.doc)); + let text = document::render(theirs.as_ref().unwrap_or(&doc)); // A file over the limit would not be read back at the next start; keep the old file. if text.len() as u64 > MAX_CONFIG_BYTES { return Err(SettingsError::Io(too_large())); @@ -486,6 +487,7 @@ impl SettingsStore { } self.files.write(&path, &text)?; drop(lock); + self.doc = doc; if let Some(theirs) = theirs { let (ours, _) = document::deserialize_sections::(&self.doc); self.doc = theirs; diff --git a/crates/settings/tests/recovery.rs b/crates/settings/tests/recovery.rs index 70453290a3..9fbb8e2ef9 100644 --- a/crates/settings/tests/recovery.rs +++ b/crates/settings/tests/recovery.rs @@ -2,7 +2,7 @@ use super::common; -use common::{config_path, open_in, read_config, write_config}; +use common::{config_path, open_in, open_keyed, read_config, write_config}; use craft_settings::{ReadOnlyReason, SettingsError, Source}; #[test] @@ -117,6 +117,30 @@ fn rejected_save_keeps_the_adopted_file_as_the_baseline() { assert!(text.contains("language = \"fr\""), "{text}"); } +#[test] +fn rejected_save_keeps_the_comment_of_a_removed_key() { + let tmp = tempfile::tempdir().unwrap(); + write_config(tmp.path(), "schema_version = 1\n\n[shortcuts]\n# note on save\nsave = \"Ctrl+S\"\n"); + let (mut store, _) = open_keyed(tmp.path()); + + // The key is removed in a save too large to write, then put back. + let huge = "a".repeat(craft_settings::store::MAX_CONFIG_BYTES as usize); + store.update(|k| { + k.shortcuts.remove("save"); + k.general.language = huge; + }); + assert!(matches!(store.flush(), Err(SettingsError::Io(e)) if e.kind() == std::io::ErrorKind::FileTooLarge)); + store.update(|k| { + k.shortcuts.insert("save".into(), "Ctrl+S".into()); + k.general.language = "fr".into(); + }); + store.flush().unwrap(); + + let text = read_config(tmp.path()); + assert!(text.contains("# note on save\nsave = \"Ctrl+S\""), "{text}"); + assert!(text.contains("language = \"fr\""), "{text}"); +} + #[test] fn newer_schema_opens_read_only_and_never_overwrites() { let tmp = tempfile::tempdir().unwrap(); From 9219c6c0eb7da3cc3c31597eb02c168ca5edd615 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:01:17 -0800 Subject: [PATCH 178/235] craft-quit: Note forget finishing the guard and the browser prompt being best effort --- crates/quit/README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/quit/README.md b/crates/quit/README.md index 22417fe830..56f7e2cbf9 100644 --- a/crates/quit/README.md +++ b/crates/quit/README.md @@ -94,7 +94,9 @@ The app shows the question for `current()` (craft-ui's `UnsavedChangesDialog`), stops the operation. - `retry_after_failure()` puts the document back at the front, clears the "Apply to All" answer and asks about that document again. -- `forget(&doc)` drops a document that closed elsewhere while the guard ran. +- `forget(&doc)` drops a document that closed elsewhere while the guard ran. It returns no step. When + it removed the last waiting document and no save is in progress, `is_finished()` is `true`: the app then treats the operation + as `Finished` and does what the `Finished` row above says. - `remaining()` counts the documents still waiting, the current one included. The prompt shows "Apply to All" when it is more than one. @@ -116,8 +118,9 @@ craft-menu uses this id for its Quit item. An app without a menu of its own call A browser tab has no close request an app can answer. On `wasm32`, call `craft_quit::web::hold_leave(unsaved)` each frame. While the last call passed `true`, the page's -`beforeunload` listener calls `prevent_default`, and the browser asks the user before leaving. The -first call adds the listener; a page without a window gets none, and a later call tries again. +`beforeunload` listener calls `prevent_default`, and the browser may ask the user before leaving. +Browsers decide whether to show the prompt (some skip it when the page has had no user interaction), +and the prompt cannot be customized, so treat it as best effort. The first call adds the listener; a page without a window gets none, and a later call tries again. ## Notes From 1cdb01c1746439d7d46805d1d502f5c1246f3e56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:05:54 -0800 Subject: [PATCH 179/235] Share: a link answer with no sheet open does not reload destinations A link request still pending at sign-out can be answered after the sheet has closed. The answer no longer asks the provider for destinations when no sheet is open. --- crates/cloud-ui/src/share/mod.rs | 17 ++++++++++------- crates/cloud-ui/src/share/tests.rs | 9 +++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/cloud-ui/src/share/mod.rs b/crates/cloud-ui/src/share/mod.rs index 05d32e4de6..9d03472e50 100644 --- a/crates/cloud-ui/src/share/mod.rs +++ b/crates/cloud-ui/src/share/mod.rs @@ -740,13 +740,16 @@ impl ShareDialog { } } Answer::Linked => { - // An account arrived, so the list is stale. - if let Some(sheet) = &mut self.open { - sheet.destinations = None; - } - let seq = self.issue(Request::Destinations); - if let Some(sheet) = &mut self.open { - sheet.destinations_seq = Some(seq); + // An account arrived, so the list is stale. With no sheet open + // there is no list to reload. + if self.open.is_some() { + if let Some(sheet) = &mut self.open { + sheet.destinations = None; + } + let seq = self.issue(Request::Destinations); + if let Some(sheet) = &mut self.open { + sheet.destinations_seq = Some(seq); + } } } Answer::Withdrawn { share_id } => { diff --git a/crates/cloud-ui/src/share/tests.rs b/crates/cloud-ui/src/share/tests.rs index 40d653b929..283ce0274b 100644 --- a/crates/cloud-ui/src/share/tests.rs +++ b/crates/cloud-ui/src/share/tests.rs @@ -598,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() { assert!(shared.is_empty() && failed.is_empty()); } +#[test] +fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() { + let (ctx, mut dialog, backend) = ready(); + dialog.signed_out(); + let before = backend.seen().len(); + dialog.receive(&ctx, 99, Ok(Answer::Linked)); + assert_eq!(backend.seen().len(), before); +} + #[test] fn pressing_return_takes_the_first_match_or_an_address() { let (_ctx, mut dialog, _) = ready(); From fbb88153e1ed55f640232eec0c4e55aa0db9baa4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:14:58 -0800 Subject: [PATCH 180/235] Cloud: Save As is refused while signed out After sign-out the Save As page no longer creates a file until the next sign-in, so a provider that has not ended the session cannot receive it for the account that left. --- crates/cloud-ui/src/cloud/conflict_tests.rs | 15 +++++++++++++++ crates/cloud-ui/src/cloud/mod.rs | 3 +++ 2 files changed, 18 insertions(+) diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index f5ed07a65e..03b6257ed8 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -319,6 +319,21 @@ fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() { assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again"); } +/// Save As while signed out has no account to land in. A provider that has not ended the session +/// yet would create the file in the account that is leaving. +#[test] +fn save_as_after_sign_out_is_refused_until_the_next_sign_in() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + let refused = save_as(&mut app, "", "Plan"); + assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}"); + assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out"); +} + /// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The /// second click, with a name, must still copy the conflicted document A, not the active tab B. #[test] diff --git a/crates/cloud-ui/src/cloud/mod.rs b/crates/cloud-ui/src/cloud/mod.rs index 46daa6ad8a..b99ea2f612 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -648,6 +648,9 @@ pub fn save_as(app: &mut A, folder: &str, name: &str) -> Result Date: Thu, 26 Nov 2026 16:30:14 +0700 Subject: [PATCH 181/235] docs: contract-api lists FieldLook, StyleCx::quiet_field and TextOptions::look Regenerated with the contract-api bin; only the three entries this PR adds are taken, the file's other drift on next is left alone. --- docs/contract-api.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 8f2a44a730..7e369a32ae 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -3295,7 +3295,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn row_lines(&self) -> Vec<(String, egui::Rect, Vec)>`. Every row as its text, its rect from the galley's origin and its bidi runs: the one per-row geometry, read by - `pub fn size(&self) -> egui::Vec2`. The galley size. - `pub fn char_x(&self, chars: usize) -> f32`. Where a caret before character `chars` (counted from the start of the text) stands, from the layout's left edge: -- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option

(ctx).is_some_and(|payload| matches(&payload))); + let show = Box::new(move |ui: &mut Ui, action: &FooterAction, id: Id| { let accepts = Arc::clone(&accepts); - let slot = DropAction::new(move |payload: &P| accepts(payload)).enabled(action.enabled || action.takes_drops_disabled); + let slot = DropAction::new(move |payload: &P| accepts(payload)).enabled(action.enabled || action.takes_drops_disabled).id(id); let shown = slot.show(ui, |ui, _| action.icon_button(DropAction::

::accepting(ui)).show(ui).response); let response = shown.inner.unwrap_or_else(|| shown.output.response.clone()); DropShown { response, dropped: shown.output.dropped.map(|payload| Arc::new(payload) as Dropped), over: shown.output.over } - })); + }); + self.drops.push(Arc::new(ActionDrop { matches, show })); self } + fn drop_slot(&self, ctx: &Context) -> Option<&ActionDrop> { + let first = self.drops.first()?; + let slot = if self.drops.len() > 1 { self.drops.iter().find(|drop| (drop.matches)(ctx)).unwrap_or(first) } else { first }; + Some(slot) + } + /// The button, enabled when the action is or when `accepting` lifts it for an accepted drag over it. fn icon_button(&self, accepting: bool) -> IconButton<'static> { let mut button = IconButton::new(self.icon.clone()).label(self.label.clone()).enabled(self.enabled || accepting).selected(self.pressed); @@ -810,9 +833,11 @@ impl FooterBar { fn show_actions(ui: &mut Ui, actions: &[FooterAction], order: impl Iterator, shown: &mut Shown) { for at in order { let action = &actions[at]; - let response = match &action.drops { + let response = match action.drop_slot(ui.ctx()) { Some(drops) => { - let slot = drops(ui, action); + // All payload types share this slot and its child button. A different type can be over it next pass. + let id = ui.scope_id().with(("footer-action-drop", at)); + let slot = (drops.show)(ui, action, id); if let Some(payload) = slot.dropped { shown.dropped = Some(FooterDrop { index: at, payload }); } diff --git a/crates/ui-panels/tests/it/sections/footer_row.rs b/crates/ui-panels/tests/it/sections/footer_row.rs index cd886691c1..fb480e64ab 100644 --- a/crates/ui-panels/tests/it/sections/footer_row.rs +++ b/crates/ui-panels/tests/it/sections/footer_row.rs @@ -10,7 +10,7 @@ use craft_ui::sections::{DropAction, FooterAction, FooterBar, ReorderableSection use craft_ui::testing::{Fixture, pointer, trial}; use craft_ui::tile_grid::{ThumbnailSlider, TileZoom}; use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; /// The view modes' rect, the slider's rect and the rects of the footer bar's actions, in a footer row `width` wide. @@ -142,6 +142,64 @@ fn a_drop_on_an_action_reports_the_modifiers_held_at_the_release() { assert!(picked.iter().all(|(.., shift)| *shift), "the pick reports the Shift of the release: {picked:?}"); } +#[trial] +fn one_footer_action_takes_two_payload_types() { + use craft_ui::contract::{SelectMode, ShowCollection as _}; + use craft_ui::list::{List, ListRow}; + use craft_ui::runtime::drag; + + fn source(ui: &mut Ui, label: &'static str, payload: P) { + let keys = [0_u8]; + List::::new(label) + .id_salt(label) + .select(SelectMode::None) + .natural_height(true) + .drag_payload(move |_: &ListDrag| Some(payload.clone())) + .show_items(ui, &craft_behavior::keyed(&keys, |key: &u8| *key), &mut |_, _| ListRow::new(label)); + } + + let taken = Rc::new(RefCell::new(Vec::new())); + let second_type = Rc::new(Cell::new(true)); + let seen = Rc::clone(&taken); + let with_second = Rc::clone(&second_type); + let mut fixture = Fixture::new(move |ui| { + source(ui, "Accepted number", 4_u8); + source(ui, "Accepted word", "word"); + source(ui, "Rejected word", "other"); + let action = + FooterAction::new(IconId::new("trash"), "Delete").enabled(false).takes_drops_disabled(true).accepts_drops(|number: &u8| *number == 4); + let action = if with_second.get() { action.also_accepts_drops(|word: &&str| *word == "word") } else { action }; + let out = FooterBar::actions([action]).show_footer(ui); + if let Some(drop) = out.dropped { + assert_eq!(drop.index, 0, "both payloads belong to the same action"); + let report = (drop.payload::().copied(), drop.payload::<&str>().copied()); + seen.borrow_mut().push(report); + } + }); + fixture.room(Vec2::new(400.0, 300.0)).settle(); + let delete = fixture.by_label("Delete").expect("the one footer action"); + assert!(fixture.tree().is_disabled_key(delete.node)); + + for (label, accepted) in [("Accepted number", true), ("Accepted word", true), ("Rejected word", false)] { + let from = fixture.by_label(label).expect("the source").center(); + fixture.drag_hold_at(from, delete.center() - from); + assert_eq!(drag::mark(fixture.ctx()).is_some(), accepted, "{label}: the indicator follows the predicate"); + let current = fixture.by_label("Delete").expect("the same footer action"); + assert_eq!(current.node, delete.node, "{label}: handling a different payload keeps the control's identity"); + assert_eq!(fixture.tree().is_disabled_key(current.node), !accepted, "{label}: an accepted drag enables the action"); + fixture.release_at(delete.center()).settle(); + } + assert_eq!(&*taken.borrow(), &[(Some(4), None), (None, Some("word"))], "each accepted drop reports its original typed payload once"); + + let from = fixture.by_label("Accepted number").unwrap().center(); + fixture.drag_hold_at(from, delete.center() - from); + assert!(drag::mark(fixture.ctx()).is_some()); + second_type.set(false); + fixture.release_at(delete.center()).settle(); + assert_eq!(fixture.by_label("Delete").unwrap().node, delete.node, "removing the second predicate also keeps the control's identity"); + assert_eq!(taken.borrow().get(2), Some(&(Some(4), None)), "the same action can still take the drop on the pass the predicate is removed"); +} + #[trial] fn the_start_and_end_groups_of_a_footer_bar_sit_at_their_edges() { use craft_ui::runtime::env::Direction; From 0526ebed50bc56b517d82cdae8a02177277339eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:04:07 -0800 Subject: [PATCH 200/235] Open the tab overflow menu from the keyboard --- crates/ui-widgets/src/tabs/strip.rs | 33 +++++++++--------- crates/ui-widgets/tests/it/tabs.rs | 54 +++++++++++++++++++++++++++-- 2 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 97dce4ce93..3e877dd734 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -859,6 +859,21 @@ impl Component f self.more = None; let report = self.report(); let flow = Flow::new(cx.content_rect, cx.flow.is_rtl()); + // Alt+Down from the strip itself opens the first declared popup. Focused end items open their own menus. + if report.overflow > 0.0 { + let tabs = flow.take_end(report.ends_room).1; + let slot = match self.kind.overflow_place() { + OverflowPlace::StripEnd => tabs.take_end(report.overflow).0, + OverflowPlace::AfterTabs => tabs.take_start(report.tabs_end).1.take_start(report.overflow).0, + }; + self.more = Some(slot); + cx.part(OVERFLOW, slot) + .sense(Sense::CLICK) + .priority(HitPriority::new(HitLevel::Edge, 0)) + .over() + .toggles("menu") + .pointer_only("Alt+Down opens the overflow menu"); + } for slot in &report.ends { let Some(end) = self.trailing.get(slot.item) else { continue }; let enabled = end.enabled::(&**cx); @@ -881,21 +896,6 @@ impl Component f let _ = cx.part(GHOST.at(at as u64), flow.span(start, width)); } } - if report.overflow <= 0.0 { - return; - } - let tabs = flow.take_end(report.ends_room).1; - let slot = match self.kind.overflow_place() { - OverflowPlace::StripEnd => tabs.take_end(report.overflow).0, - OverflowPlace::AfterTabs => tabs.take_start(report.tabs_end).1.take_start(report.overflow).0, - }; - self.more = Some(slot); - cx.part(OVERFLOW, slot) - .sense(Sense::CLICK) - .priority(HitPriority::new(HitLevel::Edge, 0)) - .over() - .toggles("menu") - .pointer_only("Alt+Down opens the overflow menu"); } /// A drag or a double click that starts on the empty room is reported; a drag of this strip's tabs that no target @@ -958,11 +958,12 @@ impl Component f } } - /// The overflow button and each end item are buttons named by their labels; an end item with a menu says so. + /// The overflow button and each end item are buttons named by their labels and announce the menus they open. fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { if self.more.is_some() { let node = access.node(OVERFLOW, Role::BUTTON); node.name = Name::Text(cx.words::().more.as_str().to_owned()); + node.has_popup(PopupKind::Menu); } for slot in self.report().ends { let Some(end) = self.trailing.get(slot.item) else { continue }; diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index 903bf220ef..080b4ea923 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -19,6 +19,7 @@ const REST_FRAMES: usize = (craft_ui::contract::tooltip::DELAY * 60.0) as usize #[trial] fn overflowing_document_tabs_remain_readable_and_list_every_document() { + use craft_ui::contract::PopupKind; use craft_ui::tabs::{DocumentTab, DocumentTabs}; let mut reference = Fixture::new(|ui| { let tabs = [DocumentTab::new(0, "Document num")]; @@ -39,8 +40,11 @@ fn overflowing_document_tabs_remain_readable_and_list_every_document() { shown.iter().all(|tab| tab.width() + 0.5 >= minimum), "tabs fit their first 12 characters and close button: {shown:?}, minimum {minimum}" ); - let more = fixture.by_label("More tabs").expect("overflow button").center(); - fixture.click_at(more).settle(); + let more = fixture.by_label("More tabs").expect("overflow button"); + assert_eq!(fixture.tree().has_popup_of(more.node), Some(PopupKind::Menu), "More tabs announces that it opens a menu"); + assert_eq!(fixture.tree().expanded_of(more.node), Some(false), "More tabs starts collapsed"); + fixture.click(&more).settle(); + assert_eq!(fixture.tree().expanded_of(more.node), Some(true), "More tabs is expanded while the menu is open"); for i in 0..12 { let name = format!("Document number {i}, scanned.pdf"); let tree = fixture.tree(); @@ -1168,6 +1172,52 @@ fn a_menu_end_item_shows_the_menu_chevron() { assert!(menu > command + 4.0, "the menu item is wider by its chevron: {menu} against {command}"); } +#[trial] +fn alt_down_on_an_overflowing_tab_opens_more_tabs_beside_an_end_menu() { + use craft_behavior::IconId; + use craft_ui::contract::Entry; + use craft_ui::runtime::commands::{CommandRef, EditCommands}; + use craft_ui::tabs::StripEnd; + use craft_ui::testing::access::focused_key; + + let mut fixture = Fixture::new(|ui| { + let rows: [Entry; 1] = [Entry::new(EditCommands::Paste.into(), "Show comments")]; + let items = [StripEnd::menu("Comments", IconId::new("list").into(), &rows)]; + let keys: Vec<_> = (0..RIBBON.len()).collect(); + let source = keyed(&keys, |key: &usize| *key).with_text(|key| std::borrow::Cow::Borrowed(RIBBON[*key])); + let strip = TabStrip::new("Ribbon").kind(TabKind::Ribbon).shown(1).trailing(&items); + let _ = strip.show_items(ui, &source, &mut |key, _| Tab::new(RIBBON[*key])); + }); + fixture.room(egui::vec2(240.0, 120.0)).settle(); + let hidden = RIBBON.iter().copied().find(|name| fixture.by_label(name).is_none()).expect("a tab needs the overflow menu"); + let comments = fixture.by_label("Comments").expect("the trailing menu button"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let tab_focus = fixture.focused_stop().expect("the tab strip has keyboard focus"); + let menu_has_focus = |fixture: &Fixture| { + matches!( + fixture.tree().role_of(focused_key(fixture.tree())), + Some(Role::MENU | Role::MENU_ITEM | Role::MENU_ITEM_CHECK_BOX | Role::MENU_ITEM_RADIO) + ) + }; + + fixture.key(Key::ArrowDown, Modifiers::ALT).settle(); + assert!(fixture.by_label(hidden).is_some(), "Alt+Down on the tabs opens the overflow menu"); + assert!(fixture.by_label("Show comments").is_none(), "the trailing menu stays closed"); + assert!(menu_has_focus(&fixture), "focus enters the overflow menu"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!(fixture.by_label(hidden).is_none(), "Escape closes the overflow menu"); + assert_eq!(fixture.focused_stop(), Some(tab_focus), "Escape restores focus to the tabs"); + + fixture.key(Key::Tab, Modifiers::NONE).settle(); + assert_eq!(focused_key(fixture.tree()), comments.node, "Tab reaches the trailing menu button"); + fixture.key(Key::ArrowDown, Modifiers::ALT).settle(); + assert!(fixture.by_label("Show comments").is_some(), "Alt+Down opens the trailing menu when its button has focus"); + assert!(menu_has_focus(&fixture), "focus enters the trailing menu"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!(fixture.by_label("Show comments").is_none(), "Escape closes the trailing menu"); + assert_eq!(focused_key(fixture.tree()), comments.node, "Escape restores focus to the trailing menu button"); +} + /// A contextual tab the source drops fades out at its slot: while it fades it has no node, a click on its slot /// selects nothing and the overflow menu does not list it; once the fade ends it is not painted. A frame of two /// passes paints the fade as one does. A contextual tab that comes back is hit from its first frame. From a810e21237b6d19c122ff253dee78c79e46e2f8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:09:35 -0800 Subject: [PATCH 201/235] Apply custom unit labels to length fields --- .../src/patterns/form_dialogs/rows.rs | 3 +++ .../tests/it/form_dialogs/params.rs | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs index bc28c3cbd6..14f974e0c4 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs @@ -960,6 +960,9 @@ impl<'p> Pass<'p> { (None, codec) => line.scalar_field(self.units, line.bind(Some(value), default), decimals, codec, self.shaded), } .step(step); + if let Some(text) = line.param.unit_label_text() { + field = field.unit(text.clone()); + } if let Some(range) = range.clone() { field = field.range(range); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/params.rs b/crates/ui-patterns/tests/it/form_dialogs/params.rs index 1c6233cb43..5f4050a44f 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/params.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/params.rs @@ -958,6 +958,33 @@ fn rows_show_unit_text_and_milliseconds() { assert_eq!(held.number("delay"), Some(120.0), "a row with unit text still reads its kind's spelling"); } +#[trial] +fn length_rows_show_custom_unit_text_without_changing_their_readers() { + let lengths = craft_ui::runtime::env::LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0); + let doubled = craft_behavior::NumberCodec::new(craft_behavior::Reader::new().bare(2.0), 2); + let params = vec![ + Param::number("plain", "Plain", 0.0, 1.0, 2).length(lengths).unit_label("length label"), + Param::number("coded", "Coded", 0.0, 1.0, 2).length(lengths).codec(doubled).unit_label("codec label"), + Param::number("hidden", "Hidden unit", 0.0, 1.0, 2).length(lengths).unit_label(""), + ]; + let values = Rc::new(RefCell::new(DialogFields::new())); + let mut fixture = rows(params, &values); + fixture.room(Vec2::new(1280.0, 800.0)).settle(); + for unit in ["length label", "codec label"] { + assert!(fixture.texts().iter().any(|text| text.text == unit && !text.elided && text.clip.contains_rect(text.rect)), "{unit}"); + } + assert!(!fixture.texts().iter().any(|text| text.text == "pt" && !text.elided)); + for (label, typed) in [("Plain", "3pt"), ("Coded", "3"), ("Hidden unit", "3pt")] { + let field = fixture.by_label(label).expect("the length row"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text(typed).key(Key::Enter, Modifiers::NONE).settle(); + } + let (plain, coded) = (values.borrow().number("plain"), values.borrow().number("coded")); + assert_eq!(plain, Some(3.0)); + assert_eq!(values.borrow().number("hidden"), plain); + assert!(plain.zip(coded).is_some_and(|(plain, coded)| coded == 2.0 * plain), "{plain:?}, {coded:?}"); +} + /// A count per inch shows `/in` after its number, apart in the field or in the number's own run in the inline look, and /// a typed number or an edit of that run is read back as the count. #[trial] From 1750237164f522740adf65976545fc3d231f4f5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:14:24 -0800 Subject: [PATCH 202/235] Report pressed state only on stateful footer actions --- crates/ui-panels/src/sections/footer.rs | 15 +++++---- .../tests/it/sections/footer_keys.rs | 33 +++++++++++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index 40427888a3..bd20f8eee3 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -88,7 +88,7 @@ pub struct FooterAction { icon: IconSpec<'static>, label: Label, enabled: bool, - pressed: bool, + pressed: Option, tone: Option, popup: Option, expanded: Option, @@ -121,7 +121,7 @@ impl FooterAction { icon: icon.into(), label: label.into(), enabled: true, - pressed: false, + pressed: None, tone: None, popup: None, expanded: None, @@ -139,11 +139,11 @@ impl FooterAction { self } - /// Whether the action shows the host's state, as the on look: Button Mode while the panel is in it, Record - /// while recording. A click is reported as usual; the host changes its state or ignores the click. + /// The host's on or off state for a stateful action, reported to assistive technology and shown in its face. + /// A click is reported as usual; the host changes its state or ignores the click. #[must_use] pub fn pressed(mut self, on: bool) -> Self { - self.pressed = on; + self.pressed = Some(on); self } @@ -201,7 +201,10 @@ impl FooterAction { /// The button, enabled when the action is or when `accepting` lifts it for an accepted drag over it. fn icon_button(&self, accepting: bool) -> IconButton<'static> { - let mut button = IconButton::new(self.icon.clone()).label(self.label.clone()).enabled(self.enabled || accepting).selected(self.pressed); + let mut button = IconButton::new(self.icon.clone()).label(self.label.clone()).enabled(self.enabled || accepting); + if let Some(on) = self.pressed { + button = button.selected(on); + } if let Some(tone) = self.tone { button = button.variant(Variant::look(Emphasis::Ghost, tone)); } diff --git a/crates/ui-panels/tests/it/sections/footer_keys.rs b/crates/ui-panels/tests/it/sections/footer_keys.rs index 2fb7d9acf4..024249ba5c 100644 --- a/crates/ui-panels/tests/it/sections/footer_keys.rs +++ b/crates/ui-panels/tests/it/sections/footer_keys.rs @@ -34,3 +34,36 @@ fn each_footer_button_is_its_own_tab_stop() { let second = focused(&fixture, &labels).expect("Tab stays among the labelled stops"); assert!(second != first && second != "Before", "Tab moves to the other footer button"); } + +#[trial] +fn only_stateful_footer_actions_announce_a_pressed_state() { + use craft_behavior::{IconId, Mixed}; + use craft_ui::contract::PopupKind; + use craft_ui::sections::FooterAction; + use craft_ui::testing::focus::AccessActionKind; + use std::cell::Cell; + + let pressed = Cell::new(false); + let mut fixture = Fixture::new(move |ui| { + let actions = [ + FooterAction::new(IconId::new("trash-2"), "Delete Selected Item"), + FooterAction::new(IconId::new("list"), "Show Swatch Kinds").pressed(pressed.get()), + FooterAction::new(IconId::new("plus"), "Add New Effect").popup(PopupKind::Menu), + ]; + if FooterBar::actions(actions).show_footer(ui).picked == Some(1) { + pressed.set(!pressed.get()); + } + }); + fixture.settle(); + let delete = fixture.by_label("Delete Selected Item").expect("the ordinary action"); + let filter = fixture.by_label("Show Swatch Kinds").expect("the stateful action"); + let effect = fixture.by_label("Add New Effect").expect("the menu action"); + assert_eq!(fixture.tree().toggled_of(delete.node), None, "an ordinary action is not announced as a toggle"); + assert_eq!(fixture.tree().has_popup_of(effect.node), Some(PopupKind::Menu), "a menu action still announces its menu"); + assert_eq!(fixture.tree().toggled_of(effect.node), None, "a menu by itself does not make an action a toggle"); + assert_eq!(fixture.tree().toggled_of(filter.node), Some(Mixed::Same(false)), "an explicitly off action is announced as off"); + fixture.click(&filter).settle(); + assert_eq!(fixture.tree().toggled_of(filter.node), Some(Mixed::Same(true)), "the action is announced as on after activation"); + fixture.access(AccessActionKind::Click, &filter).settle(); + assert_eq!(fixture.tree().toggled_of(filter.node), Some(Mixed::Same(false)), "the action is announced as off after the next activation"); +} From a7c2da8c0b5d4de8e14829b0a0362fc5821b8863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:20:29 -0800 Subject: [PATCH 203/235] Parameter forms: name fields with hidden side captions --- .../src/patterns/form_dialogs/param.rs | 15 +++++++ .../src/patterns/form_dialogs/rows.rs | 21 +++++---- .../tests/it/form_dialogs/params.rs | 45 +++++++++++++++++++ 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index f83dbadd15..1ac58aa3ec 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -583,6 +583,7 @@ pub(crate) struct RowOptions { eyedropper: bool, eyedropper_armed: bool, full_width: bool, + hide_caption: bool, /// The row or section stands beside the one before it ([`Param::beside`]). beside: bool, /// The field pairs with the next one in its section ([`Param::beside_next`]). @@ -659,6 +660,11 @@ pub(crate) enum Head { } impl RowOptions { + /// Whether the field's label names it without drawing a caption. + pub(crate) fn hides_caption(&self) -> bool { + self.hide_caption + } + /// Whether the row or section stands beside the one before it. pub(crate) fn beside(&self) -> bool { self.beside @@ -1304,6 +1310,15 @@ impl Param { self } + /// For a field with a side caption, hides the caption while keeping the row label as its accessible name. + /// Resettable fields keep their caption and reset dot. Separate headings, radio groups and stacked sliders + /// keep their own captions. + #[must_use] + pub fn hide_caption(mut self) -> Self { + self.options.get_or_insert_default().hide_caption = true; + self + } + /// For a [`ParamKind::Range`] row: the slider asks for a short field's length and the number field is as wide as /// its widest value, so the row takes its content's width rather than the form's (production's Opacity). Other /// kinds and a popup slider are unchanged. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs index b0243a7bf0..a67b9f4cee 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs @@ -13,8 +13,8 @@ use super::words::ParamWords; use crate::buttons::{Button, IconButton, ToggleButton}; use crate::choice::{Checkbox, Radio, RadioGroup, Swatch}; use crate::contract::{ - Bind, BodyCx, CanvasGesture, CaptionColumn, Entry, FieldLayout, LabelScheme, NoValue, Outcome, Pad, Props as _, Remember as _, Sampler as _, - Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec, clicked, + Bind, BodyCx, CanvasGesture, CaptionColumn, Entry, FieldLayout, LabelKind, LabelScheme, NoValue, Outcome, Pad, Props as _, Remember as _, + Sampler as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec, clicked, }; use crate::display::Text; use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout}; @@ -451,10 +451,9 @@ impl Line<'_> { // the captions share a column ([`CaptionColumn`]), where it stands beside the group as every caption does. let env = Env::of(ui); let view = env.view(); - if matches!(self.param.kind, ParamKind::Custom(_)) - && view.get::() == LabelScheme::Inline - && !view.get::().shared() - { + let own_caption = view.get::() == LabelScheme::Inline && !view.get::().shared(); + let heading = matches!(self.param.kind, ParamKind::Custom(_)) && own_caption; + if heading { field = field.layout(FieldLayout::Above); } if self.compact { @@ -463,10 +462,16 @@ impl Line<'_> { if let Some(tip) = self.param.tooltip_text() { field = field.tooltip(tip.clone()); } - if self.param.option().resettable() { + let options = self.param.option(); + if options.resettable() { field = field.side(SideLabel::new().reset_dot(true)); + } else if options.hides_caption() && !heading { + field = field.side(SideLabel::new().kind(LabelKind::Hidden)); + if own_caption { + field = field.layout(FieldLayout::Above); + } } - field.show(ui, |ui, _| match self.param.option().help_link() { + field.show(ui, |ui, _| match options.help_link() { None => body(ui), Some(_) => beside(ui, |ui| { body(ui); diff --git a/crates/ui-patterns/tests/it/form_dialogs/params.rs b/crates/ui-patterns/tests/it/form_dialogs/params.rs index ed2792b745..ff3181c30c 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/params.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/params.rs @@ -77,6 +77,28 @@ fn rows(params: Vec, values: &Rc>) -> Fixture { fixture } +#[trial] +fn a_hidden_caption_keeps_the_controls_name() { + let lengths = craft_ui::runtime::env::LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0); + let fixture = rows( + vec![ + Param::number("width", "Width", 100.0, 1.0, 2).length(lengths).hide_caption(), + Param::new("range", "Range", ParamKind::text("1-3")).hide_caption(), + Param::new("height", "Height", ParamKind::int(None, None, 100)), + Param::new("amount", "Amount", ParamKind::range(0.0, 10.0, 5.0, SliderScale::Linear)).hide_caption().resettable(), + ], + &Rc::new(RefCell::new(DialogFields::new())), + ); + let tree = fixture.tree(); + assert!(fixture.by_role(Role::SPIN_BUTTON).iter().any(|target| tree.name_of(target.node) == Some("Width"))); + assert!(fixture.by_role(Role::TEXT_INPUT).iter().any(|target| tree.name_of(target.node) == Some("Range"))); + let texts = fixture.texts(); + let paints = |caption: &str| texts.iter().any(|run| run.text.trim_end_matches(':') == caption); + assert!(paints("Height"), "ordinary rows still paint their caption"); + assert!(paints("Amount"), "resettable rows keep the caption with the reset dot"); + assert!(!paints("Width") && !paints("Range"), "hidden captions use no paint"); +} + /// The opt-in range keeps its numeric value and only opens its slider from the field's arrow. #[trial] fn a_popup_slider_opens_from_a_typed_range_row() { @@ -1178,6 +1200,29 @@ fn a_group_row_under_a_heading_of_its_name_shows_the_name_once() { assert!(text_at(&texts, "The options").is_some(), "the group shows: {texts:?}"); } +#[trial] +fn hiding_side_captions_keeps_the_heading_above_a_custom_row() { + let params = vec![Param::custom("pages", "Pages", |ui, _, _| ui.label("The options")).hide_caption()]; + let texts = inline_texts(params); + assert!(text_at(&texts, "Pages").unwrap().bottom() <= text_at(&texts, "The options").unwrap().top()); +} + +#[trial] +fn a_hidden_caption_does_not_indent_an_inline_field_without_a_shared_column() { + let params = [ + Param::new("first", "A long visible caption", ParamKind::text("first")), + Param::new("second", "Second", ParamKind::text("second")).hide_caption(), + ]; + let mut values = DialogFields::new(); + let mut fixture = Fixture::new(move |ui| { + ParamRows::new("Form", ¶ms, Bind::bound(&mut values)).labels(LabelScheme::Inline).show(ui); + }); + fixture.settle(); + let name = fixture.texts().iter().find(|text| text.text.contains("A long visible caption")).unwrap(); + let hidden = fixture.by_role(Role::TEXT_INPUT).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Second")).unwrap(); + assert!((name.rect.left() - hidden.rect.left()).abs() <= 1.0, "the hidden row starts at the leading edge: {hidden:?}"); +} + /// A text row with `select_on_focus` selects its whole text when it takes the focus, so typing replaces it (PdfCraft's /// Rename opens on the name selected); a row without it keeps the text and types at the caret. #[trial] From 34b197b52ac7c30b415b8ca9e8cd544294a4a95b Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 26 Nov 2026 18:37:23 +0100 Subject: [PATCH 204/235] WIP: the gesture readout stands between moves (photocraft#17121) Co-Authored-By: Claude Opus 5.5 From 554f7877e0ccc7fb49bc261a079ed979d32e83fb Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 26 Nov 2026 18:49:22 +0100 Subject: [PATCH 205/235] Tool host: a gesture's readout stands between its moves (photocraft#17121) The host painted a tool's readout or hud only in a pass where the tool asked for it, and a tool asks from press or drag, which run only in a pass with a pointer move. Every other pass of the drag (the ants and the live outline repaint all the time) painted no box, so the marquee's W/H box blinked. The host now keeps the box the gesture's last press or drag asked for and shows it again in passes with neither; a drag that asks for nothing drops it, and it ends with the gesture. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/tool_host.rs | 31 ++++++++++- crates/ui-canvas/tests/it/canvas/tool.rs | 68 ++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index 635194131a..c7ac8c2799 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -399,11 +399,34 @@ struct HostState { /// The tip the tool's last hover asked for: the tool answers again only when the pointer moves, so it stands /// while the pointer rests, until a press, a gesture or the pointer leaving drops it. tip: Option, + /// The box the running gesture's last press or drag asked for (its hud, its readout): a pass with neither, where + /// the pointer rested or something else repainted, shows it again, so the box does not blink out between moves. + gesture_box: Option, /// A press ran since the last hover: the next resting pass hovers at the pointer even when it did not move, so the /// tool answers again for where the pointer rests and the tip the press dropped comes back. rehover: bool, } +/// The rows a gesture's press or drag asked to show beside the pointer. +#[derive(Clone, Debug, Default)] +struct GestureBox { + hud: Option>, + readout: Option>, +} + +/// The gesture's box stands between its moves: a pass whose press or drag `answered` keeps what it asked for, one with +/// neither shows the last box again. The box ends with the gesture. +fn keep_gesture_box(state: &mut HostState, requests: &mut ToolRequests, answered: bool) { + if state.gesture.is_none() { + state.gesture_box = None; + } else if answered || requests.hud.is_some() || requests.readout.is_some() { + state.gesture_box = Some(GestureBox { hud: requests.hud.clone(), readout: requests.readout.clone() }); + } else if let Some(shown) = state.gesture_box.clone() { + requests.hud = shown.hud; + requests.readout = shown.readout; + } +} + fn state_id(canvas: Id) -> Id { global("craft-ui tool host", canvas) } @@ -608,6 +631,7 @@ impl<'m> ToolHost<'m> { pending_drag: None, ended_session: false, hovered: false, + answered: false, }; run.call(None, |tool, cx| tool.each_pass(cx)); run.hover_scrolls = run.pick_as(None).autoscrolls_on_hover(); @@ -622,7 +646,8 @@ impl<'m> ToolHost<'m> { run.keys(&ctx, pass.id, env.direction.is_rtl()); run.menu_key(); } - let Run { mut response, requests, momentary: momentary_tool, hovered, .. } = run; + let Run { mut response, mut requests, momentary: momentary_tool, hovered, answered, .. } = run; + keep_gesture_box(&mut state, &mut requests, answered); let before = space.map(|space| space.target()); if let Some(past) = response.past_edge { let step = frame_step(input.time - state.time.unwrap_or(input.time)); @@ -1028,6 +1053,8 @@ struct Run<'a, 't> { pending_drag: Option, /// The gesture whose release or cancel is being delivered started a drag session. ended_session: bool, + /// The tool had a press or a drag call this pass: what it asked to show beside the pointer replaces the gesture's box. + answered: bool, } impl<'a, 't: 'a> Run<'a, 't> { @@ -1197,6 +1224,7 @@ impl<'a, 't: 'a> Run<'a, 't> { let id = next_gesture_id(self.ctx); self.ending = Some(id); self.pending_drag = None; + self.answered = true; let mut action = self.call_as(who, Some(pointer), |tool, cx| tool.press(&pointer, cx)); if action == ToolAction::Ignored && who.is_none() @@ -1235,6 +1263,7 @@ impl<'a, 't: 'a> Run<'a, 't> { let Some(active) = self.state.gesture.as_mut() else { return }; active.last = pointer; active.dragged = true; + self.answered = true; self.call(Some(pointer), |tool, cx| tool.drag(&pointer, cx)); self.report(GesturePhase::Update); let who = self.state.gesture.and_then(|active| active.stand_in); diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 34b3c8525c..2074e70bbe 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -1982,6 +1982,74 @@ fn a_drags_readout_is_not_reported_in_the_pass_its_release_ends_the_gesture() { assert!(!reported.get(), "the release pass reports none"); } +/// A tool whose drag asks for a readout while `asks` holds and for none once it is cleared. +struct Pausing { + asks: Rc>, +} + +impl CanvasTool for Pausing { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) { + if self.asks.get() { + cx.readout(vec![(craft_ui::runtime::env::Label::from("W"), "123 px".to_owned())]); + } + } + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Pause command") + } +} + +#[trial] +fn a_drags_readout_stands_in_the_passes_between_its_moves() { + let reported = Rc::new(Cell::new(false)); + let seen = Rc::clone(&reported); + let asks = Rc::new(Cell::new(true)); + let tool = RefCell::new(Pausing { asks: Rc::clone(&asks) }); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let mut reply = None; + let _ = Canvas::new("Document").document(DOCUMENT).view(CanvasView::new(room, Point::new(600.0, 450.0), 0.5)).show(ui, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + reply = Some(ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut())); + } + }); + seen.set(reply.unwrap_or_default().readout.is_some()); + }); + fixture.settle(); + let centre = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").center(); + fixture.frame(vec![pointer::moved(centre)]); + fixture.frame(vec![pointer::press(centre)]); + for step in 1..=4 { + fixture.frame(vec![pointer::moved(centre + BY * (step as f32 / 4.0))]); + } + // A pass with no move (the pointer rests, the ants or anything else repaint) gives the tool no drag call. + for _ in 0..3 { + fixture.frame(Vec::new()); + assert!(reported.get(), "the readout stays while the pointer rests mid-drag"); + assert!(fixture.texts().iter().any(|run| run.text.contains("123 px")), "and it still paints"); + } + asks.set(false); + fixture.frame(vec![pointer::moved(centre + BY * 1.25)]); + assert!(!reported.get(), "a drag that asks for none drops it"); + fixture.frame(Vec::new()); + assert!(!reported.get(), "and it does not come back while the pointer rests"); + asks.set(true); + fixture.frame(vec![pointer::moved(centre + BY * 1.5)]); + fixture.frame(vec![pointer::release(centre + BY * 1.5)]); + fixture.frame(Vec::new()); + assert!(!reported.get(), "the readout ends with its gesture"); +} + #[trial] fn show_transformation_values_gates_the_readouts_paint_and_never_the_hud() { assert_eq!(readout_during_a_drag(false, None), (true, true), "by default a tool's readout paints and is reported"); From 33424a99c7b17c99d8e4b6d33bab70897692137b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:16:12 -0800 Subject: [PATCH 206/235] Check dialog move-band padding against its spacing token --- crates/ui-panels/src/dialog/trials.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-panels/src/dialog/trials.rs b/crates/ui-panels/src/dialog/trials.rs index 9ddc6e140d..04a13aa638 100644 --- a/crates/ui-panels/src/dialog/trials.rs +++ b/crates/ui-panels/src/dialog/trials.rs @@ -598,7 +598,8 @@ fn a_dialog_moves_by_the_padding_around_its_title() { }; let start = dialog(&fixture); let line = title(&fixture); - assert!(line.top() - start.top() >= 4.0, "the title lies inside the frame's padding: {line:?} in {start:?}"); + let padding = crate::runtime::env::Env::of_root(fixture.ctx()).tokens.space.pad.dialog; + assert!(line.top() - start.top() >= padding, "the title lies inside the frame's padding: {line:?} in {start:?}"); let points = [ ("above the title", Pos2::new(line.center().x, (start.top() + line.top()) / 2.0)), ("before the title", Pos2::new((start.left() + line.left()) / 2.0, line.center().y)), From c4c52fe1f034f123fd913b2058209be56c920246 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:15:22 -0800 Subject: [PATCH 207/235] menu: the shortcut detail pane can replace each saved binding --- crates/menu/src/shortcuts/pages.rs | 12 +- crates/menu/src/shortcuts/recorder.rs | 19 +- crates/menu/src/shortcuts/state.rs | 52 ++++- crates/menu/src/shortcuts/view/detail.rs | 108 ++++++++--- crates/menu/src/shortcuts/words.rs | 1 + crates/menu/tests/it/shortcuts/hold.rs | 21 +++ crates/menu/tests/it/shortcuts/recorder.rs | 210 ++++++++++++++++++++- 7 files changed, 378 insertions(+), 45 deletions(-) diff --git a/crates/menu/src/shortcuts/pages.rs b/crates/menu/src/shortcuts/pages.rs index bd85dac7b3..dee3c9589d 100644 --- a/crates/menu/src/shortcuts/pages.rs +++ b/crates/menu/src/shortcuts/pages.rs @@ -12,7 +12,7 @@ use serde::Serialize; use craft_keymap::{CommandDef, CommandKind, CommandRef, Keymap}; -use super::state::{Review, Target}; +use super::state::Review; use super::view::area_key; use super::{Area, DialogState, ShortcutsDialog}; @@ -241,18 +241,12 @@ impl DialogState { selected: self.selected.clone(), overrides: keymap.overrides().iter().filter_map(|(key, texts)| Some((command(key)?, texts.to_vec()))).collect(), conflict: self.conflict.as_ref().map(|c| (c.binding.to_string(), c.holders.iter().map(|h| h.command.clone()).collect())), - recording: self.recording.as_ref().and_then(|r| match &r.target { - Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Field { command } => Some(command.clone()), - Target::Search | Target::Code { .. } => None, - }), + recording: self.recording.as_ref().and_then(|r| r.target.command().cloned()), set: self.set.clone(), can_undo: self.can_undo(), // The switch sets the setting and the keymap's holds in one step, so the keymap's flag is the setting's. holds: self.holds_shown.then(|| keymap.holds()), - recording_hold: self.recording.as_ref().and_then(|r| match &r.target { - Target::HoldCell { command, .. } => Some(command.clone()), - _ => None, - }), + recording_hold: self.recording.as_ref().filter(|r| r.target.is_hold()).and_then(|r| r.target.command().cloned()), review: self.review.as_ref().map(ReviewSnapshot::of), pressed: self.field.as_ref().map(|f| f.binding.to_string()), holders: self.field.as_ref().map(|f| f.holders.iter().map(|h| h.command.clone()).collect()).unwrap_or_default(), diff --git a/crates/menu/src/shortcuts/recorder.rs b/crates/menu/src/shortcuts/recorder.rs index 283776d9a4..e4eb18ea25 100644 --- a/crates/menu/src/shortcuts/recorder.rs +++ b/crates/menu/src/shortcuts/recorder.rs @@ -3,7 +3,7 @@ //! //! One component serves both states. Idle, the field has the plain widget keys (Tab leaves, Enter and Space start //! recording). Recording, its key use is `KeyUse::RECORDER` (every key is a chord; bare Tab stays a chord because -//! the field keeps Tab). The recording field takes key focus on every run it lacks it. +//! the field keeps Tab). A recording field can take key focus when its caller allows it. use craft_behavior::{Metrics, Proposal, Sense}; use craft_keymap::{Chord, Key}; @@ -85,6 +85,7 @@ struct Recorder { shown: Label, chords: Vec, started: bool, + take_focus: bool, } impl Component for Recorder { @@ -114,6 +115,9 @@ impl Component for Recorder { fn update(&mut self, cx: &mut Cx<'_, Self>) { if self.recording { if !cx.response.has_focus() { + if !self.take_focus { + return; + } focus::request(&cx.response.ctx, FocusTarget::Id(cx.response.id)); } self.chords.extend(cx.intents().take_chords()); @@ -147,12 +151,13 @@ pub(crate) struct ChordRecorder { recording: bool, shown: Label, salt: Option<&'static str>, + take_focus: bool, } impl ChordRecorder { /// A recorder named `label` showing `shown`. pub(crate) fn new(label: impl Into

{character} \n

"); + assert_eq!(options.parse(document.as_bytes()).unwrap().text(), text); + } + let root = options.parse(b"

\t\r\n\n

").unwrap(); + assert_eq!(root.children.len(), 1); +} + +#[test] +fn drop_blank_text_preserves_spaces_beside_meaningful_cdata() { + let options = Options { cdata: true, drop_blank_text: true, ..Options::default() }.strict(); + for content in ["text", "\u{a0}"] { + let document = format!("

\n

"); + assert_eq!(options.parse(document.as_bytes()).unwrap().text(), format!(" {content}\n")); + } +} + /// Every way of reading, lenient and strict. fn all_options() -> Vec> { let full = From e11dc10b538aad54ab5aef65f45b40dfcca2de55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:58:29 -0800 Subject: [PATCH 227/235] Drop queued actions when Check Spelling restarts --- crates/text/src/ui/spelling.rs | 1 + crates/text/tests/it/spelling.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/text/src/ui/spelling.rs b/crates/text/src/ui/spelling.rs index b78480f06b..49ce0c4db9 100644 --- a/crates/text/src/ui/spelling.rs +++ b/crates/text/src/ui/spelling.rs @@ -225,6 +225,7 @@ impl CheckSpellingDialog { /// Replaces the list and shows its first item (Change To from its first suggestion): a host that walks its text /// itself hands the dialog the words from its current place. pub fn restart(&mut self, items: Vec) { + self.action = None; self.index = 0; self.set_items(items); } diff --git a/crates/text/tests/it/spelling.rs b/crates/text/tests/it/spelling.rs index c11aa771d2..0bee60e0e3 100644 --- a/crates/text/tests/it/spelling.rs +++ b/crates/text/tests/it/spelling.rs @@ -37,3 +37,22 @@ fn ignore_reports_its_item_and_restart_shows_the_first_item() { assert_eq!(word(&dialog), json!("teh"), "restart shows the first item"); assert_eq!(dialog.borrow().json_fields().expect("fields")["changeTo"], json!("the"), "with its first suggestion"); } + +#[trial] +fn restarting_drops_a_change_waiting_on_the_previous_word() { + let dialog = Rc::new(RefCell::new(CheckSpellingDialog::new(items()))); + let shown = dialog.clone(); + let mut fixture = Fixture::new(move |ui| { + shown.borrow_mut().show(ui); + }); + fixture.settle(); + let change = fixture.by_label("Change").expect("the Change button"); + fixture.click(&change).settle(); + let next = SpellingItem::new(2, 0..3, "adn", vec!["and".to_owned()]); + dialog.borrow_mut().restart(vec![next.clone()]); + assert!(dialog.borrow_mut().take_action().is_none(), "the previous word's change is discarded"); + fixture.settle(); + let change = fixture.by_label("Change").expect("the restarted Change button"); + fixture.click(&change).settle(); + assert_eq!(dialog.borrow_mut().take_action(), Some(SpellingAction::Change { item: next, to: "and".to_owned() })); +} From ad46e895fb18432d5081497d6600ceaa5e6cef26 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 03:11:45 +0000 Subject: [PATCH 228/235] ui-contract suite: sample repeats unless CRAFT_HOSTILE_DIVISOR=1, and sample the activation group's stories --- .github/workflows/full-validation.yml | 4 +++- .github/workflows/nightly.yml | 6 ++++-- crates/ui-contract/src/testing/suite.rs | 2 +- crates/ui-contract/src/testing/suite/nodes.rs | 6 +++--- scripts/ci-full-validation.sh | 3 ++- scripts/test-full-validation.py | 7 ++++--- 6 files changed, 17 insertions(+), 11 deletions(-) diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml index 85ad96f2fe..652e2b1f13 100644 --- a/.github/workflows/full-validation.yml +++ b/.github/workflows/full-validation.yml @@ -32,7 +32,9 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh command: | python scripts/test-full-validation.py diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5cc8032668..63c6362a04 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,7 +1,7 @@ name: Nightly full tests # The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep -# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The +# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The # rest of the workspace's tests run with them, on Linux, with the gate's setup. on: schedule: @@ -26,7 +26,9 @@ jobs: packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan - env: CRAFT_PRINT_REQUIRE_QUEUE=0 + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=1 setup-command: bash scripts/ci-test-inputs.sh cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus diff --git a/crates/ui-contract/src/testing/suite.rs b/crates/ui-contract/src/testing/suite.rs index 9e98515818..f8422c606f 100644 --- a/crates/ui-contract/src/testing/suite.rs +++ b/crates/ui-contract/src/testing/suite.rs @@ -175,7 +175,7 @@ fn panic_text(payload: Box) -> String { /// each exemption names a known case. `home`: the stories are the package's that registers the type ([`Subject::home`]). fn run_group(probe: Probe, group: &'static Group, check_exemptions: bool, home: bool, stories: Vec) -> Result<(), Failed> { // The cases that read the type as a whole look at one story of each kind at the gate; the others keep every story. - let stories = if matches!(group.name, "reads" | "variants" | "containers") { nodes::sampled_stories(stories) } else { stories }; + let stories = if matches!(group.name, "reads" | "activation" | "variants" | "containers") { nodes::sampled_stories(stories) } else { stories }; let subject = Subject::new(&probe, stories, home); let mut failures = Vec::new(); if check_exemptions && home { diff --git a/crates/ui-contract/src/testing/suite/nodes.rs b/crates/ui-contract/src/testing/suite/nodes.rs index 81321a4d18..23e35c1fab 100644 --- a/crates/ui-contract/src/testing/suite/nodes.rs +++ b/crates/ui-contract/src/testing/suite/nodes.rs @@ -81,12 +81,12 @@ pub(super) fn is_selected(fixture: &Fixture, node: NodeKey) -> bool { } /// Whether the cases that run once per member of a repeated set (each repeat of a part, each row that declares an -/// action) run on a fixed sample of the set: under the gate's sweep fraction, `craft_testkit::hostile::divisor` above -/// 1. The nightly run sets no fraction and checks every member. +/// action) run on a fixed sample of the set: when no sweep fraction is set (a local run) or it is above 1 (the gate). +/// Only an explicit `CRAFT_HOSTILE_DIVISOR=1`, which the nightly and full-validation runs set, checks every member. fn samples_repeats() -> bool { #[cfg(not(target_arch = "wasm32"))] { - craft_testkit::hostile::divisor() > 1 + std::env::var_os(craft_testkit::hostile::DIVISOR_VARIABLE).is_none() || craft_testkit::hostile::divisor() > 1 } #[cfg(target_arch = "wasm32")] { diff --git a/scripts/ci-full-validation.sh b/scripts/ci-full-validation.sh index 593a3ee091..6461091402 100644 --- a/scripts/ci-full-validation.sh +++ b/scripts/ci-full-validation.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Restore both runtime feature configurations, docs and ordinary example linking, without fuzz caps. set -euo pipefail -unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES +unset PROPTEST_CASES +export CRAFT_HOSTILE_DIVISOR=1 if [[ "${RUNNER_OS:-}" = Windows ]]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi diff --git a/scripts/test-full-validation.py b/scripts/test-full-validation.py index f3394c1cd1..bdf6274263 100644 --- a/scripts/test-full-validation.py +++ b/scripts/test-full-validation.py @@ -25,7 +25,8 @@ COMMANDS = [ # Repository-file bytes must never become bash -c source in a mock-only harness. SOURCE = r""" set -euo pipefail -unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES +unset PROPTEST_CASES +export CRAFT_HOSTILE_DIVISOR=1 if [[ "${RUNNER_OS:-}" = Windows ]]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi @@ -53,7 +54,7 @@ def run(os_name, fail=""): CRAFT_HOSTILE_DIVISOR="8", PROPTEST_CASES="64") mock = r""" cargo() { - test -z "${CRAFT_HOSTILE_DIVISOR+x}" && test -z "${PROPTEST_CASES+x}" || return 29 + test "${CRAFT_HOSTILE_DIVISOR-}" = 1 && test -z "${PROPTEST_CASES+x}" || return 29 printf '%s\n' "$*" if [ "$*" = "$FAIL" ]; then return 17; fi } @@ -112,7 +113,7 @@ class FullValidation(unittest.TestCase): self.assertIn("bash scripts/ci-full-validation.sh", text) self.assertIn("github.event.label.name != 'full-validation' && github.run_id", text) self.assertIn("github.event.action != 'labeled' || github.event.label.name == 'full-validation'", text) - self.assertNotIn("CRAFT_HOSTILE_DIVISOR=", text) + self.assertNotIn("CRAFT_HOSTILE_DIVISOR=8", text) self.assertNotIn("PROPTEST_CASES=", text) def test_pdf_contracts_are_separate_and_uncapped(self): From 90f6dd69f9c7a80f1d3cb1cf23fc6fae57dec212 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:16:58 -0800 Subject: [PATCH 229/235] Discard an uncommitted number draft when its edit target changes --- crates/ui-contract/src/contract/text.rs | 5 +++ .../src/primitives/text_adapter.rs | 1 + .../ui-contract/src/primitives/text_input.rs | 3 ++ crates/ui-widgets/src/text/number.rs | 9 +++++ crates/ui-widgets/tests/it/text/number.rs | 39 +++++++++++++++++++ 5 files changed, 57 insertions(+) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 5a855c7f06..9bbf1478ab 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -606,7 +606,12 @@ pub(crate) fn run( // ended its gesture without putting back the value from before it), and the part starts afresh from its value. if !crate::runtime::memory::shown_last_pass(&ctx, id) { state = TextState::default(); + } else if state.edit_target != part.options.edit_target { + // The old target's draft and gesture must never reach the new target's binding. + cx.cancel(CancelReason::HostChanged); + state = TextState::default(); } + state.edit_target = part.options.edit_target; (decl.values.resync)(&mut state, shown_copy(cx).as_ref()); let text = prepare(cx.core, ui, part, &mut state, AdapterSettings { keys, rtl, ink, underline }, step.commit_now); let PreparedText { widget, out, read_only, list_open, caret_visible, commit_now, was_focused, window_blur, menu_open, left_for_part } = text; diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 1de2a0cc72..80d002ac6b 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -56,6 +56,7 @@ pub(crate) struct Preedit { /// What the adapter keeps per text part between passes. #[derive(Clone, Default)] pub(crate) struct TextState { + pub edit_target: Option, pub draft: Option, /// The value when the run began (a `K::Value`). pub start: Option>, diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index cf33679f78..2573d0c64a 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -67,6 +67,8 @@ pub struct TextOptions { pub mask: bool, /// A parsable draft applies as typed whatever the codec says. pub live: bool, + /// The owner of the current draft, when the same field can edit different values. + pub edit_target: Option, /// Escape clears the text and commits the empty text while text shows, and goes on to the host once it is empty. pub clear_on_escape: bool, /// Escape keeps the text: an open typing run commits once, editing ends by leaving focus, and the same Escape @@ -161,6 +163,7 @@ impl Default for TextOptions { limit: None, mask: false, live: false, + edit_target: None, clear_on_escape: false, keep_on_escape: false, mono: false, diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index ee912d908e..351624b5c9 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -352,6 +352,15 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { self } + /// Identifies the target of this field's edit, for a control reused across drawings or selections. + /// Changing the key discards the previous draft even when the two bound values are equal. + /// The field keeps its identity and focus. + #[must_use] + pub fn edit_target(mut self, key: impl egui::AsIdSalt) -> Self { + self.options.edit_target = Some(egui::IdSalt::new(key)); + self + } + /// Zoom typing: a Tab rewrites the draft (with no draft it moves focus) and a press on the field's other parts /// keeps it unapplied. #[must_use] diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index 3420c531a2..800e197568 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -797,3 +797,42 @@ fn a_percent_field_shows_the_decimals_its_caller_commits() { let default = shown(None); assert!(default.iter().any(|text| text == "10.0"), "with no decimals set the field shows 10.0%: {default:?}"); } + +#[trial] +fn changing_a_number_fields_edit_target_clears_the_old_draft_with_equal_values() { + use craft_ui::testing::Fixture; + use std::rc::Rc; + + for expression in ["10+", "9+9"] { + let target = Rc::new(Cell::new(0)); + let values = Rc::new([Cell::new(Some(START)), Cell::new(Some(START))]); + let id = Rc::new(Cell::new(egui::Id::NULL)); + let (shown_target, shown_values, shown_id) = (target.clone(), values.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let current = shown_target.get(); + let model = &shown_values[current]; + let mut value = model.get(); + let out = NumberField::new("Size", Bind::bound(&mut value)).id_salt("size").edit_target(current).show(ui); + shown_id.set(out.response.id); + model.set(value); + }); + fixture.settle(); + let field = fixture.by_label("Size").expect("the number field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text(expression).settle(); + assert!(fixture.texts().iter().any(|text| text.text == expression)); + assert_eq!(values[0].get(), Some(START)); + + let stable = id.get(); + target.set(1); + fixture.settle(); + assert_eq!(id.get(), stable); + assert!(fixture.focused_stop().is_some_and(|(stop, _)| stop == stable)); + assert!(!fixture.texts().iter().any(|text| text.text == expression)); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(START))); + + fixture.key(Key::A, Modifiers::COMMAND).type_text("5+8").key(Key::Enter, Modifiers::NONE).settle(); + assert_eq!((values[0].get(), values[1].get()), (Some(START), Some(13.0))); + } +} From 2720ace3455d68aa98cab1e1c3990d53394b3111 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 03:18:58 +0000 Subject: [PATCH 230/235] ui-contract suite: cut the default run's fixtures per story and per case Under the sampling gate (CRAFT_HOSTILE_DIVISOR unset or above 1; an explicit 1 runs everything): - sampled_actions groups nodes by role and parent role, so the cells and toggles of every row of a table are one set cut to first, middle and last, not one set per row. - activation and variants drop a story that covers only Empty or One while another story remains: there is nothing to act on, and reads and containers keep every kind, so required-state coverage and items-empty still run. - every_intent_has_a_declared_action runs Enter, Space, Right and Left (Up and Down take the same intents through the same code) and reads the declared actions in one tree walk. - the items-* cases stop after the first story that ran the case (stories they skip, for lack of rows or rename support, do not count). Settling once in input_fixture needed no change: it already settles once. --- crates/ui-contract/src/testing/suite.rs | 6 +++- .../src/testing/suite/activation.rs | 17 ++++++++-- .../src/testing/suite/collection.rs | 32 +++++++++++++++++++ crates/ui-contract/src/testing/suite/nodes.rs | 20 ++++++++---- 4 files changed, 65 insertions(+), 10 deletions(-) diff --git a/crates/ui-contract/src/testing/suite.rs b/crates/ui-contract/src/testing/suite.rs index f8422c606f..73b473ecbf 100644 --- a/crates/ui-contract/src/testing/suite.rs +++ b/crates/ui-contract/src/testing/suite.rs @@ -175,7 +175,11 @@ fn panic_text(payload: Box) -> String { /// each exemption names a known case. `home`: the stories are the package's that registers the type ([`Subject::home`]). fn run_group(probe: Probe, group: &'static Group, check_exemptions: bool, home: bool, stories: Vec) -> Result<(), Failed> { // The cases that read the type as a whole look at one story of each kind at the gate; the others keep every story. - let stories = if matches!(group.name, "reads" | "activation" | "variants" | "containers") { nodes::sampled_stories(stories) } else { stories }; + let stories = match group.name { + "reads" | "containers" => nodes::sampled_stories(stories, false), + "activation" | "variants" => nodes::sampled_stories(stories, true), + _ => stories, + }; let subject = Subject::new(&probe, stories, home); let mut failures = Vec::new(); if check_exemptions && home { diff --git a/crates/ui-contract/src/testing/suite/activation.rs b/crates/ui-contract/src/testing/suite/activation.rs index dd74cfdea8..9e139e0570 100644 --- a/crates/ui-contract/src/testing/suite/activation.rs +++ b/crates/ui-contract/src/testing/suite/activation.rs @@ -220,15 +220,26 @@ fn every_intent_has_a_declared_action(subject: &Subject) -> Result<(), String> { _ => None, }; for story in subject.stories.iter().filter(|story| !story.covers.contains(&Required::Invalid)) { - for &(key, _, step) in keys.iter().filter(|(_, kept, _)| *kept) { + // Up and Down take the intents Right and Left do through the same code, so the sampled run leaves them out. + let sampled = nodes::samples_repeats(); + for &(key, _, step) in keys.iter().filter(|(key, kept, _)| *kept && !(sampled && matches!(key, Key::ArrowUp | Key::ArrowDown))) { let mut fixture = input_fixture(story); fixture.key(Key::Tab, Modifiers::NONE); fixture.settle(); let (before, was_open) = (fixture.data().snapshot(), any_expanded(fixture.tree())); - let declares_before = |declared| { + let declared_before: Vec = { let tree = fixture.tree(); - tree.keys().into_iter().any(|node| tree.declares_key(node, declared)) + let mut found = Vec::new(); + for node in tree.keys() { + for declared in [Declared::Expand, Declared::Collapse, Declared::Click, Declared::Increment, Declared::Decrement] { + if !found.contains(&declared) && tree.declares_key(node, declared) { + found.push(declared); + } + } + } + found }; + let declares_before = |declared| declared_before.contains(&declared); let (can_expand, can_collapse) = (declares_before(Declared::Expand), declares_before(Declared::Collapse)); let can_click = declares_before(Declared::Click); let steps_before = (declares_before(Declared::Increment), declares_before(Declared::Decrement)); diff --git a/crates/ui-contract/src/testing/suite/collection.rs b/crates/ui-contract/src/testing/suite/collection.rs index e2c43420d4..167aa0a8e2 100644 --- a/crates/ui-contract/src/testing/suite/collection.rs +++ b/crates/ui-contract/src/testing/suite/collection.rs @@ -145,6 +145,10 @@ pub(super) fn keys_move_the_lead(subject: &Subject) -> Result<(), String> { if lead(&fixture, &container).is_none_or(|found| found == 0) { return Err(format!("{name}: Page Down left the lead on the first row")); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -170,6 +174,10 @@ pub(super) fn click_selects_one_row(subject: &Subject) -> Result<(), String> { if !now.iter().any(|row| row.node == shown[1].node && super::nodes::is_selected(&fixture, row.node)) { return Err(format!("{}: the clicked row does not report itself selected", story.name)); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -199,6 +207,10 @@ pub(super) fn type_ahead_moves_the_lead(subject: &Subject) -> Result<(), String> if found != Some(target) { return Err(format!("{}: typing `{letter}` left the lead at {found:?} of {size}, expected row {target}", story.name)); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -247,6 +259,10 @@ pub(super) fn rename_commits_and_cancels_once(subject: &Subject) -> Result<(), S if lead(&fixture, &container).is_none() { return Err(format!("{name}: Escape left the focus off the rows")); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -278,6 +294,10 @@ pub(super) fn rename_ends_when_the_editor_loses_focus(subject: &Subject) -> Resu if fixture.tree().role_of(fixture.tree().focused_key()) == Some(Role::TEXT_INPUT) { return Err(format!("{name}: the rename ended and the editor still holds the focus")); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -317,6 +337,10 @@ pub(super) fn keyboard_reorder_ends_once(subject: &Subject) -> Result<(), String if ends != 1 || moved.contains(&EditKind::Cancel) { return Err(format!("{}: a stacking key gave the reorder events {moved:?}", story.name)); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -374,6 +398,10 @@ pub(super) fn long_collection_builds_rows_within_the_room_only(subject: &Subject if shown.len() >= size { return Err(format!("{}: all {size} rows are built though the room holds about {}", story.name, (room.y / row) as usize + 1)); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } @@ -414,6 +442,10 @@ pub(super) fn scroll_shows_rows_in_the_same_frame(subject: &Subject) -> Result<( if now.windows(2).any(|pair| pair[1].rect.min.y - pair[0].rect.max.y > row && !filled(pair[0].rect.max.y, pair[1].rect.min.y)) { return Err(format!("{}: the frame of the scroll shows rows with a gap between them", story.name)); } + // One story that ran the case stands for the type under the sampling gate. + if super::nodes::samples_repeats() { + break; + } } Ok(()) } diff --git a/crates/ui-contract/src/testing/suite/nodes.rs b/crates/ui-contract/src/testing/suite/nodes.rs index 23e35c1fab..5182305e35 100644 --- a/crates/ui-contract/src/testing/suite/nodes.rs +++ b/crates/ui-contract/src/testing/suite/nodes.rs @@ -3,7 +3,7 @@ use crate::runtime::access::Role; use crate::runtime::egui::access::{AccessTree, Declared, NodeKey}; use crate::testing::fixture::{Fixture, Target}; -use crate::testing::story::Story; +use crate::testing::story::{Required, Story}; use craft_behavior::PartRef; /// `node` and every node below it. @@ -83,7 +83,7 @@ pub(super) fn is_selected(fixture: &Fixture, node: NodeKey) -> bool { /// Whether the cases that run once per member of a repeated set (each repeat of a part, each row that declares an /// action) run on a fixed sample of the set: when no sweep fraction is set (a local run) or it is above 1 (the gate). /// Only an explicit `CRAFT_HOSTILE_DIVISOR=1`, which the nightly and full-validation runs set, checks every member. -fn samples_repeats() -> bool { +pub(super) fn samples_repeats() -> bool { #[cfg(not(target_arch = "wasm32"))] { std::env::var_os(craft_testkit::hostile::DIVISOR_VARIABLE).is_none() || craft_testkit::hostile::divisor() > 1 @@ -143,7 +143,8 @@ fn tree_order(tree: &AccessTree) -> Vec { } /// `pairs` (a node and an action it declares) in tree order; when [`samples_repeats`], set by set, each repeated set -/// cut to its first, middle and last node. Nodes that share a parent and a role and declare the same action are one set. +/// cut to its first, middle and last node. Nodes of one role and parent role that declare the same action are one set, +/// so the cells of every row of a table are one set, not one set per row. pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declared)>) -> Vec<(NodeKey, Declared)> { let rank: std::collections::HashMap = tree_order(tree).into_iter().enumerate().map(|(at, key)| (key, at)).collect(); pairs.sort_by_key(|(node, _)| rank.get(node).copied().unwrap_or(usize::MAX)); @@ -151,7 +152,8 @@ pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declar if !samples_repeats() { return ordered; } - let set_of = |(node, declared): &(NodeKey, Declared)| (tree.parent_of_key(*node), tree.role_of(*node), *declared); + let set_of = + |(node, declared): &(NodeKey, Declared)| (tree.parent_of_key(*node).and_then(|parent| tree.role_of(parent)), tree.role_of(*node), *declared); let mut sets: Vec> = Vec::new(); for pair in ordered { match sets.iter_mut().find(|set| set_of(&set[0]) == set_of(&pair)) { @@ -165,11 +167,17 @@ pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declar /// `stories` cut, when [`samples_repeats`], to the first story of each distinct kind: stories that cover the same /// required states, drive the same way, give the same disabled reason and set command states alike differ only in /// what they show, which the cases that read the type as a whole (`reads`, `variants`, `containers`) see through -/// the first of them. The nightly run keeps every story. -pub(super) fn sampled_stories(stories: Vec) -> Vec { +/// the first of them. With `by_content`, a story that covers only `Empty` or `One` is dropped while another story +/// remains: the cases that act on what a story shows (activation) have nothing to act on in a collection with no +/// rows or one row, and the cases that need those stories (the required states, `items-empty`) run without it. +/// The nightly run keeps every story. +pub(super) fn sampled_stories(stories: Vec, by_content: bool) -> Vec { if !samples_repeats() { return stories; } + let few_rows = + |story: &Story| by_content && !story.covers.is_empty() && story.covers.iter().all(|state| matches!(state, Required::Empty | Required::One)); + let stories = if stories.iter().any(|story| !few_rows(story)) { stories.into_iter().filter(|story| !few_rows(story)).collect() } else { stories }; let kind = |story: &Story| (story.covers, std::mem::discriminant(&story.drive), story.disabled_text, story.commands.is_some()); let mut kept: Vec = Vec::new(); for story in stories { From 4e93d8f6f485c3c5affaa3f99ff41233bd08954b Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 03:32:00 +0000 Subject: [PATCH 231/235] ui-contract suite: run the collection and action cases on fewer stories under the sampling gate Under the sampling gate (CRAFT_HOSTILE_DIVISOR unset or above 1; an explicit 1 runs everything): - sampled_actions groups nodes by role and parent role, and a set already read in an earlier story is not read again, so a table's rows and headers are read in its first story only. - activation and variants drop a story that covers only Empty or One while another story remains; reads and containers keep every kind, so required-state coverage and items-empty still run. - every_intent_has_a_declared_action runs Enter, Space, Right and Left (Up and Down take the same intents through the same code) and reads the declared actions in one tree walk. - the items-* cases stop after the first story that ran the case. A story that cannot run click-select, type-ahead, rename or reorder (read once per story from the key role and selection a click on a row gives) is skipped without building a fixture per case, and items-cells reads its cells and its headers on the first story that has them. Settling once in input_fixture needed no change: it already settles once. --- crates/ui-contract/src/testing/suite.rs | 11 ++- .../src/testing/suite/activation.rs | 4 +- .../src/testing/suite/collection.rs | 72 ++++++++++++++++--- crates/ui-contract/src/testing/suite/nodes.rs | 14 +++- 4 files changed, 87 insertions(+), 14 deletions(-) diff --git a/crates/ui-contract/src/testing/suite.rs b/crates/ui-contract/src/testing/suite.rs index 73b473ecbf..c9be105ceb 100644 --- a/crates/ui-contract/src/testing/suite.rs +++ b/crates/ui-contract/src/testing/suite.rs @@ -49,6 +49,8 @@ struct Subject<'a> { home: bool, /// Each story's [`Base`], built when a case first asks for it. bases: Vec>, + /// What each story's rows allow, read once for the collection cases that run on one capable story ([`collection::probe_rows`]). + row_probes: Vec>, /// The style sources the style cases measure, read once for all of them. style_sources: OnceCell, String>>, /// The context the style cases resolve looks in. @@ -66,7 +68,8 @@ struct Base { impl<'a> Subject<'a> { fn new(probe: &'a Probe, stories: Vec, home: bool) -> Self { let bases = stories.iter().map(|_| OnceCell::new()).collect(); - Subject { probe, stories, home, bases, style_sources: OnceCell::new(), style_ctx: OnceCell::new() } + let row_probes = stories.iter().map(|_| OnceCell::new()).collect(); + Subject { probe, stories, home, bases, row_probes, style_sources: OnceCell::new(), style_ctx: OnceCell::new() } } /// The shared [`Base`] of `story`, which is one of `self.stories`. @@ -78,6 +81,12 @@ impl<'a> Subject<'a> { } /// Whether the case `name` runs for this type: its shapes take the type and the type is not exempt from it. + /// What the rows of `story` allow ([`collection::probe_rows`]), read on first use. + fn row_probe(&self, story: &Story) -> &collection::RowsProbe { + let index = self.stories.iter().position(|known| std::ptr::eq(known, story)).unwrap_or_default(); + self.row_probes[index].get_or_init(|| collection::probe_rows(story)) + } + fn runs(&self, name: &str) -> bool { cases().any(|case| case.name == name && runs_for(case, self.probe)) } diff --git a/crates/ui-contract/src/testing/suite/activation.rs b/crates/ui-contract/src/testing/suite/activation.rs index 9e139e0570..7f18819c54 100644 --- a/crates/ui-contract/src/testing/suite/activation.rs +++ b/crates/ui-contract/src/testing/suite/activation.rs @@ -149,6 +149,8 @@ fn signature(tree: &AccessTree) -> HashMap { /// Every action a node declares changes something: a click, an edit, a node state or the focus. A repeated set of /// nodes runs on a fixed sample under the gate's fraction ([`nodes::sampled_actions`]). fn declared_actions_are_handled(subject: &Subject) -> Result<(), String> { + // The sets of nodes read so far, so that under the sampling gate a set of one role shown by every story is read once. + let mut seen = Vec::new(); for story in subject.stories.iter().filter(|story| !story.covers.contains(&Required::Invalid)) { let fixture = &subject.base(story).fixture; let actions = [ @@ -163,7 +165,7 @@ fn declared_actions_are_handled(subject: &Subject) -> Result<(), String> { .filter(|key| tree.data_of(*key).is_some_and(|node| !node.is_disabled())) .flat_map(|key| actions.iter().filter(move |(declared, _)| tree.declares_key(key, *declared)).map(move |(declared, _)| (key, *declared))) .collect(); - let nodes = nodes::sampled_actions(tree, declared) + let nodes = nodes::sampled_actions(tree, declared, &mut seen) .into_iter() .filter_map(|(key, declared)| actions.iter().find(|(known, _)| *known == declared).map(|(_, kind)| (key, *kind))); for (key, kind) in nodes { diff --git a/crates/ui-contract/src/testing/suite/collection.rs b/crates/ui-contract/src/testing/suite/collection.rs index 167aa0a8e2..dfb80fc6a1 100644 --- a/crates/ui-contract/src/testing/suite/collection.rs +++ b/crates/ui-contract/src/testing/suite/collection.rs @@ -35,6 +35,30 @@ fn with_rows(story: &Story, least: usize) -> Option<(Fixture, Target, Vec= least).then_some((fixture, container, shown)) } +/// What the first rows of a story allow, as a click on a row shows it: the key role the focused stop takes and whether +/// the click selects. +#[derive(Default)] +pub(super) struct RowsProbe { + role: Option, + selects: bool, +} + +/// The [`RowsProbe`] of `story`: one fixture, one click. +pub(super) fn probe_rows(story: &Story) -> RowsProbe { + let Some((mut fixture, _, shown)) = with_rows(story, 1) else { return RowsProbe::default() }; + fixture.take_outputs(); + row_click::click(&mut fixture, &shown[shown.len().min(2) - 1]); + let selects = events(&mut fixture).contains(&CollectionKind::Selection); + RowsProbe { role: fixture.focused_role(), selects } +} + +/// Whether a story can run a case that needs `wanted` of its rows. Under the sampling gate the cases that run on +/// one story skip, from one shared probe, the stories that cannot run them; a run that does not sample runs every +/// story and decides in the case. +fn can_run(subject: &Subject, story: &Story, wanted: impl Fn(&RowsProbe) -> bool) -> bool { + !super::nodes::samples_repeats() || wanted(subject.row_probe(story)) +} + /// The collection events of every pass since the last call. fn events(fixture: &mut Fixture) -> Vec { fixture.take_outputs().into_iter().flat_map(|output| output.collection).collect() @@ -159,6 +183,9 @@ pub(super) fn click_selects_one_row(subject: &Subject) -> Result<(), String> { return Ok(()); } for story in &subject.stories { + if !can_run(subject, story, |probe| probe.selects) { + continue; + } let Some((mut fixture, container, shown)) = with_rows(story, 2) else { continue }; fixture.take_outputs(); row_click::click(&mut fixture, &shown[1]); @@ -189,6 +216,9 @@ pub(super) fn type_ahead_moves_the_lead(subject: &Subject) -> Result<(), String> return Ok(()); } for story in &subject.stories { + if !can_run(subject, story, |probe| probe.role.is_some_and(|role| role.type_ahead)) { + continue; + } let Some((mut fixture, container, shown)) = with_rows(story, 3) else { continue }; let names: Vec> = shown.iter().map(|row| fixture.tree().name_of(row.node).and_then(|name| name.chars().next())).collect(); let Some(first) = names[0] else { continue }; @@ -223,6 +253,9 @@ pub(super) fn rename_commits_and_cancels_once(subject: &Subject) -> Result<(), S } let rename = |kinds: &[CollectionKind], edit: EditKind| kinds.iter().filter(|kind| **kind == CollectionKind::Rename(edit)).count(); for story in &subject.stories { + if !can_run(subject, story, |probe| probe.role.is_some_and(|role| role.rename)) { + continue; + } let Some((mut fixture, container, shown)) = with_rows(story, 1) else { continue }; row_click::click(&mut fixture, &shown[0]); fixture.take_outputs(); @@ -276,6 +309,9 @@ pub(super) fn rename_ends_when_the_editor_loses_focus(subject: &Subject) -> Resu } let rename = |kinds: &[CollectionKind], edit: EditKind| kinds.iter().filter(|kind| **kind == CollectionKind::Rename(edit)).count(); for story in &subject.stories { + if !can_run(subject, story, |probe| probe.role.is_some_and(|role| role.rename)) { + continue; + } let Some((mut fixture, _, shown)) = with_rows(story, 2) else { continue }; row_click::click(&mut fixture, &shown[0]); fixture.take_outputs(); @@ -318,6 +354,9 @@ pub(super) fn keyboard_reorder_ends_once(subject: &Subject) -> Result<(), String .collect() }; for story in &subject.stories { + if !can_run(subject, story, |probe| probe.role.is_some_and(|role| role.reorderable.is_some())) { + continue; + } let Some((mut fixture, _, shown)) = with_rows(story, 2) else { continue }; row_click::click(&mut fixture, &shown[0]); fixture.take_outputs(); @@ -460,14 +499,14 @@ fn nodes_of(fixture: &Fixture, container: &Target, role: Role) -> Vec { /// A click on a cell that changes the selection leaves that cell's sub-node reporting `SELECTED`, and a cell in /// another row reporting none. A collection whose click selects nothing is not read. -fn selected_cell_reports_selected(story: &Story) -> Result<(), String> { - let Some((mut fixture, container, _)) = with_rows(story, 2) else { return Ok(()) }; +fn selected_cell_reports_selected(story: &Story) -> Result { + let Some((mut fixture, container, _)) = with_rows(story, 2) else { return Ok(false) }; let cells = nodes_of(&fixture, &container, Role::CELL); - let Some(clicked) = cells.first().copied() else { return Ok(()) }; + let Some(clicked) = cells.first().copied() else { return Ok(false) }; fixture.take_outputs(); fixture.click(&clicked); if !events(&mut fixture).contains(&CollectionKind::Selection) { - return Ok(()); + return Ok(false); } let now = nodes_of(&fixture, &container, Role::CELL); if !now.iter().any(|cell| cell.node == clicked.node && super::nodes::is_selected(&fixture, cell.node)) { @@ -479,16 +518,16 @@ fn selected_cell_reports_selected(story: &Story) -> Result<(), String> { { return Err(format!("{}: a cell outside the selection reports `SELECTED`", story.name)); } - Ok(()) + Ok(true) } /// Header cells carry a name. From the keyboard, Enter on a header cell that declares `Click` and a sort direction (a sortable column) gives a column event, /// and the resize and move commands that are enabled for the focused column give one: a resize through the arrow /// keys, a move at once. A column that is not movable or resizable leaves its command disabled and is not read. -fn header_cells_report_column_events(story: &Story) -> Result<(), String> { - let Some((mut fixture, container, _)) = with_rows(story, 0) else { return Ok(()) }; +fn header_cells_report_column_events(story: &Story) -> Result { + let Some((mut fixture, container, _)) = with_rows(story, 0) else { return Ok(false) }; let headers = nodes_of(&fixture, &container, Role::COLUMN_HEADER); - let Some(first) = headers.first().copied() else { return Ok(()) }; + let Some(first) = headers.first().copied() else { return Ok(false) }; let name = story.name; if headers.iter().any(|header| fixture.tree().name_of(header.node).is_none_or(str::is_empty)) { return Err(format!("{name}: a column header has no name")); @@ -527,7 +566,7 @@ fn header_cells_report_column_events(story: &Story) -> Result<(), String> { } } } - Ok(()) + Ok(true) } /// The sub-nodes of cells and columns: a selected cell's sub-node reports `SELECTED`, and header cells are announced @@ -536,9 +575,20 @@ pub(super) fn cells_and_columns_are_reported(subject: &Subject) -> Result<(), St if !is_items(subject) { return Ok(()); } + // Under the sampling gate each check runs on the first story that gets past its gates (cells, a selecting click, + // column headers) and is not repeated on the others. + let sampled = super::nodes::samples_repeats(); + let (mut cells_read, mut headers_read) = (false, false); for story in &subject.stories { - selected_cell_reports_selected(story)?; - header_cells_report_column_events(story)?; + if !(sampled && cells_read) { + cells_read |= selected_cell_reports_selected(story)?; + } + if !(sampled && headers_read) { + headers_read |= header_cells_report_column_events(story)?; + } + if sampled && cells_read && headers_read { + break; + } } Ok(()) } diff --git a/crates/ui-contract/src/testing/suite/nodes.rs b/crates/ui-contract/src/testing/suite/nodes.rs index 5182305e35..ec3f11ffd3 100644 --- a/crates/ui-contract/src/testing/suite/nodes.rs +++ b/crates/ui-contract/src/testing/suite/nodes.rs @@ -142,10 +142,13 @@ fn tree_order(tree: &AccessTree) -> Vec { ordered } +/// What makes nodes one set for [`sampled_actions`]: the role of the parent, the role of the node and the action. +pub(super) type ActionSet = (Option, Option, Declared); + /// `pairs` (a node and an action it declares) in tree order; when [`samples_repeats`], set by set, each repeated set /// cut to its first, middle and last node. Nodes of one role and parent role that declare the same action are one set, /// so the cells of every row of a table are one set, not one set per row. -pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declared)>) -> Vec<(NodeKey, Declared)> { +pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declared)>, seen: &mut Vec) -> Vec<(NodeKey, Declared)> { let rank: std::collections::HashMap = tree_order(tree).into_iter().enumerate().map(|(at, key)| (key, at)).collect(); pairs.sort_by_key(|(node, _)| rank.get(node).copied().unwrap_or(usize::MAX)); let ordered = pairs; @@ -161,6 +164,15 @@ pub(super) fn sampled_actions(tree: &AccessTree, mut pairs: Vec<(NodeKey, Declar None => sets.push(vec![pair]), } } + // A set the component shows in more than one story (a table's rows and headers) is read in the first story only. + sets.retain(|set| { + let key = set_of(&set[0]); + let new = !seen.contains(&key); + if new { + seen.push(key); + } + new + }); sets.iter().flat_map(|set| sample(set)).collect() } From cf687cd202ff40e39687603bedc9f19afb651acd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 20:07:03 -0800 Subject: [PATCH 232/235] Advance closed ComboBox from each queued arrow step --- crates/ui-widgets/src/pickers/combo_box.rs | 6 +++--- crates/ui-widgets/tests/it/pickers/combo_list.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-widgets/src/pickers/combo_box.rs b/crates/ui-widgets/src/pickers/combo_box.rs index b514db91c7..10c0f5278c 100644 --- a/crates/ui-widgets/src/pickers/combo_box.rs +++ b/crates/ui-widgets/src/pickers/combo_box.rs @@ -252,20 +252,20 @@ impl Component for ComboBox<'_> { } // A list closed by any path (a pick, Escape, a click outside, the draft ending) ends its preview. self.end_preview(cx); - let text = cx.value().cloned().unwrap_or_default(); while let Some((step, mods)) = cx.intents().take_move() { let forward = match step { NavMove::Down if !mods.fine => true, NavMove::Up if !mods.fine => false, _ => continue, }; - if let Some(value) = self.neighbour(&text, forward).and_then(|at| self.options[at].value()) { + let text = cx.value().map_or("", String::as_str); + if let Some(value) = self.neighbour(text, forward).and_then(|at| self.options[at].value()) { cx.set(value.clone()); } } if let Some(wheel) = cx.take_wheel() && wheel.scroll.y != 0.0 - && let Some(value) = self.neighbour(&text, wheel.scroll.y < 0.0).and_then(|at| self.options[at].value()) + && let Some(value) = self.neighbour(cx.value().map_or("", String::as_str), wheel.scroll.y < 0.0).and_then(|at| self.options[at].value()) { cx.set(value.clone()); } diff --git a/crates/ui-widgets/tests/it/pickers/combo_list.rs b/crates/ui-widgets/tests/it/pickers/combo_list.rs index a2eedcaf9b..e7c5c17268 100644 --- a/crates/ui-widgets/tests/it/pickers/combo_list.rs +++ b/crates/ui-widgets/tests/it/pickers/combo_list.rs @@ -38,6 +38,18 @@ fn reports(fixture: &mut Fixture) -> u32 { *fixture.data().value("reports", 0_u32) } +#[trial] +fn closed_combo_steps_for_each_arrow_in_one_frame() { + use craft_ui::testing::{focus, input}; + + let mut fixture = Fixture::story(&Story::new("combo_moves", combo)); + fixture.settle().key(Key::Tab, Modifiers::NONE).settle(); + assert!(!list_open(&mut fixture), "the combo's list stays closed"); + let step = || [input::key_press(Key::ArrowUp, Modifiers::NONE), focus::key_release(Key::ArrowUp, Modifiers::NONE)]; + fixture.frame([step(), step()].into_iter().flatten().collect()).settle(); + assert_eq!(font(&mut fixture), "Garamond", "the two ArrowUp presses should advance through Georgia"); +} + #[trial] fn the_hovered_option_is_previewed_until_the_pointer_leaves_the_list() { let mut fixture = Fixture::story(&Story::new("combo_preview", previewing)); From 5f896c5bdf8a695b4210ef237f073e32370461cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:00:09 -0800 Subject: [PATCH 233/235] Document the PerInch unit variant --- docs/contract-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index ef6797c0d7..3b07730b90 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4078,7 +4078,7 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn mode(mut self, mode: Mode) -> Self`. Resolves in `mode`: a plot that is dark in every theme, a preview of the other mode. - `pub fn contrast(mut self, contrast: Contrast) -> Self`. Resolves under `contrast`. - `pub fn density(mut self, density: Size) -> Self`. Resolves at the density preset `density`. -- `craft_ui::runtime::env::UnitKind`: `pub enum UnitKind { Pixels, Percent, Degrees, Points, Times, Inches, Centimetres, Millimetres, Picas, PixelsPerInch, PixelsPerCentimetre, Minutes, Columns, LinesPerInch, LinesPerCentimetre, Feet, Yards, Metres, Q, Ha, Letters, Hyphens, Milliseconds }`. What a number counts. +- `craft_ui::runtime::env::UnitKind`: `pub enum UnitKind { Pixels, Percent, Degrees, Points, Times, Inches, Centimetres, Millimetres, Picas, PixelsPerInch, PixelsPerCentimetre, Minutes, Columns, LinesPerInch, LinesPerCentimetre, Feet, Yards, Metres, Q, Ha, Letters, Hyphens, PerInch, Milliseconds }`. What a number counts. - `pub const LENGTHS: [UnitKind; 5]`. The lengths a unit choice offers. [`per_inch`](Self::per_inch) answers for more kinds (feet, yards, metres, Q, - `pub const fn decimals(self) -> RangeInclusive`. The digits after the decimal mark a number of this kind shows by default, at most. - `pub const fn step(self) -> f64`. What one arrow press, wheel notch or scrub point changes a number of this kind by, where the control that shows From 0fd61ad96865267557e7a557e80e11846855b502 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:48:19 -0800 Subject: [PATCH 234/235] Let preset host tools lead the toolbar on opt-in --- crates/color-ui/src/ui/swatches/panel.rs | 10 +++++ .../src/patterns/presets/browser.rs | 24 +++++++++--- .../ui-patterns/tests/it/presets/browser.rs | 38 +++++++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/color-ui/src/ui/swatches/panel.rs b/crates/color-ui/src/ui/swatches/panel.rs index 18c05a3691..85f60fc84b 100644 --- a/crates/color-ui/src/ui/swatches/panel.rs +++ b/crates/color-ui/src/ui/swatches/panel.rs @@ -89,6 +89,7 @@ pub struct SwatchesPanel<'a> { foreground: Srgba, thumb: Option>, tools: Option>, + tools_at_start: bool, drop_zone: Option, footer: Option>>, reveal: Option, @@ -120,6 +121,7 @@ impl<'a> SwatchesPanel<'a> { foreground, thumb: None, tools: None, + tools_at_start: false, drop_zone: None, footer: None, reveal: None, @@ -154,6 +156,12 @@ impl<'a> SwatchesPanel<'a> { self } + /// Places the host's tools before the browser controls in the toolbar. Off by default. + pub fn tools_at_start(mut self, at_start: bool) -> Self { + self.tools_at_start = at_start; + self + } + /// Where a drop onto the panel lands. pub fn drop_zone(mut self, zone: DropZone) -> Self { self.drop_zone = Some(zone); @@ -237,6 +245,7 @@ impl<'a> SwatchesPanel<'a> { foreground, thumb, mut tools, + tools_at_start, drop_zone, footer, reveal, @@ -278,6 +287,7 @@ impl<'a> SwatchesPanel<'a> { let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source) .thumb_range(SWATCH_ZOOM) .toolbar(true) + .tools_at_start(tools_at_start) .search(search) .select(select) .reorder(PresetReorder::items_and_groups()) diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index 06ff89253e..cc74027b23 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -324,6 +324,10 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's /// The host's controls at the reading end of the toolbar. #[prop(func = "FnMut(&mut Ui)")] tools: Option>, + /// Places the host's tools at the reading start, with the search and view controls at the end. + /// Off by default, preserving the existing toolbar order. + #[prop] + tools_at_start: bool, /// What a secondary click or the context-menu key opens: the standard row menu, the host's `row_items` alone, or /// nothing. #[prop] @@ -398,6 +402,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser toolbar: false, search: true, tools: None, + tools_at_start: false, row_menu: PresetRowMenu::Standard, row_items: None, drags: false, @@ -725,6 +730,7 @@ impl PresetBrowser<'_, toolbar, search, mut tools, + tools_at_start, row_menu, row_items, drags, @@ -775,11 +781,8 @@ impl PresetBrowser<'_, Entry::new(PresetView::List, words.list_view.clone()).icon(IconId::new("list")), ]; let locked = view_lock.is_some(); - let mut bar = Bar::new(Label::Empty, BarKind::Tool); - if let Some(tools) = tools.as_mut() { - bar = bar.trailing(|ui, _| tools.show(ui)); - } - let _ = bar.show(ui, |ui, _| { + let bar = Bar::new(Label::Empty, BarKind::Tool); + let mut controls = |ui: &mut Ui| { if search { let field = TextField::search(words.search.clone(), Bind::bound(&mut local.filter)).placeholder(words.search.clone()); let field = field.drives(list_id); @@ -789,7 +792,16 @@ impl PresetBrowser<'_, if !locked { Segmented::new(words.view.clone(), Bind::bound(&mut local.view), &modes).show(ui); } - }); + }; + if let Some(tools) = tools.as_mut() { + if tools_at_start { + let _ = bar.trailing(|ui, _| controls(ui)).show(ui, |ui, _| tools.show(ui)); + } else { + let _ = bar.trailing(|ui, _| tools.show(ui)).show(ui, |ui, _| controls(ui)); + } + } else { + let _ = bar.show(ui, |ui, _| controls(ui)); + } } // A hidden search field filters nothing: a search typed before hiding it would otherwise keep presets // out of the list with no field to show why. diff --git a/crates/ui-patterns/tests/it/presets/browser.rs b/crates/ui-patterns/tests/it/presets/browser.rs index 889de8713c..4eb45471a9 100644 --- a/crates/ui-patterns/tests/it/presets/browser.rs +++ b/crates/ui-patterns/tests/it/presets/browser.rs @@ -476,3 +476,41 @@ fn host_row_menu_rows_are_menu_items_and_only_a_checked_row_a_check_box() { assert_eq!(names(Role::MENU_ITEM), ["Options…"], "a plain host row is a menu item"); assert_eq!(names(Role::MENU_ITEM_CHECK_BOX), ["Locked"], "a checked host row is a check box"); } + +/// Host tools can share the header's reading start without changing the default order or view actions. +#[trial] +fn host_toolbar_tools_can_lead_the_view_controls_without_changing_the_default() { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + + for at_start in [false, true] { + let state = Rc::new(RefCell::new(PresetState::::new())); + let shown = Rc::clone(&state); + let rows = PresetSource::new((), PresetFns::new(|_, _| vec![PresetRow::item(ALPHA, "Alpha", 0)])); + let mut fixture = Fixture::new(move |ui| { + ui.scope_builder(UiBuilder::new().max_rect(BROWSER), |ui| { + let _ = PresetBrowser::new("Swatches", Bind::bound(&mut *shown.borrow_mut()), &rows) + .toolbar(true) + .search(false) + .tools_at_start(at_start) + .tools(|ui: &mut egui::Ui| { + Button::new("Host Tool").show(ui); + }) + .show(ui); + }); + }); + fixture.room(vec2(480.0, 320.0)).settle(); + let host = fixture.by_label("Host Tool").expect("host control").center(); + let grid = fixture.by_label("Grid View").expect("grid action").center(); + let list = fixture.by_label("List View").expect("list action").center(); + assert!((host.y - grid.y).abs() < 1.0, "both groups share the toolbar row"); + assert_eq!(host.x < grid.x, at_start, "the default stays trailing; the opt-in leads"); + assert!(grid.x < list.x, "the view choices retain their order"); + let target = fixture.by_label("List View").expect("list action"); + fixture.click(&target).settle(); + assert_eq!(state.borrow().view, PresetView::List); + let target = fixture.by_label("Grid View").expect("grid action"); + fixture.click(&target).settle(); + assert_eq!(state.borrow().view, PresetView::Grid); + } +} From 82dba501d7073a92fce8cf324efb1ec47d0451cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:55:24 -0800 Subject: [PATCH 235/235] Report only committed ColorChoice rows --- crates/color-ui/src/ui/choice.rs | 4 +- crates/color-ui/tests/it/choice.rs | 101 +++++++++++++++++++++++++++++ crates/color-ui/tests/it/main.rs | 1 + 3 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 crates/color-ui/tests/it/choice.rs diff --git a/crates/color-ui/src/ui/choice.rs b/crates/color-ui/src/ui/choice.rs index 0cd393e88e..0af3dfc6ec 100644 --- a/crates/color-ui/src/ui/choice.rs +++ b/crates/color-ui/src/ui/choice.rs @@ -59,7 +59,7 @@ pub enum ChosenColor { pub struct ColorChoiceOutput { /// The choice's response. pub response: Response, - /// The row chosen this pass; the host stores it. + /// The row committed this pass; the host stores it. Navigating an open popup reports no choice. pub chosen: Option, /// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key /// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses @@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> { entries.push(Entry::separator()); entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned())); let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui); - let picked = shown.value().cloned(); + let picked = shown.events.committed().cloned(); let mut pick_color = None; let chosen = match picked { Some(Row::Named(id)) => Some(ChosenColor::Named(id)), diff --git a/crates/color-ui/tests/it/choice.rs b/crates/color-ui/tests/it/choice.rs new file mode 100644 index 0000000000..7da086a6d9 --- /dev/null +++ b/crates/color-ui/tests/it/choice.rs @@ -0,0 +1,101 @@ +//! A named/custom color choice reports only a committed row or custom picker request. + +use std::cell::RefCell; +use std::rc::Rc; + +use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; +use craft_theme::Srgba; +use craft_ui::runtime::requests::ColorRequest; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, vec2}; + +const RED: Srgba = Srgba::rgb(0.8, 0.1, 0.2); +const BLUE: Srgba = Srgba::rgb(0.1, 0.2, 0.8); +const CUSTOM: Srgba = Srgba::rgb(0.2, 0.6, 0.4); + +#[derive(Default)] +struct Reports { + chosen: Vec, + requests: Vec, +} + +struct Rig { + fixture: Fixture, + value: Rc>, + reports: Rc>, +} + +impl Rig { + fn new(start: ChosenColor, custom: Option) -> Self { + let value = Rc::new(RefCell::new(start)); + let reports = Rc::new(RefCell::new(Reports::default())); + let (held, reported) = (value.clone(), reports.clone()); + let mut fixture = Fixture::new(move |ui| { + let value = held.borrow().clone(); + let shown = ColorChoice::new("Color", &value) + .named([NamedColor::new("red", "Red", Some(RED)), NamedColor::new("blue", "Blue", Some(BLUE))]) + .custom(custom) + .show(ui); + if let Some(chosen) = shown.chosen { + *held.borrow_mut() = chosen.clone(); + reported.borrow_mut().chosen.push(chosen); + } + reported.borrow_mut().requests.extend(shown.pick_color); + }); + fixture.room(vec2(400.0, 240.0)).settle(); + Rig { fixture, value, reports } + } + + fn open(&mut self) { + let field = self.fixture.by_label("Color").expect("the color choice"); + self.fixture.click(&field); + } +} + +/// A provisional named row never replaces the host's named or custom choice; Enter reports it once. +#[trial] +fn canceled_color_navigation_keeps_the_hosts_original_choice() { + for original in [ChosenColor::Named("red".into()), ChosenColor::Custom] { + let key = if original == ChosenColor::Custom { Key::ArrowUp } else { Key::ArrowDown }; + let mut rig = Rig::new(original.clone(), Some(CUSTOM)); + rig.open(); + rig.fixture.key(key, Modifiers::NONE).idle(2); + assert_eq!(*rig.value.borrow(), original, "navigation alone does not replace the original color"); + assert!(rig.reports.borrow().chosen.is_empty()); + rig.fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert_eq!(*rig.value.borrow(), original); + assert!(rig.reports.borrow().chosen.is_empty()); + assert!(rig.reports.borrow().requests.is_empty()); + + rig.open(); + rig.fixture.key(key, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2); + assert_eq!(*rig.value.borrow(), ChosenColor::Named("blue".into())); + assert_eq!(rig.reports.borrow().chosen, [ChosenColor::Named("blue".into())]); + assert!(rig.reports.borrow().requests.is_empty()); + } +} + +/// Proposing Select Custom Color neither requests the picker nor changes the color; Enter requests it once. +#[trial] +fn custom_color_picker_waits_for_a_committed_row() { + for custom in [Some(CUSTOM), None] { + let original = ChosenColor::Named("blue".into()); + let mut rig = Rig::new(original.clone(), custom); + rig.open(); + rig.fixture.key(Key::End, Modifiers::NONE).idle(2); + assert!(rig.reports.borrow().requests.is_empty(), "a provisional custom row cannot open a picker"); + rig.fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert_eq!(*rig.value.borrow(), original); + assert!(rig.reports.borrow().requests.is_empty()); + assert!(rig.reports.borrow().chosen.is_empty()); + + rig.open(); + rig.fixture.key(Key::End, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2); + assert_eq!(*rig.value.borrow(), original, "the host changes its color only after the requested picker answers"); + let reports = rig.reports.borrow(); + assert!(reports.chosen.is_empty()); + assert_eq!(reports.requests.len(), 1); + assert_eq!(reports.requests[0].key, ColorChoice::CUSTOM_KEY); + assert_eq!(reports.requests[0].color, Some(custom.unwrap_or(BLUE))); + } +} diff --git a/crates/color-ui/tests/it/main.rs b/crates/color-ui/tests/it/main.rs index dfe187fd0e..b4a5c73f5b 100644 --- a/crates/color-ui/tests/it/main.rs +++ b/crates/color-ui/tests/it/main.rs @@ -1,6 +1,7 @@ //! The screen tests of craft-color-ui, folded into the lib's test target. pub(crate) mod area_gamut; +pub(crate) mod choice; pub(crate) mod color_parts; pub(crate) mod gradient_bar; pub(crate) mod paint_chip;