From 20368232acacc11bb5b83817ca9a62be80c6a6a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 08:56:01 -0800 Subject: [PATCH 001/154] 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/154] 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/154] 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 61aaf23e7287d9f3c5a78dd4a8d231cfdf42f541 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:15:12 -0800 Subject: [PATCH 004/154] 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 005/154] 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 006/154] 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 007/154] 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 008/154] 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 009/154] 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 010/154] 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 011/154] 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 012/154] 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 013/154] 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 014/154] 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 015/154] 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 016/154] 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 017/154] 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 018/154] 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 019/154] 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 020/154] 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 021/154] 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 81e67a6130619f7413883b22a98e9c83d60761ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:10:32 -0800 Subject: [PATCH 022/154] 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 023/154] 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 024/154] 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 42958efaa40d5d62d30b52a4490e34f1250ad879 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sat, 21 Nov 2026 21:54:24 +0530 Subject: [PATCH 025/154] Proofing: add Gujarati (gu_IN) spelling, suggestion dispatch and grammar checks --- crates/proof/src/gu/grammar.rs | 111 +++++++++++++++++++ crates/proof/src/gu/mod.rs | 182 +++++++++++++++++++++++++++++++ crates/proof/src/gu/suggest.rs | 61 +++++++++++ crates/proof/src/gu/test_dict.rs | 51 +++++++++ crates/proof/src/hyphen.rs | 4 +- crates/proof/src/lang.rs | 13 ++- crates/proof/src/lib.rs | 31 +++++- crates/proof/src/no_data.rs | 4 +- crates/proof/src/packs.rs | 1 + 9 files changed, 451 insertions(+), 7 deletions(-) create mode 100644 crates/proof/src/gu/grammar.rs create mode 100644 crates/proof/src/gu/mod.rs create mode 100644 crates/proof/src/gu/suggest.rs create mode 100644 crates/proof/src/gu/test_dict.rs diff --git a/crates/proof/src/gu/grammar.rs b/crates/proof/src/gu/grammar.rs new file mode 100644 index 0000000000..ac6e3b3bd6 --- /dev/null +++ b/crates/proof/src/gu/grammar.rs @@ -0,0 +1,111 @@ +//! Generic repeated-word and spacing checks with Gujarati messages. +//! No Gujarati-specific grammar or case rules are inferred. + +use crate::{Issue, IssueKind, ProofLang, words}; + +fn issue(start: usize, end: usize, message: String, suggestions: Vec) -> Issue { + Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: ProofLang::Gu } +} + +pub fn check(text: &str) -> Vec { + let mut issues = Vec::new(); + repeated_words(text, &words(text), &mut issues); + spaces(text, &mut issues); + issues.sort_by_key(|i| (i.start, i.end)); + issues +} + +/// Words Gujarati repeats on purpose (`હા હા`, `ના ના`, `ધીમે ધીમે`, `સાચે સાચે`). +const ALLOWED_REPEATS: &[&str] = &["હા", "ના", "ધીમે", "જલ્દી", "વારંવાર", "સાચે", "રોજે", "ખરેખર", "જરા", "થોડું", "સાથે", "પાસે"]; + +fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec) { + for pair in ws.windows(2) { + let [(a0, b0), (a1, b1)] = pair else { continue }; + let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; + if !gap.is_empty() + && gap.chars().all(char::is_whitespace) + && w0.chars().all(|c| c.is_alphabetic() || ('\u{0A80}'..='\u{0AFF}').contains(&c)) + && w0 == w1 + && !ALLOWED_REPEATS.contains(&w0) + { + v.push(issue(*a0, *b1, format!("પુનરાવર્તિત શબ્દ: “{w1}”"), vec![w0.to_string()])); + } + } +} + +fn spaces(text: &str, v: &mut Vec) { + for (i, c) in text.char_indices() { + if c != ' ' { + continue; + } + let rest = text.get(i + 1..).unwrap_or(""); + let mut it = rest.chars(); + let Some(p) = it.next() else { continue }; + let after = it.next(); + // A ratio/score keeps the spaces in digit-space-colon-space-digit. + let ratio = p == ':' + && text.get(..i).and_then(|before| before.chars().next_back()).is_some_and(|c| c.is_ascii_digit()) + && after == Some(' ') + && it.next().is_some_and(|c| c.is_ascii_digit()); + let flag = !ratio + && match p { + ',' => true, + ';' => !matches!(after, Some(')' | '(' | '-' | 'P' | 'D')), + '.' => !matches!(after, Some('.')) && !after.is_some_and(|a| a.is_ascii_digit()), + ':' | '!' | '?' => after.is_none_or(|a| a.is_whitespace() || matches!(a, '"' | '”' | '’' | '!' | '?')), + _ => false, + }; + if flag { + v.push(issue(i, i + 1 + p.len_utf8(), "વિરામચિહ્ન પહેલાં જગ્યા".into(), vec![p.to_string()])); + } + } + for run in crate::space_runs(text) { + v.push(issue(run.start, run.end, "બેવડી જગ્યા".into(), vec![" ".into()])); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn intentional_repeats_are_fine() { + for text in ["હા હા, હું આવીશ.", "ના ના, આ નથી.", "ધીમે ધીમે ચાલ.", "સાચે સાચે બોલ."] + { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + assert_eq!(check("પુસ્તક પુસ્તક છે.").len(), 1); + } + + #[test] + fn repeated_words_and_spaces_have_gujarati_messages() { + let text = "ઘર ઘર , શાળા."; + let issues = check(text); + assert_eq!(issues.len(), 3, "{issues:?}"); + assert_eq!(issues[0].message, "પુનરાવર્તિત શબ્દ: “ઘર”"); + assert_eq!(issues[0].suggestions, ["ઘર"]); + assert!(issues.iter().any(|i| i.message == "વિરામચિહ્ન પહેલાં જગ્યા" && &text[i.start..i.end] == " ,")); + assert!(issues.iter().any(|i| i.message == "બેવડી જગ્યા")); + assert!(issues.iter().all(|i| i.lang == ProofLang::Gu && i.kind == IssueKind::Grammar)); + } + + #[test] + fn ratios_and_scores_keep_their_spaces() { + for text in ["3 : 1", "1 : 2", "સ્કોર 12 : 10."] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + for text in ["શબ્દ : બીજો", "3 : શબ્દ", "3 :"] { + assert!(check(text).iter().any(|i| i.message == "વિરામચિહ્ન પહેલાં જગ્યા"), "{text}"); + } + } + + proptest::proptest! { + #[test] + fn never_panics_and_ranges_are_valid(s in "\\PC{0,80}") { + for issue in check(&s) { + proptest::prop_assert!(issue.start <= issue.end && issue.end <= s.len()); + proptest::prop_assert!(s.is_char_boundary(issue.start) && s.is_char_boundary(issue.end)); + } + } + } +} diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs new file mode 100644 index 0000000000..f17a47ec87 --- /dev/null +++ b/crates/proof/src/gu/mod.rs @@ -0,0 +1,182 @@ +//! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled). +//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati +//! messages; hyphenation keeps the existing fallback. + +pub mod grammar; +pub(crate) mod suggest; +#[cfg(test)] +pub(crate) mod test_dict; + +use std::sync::Arc; + +use crate::affix::AffixDict; +use crate::slot::DictSlot; + +pub use suggest::suggest; + +/// File names of a Gujarati Hunspell dictionary. +const NAMES: &[&str] = &["gu_IN", "gu-IN", "gu"]; + +/// The Gujarati dictionary, found on first use (see [`DictSlot`]). +pub(crate) static DICT: DictSlot = DictSlot::new(NAMES, "Gujarati"); + +/// The Gujarati dictionary: the installed Hunspell `gu_IN` (read on first use), one given with +/// [`install_dictionary`], or an empty one when none is available (Gujarati spelling is off +/// then; see [`has_dictionary`]). +pub fn dictionary() -> Arc { + DICT.get() +} + +/// Use this Gujarati dictionary from now on (Hunspell `.aff` and `.dic` text, decoded to +/// UTF-8), for example one the user picked. On error the current dictionary stays. +pub fn install_dictionary(aff: &str, dic: &str) -> Result<(), String> { + DICT.install(aff, dic) +} + +/// Is a Gujarati dictionary available (spelling is checked)? +pub fn has_dictionary() -> bool { + DICT.has_dictionary() +} + +/// Returns `true` when `c` is in the Gujarati Unicode block (U+0A80..=U+0AFF). +pub fn is_gujarati_char(c: char) -> bool { + ('\u{0A80}'..='\u{0AFF}').contains(&c) +} + +/// Is `word` spelled correctly in Gujarati? Numbers, single letters, short words with digits and words in other scripts are accepted, and so +/// is every word when no Gujarati dictionary is installed. +pub fn is_correct(word: &str) -> bool { + is_correct_with(&dictionary(), word) +} + +/// [`is_correct`] with the File › Options › Proofing choices: with Ignore words that contain numbers off, words with digits are checked. +pub fn is_correct_with_options(word: &str, opts: &crate::Options) -> bool { + check(&dictionary(), word, opts) +} + +/// [`is_correct`] against a given dictionary (an empty one accepts everything). +pub fn is_correct_with(d: &AffixDict, word: &str) -> bool { + check(d, word, &crate::Options::default()) +} + +/// [`is_correct_with_options`] against a given dictionary. +fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool { + if d.is_empty() { + return true; + } + let w = word.trim_matches(|c: char| !c.is_alphanumeric() && !is_gujarati_char(c) && !matches!(c, '\'' | '’' | '-')); + let w = w.trim_matches(['\'', '’', '-']); + let letter_count = w.chars().filter(|&c| is_gujarati_char(c) || c.is_alphabetic()).count(); + if letter_count <= 1 || (opts.ignore_numbers && w.chars().any(char::is_numeric)) { + return true; + } + // A word in another script (or with no Gujarati characters) is not marked by this dictionary. + if !w.chars().any(is_gujarati_char) { + return true; + } + if w.contains('-') { + // The whole word first, as Hunspell does: a hyphenated entry or user word. + return known(d, w) || w.split('-').all(|p| p.chars().count() <= 1 || !p.chars().any(is_gujarati_char) || known(d, p)); + } + known(d, w) +} + +/// Is one word (no hyphens) in the dictionary or the user dictionary? +fn known(d: &AffixDict, w: &str) -> bool { + d.check(w) || crate::in_user_dictionary(&w.to_lowercase()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dictionary_lookup_accepts_gujarati_file_names() { + let dir = std::env::temp_dir().join(format!("wordcraft-gu-aliases-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for name in ["gu_IN", "gu-IN", "gu"] { + std::fs::write(dir.join(format!("{name}.aff")), test_dict::AFF).unwrap(); + std::fs::write(dir.join(format!("{name}.dic")), test_dict::DIC).unwrap(); + let (aff, dic) = crate::hunspell::find_in(&dir, NAMES).unwrap(); + let d = crate::hunspell::load(&aff, &dic).unwrap(); + assert!(is_correct_with(&d, "ઘરો")); + std::fs::remove_file(aff).unwrap(); + std::fs::remove_file(dic).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } + + #[test] + fn gujarati_words_affixes_and_case_markers() { + test_dict::install(); + let d = dictionary(); + assert!(has_dictionary()); + assert_eq!(d.len(), 15); + for w in [ + "ઘર", + "ઘરો", + "ઘરોને", + "ઘરોમાં", + "પુસ્તક", + "પુસ્તકો", + "પુસ્તકોમાં", + "પાણી", + "શાળા", + "ભાષા", + "પરીક્ષણ", + "પ્રેમ", + "શહેર", + "ગામ", + "મિત્ર", + "અઘર", + "શાળા-શહેર", + ] { + assert!(is_correct(w), "{w}"); + } + for w in ["ઘરર", "પુસ્તકક", "પાણીઈ", "શાળળા", "zqપ્રતિબંધિત"] { + assert!(!is_correct(w), "{w}"); + } + } + + #[test] + fn forbidden_words_are_rejected() { + test_dict::install(); + assert!(!is_correct("zqપ્રતિબંધિત")); + } + + #[test] + fn missing_dictionary_and_ignored_inputs_are_quiet() { + let empty = AffixDict::default(); + assert!(is_correct_with(&empty, "શાળા")); + assert!(install_dictionary("FLAG bogus\n", "1\nઘર\n").is_err()); + let d = AffixDict::from_hunspell(test_dict::AFF, test_dict::DIC, &[]).unwrap(); + for w in ["", "2026", "અ", "English", "日本語"] { + assert!(is_correct_with(&d, w), "{w}"); + } + } + + #[test] + fn user_dictionary_applies() { + test_dict::install(); + assert!(!is_correct("નવોશબ્દગુજરાતી")); + crate::add_word("નવોશબ્દગુજરાતી"); + assert!(is_correct("નવોશબ્દગુજરાતી")); + } + + #[test] + fn gujarati_dispatch_messages_options_and_mixed_spans() { + crate::hold_dictionary_tests(); + test_dict::install(); + assert!(crate::has_dictionary(Some("gu-IN"))); + assert!(crate::is_correct_for("ઘરો", Some("guj"))); + let text = "ઘર પુસ્તકક"; + let issues = crate::check_text(text, &[(0..text.len(), crate::ProofLang::Gu)]); + assert_eq!(issues.len(), 1, "{issues:?}"); + assert_eq!(&text[issues[0].start..issues[0].end], "પુસ્તકક"); + assert_eq!(issues[0].message, "શક્ય જોડણી ભૂલ"); + assert_eq!(issues[0].lang, crate::ProofLang::Gu); + let text = "ઘર this is is wrong"; + let issues = crate::check_text(text, &[(0..3, crate::ProofLang::Gu), (4..text.len(), crate::ProofLang::En)]); + assert!(issues.iter().any(|i| i.lang == crate::ProofLang::En && i.message.starts_with("Repeated word"))); + } +} diff --git a/crates/proof/src/gu/suggest.rs b/crates/proof/src/gu/suggest.rs new file mode 100644 index 0000000000..9aaaaa6526 --- /dev/null +++ b/crates/proof/src/gu/suggest.rs @@ -0,0 +1,61 @@ +//! Gujarati suggestions: the shared ranking ([`crate::affix_suggest`]) with the installed +//! dictionary's own MAP/REP/TRY/KEY tables and nothing Gujarati hard-coded. + +use crate::affix::AffixDict; +use crate::affix_suggest::Tuning; + +/// Spelling suggestions for a Gujarati word, best first, at most `max`. +pub fn suggest(word: &str, max: usize) -> Vec { + suggest_in(&super::dictionary(), word, max) +} + +/// [`suggest`] against a given dictionary. +pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec { + crate::affix_suggest::suggest_in(d, word, max, &Tuning::DEFAULT) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn suggestions_are_fast_enough() { + crate::gu::test_dict::install(); + let _ = suggest("ઘર", 1); + let t = std::time::Instant::now(); + for word in ["zqખૂબલાંબોશબ્દગુજરાતી", "પુસતક", "પરીક્ષણણ"] { + let _ = suggest(word, 6); + } + let ms = t.elapsed().as_secs_f64() * 1000.0; + eprintln!("3 Gujarati suggestion calls: {ms:.0} ms"); + assert!(ms < 20_000.0, "{ms} ms"); + } + + #[test] + fn nosuggest_stems_and_forms_are_never_offered() { + crate::affix::tests::assert_nosuggest_is_honoured(suggest_in); + } + + #[test] + fn gujarati_suggestions_use_runtime_tables() { + crate::gu::test_dict::install(); + for (word, want) in [("શાલા", "શાળા"), ("પાની", "પાણી"), ("પ્રેમમ", "પ્રેમ"), ("પરીકશણ", "પરીક્ષણ")] + { + let s = suggest(word, 8); + assert!(s.contains(&want.into()), "{word}: {s:?}"); + } + } + + #[test] + fn suggestions_stay_bounded_and_skip_forbidden_words() { + crate::gu::test_dict::install(); + for w in ["", "બે શબ્દો", &"શ".repeat(41)] { + assert!(suggest(w, 4).is_empty()); + } + assert!(suggest("ઘર", 0).is_empty()); + assert!(suggest_in(&AffixDict::default(), "ઘર", 4).is_empty()); + assert!(suggest("ઘર", 4).len() <= 4); + assert!(!suggest("ઘર", 4).contains(&"ઘર".into())); + assert!(!suggest("zqપ્રતિબંધિત", 8).contains(&"zqપ્રતિબંધિત".into())); + } +} diff --git a/crates/proof/src/gu/test_dict.rs b/crates/proof/src/gu/test_dict.rs new file mode 100644 index 0000000000..5c5bec46e7 --- /dev/null +++ b/crates/proof/src/gu/test_dict.rs @@ -0,0 +1,51 @@ +//! Hand-written synthetic Gujarati test data. No words, rules or suggestion tables were copied +//! from a system dictionary. This is a small fixture, not a redistributable Gujarati dictionary. + +pub const AFF: &str = "SET UTF-8 +FLAG UTF-8 +FORBIDDENWORD F +TRY અઆઇઈઉઊઋએઐઓઔકખગઘઙચછજઝઞટઠડઢણતથદધનપફબભમયરલવશષસહળક્ષજ્ઞાિીુૂૃૄેૈોૌ્ંઃઁ +KEY ષસ|તર +MAP 4 +MAP ઇઈિી +MAP ઉઊુૂ +MAP સશષ +MAP ણન +REP 1 +REP કશ ક્ષ +SFX N Y 4 +SFX N 0 ો/C . +SFX N 0 ો . +SFX N 0 ઓ/C . +SFX N 0 ઓ . +SFX C Y 4 +SFX C 0 ને . +SFX C 0 માં . +SFX C 0 થી . +SFX C 0 નો . +PFX X Y 1 +PFX X 0 અ . +"; + +pub const DIC: &str = "15 +ઘર/NX +પુસ્તક/NX +પાણી +શાળા +ભાષા +પરીક્ષણ +પ્રેમ +શહેર +ગામ/NX +મિત્ર/NX +ઝાડ +ફળ +કમળ +સૂર્ય +zqપ્રતિબંધિત/F +"; + +pub fn install() { + crate::hold_dictionary_tests(); + super::install_dictionary(AFF, DIC).unwrap(); +} diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index cc9d4fbdfb..c046267123 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -1008,7 +1008,9 @@ mod tests { #[test] fn languages_without_patterns_keep_the_english_ones() { for w in ["hyphenation", "typography", "internationalization"] { - for lang in [ProofLang::Other, ProofLang::Cs, ProofLang::Id, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy] { + for lang in + [ProofLang::Other, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy] + { assert_eq!(hyphen_points_in(w, &Limits::default(), lang), hyphen_points(w, &Limits::default()), "{w}"); } } diff --git a/crates/proof/src/lang.rs b/crates/proof/src/lang.rs index e5fcf3bbb9..5e087da170 100644 --- a/crates/proof/src/lang.rs +++ b/crates/proof/src/lang.rs @@ -70,6 +70,10 @@ pub enum ProofLang { /// dictionary (else the neighbouring Rioplatense `es_AR`, a Latin American or a generic one), /// and the `vos` forms of verbs (`tenés`, `vení`, `decime`) accepted ([`crate::es::voseo`]). EsUy, + /// Gujarati (`gu`, `gu-IN`, `guj`): the installed Hunspell dictionary (`gu_IN`, when there is + /// one), dictionary-driven suggestions and generic checks with Gujarati messages. Hyphenation + /// keeps the fallback patterns. + Gu, /// German (`de`, `de-DE`, `de-AT`…; `de-CH` and `de-LI` are [`ProofLang::Pack`] `de-ch`, with /// their own dictionary and these patterns): hyphenation by the German patterns (reformed /// spelling), and spelling when a German Hunspell dictionary or `de` pack is found. No grammar @@ -90,7 +94,7 @@ pub enum ProofLang { impl ProofLang { /// Every language with a spelling dictionary, in display order. - pub const PROOFED: [ProofLang; 16] = [ + pub const PROOFED: [ProofLang; 17] = [ ProofLang::En, ProofLang::EnGb, ProofLang::EnAu, @@ -107,6 +111,7 @@ impl ProofLang { ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, + ProofLang::Gu, ]; /// The proofing language of a BCP 47 tag (`pl-PL`, `en_GB`, `PL`…). The primary subtag @@ -142,6 +147,8 @@ impl ProofLang { ProofLang::Cs } else if primary.eq_ignore_ascii_case("id") || primary.eq_ignore_ascii_case("ind") || primary.eq_ignore_ascii_case("in") { ProofLang::Id + } else if primary.eq_ignore_ascii_case("gu") || primary.eq_ignore_ascii_case("guj") { + ProofLang::Gu } else if primary.eq_ignore_ascii_case("es") || primary.eq_ignore_ascii_case("spa") { ProofLang::spanish(tag) } else if ["de", "deu", "ger"].iter().any(|c| primary.eq_ignore_ascii_case(c)) { @@ -225,6 +232,7 @@ impl ProofLang { ProofLang::Ru => "ru", ProofLang::Cs => "cs", ProofLang::Id => "id", + ProofLang::Gu => "gu", ProofLang::Es | ProofLang::EsMx | ProofLang::Es419 | ProofLang::EsUy => "es", ProofLang::De => "de", ProofLang::Other => "", @@ -479,10 +487,13 @@ mod tests { assert_tags(&["it", "it-IT", "IT_it", "it-CH", "it-CH.UTF-8", " it-IT ", "ita"], ProofLang::It); assert_tags(&["cs", "cs-CZ", "CS-cz", "cs_CZ", " ces ", "CES", "cze", "CZE"], ProofLang::Cs); assert_tags(&["id", "id-ID", "ID-id", "id_ID", "id_ID.UTF-8", " id-ID ", "ind", "in", "in_ID"], ProofLang::Id); + assert_tags(&["gu", "gu-IN", "GU-in", "gu_IN", " gu-IN ", "guj", "GUJ"], ProofLang::Gu); assert_eq!(ProofLang::Cs.code(), "cs"); assert!(ProofLang::Cs.is_proofed() && ProofLang::PROOFED.contains(&ProofLang::Cs)); assert_eq!(ProofLang::Id.code(), "id"); assert!(ProofLang::Id.is_proofed() && ProofLang::PROOFED.contains(&ProofLang::Id)); + assert_eq!(ProofLang::Gu.code(), "gu"); + assert!(ProofLang::Gu.is_proofed() && ProofLang::PROOFED.contains(&ProofLang::Gu)); } #[test] diff --git a/crates/proof/src/lib.rs b/crates/proof/src/lib.rs index f0f33d0071..b7342feaa5 100644 --- a/crates/proof/src/lib.rs +++ b/crates/proof/src/lib.rs @@ -35,6 +35,9 @@ //! - **Indonesian** ([`ProofLang::Id`], module [`id`]): the installed Hunspell `id_ID` //! dictionary (not bundled), dictionary-driven suggestions and generic checks with Indonesian //! messages. Hyphenation uses the existing English fallback. +//! - **Gujarati** ([`ProofLang::Gu`], module [`gu`]): the installed Hunspell `gu_IN` +//! dictionary (not bundled), dictionary-driven suggestions and generic checks with Gujarati +//! messages. Hyphenation uses the existing English fallback. //! - **Spanish** ([`ProofLang::Es`], [`ProofLang::EsMx`], [`ProofLang::Es419`], [`ProofLang::EsUy`], //! module [`es`]): each variety's installed Hunspell dictionary (`es_ES`, `es_MX`, `es_419`, //! `es_UY`, with fallbacks; not bundled), dictionary-driven suggestions, Uruguayan `vos` forms, @@ -77,6 +80,7 @@ pub mod en_variants; mod english; pub mod es; pub mod fr; +pub mod gu; pub mod hr; pub mod hunspell; pub mod hyphen; @@ -223,7 +227,7 @@ struct Language { /// Every language proofed against a Hunspell dictionary, in the order File › Options › Proofing /// lists them. English has a built-in word list and is handled apart. -static LANGUAGES: [Language; 12] = [ +static LANGUAGES: [Language; 13] = [ Language { lang: ProofLang::Pl, slot: &pl::DICT, @@ -290,6 +294,14 @@ static LANGUAGES: [Language; 12] = [ suggest: |w, n, _| id::suggest(w, n), grammar: |t, _, _| id::grammar::check(t), }, + Language { + lang: ProofLang::Gu, + slot: &gu::DICT, + message: "શક્ય જોડણી ભૂલ", + is_correct: |w, _, o| gu::is_correct_with_options(w, o), + suggest: |w, n, _| gu::suggest(w, n), + grammar: |t, _, _| gu::grammar::check(t), + }, Language { lang: ProofLang::Es, slot: &es::SPAIN_DICT, @@ -1210,6 +1222,7 @@ mod tests { (ProofLang::Ru, "ru_RU"), (ProofLang::Cs, "cs_CZ"), (ProofLang::Id, "id_ID"), + (ProofLang::Gu, "gu_IN"), // #3360: each Spanish variety names its own. (ProofLang::Es, "es_ES"), (ProofLang::EsMx, "es_MX"), @@ -1267,6 +1280,7 @@ mod tests { ("ru_RU", ru::test_dict::AFF, ru::test_dict::DIC), ("cs_CZ", cs::test_dict::AFF, cs::test_dict::DIC), ("id_ID", id::test_dict::AFF, id::test_dict::DIC), + ("gu_IN", gu::test_dict::AFF, gu::test_dict::DIC), ("es_ES", es::test_dict::AFF, es::test_dict::DIC), ("es_MX", es::test_dict::AFF, es::test_dict::DIC_AMERICAS), ("es_419", es::test_dict::AFF, es::test_dict::DIC_AMERICAS), @@ -1507,7 +1521,7 @@ mod tests { // the languages' own tests install theirs concurrently, so an exact path would race them. // The folder is searched first whatever is in use. let found = installed_dictionaries(); - let names = ["pl_PL", "pt_BR", "it_IT", "hr_HR", "tr_TR", "ru_RU", "cs_CZ", "id_ID", "es_ES", "es_MX", "es_419", "es_UY"]; + let names = ["pl_PL", "pt_BR", "it_IT", "hr_HR", "tr_TR", "ru_RU", "cs_CZ", "id_ID", "gu_IN", "es_ES", "es_MX", "es_419", "es_UY"]; assert_eq!( found.iter().map(|(lang, _)| *lang).collect::>(), [ @@ -1519,6 +1533,7 @@ mod tests { ProofLang::Ru, ProofLang::Cs, ProofLang::Id, + ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, @@ -2631,6 +2646,7 @@ mod tests { ProofLang::Cs, ProofLang::Hr, ProofLang::Id, + ProofLang::Gu, ProofLang::Pl, ProofLang::Ru, ProofLang::Tr, @@ -3231,7 +3247,7 @@ mod tests { let _ = has_dictionary(Some(&s)); let _ = is_correct_for(&s, Some(&s)); let _ = hyphen::hyphen_points(&s, &hyphen::Limits::default()); - for lang in [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Hr, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::De, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other] { + for lang in [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Hr, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::De, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other] { let _ = check_spelling_in(&s, lang); let _ = check_grammar_in(&s, lang); let _ = is_correct_in(&s, lang); @@ -3274,6 +3290,13 @@ mod tests { let _ = is_correct_in(&s, ProofLang::Id); } + #[test] + fn gujarati_suggestions_never_panic(s in "[\\u{0A80}-\\u{0AFF}'’ -]{0,14}") { + gu::test_dict::install(); + let _ = suggest_in(&s, 4, ProofLang::Gu); + let _ = is_correct_in(&s, ProofLang::Gu); + } + #[test] fn spanish_suggestions_never_panic(s in "[a-zA-ZáéíóúüñÁÉÍÓÚÜÑ¿¡'’ -]{0,14}") { es::test_dict::install(); @@ -3285,7 +3308,7 @@ mod tests { #[test] fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..15), 0..6)) { - let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; + let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect(); for i in check_text(&s, &spans) { proptest::prop_assert!(i.start <= i.end && i.end <= s.len()); diff --git a/crates/proof/src/no_data.rs b/crates/proof/src/no_data.rs index cdd9025d41..c8912b3d6e 100644 --- a/crates/proof/src/no_data.rs +++ b/crates/proof/src/no_data.rs @@ -7,7 +7,7 @@ use crate::hyphen::{self, Limits, Source}; use crate::{EnglishSource, Options, ProofLang, dict, en_variants, patterns}; -const LANGS: [ProofLang; 19] = [ +const LANGS: [ProofLang; 20] = [ ProofLang::En, ProofLang::EnGb, ProofLang::EnAu, @@ -21,6 +21,7 @@ const LANGS: [ProofLang; 19] = [ ProofLang::Ru, ProofLang::Cs, ProofLang::Id, + ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, @@ -117,6 +118,7 @@ fn hyphenation_is_off_where_it_needs_data() { for (w, l) in [ ("hyphenation", ProofLang::En), ("hyphenation", ProofLang::Cs), + ("hyphenation", ProofLang::Gu), ("przedsiębiorstwo", ProofLang::Pl), ("computador", ProofLang::Pt), ("calcolatore", ProofLang::It), diff --git a/crates/proof/src/packs.rs b/crates/proof/src/packs.rs index eebd406ca6..e0bd38bfc8 100644 --- a/crates/proof/src/packs.rs +++ b/crates/proof/src/packs.rs @@ -545,6 +545,7 @@ fn hyphenation_locales(lang: ProofLang) -> Vec { ProofLang::Ru => &["ru"], ProofLang::Cs => &["cs"], ProofLang::Id => &["id"], + ProofLang::Gu => &["gu-in", "gu"], ProofLang::Es => &["es-es", "es"], ProofLang::EsMx => &["es-mx", "es-419", "es"], ProofLang::Es419 => &["es-419", "es"], From c29d4b7485206b5f0b4efc456a6e5efaf278e264 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sat, 21 Nov 2026 22:09:34 +0530 Subject: [PATCH 026/154] Proofing: handle Gujarati digits in grammar/spelling and check pack patterns fit --- crates/proof/src/gu/grammar.rs | 18 ++++++++++++------ crates/proof/src/gu/mod.rs | 7 +++++-- crates/proof/src/hyphen.rs | 16 +++++++++++++--- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/proof/src/gu/grammar.rs b/crates/proof/src/gu/grammar.rs index ac6e3b3bd6..e071161a0f 100644 --- a/crates/proof/src/gu/grammar.rs +++ b/crates/proof/src/gu/grammar.rs @@ -18,13 +18,17 @@ pub fn check(text: &str) -> Vec { /// Words Gujarati repeats on purpose (`હા હા`, `ના ના`, `ધીમે ધીમે`, `સાચે સાચે`). const ALLOWED_REPEATS: &[&str] = &["હા", "ના", "ધીમે", "જલ્દી", "વારંવાર", "સાચે", "રોજે", "ખરેખર", "જરા", "થોડું", "સાથે", "પાસે"]; +fn is_digit(c: char) -> bool { + c.is_ascii_digit() || ('\u{0AE6}'..='\u{0AEF}').contains(&c) +} + fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec) { for pair in ws.windows(2) { let [(a0, b0), (a1, b1)] = pair else { continue }; let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; if !gap.is_empty() && gap.chars().all(char::is_whitespace) - && w0.chars().all(|c| c.is_alphabetic() || ('\u{0A80}'..='\u{0AFF}').contains(&c)) + && w0.chars().all(|c| c.is_alphabetic() || (super::is_gujarati_char(c) && !c.is_numeric())) && w0 == w1 && !ALLOWED_REPEATS.contains(&w0) { @@ -42,11 +46,11 @@ fn spaces(text: &str, v: &mut Vec) { let mut it = rest.chars(); let Some(p) = it.next() else { continue }; let after = it.next(); - // A ratio/score keeps the spaces in digit-space-colon-space-digit. + // A ratio/score keeps the spaces in digit-space-colon-space-digit (ASCII or Gujarati digits). let ratio = p == ':' - && text.get(..i).and_then(|before| before.chars().next_back()).is_some_and(|c| c.is_ascii_digit()) + && text.get(..i).and_then(|before| before.chars().next_back()).is_some_and(is_digit) && after == Some(' ') - && it.next().is_some_and(|c| c.is_ascii_digit()); + && it.next().is_some_and(is_digit); let flag = !ratio && match p { ',' => true, @@ -75,6 +79,8 @@ mod tests { assert!(check(text).is_empty(), "{text}: {:?}", check(text)); } assert_eq!(check("પુસ્તક પુસ્તક છે.").len(), 1); + assert!(check("1 1").is_empty()); + assert!(check("૧ ૧").is_empty()); } #[test] @@ -91,10 +97,10 @@ mod tests { #[test] fn ratios_and_scores_keep_their_spaces() { - for text in ["3 : 1", "1 : 2", "સ્કોર 12 : 10."] { + for text in ["3 : 1", "1 : 2", "સ્કોર 12 : 10.", "૩ : ૧", "૧ : ૨", "સ્કોર ૧૨ : ૧૦."] { assert!(check(text).is_empty(), "{text}: {:?}", check(text)); } - for text in ["શબ્દ : બીજો", "3 : શબ્દ", "3 :"] { + for text in ["શબ્દ : બીજો", "3 : શબ્દ", "3 :", "૩ : શબ્દ", "૩ :"] { assert!(check(text).iter().any(|i| i.message == "વિરામચિહ્ન પહેલાં જગ્યા"), "{text}"); } } diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index f17a47ec87..e72089a4ca 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -66,7 +66,7 @@ fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool { } let w = word.trim_matches(|c: char| !c.is_alphanumeric() && !is_gujarati_char(c) && !matches!(c, '\'' | '’' | '-')); let w = w.trim_matches(['\'', '’', '-']); - let letter_count = w.chars().filter(|&c| is_gujarati_char(c) || c.is_alphabetic()).count(); + let letter_count = w.chars().filter(|&c| (is_gujarati_char(c) && !c.is_numeric()) || c.is_alphabetic()).count(); if letter_count <= 1 || (opts.ignore_numbers && w.chars().any(char::is_numeric)) { return true; } @@ -150,9 +150,12 @@ mod tests { assert!(is_correct_with(&empty, "શાળા")); assert!(install_dictionary("FLAG bogus\n", "1\nઘર\n").is_err()); let d = AffixDict::from_hunspell(test_dict::AFF, test_dict::DIC, &[]).unwrap(); - for w in ["", "2026", "અ", "English", "日本語"] { + for w in ["", "2026", "૧૨", "૨૦૨૬", "અ", "English", "日本語"] { assert!(is_correct_with(&d, w), "{w}"); } + let no_ignore = crate::Options { ignore_numbers: false, ..Default::default() }; + assert!(check(&d, "૧૨", &no_ignore)); + assert!(check(&d, "2026", &no_ignore)); } #[test] diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index c046267123..961546502b 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -216,9 +216,9 @@ fn composed_chars(core: &[char]) -> (Vec, Vec>) { (nfc, starts) } -/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian and Turkish: a word in -/// their script (the guard their rules use) whose letters the patterns know, so a word with a -/// letter the pack never mentions (`ё`) goes on to the built-in rules. Polish, Portuguese, Italian +/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish and Gujarati: a +/// word in their script (the guard their rules use) whose letters the patterns know, so a word with a +/// letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian /// and German: every word, as their embedded patterns do. Any other language: a word whose letters /// the patterns know. fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { @@ -227,6 +227,7 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core), ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core), ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true, + ProofLang::Gu => core.iter().all(|&c| crate::gu::is_gujarati_char(c)) && pack_knows(pats, core), _ => pats.values(core).is_some(), } } @@ -1053,4 +1054,13 @@ mod tests { assert_eq!(hyphen_points_in(w, &Limits::default(), ProofLang::Bg), hyphen_points(w, &Limits::default()), "{w}"); } } + + #[test] + fn gujarati_pack_patterns_fit_checks_script_and_exceptions() { + let pats = Patterns::parse("1ક 1ત પુ-સ્ત-ક"); + let gu_word: Vec = "પુસ્તક".chars().collect(); + assert!(pack_patterns_fit(ProofLang::Gu, &pats, &gu_word)); + let en_word: Vec = "hyphenation".chars().collect(); + assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word)); + } } From 00acaa7081d759eadf830bd40b5280a81695d649 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:28:12 -0800 Subject: [PATCH 027/154] 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 002c8f0c37b26277781d49475af9a5bb16630bf6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:08:11 -0800 Subject: [PATCH 028/154] Units: number rows can show unit text, and UnitKind gains Milliseconds A host can now show a unit after a number that no UnitKind names, such as kbps, s, MB, MiB or GiB, and count durations in milliseconds. - UnitKind::Milliseconds shows "{n} ms", reads "250 ms" and "250ms", and shows whole numbers by default. - Param::unit_label(text) shows text after the number of a number, int, optional-number, range or popup range row, in place of the symbol of the row's unit. The row's unit still reads typed text. - RowKind::unit_label(text) does the same for Preferences Int and Float rows. Int and Float rows that count a UnitKind now draw its symbol after the field, as RowKind documents. Stories show both forms, and two trials check the drawn text and that typed text is still read by the counted unit. --- crates/ui-contract/src/runtime/env/units.rs | 11 +++- .../src/patterns/form_dialogs/param.rs | 16 +++++ .../src/patterns/form_dialogs/rows.rs | 25 ++++++-- .../src/patterns/form_dialogs/rows/stories.rs | 13 ++++ .../patterns/preferences/document/texts.rs | 4 +- .../src/patterns/preferences/model.rs | 19 +++++- .../src/patterns/preferences/rows.rs | 38 ++++++++---- .../patterns/preferences/window/stories.rs | 31 +++++++++- .../tests/it/form_dialogs/params.rs | 33 ++++++++++ .../ui-patterns/tests/it/preferences/page.rs | 60 ++++++++++++++++++- docs/contract-api.md | 2 +- migration/api-map/preferences.toml | 4 +- 12 files changed, 226 insertions(+), 30 deletions(-) diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 9144236600..987d319336 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -29,6 +29,7 @@ craft_ui::words! { lines_per_centimetre: unit "units.linesPerCentimetre" = "{n} lpcm"; minutes: unit "units.minutes" = "{n} min"; columns: unit "units.columns" = "{n} col"; + milliseconds: unit "units.milliseconds" = "{n} ms"; pixels_name: "units.pixelsName" = "Pixels"; percent_name: "units.percentName" = "Percent"; degrees_name: "units.degreesName" = "Degrees"; @@ -44,6 +45,7 @@ craft_ui::words! { columns_name: "units.columnsName" = "Columns"; lines_per_inch_name: "units.linesPerInchName" = "Lines/Inch"; lines_per_centimetre_name: "units.linesPerCentimetreName" = "Lines/Centimetre"; + milliseconds_name: "units.millisecondsName" = "Milliseconds"; } } @@ -114,6 +116,8 @@ pub enum UnitKind { LinesPerInch, /// `{n} lpcm`: a halftone screen's frequency. LinesPerCentimetre, + /// `{n} ms`: a duration or delay in milliseconds. + Milliseconds, } impl UnitKind { @@ -126,7 +130,7 @@ impl UnitKind { Self::ALL.get(tag as usize).copied() } - const ALL: [UnitKind; 15] = [ + const ALL: [UnitKind; 16] = [ UnitKind::Pixels, UnitKind::Percent, UnitKind::Degrees, @@ -142,12 +146,13 @@ impl UnitKind { UnitKind::Columns, UnitKind::LinesPerInch, UnitKind::LinesPerCentimetre, + UnitKind::Milliseconds, ]; /// The digits after the decimal mark a number of this kind shows by default, at most. pub const fn decimals(self) -> RangeInclusive { match self { - UnitKind::Pixels | UnitKind::Minutes => 0..=0, + UnitKind::Pixels | UnitKind::Minutes | UnitKind::Milliseconds => 0..=0, UnitKind::Percent | UnitKind::Degrees | UnitKind::Points => 0..=1, UnitKind::Times | UnitKind::Centimetres @@ -364,6 +369,7 @@ impl Units { UnitKind::Columns => words.columns.as_str(), UnitKind::LinesPerInch => words.lines_per_inch.as_str(), UnitKind::LinesPerCentimetre => words.lines_per_centimetre.as_str(), + UnitKind::Milliseconds => words.milliseconds.as_str(), } } @@ -386,6 +392,7 @@ impl Units { UnitKind::Columns => &words.columns_name, UnitKind::LinesPerInch => &words.lines_per_inch_name, UnitKind::LinesPerCentimetre => &words.lines_per_centimetre_name, + UnitKind::Milliseconds => &words.milliseconds_name, }; name.clone() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index f3918c6a26..6d9b4862da 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -519,6 +519,8 @@ fn is_path_list(value: &FieldValue) -> bool { struct RowTexts { hint: Option".to_vec())]); + let z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"".to_vec()), ("docProps/core.xml", b"".to_vec())]); let p = Package::open(&z, &LIMITS).unwrap(); assert!(p.get("ppt/slides/slide1.xml").is_some()); assert_eq!(p.canonical("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml")); diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index becf9c966b..256bb03879 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -171,10 +171,10 @@ impl<'a> Archive<'a> { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. Names that are not text or - /// that contain path-traversal components are left out. + /// The entry names in the archive's order, folders included. A name that is not text is + /// left out. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) + self.zip.file_names().filter_map(Result::ok) } /// Is there an entry `name` (exactly as stored)? Paths containing traversal components diff --git a/crates/zip/src/entry.rs b/crates/zip/src/entry.rs index 33be92d80e..f03896a508 100644 --- a/crates/zip/src/entry.rs +++ b/crates/zip/src/entry.rs @@ -60,10 +60,11 @@ pub fn has_traversal_component_bytes(bytes: &[u8]) -> bool { /// Sanitize and validate an entry path, rejecting any zip-slip traversal vectors. /// /// Returns `None` if `path` is empty or contains parent traversal components (`..`), -/// null bytes, leading separators (`/` or `\`), or Windows drive prefixes (`C:`). -/// Returns `Some(path)` if the path is safe. +/// null bytes, or Windows drive prefixes (`C:`). +/// Strips leading separators (`/` or `\`) to ensure the path is relative. pub fn sanitize_path(path: &str) -> Option<&str> { - if path.is_empty() || has_traversal_component(path) { None } else { Some(path) } + let trimmed = path.trim_start_matches(['/', '\\']); + if trimmed.is_empty() || has_traversal_component(trimmed) { None } else { Some(trimmed) } } #[cfg(test)] @@ -94,6 +95,16 @@ mod tests { assert!(has_traversal_component("\\")); } + #[test] + fn sanitizes_leading_separators() { + assert_eq!(sanitize_path("/etc/passwd"), Some("etc/passwd")); + assert_eq!(sanitize_path(r"\windows\system32"), Some(r"windows\system32")); + assert_eq!(sanitize_path("//server/share"), Some("server/share")); + assert_eq!(sanitize_path(r"\\server\share"), Some(r"server\share")); + assert_eq!(sanitize_path("/"), None); + assert_eq!(sanitize_path("\\"), None); + } + #[test] fn detects_windows_drive_letters() { assert!(has_traversal_component("C:/test.txt")); @@ -132,7 +143,7 @@ mod tests { assert_eq!(sanitize_path("../../etc/passwd"), None); assert_eq!(sanitize_path(r"..\..\windows\system32"), None); assert_eq!(sanitize_path("C:/test.txt"), None); - assert_eq!(sanitize_path("/etc/shadow"), None); + assert_eq!(sanitize_path("/etc/shadow"), Some("etc/shadow")); assert_eq!(sanitize_path(""), None); assert_eq!(sanitize_path("safe/path.txt"), Some("safe/path.txt")); assert_eq!(sanitize_path("mimetype"), Some("mimetype")); diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index cc5bd0cc64..b776fc0890 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -227,10 +227,9 @@ impl SeekableArchive { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. Non-UTF-8 names and names - /// containing path-traversal components are omitted. + /// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) + self.zip.file_names().filter_map(Result::ok) } /// Is there an entry `name` (exactly as stored)? Paths containing traversal components @@ -551,8 +550,8 @@ mod tests { let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap(); assert!(archive.has_traversal_component()); - // Names iterator filters out traversal vectors - let names = archive.names().collect::>(); + // Entry enumeration omits traversal vectors + let names = (0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(); assert_eq!(names, vec!["valid.txt"]); // Virtual lookups reject traversal diff --git a/crates/zip/tests/archive.rs b/crates/zip/tests/archive.rs index e9b0691630..9266b65ea6 100644 --- a/crates/zip/tests/archive.rs +++ b/crates/zip/tests/archive.rs @@ -229,11 +229,12 @@ fn path_traversal_detection_flags_hostile_vectors() { // Null bytes assert!(has_traversal_component("foo\0bar")); - // Sanitization flags them safely + // Sanitization flags or cleans them safely assert_eq!(sanitize_path("../../etc/passwd"), None); assert_eq!(sanitize_path(r"..\..\windows\system32"), None); assert_eq!(sanitize_path("C:/test.txt"), None); - assert_eq!(sanitize_path("/etc/passwd"), None); + assert_eq!(sanitize_path("/etc/passwd"), Some("etc/passwd")); + assert_eq!(sanitize_path(r"\windows\system32"), Some(r"windows\system32")); assert_eq!(sanitize_path("foo\0bar"), None); // Safe relative paths are allowed @@ -264,7 +265,7 @@ fn synthetic_hostile_zip_headers_are_safely_flagged_and_rejected() { assert!(archive.has_traversal_component()); // Enumeration omits traversal components - let names = archive.names().collect::>(); + let names = (0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(); assert_eq!(names, vec!["safe/file.txt"]); assert_eq!(archive.entry_name(3).unwrap().as_deref(), Some("safe/file.txt")); assert_eq!(archive.entry_name(0).unwrap(), None); @@ -317,7 +318,7 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() { let mut archive = Archive::open(&bytes, ROOMY).unwrap(); assert!(archive.has_traversal_component()); - assert_eq!(archive.names().collect::>(), Vec::>::new()); + assert_eq!((0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(), Vec::::new()); assert_eq!(archive.entry_name(0).unwrap(), None); assert_eq!(archive.entry_sizes(0).unwrap(), None); assert_eq!(archive.read_index(0, 10).unwrap(), None); @@ -326,7 +327,7 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() { SeekableArchive::open(std::io::Cursor::new(bytes), SeekableLimits { max_entries: 100, max_metadata_bytes: 16_384, max_total_bytes: 1000 }) .unwrap(); assert!(seekable.has_traversal_component()); - assert_eq!(seekable.names().collect::>(), Vec::>::new()); + assert_eq!((0..seekable.len()).filter_map(|i| seekable.entry_name(i).unwrap()).collect::>(), Vec::::new()); assert_eq!(seekable.entry_name(0).unwrap(), None); assert_eq!(seekable.entry_sizes(0).unwrap(), None); assert_eq!(seekable.read_index(0, 10).unwrap(), None); From b1c553c20c320a6cb4caae7623d4138051dd287a Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 01:28:35 +0530 Subject: [PATCH 036/154] fix(sec): filter traversal components in names iterator and check has_traversal_component in penpot --- crates/penpot/src/lib.rs | 3 +++ crates/zip/src/archive.rs | 6 +++--- crates/zip/src/seekable.rs | 8 +++++--- crates/zip/tests/archive.rs | 10 +++++++++- 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/penpot/src/lib.rs b/crates/penpot/src/lib.rs index eda3bdf857..40a4395b14 100644 --- a/crates/penpot/src/lib.rs +++ b/crates/penpot/src/lib.rs @@ -175,6 +175,9 @@ impl<'b> Archive<'b> { if zip.has_duplicate_names() { return Err(corrupt("duplicate ZIP member names")); } + if zip.has_traversal_component() { + return Err(corrupt("unsafe ZIP member path")); + } // Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs // whose compressed size is innocuous but whose advertised uncompressed size is enormous. let names: Vec = zip.names().map(|n| n.into_owned()).collect(); diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 256bb03879..04939a71ea 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -171,10 +171,10 @@ impl<'a> Archive<'a> { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. A name that is not text is - /// left out. + /// The entry names in the archive's order, folders included. Non-UTF-8 names and names + /// containing path-traversal components are omitted. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok) + self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) } /// Is there an entry `name` (exactly as stored)? Paths containing traversal components diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index b776fc0890..457b733c81 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -227,9 +227,10 @@ impl SeekableArchive { self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) } - /// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted. + /// The entry names in the archive's order, folders included. Non-UTF-8 names and names + /// containing path-traversal components are omitted. pub fn names(&self) -> impl Iterator> { - self.zip.file_names().filter_map(Result::ok) + self.zip.file_names().filter_map(Result::ok).filter(|name| !has_traversal_component(name)) } /// Is there an entry `name` (exactly as stored)? Paths containing traversal components @@ -550,9 +551,10 @@ mod tests { let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap(); assert!(archive.has_traversal_component()); - // Entry enumeration omits traversal vectors + // Entry enumeration and names() iterator omit traversal vectors let names = (0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(); assert_eq!(names, vec!["valid.txt"]); + assert_eq!(archive.names().collect::>(), vec!["valid.txt"]); // Virtual lookups reject traversal assert!(!archive.contains("../../etc/passwd")); diff --git a/crates/zip/tests/archive.rs b/crates/zip/tests/archive.rs index 9266b65ea6..9cc5e111d8 100644 --- a/crates/zip/tests/archive.rs +++ b/crates/zip/tests/archive.rs @@ -264,9 +264,15 @@ fn synthetic_hostile_zip_headers_are_safely_flagged_and_rejected() { let mut archive = Archive::open(&bytes, ROOMY).unwrap(); assert!(archive.has_traversal_component()); - // Enumeration omits traversal components + // Enumeration and names() iterator omit traversal components let names = (0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(); assert_eq!(names, vec!["safe/file.txt"]); + assert_eq!(archive.names().collect::>(), vec!["safe/file.txt"]); + + let seekable = + SeekableArchive::open(std::io::Cursor::new(&bytes), SeekableLimits { max_entries: 100, max_metadata_bytes: 16_384, max_total_bytes: 1000 }) + .unwrap(); + assert_eq!(seekable.names().collect::>(), vec!["safe/file.txt"]); assert_eq!(archive.entry_name(3).unwrap().as_deref(), Some("safe/file.txt")); assert_eq!(archive.entry_name(0).unwrap(), None); assert_eq!(archive.entry_name(1).unwrap(), None); @@ -318,6 +324,7 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() { let mut archive = Archive::open(&bytes, ROOMY).unwrap(); assert!(archive.has_traversal_component()); + assert_eq!(archive.names().collect::>(), Vec::>::new()); assert_eq!((0..archive.len()).filter_map(|i| archive.entry_name(i).unwrap()).collect::>(), Vec::::new()); assert_eq!(archive.entry_name(0).unwrap(), None); assert_eq!(archive.entry_sizes(0).unwrap(), None); @@ -327,6 +334,7 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() { SeekableArchive::open(std::io::Cursor::new(bytes), SeekableLimits { max_entries: 100, max_metadata_bytes: 16_384, max_total_bytes: 1000 }) .unwrap(); assert!(seekable.has_traversal_component()); + assert_eq!(seekable.names().collect::>(), Vec::>::new()); assert_eq!((0..seekable.len()).filter_map(|i| seekable.entry_name(i).unwrap()).collect::>(), Vec::::new()); assert_eq!(seekable.entry_name(0).unwrap(), None); assert_eq!(seekable.entry_sizes(0).unwrap(), None); From a12bea6ada6b01f86c2a0f47a26cf5416a88109f Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 21:08:17 +0530 Subject: [PATCH 037/154] fix(docx): preserve absent compatibilityMode and hyperlink history (#3308, #3305) - Fix #3308: Represent absent compatibilityMode as Option (None = omitted). Do not synthesize or empty when omitted from input. In merged settings, support removing compatibilityMode across paired tags, alternate quotes, whitespace, and foreign vendor elements. - Fix #3305: Retain authored presence and boolean value of w:history on (Option) from read to write, defaulting newly authored links to 1. - Add comprehensive unit and integration tests across craft-docx, craft-wordmodel, and craft-doc-binary. --- crates/doc-binary/src/lib.rs | 4 +- crates/doc-binary/src/tests.rs | 2 +- crates/docx/src/read.rs | 3 +- crates/docx/src/read/meta.rs | 2 +- crates/docx/src/read/story.rs | 1 + crates/docx/src/read/story/runs.rs | 11 +- crates/docx/src/write/settings.rs | 13 +- crates/docx/src/write/settings_merge.rs | 111 +++++++++++++-- crates/docx/src/write/story/para.rs | 22 ++- crates/docx/tests/it/fixtures.rs | 20 +-- crates/docx/tests/it/picture_links.rs | 2 +- crates/docx/tests/it/roundtrip.rs | 168 ++++++++++++++++++++++- crates/docx/tests/it/settings_merge.rs | 31 +++++ crates/wordmodel/src/props/char_props.rs | 12 +- crates/wordmodel/src/settings.rs | 15 +- crates/wordmodel/src/tests.rs | 21 +++ 16 files changed, 392 insertions(+), 46 deletions(-) diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index b8c1c5c468..770376f0d1 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> let mut doc = Document::new(); // Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default // 15 would apply Word 2013+ justification and line-breaking rules to them. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(&comp) { doc.core = core; } @@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u let content = word6::content(word, &fib)?; let mut doc = Document::new(); // Word opens these files in compatibility mode 11 too. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(comp) { doc.core = core; } diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 8c1025eb27..2f380ca84a 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() { let doc = read(&f).expect("opens"); // Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and // line breaking. - assert_eq!(doc.settings.compat_mode, 11); + assert_eq!(doc.settings.compat_mode, Some(11)); } #[test] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 18c9ea47a0..a563e755e1 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -254,7 +254,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, lenient("numbering", r.read_numbering(&p)); } // Without a stated mode (or settings at all) Word lays a document out as Word 2007 did. - r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE; + // Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308). + r.doc.settings.compat_mode = None; if let Some(p) = part(rt::SETTINGS) { lenient("settings", r.read_settings(&p)); } diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index 9cc23be27c..8855d87229 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -45,7 +45,7 @@ impl Reader<'_> { }) .and_then(|c| c.attr("w:val")); if let Some(m) = mode.and_then(u32_of) { - s.compat_mode = m.clamp(11, 99); + s.compat_mode = Some(m.clamp(11, 99)); } s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off); s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off); diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 9b5b04300a..c0b98aa917 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024; pub struct RunCtx { link: Option, link_tooltip: Option>, + link_history: Option, ins: Option, del: Option, } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 0c8b699949..47e1ef36e3 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,6 +32,7 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); + c.link_history = k.attr("w:history").map(|v| !matches!(v, "0" | "false" | "off")); } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } @@ -138,6 +139,7 @@ impl Reader<'_> { let mut p = self.pc.rpr(rpr); p.link = ctx.link.clone(); p.link_tooltip = ctx.link_tooltip.clone(); + p.link_history = ctx.link_history; p.ins = ctx.ins; p.del = ctx.del; p.fmt_change = self.rpr_change(rpr); @@ -145,7 +147,14 @@ impl Reader<'_> { } fn run_props_none(&self, ctx: &RunCtx) -> CharProps { - CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } + CharProps { + link: ctx.link.clone(), + link_tooltip: ctx.link_tooltip.clone(), + link_history: ctx.link_history, + ins: ctx.ins, + del: ctx.del, + ..Default::default() + } } fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) { diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 2d97e4a01c..6458f05f84 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -144,6 +144,13 @@ fn write_note_settings( } fn write_compatibility_settings(w: &mut W, doc: &Document) { + let has_compat = doc.settings.do_not_expand_shift_return + || doc.settings.sum_paragraph_spacing + || doc.settings.allow_space_of_same_style_in_table + || doc.settings.compat_mode.is_some(); + if !has_compat { + return; + } w.open("w:compat", &[]); // CT_Compat: the older switches come before the `w:compatSetting`s. if doc.settings.do_not_expand_shift_return { @@ -155,8 +162,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) { if doc.settings.allow_space_of_same_style_in_table { w.empty("w:allowSpaceOfSameStyleInTable", &[]); } - let mode = doc.settings.compat_mode.clamp(11, 15).to_string(); - w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + if let Some(mode) = doc.settings.compat_mode { + let mode = mode.clamp(11, 15).to_string(); + w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + } w.close("w:compat"); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 6add6f0ebb..c8ff49b4d3 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -230,16 +230,74 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { Some((open_end, close, out)) } -/// The original `w:compat` with its `compatibilityMode` taken from the generated one. -fn merge_compat(orig: &str, generated: &str) -> Option { +const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; +const WML_STRICT: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main"; + +/// The original `w:compat` with its `compatibilityMode` taken from the generated one, +/// or removed if the generated settings omit it. +fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { let mode = |s: &str| -> Option<(usize, usize)> { - let at = s.find("w:name=\"compatibilityMode\"")?; - let tag_start = s.get(..at)?.rfind('<')?; - let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1; - Some((tag_start, tag_end)) + let (_, _, kids) = children(s, "w:compat")?; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + for k in kids { + let child_str = s.get(k.start..k.end)?; + let mut xml = String::with_capacity(root.len() + child_str.len() + 16); + xml.push_str(root); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + loop { + match reader.read_resolved_event().ok()? { + (_, quick_xml::events::Event::Start(_)) => break, + (_, quick_xml::events::Event::Eof) => return None, + _ => {} + } + } + let w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => { + w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT + } + _ => false, + }; + if !is_wml_elem || e.local_name().as_ref() != b"compatSetting" { + continue; + } + let mut is_compat_mode = false; + let mut uri_ok = true; + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + let is_wml_attr = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => { + w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT + } + quick_xml::name::ResolveResult::Unbound => true, + _ => false, + }; + if is_wml_attr && local.as_ref() == b"name" && attr.value.as_ref() == b"compatibilityMode" { + is_compat_mode = true; + } else if is_wml_attr && local.as_ref() == b"uri" && attr.value.as_ref() != b"http://schemas.microsoft.com/office/word" { + uri_ok = false; + } + } + if is_compat_mode && uri_ok { + return Some((k.start, k.end)); + } + } + } + None }; match (mode(orig), mode(generated)) { (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), + (Some((a, b)), None) => Some(format!("{}{}", orig.get(..a)?, orig.get(b..)?)), (None, Some((c, d))) => { // No mode in the original: add the generated one before ``, or expand a self-closing ``. if let Some(close) = orig.rfind("") { @@ -251,7 +309,7 @@ fn merge_compat(orig: &str, generated: &str) -> Option { None } } - _ => Some(orig.to_string()), + (None, None) => Some(orig.to_string()), } } @@ -356,10 +414,8 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } } else if k.name == "w:compat" { - let merged = match mark("w:compat", &mut used) { - Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?, - None => text.to_string(), - }; + let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); + let merged = merge_compat(root_tag, text, g_compat.as_deref().unwrap_or(""))?; out.push((k.name.clone(), merged)); } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); @@ -473,4 +529,37 @@ mod tests { // A file whose only extra setting is this one has nothing foreign to keep. assert!(!has_unowned(br#""#)); } + + #[test] + fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() { + let gen_no_mode = r#""#; + + // Paired tag with closing + let orig_paired = r#""#; + assert!(has_unowned(orig_paired.as_bytes())); + let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_paired.contains("compatibilityMode"), "{out_paired}"); + assert!(!out_paired.contains(""), "{out_paired}"); + assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}"); + + // Single quotes + let orig_single_quotes = r#""#; + let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sq.contains("compatibilityMode"), "{out_sq}"); + assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}"); + + // Whitespace around equals + let orig_spaces = r#""#; + let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sp.contains("compatibilityMode"), "{out_sp}"); + assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}"); + + // Foreign vendor compatSetting element is preserved + let orig_foreign = r#""#; + let gen_foreign = + r#""#; + let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); + assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); + assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index babed9de51..c4f763bc85 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -213,17 +213,17 @@ impl Writer<'_> { i += 1; continue; } - // Hyperlinks with different ScreenTips stay separate even if their target is shared. + // Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared. let link = props .link .as_deref() .filter(|target| !target.is_empty()) - .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))); + .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip), props.link_history)); if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); } - if let Some((link, tip)) = link { + if let Some((link, tip, hist)) = link { let id; let target = if let Some(anchor) = link.strip_prefix('#') { ("w:anchor", anchor) @@ -231,11 +231,19 @@ impl Writer<'_> { id = rels.add(rt::HYPERLINK, link, true); ("r:id", id.as_str()) }; - if let Some(tip) = tip { - w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]); - } else { - w.open("w:hyperlink", &[target, ("w:history", "1")]); + let mut attrs = [("", ""); 3]; + let mut n = 0; + attrs[n] = target; + n += 1; + if let Some(h) = hist { + attrs[n] = ("w:history", if h { "1" } else { "0" }); + n += 1; } + if let Some(tip) = tip { + attrs[n] = ("w:tooltip", tip); + n += 1; + } + w.open("w:hyperlink", &attrs[..n]); } open_link = link; } diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 4f2b9de277..821d890b2a 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() { let compat = |v: &str| { format!(r#""#) }; - assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15); - assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14); + assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15)); + assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14)); // Unnamed, out of range or junk values. - assert_eq!(with_settings(Some("")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11); - assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99); - assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some("")).settings.compat_mode, None); + assert_eq!(with_settings(None).settings.compat_mode, None); + assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11)); + assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99)); + assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None); // Another vendor's setting of the same name is ignored. let other = r#""#; - assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some(other)).settings.compat_mode, None); } #[test] @@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() { #[test] fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() { - assert_eq!(read_body("").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + let d = read_body(""); + assert_eq!(d.settings.compat_mode, None); + assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); } #[test] diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index dc5f53e19c..e84ccb10c5 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -107,7 +107,7 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { let back = craft_docx::read(&bytes).unwrap(); assert_eq!(picture_links(&back), [Some("https://example.com/saved".to_string()), Some("#Spot".to_string())]); // The drawing's link alone (as Word writes it) reads back the same. - let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); + let without_run_link = xml.replace(&format!(r#""#), "").replacen("", "", 1); assert_ne!(without_run_link, xml); let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 4927cd09c8..21dfd82505 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -143,6 +143,7 @@ fn every_char_prop_round_trips() { }), link: None, link_tooltip: None, + link_history: None, ins: None, del: None, fmt_change: None, @@ -1487,11 +1488,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { for mode in [11, 12, 14, 15] { for allow in [false, true] { let mut d = Document::new(); - d.settings.compat_mode = mode; + d.settings.compat_mode = Some(mode); d.settings.allow_space_of_same_style_in_table = allow; let r = rt(&d); assert_eq!(r.settings.allow_space_of_same_style_in_table, allow); - assert_eq!(r.settings.compat_mode, mode); + assert_eq!(r.settings.compat_mode, Some(mode)); if allow { let bytes = craft_docx::write(&d).unwrap(); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); @@ -1508,14 +1509,171 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { fn compatibility_mode_round_trips() { // New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't // change how Word lays it out. - assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT); + assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT)); for mode in [11, 12, 14, 15] { let mut d = Document::new(); - d.settings.compat_mode = mode; - assert_eq!(rt(&d).settings.compat_mode, mode); + d.settings.compat_mode = Some(mode); + assert_eq!(rt(&d).settings.compat_mode, Some(mode)); } } +/// #3308: A document without `` or without `` +/// round-trips without synthesizing the tag on save. +#[test] +fn compatibility_mode_omitted_round_trips_without_synthesizing() { + let settings_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + match zip.by_name("word/settings.xml") { + Ok(mut file) => { + std::io::Read::read_to_string(&mut file, &mut xml).unwrap(); + Some(xml) + } + Err(zip::result::ZipError::FileNotFound) => None, + Err(e) => panic!("zip error: {e:?}"), + } + }; + + // Case 1: settings.xml without `` at all. + let base_docx = craft_docx::write(&Document::new()).unwrap(); + let original_settings = settings_xml_of(&base_docx).unwrap(); + let without_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, without_compat); + let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes()); + + let doc = craft_docx::read(&docx_without_compat).unwrap(); + assert_eq!(doc.settings.compat_mode, None); + assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); + + let saved_bytes = craft_docx::write(&doc).unwrap(); + let saved_settings = settings_xml_of(&saved_bytes).unwrap(); + assert!(!saved_settings.contains(", got: {saved_settings}"); + assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}"); + + let read_back = craft_docx::read(&saved_bytes).unwrap(); + assert_eq!(read_back.settings.compat_mode, None); + + // Case 2: settings.xml with `` but without `` + // (e.g. only legacy compatibility flags like ``). + let with_other_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, with_other_compat); + let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes()); + + let doc2 = craft_docx::read(&docx_with_other).unwrap(); + assert_eq!(doc2.settings.compat_mode, None); + assert!(doc2.settings.do_not_expand_shift_return); + + let saved_bytes2 = craft_docx::write(&doc2).unwrap(); + let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap(); + assert!(saved_settings2.contains(""), "expected , got: {saved_settings2}"); + assert!(saved_settings2.contains(""), "expected doNotExpandShiftReturn, got: {saved_settings2}"); + assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}"); + + let read_back2 = craft_docx::read(&saved_bytes2).unwrap(); + assert_eq!(read_back2.settings.compat_mode, None); + assert!(read_back2.settings.do_not_expand_shift_return); +} + +/// #3305: Hyperlinks without `w:history`, with `w:history="0"`, or with `w:history="1"` +/// round-trip with the exact attribute state preserved. +#[test] +fn hyperlink_history_attribute_preservation_round_trips() { + let doc_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + xml + }; + + // 1. In-memory / programmatic round-trip with different history settings: + // a) omitted (`None`) + let mut p_none = Paragraph::new(); + p_none + .insert_text( + 0, + "link without history", + &CharProps { link: Some("https://example.com/no-hist".into()), link_history: None, ..Default::default() }, + ) + .unwrap(); + let d_none = doc_with(vec![p_none]); + let bytes_none = craft_docx::write(&d_none).unwrap(); + let xml_none = doc_xml_of(&bytes_none); + assert!(xml_none.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +#[test] +fn cleared_compatibility_mode_removes_it_from_merged_settings() { + let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap(); + assert_eq!(doc.settings.compat_mode, Some(15)); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + + // Case 1: compat_mode is set to None, and no other compat switch is enabled. + doc.settings.compat_mode = None; + let files = save(&doc); + let s = text(&files, "word/settings.xml"); + assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}"); + assert!(s.contains(""), "expected w:compat preserved for unowned settings: {s}"); + assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}"); + assert!(s.contains("enableOpenTypeFeatures"), "{s}"); + + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.settings.compat_mode, None); + + // Case 2: compat_mode is set to None, but another switch is enabled. + doc.settings.do_not_expand_shift_return = true; + let files2 = save(&doc); + let s2 = text(&files2, "word/settings.xml"); + assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); + assert!(s2.contains(""), "{s2}"); + assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); + assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); + + let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened2.settings.compat_mode, None); +} diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index 556d035406..f6949d3c98 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -435,6 +435,10 @@ pub struct CharProps { /// Optional ScreenTip for the hyperlink. Runs from one link can share its text. #[serde(skip_serializing_if = "Option::is_none")] pub link_tooltip: Option>, + /// Whether to add the hyperlink to the browser's/Word's history (`w:history`). + /// `None` indicates the attribute was omitted from the source document. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_history: Option, /// Tracked insertion: index into `Document::revisions`. #[serde(skip_serializing_if = "Option::is_none")] pub ins: Option, @@ -572,6 +576,7 @@ impl CharProps { c.style = None; } c.link_tooltip = None; + c.link_history = None; c } @@ -632,9 +637,10 @@ impl CharProps { } fn minus_document_marks(&mut self, base: &CharProps) { - if self.link == base.link && self.link_tooltip == base.link_tooltip { + if self.link == base.link && self.link_tooltip == base.link_tooltip && self.link_history == base.link_history { self.link = None; self.link_tooltip = None; + self.link_history = None; } drop_same_fields!(self, base; ins, del, ligatures); } @@ -689,6 +695,7 @@ impl CharProps { if let Some(link) = &patch.link { self.link = Some(link.clone()); self.link_tooltip = patch.link_tooltip.clone(); + self.link_history = patch.link_history; } overlay_fields!(self, patch; ins, del, fmt_change, ligatures); } @@ -716,6 +723,7 @@ impl CharProps { CharProps { link: self.link.clone(), link_tooltip: self.link_tooltip.clone(), + link_history: self.link_history, ins: self.ins, del: self.del, fmt_change: self.fmt_change.clone(), @@ -726,6 +734,6 @@ impl CharProps { } /// Just the formatting: without the link, revision marks and tracked formatting change. pub fn formatting(&self) -> CharProps { - CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() } + CharProps { link: None, link_tooltip: None, link_history: None, ins: None, del: None, fmt_change: None, ..self.clone() } } } diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 1f75af2626..64df9e1885 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -124,8 +124,9 @@ pub struct Settings { pub protect_hash: Vec<(String, String)>, /// Word compatibility mode the document is laid out in (`compatibilityMode`): 15 for Word /// 2013 and later, which places a table's border at the margin rather than its text and lets - /// justified lines shrink their spaces to fit more text. - pub compat_mode: u32, + /// justified lines shrink their spaces to fit more text. `None` when omitted from the file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compat_mode: Option, /// Fonts the document's font table classes as roman (serif, `w:family w:val="roman"`): Word /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -319,7 +320,7 @@ impl Default for Settings { protection: None, protect_formatting: false, protect_hash: Vec::new(), - compat_mode: COMPAT_MODE_CURRENT, + compat_mode: Some(COMPAT_MODE_CURRENT), roman_fonts: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, @@ -337,3 +338,11 @@ impl Default for Settings { } } } + +impl Settings { + /// The effective compatibility mode: the authored mode, or Word 2007 (`LEGACY_COMPAT_MODE` = 12) + /// when omitted from the file. + pub fn effective_compat_mode(&self) -> u32 { + self.compat_mode.unwrap_or(LEGACY_COMPAT_MODE) + } +} diff --git a/crates/wordmodel/src/tests.rs b/crates/wordmodel/src/tests.rs index b4d1b17dd4..f5ab928c7f 100644 --- a/crates/wordmodel/src/tests.rs +++ b/crates/wordmodel/src/tests.rs @@ -309,6 +309,27 @@ fn json_round_trip() { assert_eq!(back.para(StoryRef::Body, &Path::top(0)).unwrap().runs[0].props.bold, Some(true)); } +#[test] +fn settings_compat_mode_serde_round_trip() { + let mut s = Settings::default(); + assert_eq!(s.compat_mode, Some(COMPAT_MODE_CURRENT)); + s.compat_mode = None; + let json = serde_json::to_string(&s).unwrap(); + assert!(!json.contains("compatMode"), "expected compatMode omitted: {json}"); + let back: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(back.compat_mode, None); + assert_eq!(back.effective_compat_mode(), LEGACY_COMPAT_MODE); + + let from_empty: Settings = serde_json::from_str("{}").unwrap(); + assert_eq!(from_empty.compat_mode, None); + + s.compat_mode = Some(14); + let json14 = serde_json::to_string(&s).unwrap(); + assert!(json14.contains(r#""compatMode":14"#), "{json14}"); + let back14: Settings = serde_json::from_str(&json14).unwrap(); + assert_eq!(back14.compat_mode, Some(14)); +} + #[test] fn ensure_nonempty_repairs() { let mut d = Document::new(); From 7f16b42210af6aa09b7c712978d80817834165ae Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 21:25:20 +0530 Subject: [PATCH 038/154] fix(docx): address CodeRabbit review feedback on settings merge and ruby links - Copy link_history in read_ruby alongside link, preserving None when omitted. - Include w:compat opening tag in settings merge NsReader reconstruction to preserve namespaces declared on w:compat. - Normalize attribute values using normalized_value() before comparing name and uri. - Update GEN test fixture w:uri to standard Microsoft Word URI. - Add regression tests covering w:compat-level namespace declarations and escaped attribute entities. --- crates/docx/src/read/story/runs.rs | 2 +- crates/docx/src/write/settings_merge.rs | 38 +++++++++++++++++++++---- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 47e1ef36e3..6ade0f9019 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -363,7 +363,7 @@ impl Reader<'_> { let (base, base_props) = part("w:rubyBase"); let (ruby, ruby_props) = part("w:rt"); let mut bp = base_props.unwrap_or_default(); - (bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del); + (bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del); if base.is_empty() { return; } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index c8ff49b4d3..4fbdda3cfa 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -243,16 +243,25 @@ fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { } else { r#""# }; + let compat_open_end = tag_end(s)? + 1; + let compat_open = s.get(..compat_open_end)?; for k in kids { let child_str = s.get(k.start..k.end)?; - let mut xml = String::with_capacity(root.len() + child_str.len() + 16); + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); xml.push_str(root); + xml.push_str(compat_open); xml.push_str(child_str); - xml.push_str(""); + xml.push_str(""); let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; loop { match reader.read_resolved_event().ok()? { - (_, quick_xml::events::Event::Start(_)) => break, + (_, quick_xml::events::Event::Start(_)) => { + depth += 1; + if depth == 2 { + break; + } + } (_, quick_xml::events::Event::Eof) => return None, _ => {} } @@ -282,9 +291,13 @@ fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { quick_xml::name::ResolveResult::Unbound => true, _ => false, }; - if is_wml_attr && local.as_ref() == b"name" && attr.value.as_ref() == b"compatibilityMode" { + if !is_wml_attr { + continue; + } + let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + if local.as_ref() == b"name" && val.as_deref() == Some("compatibilityMode") { is_compat_mode = true; - } else if is_wml_attr && local.as_ref() == b"uri" && attr.value.as_ref() != b"http://schemas.microsoft.com/office/word" { + } else if local.as_ref() == b"uri" && val.as_deref() != Some("http://schemas.microsoft.com/office/word") { uri_ok = false; } } @@ -443,7 +456,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { mod tests { use super::*; - const GEN: &str = r#""#; + const GEN: &str = r#""#; #[test] fn odd_or_hostile_originals_fall_back_or_merge_without_panicking() { @@ -561,5 +574,18 @@ mod tests { let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + + // Namespace declared directly on w:compat (not root) with mode replacement + let orig_compat_ns = r#""#; + let gen_new_mode = r#""#; + let out_ns = String::from_utf8(merge(orig_compat_ns.as_bytes(), gen_new_mode.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_ns.matches("compatibilityMode").count(), 1, "{out_ns}"); + assert!(out_ns.contains(r#"w:val="14""#), "{out_ns}"); + + // Escaped XML entities in attribute values + let orig_escaped = r#""#; + let out_esc = String::from_utf8(merge(orig_escaped.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_esc.contains("compatibility"), "{out_esc}"); + assert!(out_esc.contains("overrideTableStyleFontSizeAndJustification"), "{out_esc}"); } } From c0024b06a97d143e5691f78e478ca3a3a33e3565 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:29:48 +0530 Subject: [PATCH 039/154] fix(docx): preserve compat block namespaces and handle whitespace in on-off (#3308, #3305) --- crates/docx/src/read/story.rs | 2 +- crates/docx/src/read/story/runs.rs | 2 +- crates/docx/src/units.rs | 7 +- crates/docx/src/write/settings_merge.rs | 986 +++++++++++++++++++++--- crates/docx/tests/it/roundtrip.rs | 11 + crates/docx/tests/it/settings_merge.rs | 30 + 6 files changed, 929 insertions(+), 109 deletions(-) diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index c0b98aa917..15ab338e10 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -213,5 +213,5 @@ fn placeholder_of(s: &str) -> String { } fn on_off_attr(e: &El, name: &str) -> bool { - e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off")) + e.attr(name).is_some_and(|v| !crate::units::is_off_val(v)) } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 6ade0f9019..4efd07cac7 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,7 +32,7 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); - c.link_history = k.attr("w:history").map(|v| !matches!(v, "0" | "false" | "off")); + c.link_history = k.attr("w:history").map(|v| !crate::units::is_off_val(v)); } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 295fe76215..cefd1977c7 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option { } } +/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false. +pub fn is_off_val(v: &str) -> bool { + matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE") +} + /// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off. pub fn on_off(e: &El) -> bool { match e.attr("w:val") { None => true, - Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + Some(v) => !is_off_val(v), } } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 4fbdda3cfa..61c096b565 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -179,16 +179,15 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { if xml.get(open_end - 2..open_end)? == "/>" { return None; } - let close = xml.rfind(&format!(""))?; let mut out = Vec::new(); let mut depth = 0usize; let mut i = open_end; let mut cur: Option<(String, usize)> = None; - while i < close { - let rest = xml.get(i..close)?; - let Some(lt) = rest.find('<') else { break }; + let close = loop { + let rest = xml.get(i..)?; + let lt = rest.find('<')?; let at = i + lt; - let tail = xml.get(at..close)?; + let tail = xml.get(at..)?; if tail.starts_with("")? + 3; continue; @@ -203,6 +202,13 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { let gt = at + tag_end(tail)? + 1; let tag = xml.get(at..gt)?; if tag.starts_with(" Option<(usize, usize, Vec)> { } } i = gt; - } + }; if depth != 0 { return None; } - Some((open_end, close, out)) + Some((open, open_end, close, out)) +} + +fn find_close_tag(xml: &str, tag_name: &str) -> Option { + children(xml, tag_name).map(|(_, _, close, _)| close) } const WML: &[u8] = b"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const WML_STRICT: &[u8] = b"http://purl.oclc.org/ooxml/wordprocessingml/main"; +const REL_NS: &[u8] = b"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const REL_STRICT_NS: &[u8] = b"http://purl.oclc.org/ooxml/officeDocument/relationships"; + +fn is_rel_ns(ns: &[u8]) -> bool { + let unesc = unescaped_ns(ns); + unesc.as_ref() == REL_NS || unesc.as_ref() == REL_STRICT_NS +} + +fn unescaped_ns(ns: &[u8]) -> std::borrow::Cow<'_, [u8]> { + if ns.contains(&b'&') + && let Ok(s) = std::str::from_utf8(ns) + && let Ok(unesc) = quick_xml::escape::unescape(s) + { + return std::borrow::Cow::Owned(unesc.into_owned().into_bytes()); + } + std::borrow::Cow::Borrowed(ns) +} + +fn is_wml_ns(ns: &[u8], root_w: &[u8]) -> bool { + let unesc_ns = unescaped_ns(ns); + let unesc_root = unescaped_ns(root_w); + (!unesc_root.is_empty() && unesc_ns.as_ref() == unesc_root.as_ref()) || unesc_ns.as_ref() == WML || unesc_ns.as_ref() == WML_STRICT +} + +const OWNED_COMPAT_SWITCHES: &[&str] = &["doNotExpandShiftReturn", "doNotUseHTMLParagraphAutoSpacing", "allowSpaceOfSameStyleInTable"]; + +fn check_compat_child(root_tag: &str, compat_s: &str, k: &Child, check: F) -> bool +where + F: FnOnce(&quick_xml::events::BytesStart<'_>, &quick_xml::NsReader<&[u8]>, &[u8]) -> bool, +{ + let Some(child_str) = compat_s.get(k.start..k.end) else { return false }; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(compat_open_end) = tag_end(compat_s).map(|e| e + 1) else { return false }; + let Some(compat_open) = compat_s.get(..compat_open_end) else { return false }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(_))) => { + depth += 1; + if depth == 1 { + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } else if depth == 2 { + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, + _ => {} + } + } + if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), + _ => false, + }; + if !is_wml_elem { + return false; + } + check(e, &reader, root_w_ns.as_deref().unwrap_or(b"")) + } else { + false + } +} + +fn is_compat_mode_child(root_tag: &str, compat_s: &str, k: &Child) -> bool { + check_compat_child(root_tag, compat_s, k, |e, reader, root_w| { + if e.local_name().as_ref() != b"compatSetting" { + return false; + } + let mut w_name = None; + let mut un_name = None; + let mut w_uri = None; + let mut un_uri = None; + + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + let is_wml = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), + _ => false, + }; + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + + if local.as_ref() == b"name" { + if is_wml { + w_name = val; + } else if is_unbound { + un_name = val; + } + } else if local.as_ref() == b"uri" { + if is_wml { + w_uri = val; + } else if is_unbound { + un_uri = val; + } + } + } + + let name = w_name.or(un_name); + let uri = w_uri.or(un_uri); + name.as_deref() == Some("compatibilityMode") && uri.as_deref().is_none_or(|u| u == "http://schemas.microsoft.com/office/word") + }) +} + +fn is_wml_switch_child(root_tag: &str, compat_s: &str, k: &Child, sw_local: &str) -> bool { + check_compat_child(root_tag, compat_s, k, |e, _reader, _root_w| e.local_name().as_ref() == sw_local.as_bytes()) +} + +const CT_COMPAT_ORDER: &[&str] = &[ + "useSingleBorderforContiguousCells", + "wpJustification", + "noTabHangInd", + "noLeading", + "spaceForUL", + "noColumnBalance", + "balanceSingleByteDoubleByteWidth", + "noExtraLineSpacing", + "doNotLeaveBackslashAlone", + "ulTrailSpace", + "doNotExpandShiftReturn", + "spacingInWholePoints", + "lineWrapLikeWord6", + "printBodyTextBeforeHeader", + "printColBlack", + "wpSpaceWidth", + "showBreaksInFrames", + "subFontBySize", + "suppressBottomSpacing", + "suppressTopSpacing", + "suppressSpacingAtTopOfPage", + "suppressTopSpacingWP", + "suppressSpBfAfterPgBrk", + "swapBordersFacingPages", + "convMailMergeEsc", + "truncateFontHeightsLikeWP6", + "mwSmallCaps", + "usePrinterMetrics", + "doNotSuppressParagraphBorders", + "wrapTrailSpaces", + "footnoteLayoutLikeWW8", + "shapeLayoutLikeWW8", + "alignTablesRowByRow", + "forgetLastTabAlignment", + "adjustLineHeightInTable", + "autoSpaceLikeWord95", + "noSpaceRaiseLower", + "doNotUseHTMLParagraphAutoSpacing", + "layoutRawTableWidth", + "layoutTableRowsApart", + "useWord97LineBreakRules", + "doNotBreakWrappedTables", + "doNotSnapToGridInCell", + "selectFldWithFirstOrLastChar", + "applyBreakingRules", + "doNotWrapTextWithPunct", + "doNotUseEastAsianBreakRules", + "useWord2002TableStyleRules", + "growAutofit", + "useFELayout", + "useNormalStyleForList", + "doNotUseIndentAsNumberingTabStop", + "useAltKinsokuLineBreakRules", + "allowSpaceOfSameStyleInTable", + "doNotSuppressIndentation", + "doNotAutofitConstrainedTables", + "autofitToFirstFixedWidthCell", + "underlineTabInNumList", + "displayHangulFixedWidth", + "splitPgBreakAndParaMark", + "doNotVertAlignCellWithSp", + "doNotBreakConstrainedForcedTable", + "doNotVertAlignInTxbx", + "useAnsiKerningPairs", + "cachedColBalance", + "compatSetting", +]; + +fn compat_child_rank(name: &str) -> usize { + let local = name.rsplit(':').next().unwrap_or(name); + CT_COMPAT_ORDER.iter().position(|&n| n == local).unwrap_or(CT_COMPAT_ORDER.len()) +} + +fn recognized_compat_child_rank(root_tag: &str, compat_s: &str, k: &Child) -> Option { + let local = k.name.rsplit(':').next().unwrap_or(&k.name); + let rank = CT_COMPAT_ORDER.iter().position(|&n| n == local)?; + if check_compat_child(root_tag, compat_s, k, |_, _, _| true) { Some(rank) } else { None } +} + +fn is_wml_compat_switch(root_tag: &str, compat_s: &str, k: &Child) -> bool { + OWNED_COMPAT_SWITCHES.iter().any(|sw| is_wml_switch_child(root_tag, compat_s, k, sw)) +} + +fn is_wml_compat_container(root_tag: &str, orig: &str, k: &Child) -> bool { + let Some(child_str) = orig.get(k.start..k.end) else { return false }; + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(child_str).map(|e| e + 1) else { return false }; + let Some(open_tag) = child_str.get(..open_end) else { return false }; + let mut xml = String::with_capacity(root.len() + open_tag.len() + 64); + xml.push_str(root); + if open_tag.ends_with("/>") { + xml.push_str(open_tag); + } else { + let tag_name = &k.name; + xml.push_str(open_tag); + xml.push_str(&format!("")); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(_))) if depth == 0 => { + depth = 1; + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } + Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) if depth == 1 => { + let is_wml_elem = match res { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w_ns.as_deref().unwrap_or(b"")), + _ => false, + }; + return is_wml_elem && e.local_name().as_ref() == b"compat"; + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => return false, + _ => {} + } + } +} + +fn compat_destination_and_w_ns(root_tag: &str, compat_s: &str) -> (Vec, Option>) { + let root = if root_tag.trim_start().starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { + return (WML.to_vec(), Some(WML.to_vec())); + }; + let Some(compat_open) = compat_s.get(..open_end) else { + return (WML.to_vec(), Some(WML.to_vec())); + }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + 64); + xml.push_str(root); + xml.push_str(compat_open); + if !compat_open.ends_with("/>") { + xml.push_str(""); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut compat_ns = WML.to_vec(); + let mut w_ns = None; + while let Ok((res, ev)) = reader.read_resolved_event() { + match ev { + quick_xml::events::Event::Start(_) => depth += 1, + quick_xml::events::Event::Empty(_) if depth == 1 => depth = 2, + quick_xml::events::Event::Eof => break, + _ => {} + } + if depth == 2 { + if let quick_xml::name::ResolveResult::Bound(ns) = res { + compat_ns = unescaped_ns(ns.as_ref()).into_owned(); + } + if let quick_xml::name::ResolveResult::Bound(ns) = reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + w_ns = Some(unescaped_ns(ns.as_ref()).into_owned()); + } + break; + } + } + (compat_ns, w_ns) +} + +fn qualify_wml_child(g_text: &str, root_tag: &str, compat_s: &str) -> String { + let (compat_ns, w_ns) = compat_destination_and_w_ns(root_tag, compat_s); + if w_ns.as_deref() == Some(&compat_ns) { + g_text.to_string() + } else { + let uri_str = std::str::from_utf8(&compat_ns).unwrap_or("http://schemas.openxmlformats.org/wordprocessingml/2006/main"); + if let Some(space_pos) = g_text.find(|c: char| c.is_whitespace() || c == '/' || c == '>') { + let mut s = g_text.to_string(); + s.insert_str(space_pos, &format!(r#" xmlns:w="{uri_str}""#)); + s + } else { + g_text.to_string() + } + } +} + +fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> String { + let root = if root_tag.trim_start().starts_with('<') { + root_tag + } else { + r#""# + }; + let Some(open_end) = tag_end(compat_s).map(|e| e + 1) else { return elem_str.to_string() }; + let Some(compat_open) = compat_s.get(..open_end) else { return elem_str.to_string() }; + let elem_offset_in_xml = root.len() + compat_open.len(); + let mut xml = String::with_capacity(root.len() + compat_open.len() + elem_str.len() + 64); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(elem_str); + if !elem_str.ends_with("/>") { + xml.push_str(""); + } + if !compat_open.ends_with("/>") { + xml.push_str(""); + } + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + let mut root_w_ns = None; + let mut disabled_val_range: Option<(usize, usize)> = None; + + while let Ok((_, ev)) = reader.read_resolved_event() { + match ev { + quick_xml::events::Event::Start(_) if depth == 0 => { + depth = 1; + root_w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { + quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), + _ => None, + }; + } + quick_xml::events::Event::Start(_) if depth == 1 => { + depth = 2; + } + quick_xml::events::Event::Empty(ref e) | quick_xml::events::Event::Start(ref e) if depth >= 2 => { + let mut w_val = None; + let mut un_val = None; + let root_w = root_w_ns.as_deref().unwrap_or(b""); + for attr in e.attributes().with_checks(false).flatten() { + let (ares, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"val" { + let is_wml = match ares { + quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), + _ => false, + }; + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + let val_str = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); + let start_in_xml = attr.value.as_ptr() as usize - xml.as_ptr() as usize; + if start_in_xml >= elem_offset_in_xml { + let start = start_in_xml - elem_offset_in_xml; + let end = start + attr.value.len(); + if is_wml { + w_val = Some((val_str, (start, end))); + } else if is_unbound { + un_val = Some((val_str, (start, end))); + } + } + } + } + let chosen = w_val.or(un_val); + if let Some((Some(v), span)) = chosen + && crate::units::is_off_val(&v) + { + disabled_val_range = Some(span); + } + break; + } + quick_xml::events::Event::Eof => break, + _ => {} + } + } + + if let Some((start, end)) = disabled_val_range + && start < end + && end <= elem_str.len() + { + let mut s = elem_str.to_string(); + s.replace_range(start..end, "1"); + return s; + } + elem_str.to_string() +} + +fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generated: &str, sw_local: &str) -> Option<()> { + let gen_sw = children(generated, "w:compat").and_then(|(_, _, _, g_kids)| { + g_kids.into_iter().find(|k| is_wml_switch_child(root_tag, generated, k, sw_local)).and_then(|k| generated.get(k.start..k.end)) + }); + + let (_, _, o_close, o_kids) = children(orig, orig_tag)?; + let orig_matches: Vec<(usize, usize)> = + o_kids.iter().filter(|k| is_wml_switch_child(root_tag, orig, k, sw_local)).map(|k| (k.start, k.end)).collect(); + + match (orig_matches.as_slice(), gen_sw) { + ([], None) => {} + (matches, None) => { + for &(a, b) in matches.iter().rev() { + orig.replace_range(a..b, ""); + } + } + ([], Some(g_text)) => { + let my_rank = compat_child_rank(sw_local); + let at = o_kids + .iter() + .find(|k| recognized_compat_child_rank(root_tag, orig, k).is_some_and(|r| r > my_rank)) + .map(|k| k.start) + .unwrap_or(o_close); + let child = qualify_wml_child(g_text, root_tag, orig); + orig.insert_str(at, &child); + } + (matches, Some(_g_text)) => { + for &(a, b) in matches[1..].iter().rev() { + orig.replace_range(a..b, ""); + } + let (first_a, first_b) = matches[0]; + let orig_elem = &orig[first_a..first_b]; + let updated = enable_switch_element(orig_elem, root_tag, orig); + orig.replace_range(first_a..first_b, &updated); + } + } + Some(()) +} /// The original `w:compat` with its `compatibilityMode` taken from the generated one, /// or removed if the generated settings omit it. -fn merge_compat(root_tag: &str, orig: &str, generated: &str) -> Option { - let mode = |s: &str| -> Option<(usize, usize)> { - let (_, _, kids) = children(s, "w:compat")?; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; - let compat_open_end = tag_end(s)? + 1; - let compat_open = s.get(..compat_open_end)?; - for k in kids { - let child_str = s.get(k.start..k.end)?; - let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); - xml.push_str(root); - xml.push_str(compat_open); - xml.push_str(child_str); - xml.push_str(""); - let mut reader = quick_xml::NsReader::from_str(&xml); - let mut depth = 0; - loop { - match reader.read_resolved_event().ok()? { - (_, quick_xml::events::Event::Start(_)) => { - depth += 1; - if depth == 2 { - break; - } - } - (_, quick_xml::events::Event::Eof) => return None, - _ => {} - } - } - let w_ns = match reader.resolver().resolve_element(quick_xml::name::QName(b"w:dummy")).0 { - quick_xml::name::ResolveResult::Bound(ns) => Some(ns.as_ref().to_vec()), - _ => None, - }; - if let Ok((res, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) = reader.read_resolved_event() { - let is_wml_elem = match res { - quick_xml::name::ResolveResult::Bound(ref ns) => { - w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT - } - _ => false, - }; - if !is_wml_elem || e.local_name().as_ref() != b"compatSetting" { - continue; - } - let mut is_compat_mode = false; - let mut uri_ok = true; - for attr in e.attributes().with_checks(false).flatten() { - let (ares, local) = reader.resolver().resolve_attribute(attr.key); - let is_wml_attr = match ares { - quick_xml::name::ResolveResult::Bound(ref ns) => { - w_ns.as_deref().is_some_and(|w| ns.as_ref() == w) || ns.as_ref() == WML || ns.as_ref() == WML_STRICT - } - quick_xml::name::ResolveResult::Unbound => true, - _ => false, - }; - if !is_wml_attr { - continue; - } - let val = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); - if local.as_ref() == b"name" && val.as_deref() == Some("compatibilityMode") { - is_compat_mode = true; - } else if local.as_ref() == b"uri" && val.as_deref() != Some("http://schemas.microsoft.com/office/word") { - uri_ok = false; - } - } - if is_compat_mode && uri_ok { - return Some((k.start, k.end)); - } - } - } - None +fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> Option { + let mode_spans = |s: &str, tag: &str| -> Vec<(usize, usize)> { + children(s, tag) + .map(|(_, _, _, kids)| kids.into_iter().filter(|k| is_compat_mode_child(root_tag, s, k)).map(|k| (k.start, k.end)).collect()) + .unwrap_or_default() }; - match (mode(orig), mode(generated)) { - (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), - (Some((a, b)), None) => Some(format!("{}{}", orig.get(..a)?, orig.get(b..)?)), - (None, Some((c, d))) => { - // No mode in the original: add the generated one before ``, or expand a self-closing ``. - if let Some(close) = orig.rfind("") { - Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?)) - } else if let Some(slash) = orig.rfind("/>") { - let open = orig.get(..slash)?.trim_end(); - Some(format!("{open}>{}", generated.get(c..d)?)) - } else { - None + + let has_any_gen_switch = + children(generated, "w:compat").is_some_and(|(_, _, _, g_kids)| g_kids.iter().any(|k| is_wml_compat_switch(root_tag, generated, k))); + + let open_end = tag_end(orig)? + 1; + let is_self_closing = orig.get(open_end - 2..open_end) == Some("/>"); + let compat_open = orig.get(..open_end)?; + + if tag_has_rel_id(root_tag, compat_open) { + return children(generated, "w:compat").is_some().then(|| generated.to_string()).or_else(|| Some(String::new())); + } + + let gen_modes = mode_spans(generated, "w:compat"); + if is_self_closing && gen_modes.is_empty() && !has_any_gen_switch { + return Some(orig.to_string()); + } + + let mut out = if is_self_closing { + let open = orig.get(..open_end - 2)?.trim_end(); + format!("{open}>") + } else { + orig.to_string() + }; + + // Omit relationship-bearing children whose relationships cannot be remapped in settings.xml.rels + if let Some((_, _, _, kids)) = children(&out, orig_tag) { + for k in kids.into_iter().rev() { + if let Some(child_str) = out.get(k.start..k.end) + && child_has_rel_id(root_tag, compat_open, child_str) + { + out.replace_range(k.start..k.end, ""); } } - (None, None) => Some(orig.to_string()), } + + for sw in OWNED_COMPAT_SWITCHES { + sync_compat_switch(root_tag, &mut out, orig_tag, generated, sw)?; + } + + let o_modes = mode_spans(&out, orig_tag); + match (o_modes.as_slice(), gen_modes.first()) { + ([], None) => {} + (matches, None) => { + for &(a, b) in matches.iter().rev() { + out.replace_range(a..b, ""); + } + } + ([], Some(&(c, d))) => { + let g_text = generated.get(c..d)?; + let close = find_close_tag(&out, orig_tag)?; + let child = qualify_wml_child(g_text, root_tag, &out); + out.insert_str(close, &child); + } + (matches, Some(&(c, d))) => { + let g_text = generated.get(c..d)?; + for &(a, b) in matches[1..].iter().rev() { + out.replace_range(a..b, ""); + } + let (first_a, first_b) = matches[0]; + let child = qualify_wml_child(g_text, root_tag, &out); + out.replace_range(first_a..first_b, &child); + } + } + + if let Some((c_start, c_open, _, remaining_kids)) = children(&out, orig_tag) + && remaining_kids.is_empty() + && !compat_has_unmodeled_attrs(root_tag, &out[c_start..c_open]) + { + return Some(String::new()); + } + + Some(out) +} + +fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + tag_str.len() + 32); + xml.push_str(root); + xml.push_str(tag_str); + if !tag_str.ends_with("/>") { + xml.push_str(""); + } else { + xml.push_str(""); + } + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth == 2 { + for attr in e.attributes().with_checks(false).flatten() { + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + return true; + } + } + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false +} + +fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); + xml.push_str(root); + xml.push_str(compat_open); + xml.push_str(child_str); + xml.push_str(""); + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth >= 3 { + for attr in e.attributes().with_checks(false).flatten() { + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + return true; + } + } + } + } + Ok((_, quick_xml::events::Event::End(_))) => { + depth -= 1; + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false +} + +fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { + let root = if root_tag.starts_with('<') { + root_tag + } else { + r#""# + }; + let mut xml = String::with_capacity(root.len() + compat_tag.len() + 32); + xml.push_str(root); + xml.push_str(compat_tag); + if !compat_tag.ends_with("/>") { + xml.push_str(""); + } else { + xml.push_str(""); + } + let mut reader = quick_xml::NsReader::from_str(&xml); + let mut depth = 0; + loop { + match reader.read_resolved_event() { + Ok((_, quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e))) => { + depth += 1; + if depth == 2 { + for attr in e.attributes().with_checks(false).flatten() { + let key = attr.key.as_ref(); + if key.starts_with(b"xmlns:") || key == b"xmlns" { + continue; + } + let (res, local) = reader.resolver().resolve_attribute(attr.key); + if local.as_ref() == b"id" + && let quick_xml::name::ResolveResult::Bound(ns) = res + && is_rel_ns(ns.as_ref()) + { + continue; + } + return true; + } + break; + } + } + Ok((_, quick_xml::events::Event::Eof)) | Err(_) => break, + _ => {} + } + } + false } /// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps /// it for [`merge`]. False for parts WordCraft wrote itself, and for anything it can't scan. pub fn has_unowned(original: &[u8]) -> bool { let Some(xml) = std::str::from_utf8(original).ok() else { return false }; - let Some((_, _, kids)) = children(xml, "w:settings") else { return false }; + let Some((o_start, open_end, _, kids)) = children(xml, "w:settings") else { return false }; + let root_tag = xml.get(o_start..open_end).unwrap_or(""); if kids.iter().any(|child| child.name == "w:mailMerge") { let Some(parsed) = crate::xml::parse(original).ok() else { return false }; if kids.len() == parsed.els().count() @@ -339,13 +895,26 @@ pub fn has_unowned(original: &[u8]) -> bool { return true; } } - kids.iter().any(|k| match k.name.as_str() { - // Anything in `w:compat` beyond its own tag and the compatibility mode. - "w:compat" => xml.get(k.start..k.end).is_some_and(|c| { - let mode = usize::from(c.contains("w:name=\"compatibilityMode\"")); - c.matches(" 0 - }), - n => !OWNED.contains(&n), + kids.iter().any(|k| { + if is_wml_compat_container(root_tag, xml, k) { + xml.get(k.start..k.end).is_some_and(|c| { + let open_end = tag_end(c).map(|e| e + 1).unwrap_or(0); + let compat_open = c.get(..open_end).unwrap_or(""); + if tag_has_rel_id(root_tag, compat_open) { + return false; + } + if compat_has_unmodeled_attrs(root_tag, compat_open) { + return true; + } + let Some((_, _, _, compat_kids)) = children(c, &k.name) else { return false }; + compat_kids.iter().any(|kid| { + !is_compat_mode_child(root_tag, c, kid) + && c.get(kid.start..kid.end).is_some_and(|child_str| !child_has_rel_id(root_tag, compat_open, child_str)) + }) + }) + } else { + !OWNED.contains(&k.name.as_str()) && !xml.get(k.start..k.end).is_some_and(|s| s.contains("r:id=")) + } }) } @@ -353,8 +922,8 @@ pub fn has_unowned(original: &[u8]) -> bool { pub fn merge(original: &[u8], generated: &[u8]) -> Option> { let orig = std::str::from_utf8(original).ok()?; let gen_s = std::str::from_utf8(generated).ok()?; - let (o_open, o_close, mut o_kids) = children(orig, "w:settings")?; - let (_, _, g_kids) = children(gen_s, "w:settings")?; + let (o_start, o_open, o_close, mut o_kids) = children(orig, "w:settings")?; + let (_, _, _, g_kids) = children(gen_s, "w:settings")?; // Mail merge is regenerated from the namespace-aware tree. Recognise the same children // here, including local/default aliases, so a recovered save can remove the original too. // Keep every other child's existing byte-preserving merge policy. @@ -370,7 +939,8 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { } } // Prefixes the generated children use must be declared by the original root. - let root_tag = orig.get(..o_open)?; + let root_tag = orig.get(o_start..o_open)?; + let preamble = orig.get(..o_start)?; for p in ["w", "m", "r"] { if g_kids.iter().any(|k| k.name.starts_with(&format!("{p}:"))) && !root_tag.contains(&format!("xmlns:{p}=")) { return None; @@ -426,10 +996,12 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { if let Some(gi) = mark(&k.name, &mut used) { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } - } else if k.name == "w:compat" { + } else if is_wml_compat_container(root_tag, orig, k) { let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); - let merged = merge_compat(root_tag, text, g_compat.as_deref().unwrap_or(""))?; - out.push((k.name.clone(), merged)); + let merged = merge_compat(root_tag, text, &k.name, g_compat.as_deref().unwrap_or(""))?; + if !merged.is_empty() { + out.push(("w:compat".to_string(), merged)); + } } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); } @@ -444,6 +1016,7 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.insert(at, (g.name.clone(), g_text(g)?)); } let mut s = String::with_capacity(orig.len() + 256); + s.push_str(preamble); s.push_str(root_tag); for (_, t) in &out { s.push_str(t); @@ -587,5 +1160,206 @@ mod tests { let out_esc = String::from_utf8(merge(orig_escaped.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); assert!(!out_esc.contains("compatibility"), "{out_esc}"); assert!(out_esc.contains("overrideTableStyleFontSizeAndJustification"), "{out_esc}"); + + // Leading whitespace before w:settings and root-declared alias + let orig_ws = r#" + "#; + let out_ws = String::from_utf8(merge(orig_ws.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_ws.contains("compatibilityMode"), "{out_ws}"); + assert!(out_ws.contains("overrideTableStyleFontSizeAndJustification"), "{out_ws}"); + } + + #[test] + fn compat_block_closing_tag_with_whitespace_preserves_unowned_children() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes()), "expected has_unowned with "); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("compatibilityMode"), "{merged}"); + } + + #[test] + fn compat_mode_matching_ignores_unqualified_attributes() { + // A compatSetting with unqualified name="compatibilityMode" (no namespace) and w:name="vendorOption" + let orig = r#""#; + // Since it's not a true compatibilityMode, has_unowned treats it as unowned vendor setting + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + // The vendor setting is preserved on save + assert!(merged.contains(r#"w:name="vendorOption""#), "{merged}"); + } + + #[test] + fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() { + let orig_two = r#""#; + // Disabled in generated: both must be removed + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + + // Enabled in generated: exactly one occurrence emitted + let gen_enabled = r#""#; + let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}"); + assert!(out_enabled.contains(""), "{out_enabled}"); + } + + #[test] + fn new_compat_switches_are_inserted_in_schema_order() { + // spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}"); + } + + #[test] + fn aliased_compat_container_and_switches_synchronize() { + // Document uses aliased prefix a: for WordprocessingML + let orig = r#""#; + // User disabled switch + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + } + + #[test] + fn clearing_mode_removes_every_matching_word_mode() { + // Multiple Word mode entries (e.g. 15 and 14) and one vendor entry + let orig = r#""#; + let gen_no_mode = + r#""#; + let out = String::from_utf8(merge(orig.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains(r#"w:val="15""#), "{out}"); + assert!(!out.contains(r#"w:val="14""#), "{out}"); + assert!(out.contains(r#"w:uri="urn:vendor""#), "{out}"); + } + + #[test] + fn mode_attribute_lookup_precedence_matches_reader() { + // Fallback to unqualified uri="urn:vendor" excludes vendor entry + let orig_vendor_uri = r#""#; + assert!(has_unowned(orig_vendor_uri.as_bytes())); + + // Fallback to unqualified name="compatibilityMode" when w:name is absent recognizes mode + let orig_unqual_name = r#""#; + let gen_no_mode = + r#""#; + let out = String::from_utf8(merge(orig_unqual_name.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains("compatibilityMode"), "{out}"); + assert!(out.contains(""), "{out}"); + } + + #[test] + fn aliased_compat_container_orders_before_math_pr() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_compat = merged.find("").unwrap(); + let idx_math = merged.find("").unwrap(); + assert!(idx_compat < idx_math, "a:compat must precede m:mathPr: {merged}"); + } + + #[test] + fn comment_with_closing_tag_syntax_does_not_interfere() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn foreign_child_is_ignored_when_finding_switch_insertion_point() { + // x:spacingInWholePoints precedes w:ulTrailSpace + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_custom = merged.find("").unwrap(); + let idx_trail = merged.find("").unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_custom < idx_trail, "custom before trail: {merged}"); + assert!(idx_trail < idx_shift, "trail before shift: {merged}"); + assert!(idx_shift < idx_spacing, "shift before spacing: {merged}"); + } + + #[test] + fn self_closing_compat_container_with_unmodeled_attr_is_retained() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes()), "expected self-closing compat with unmodeled attr to be retained"); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:layout="legacy""#), "{merged}"); + } + + #[test] + fn unmodeled_attributes_on_enabled_switch_are_preserved() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); + } + + #[test] + fn generated_compat_child_in_vendor_rebound_w_prefix_declares_wml_namespace() { + // Document binds prefix 'w' locally to urn:vendor on a:compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#""#), "{merged}"); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn aliased_compat_drops_unremapped_relationship_markup_while_preserving_relationship_free_markup() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(merged.contains(r#"x:note="example r:id=text""#), "text mentioning r:id= must be preserved: {merged}"); + assert!(!merged.contains("rId5"), "expected unremapped r:id to be omitted: {merged}"); + assert!(!merged.contains("rId6"), "expected unremapped rel:id to be omitted: {merged}"); + assert!(!merged.contains("rId7"), "expected unremapped spaced r:id to be omitted: {merged}"); + } + + #[test] + fn switch_with_padded_zero_value_is_enabled_when_model_enables_it() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"w:val="1""#), "{merged}"); + assert!(merged.contains(r#"x:vendor="custom""#), "{merged}"); + } + + #[test] + fn aliased_compat_container_with_bom_and_cleared_mode_removes_old_mode() { + let orig = "\u{FEFF}"; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged_bytes = merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap(); + let merged = String::from_utf8(merged_bytes).unwrap(); + assert!(merged.starts_with('\u{FEFF}'), "expected BOM to be preserved in output: {merged}"); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("compatibilityMode"), "expected compatibilityMode to be removed: {merged}"); + } + + #[test] + fn aliased_compat_drops_strict_relationship_markup() { + let orig = r#""#; + assert!(has_unowned(orig.as_bytes())); + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(""), "{merged}"); + assert!(!merged.contains("rId8"), "expected Strict r:id to be omitted: {merged}"); } } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 21dfd82505..8e735a0903 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -1672,6 +1672,17 @@ fn hyperlink_history_attribute_preservation_round_trips() { let saved_zero = craft_docx::write(&read_zero).unwrap(); let resaved_zero_xml = doc_xml_of(&saved_zero); assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}"); + + // Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false) + let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#); + assert_ne!(orig_doc_xml, xml_padded_zero); + let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes()); + + let read_padded = craft_docx::read(&file_padded).unwrap(); + assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(false)); + let saved_padded = craft_docx::write(&read_padded).unwrap(); + let resaved_padded_xml = doc_xml_of(&saved_padded); + assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}"); } /// Tools › Templates and Add-ins: the attached template (an external relationship of the settings diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index 553d23b7d3..5c1ccf3dff 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -229,9 +229,39 @@ fn cleared_compatibility_mode_removes_it_from_merged_settings() { let s2 = text(&files2, "word/settings.xml"); assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); assert!(s2.contains(""), "{s2}"); + assert!(s2.contains(""), "expected switch preserved: {s2}"); assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); assert_eq!(reopened2.settings.compat_mode, None); + assert!(reopened2.settings.do_not_expand_shift_return); +} + +#[test] +fn foreign_namespace_compat_child_is_preserved_through_round_trip() { + let settings = r#" +"#; + let pkg = with_settings(settings); + let doc = craft_docx::read(&pkg).unwrap(); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + let saved = save(&doc); + let s = text(&saved, "word/settings.xml"); + assert!(s.contains(" +"#; + let pkg = with_settings(settings); + let mut doc = craft_docx::read(&pkg).unwrap(); + assert!(doc.passthrough.contains_key("wordcraft:settings.orig")); + doc.settings.compat_mode = None; + let saved = save(&doc); + let s = text(&saved, "word/settings.xml"); + assert!(s.contains(""), "expected unowned setting preserved: {s}"); + assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}"); } From 18d3d383c3581ec1fbe9c5518de960861832d316 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:31:02 +0530 Subject: [PATCH 040/154] style(docx): format settings_merge.rs --- crates/docx/src/write/settings_merge.rs | 41 ++++++++----------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 61c096b565..5437aece4a 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -171,9 +171,9 @@ fn tag_end(s: &str) -> Option { None } -/// The root start tag's span end and the root's direct children, or `None` for anything the -/// scanner doesn't expect (CDATA, DOCTYPE, a different root). -fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { +/// The root start tag's span start, span end, close tag start, and the root's direct children, +/// or `None` for anything the scanner doesn't expect (CDATA, DOCTYPE, a different root). +fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> { let open = xml.find(&format!("<{root}"))?; let open_end = open + tag_end(xml.get(open..)?)? + 1; if xml.get(open_end - 2..open_end)? == "/>" { @@ -273,11 +273,8 @@ where F: FnOnce(&quick_xml::events::BytesStart<'_>, &quick_xml::NsReader<&[u8]>, &[u8]) -> bool, { let Some(child_str) = compat_s.get(k.start..k.end) else { return false }; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let Some(compat_open_end) = tag_end(compat_s).map(|e| e + 1) else { return false }; let Some(compat_open) = compat_s.get(..compat_open_end) else { return false }; let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); @@ -449,11 +446,8 @@ fn is_wml_compat_switch(root_tag: &str, compat_s: &str, k: &Child) -> bool { fn is_wml_compat_container(root_tag: &str, orig: &str, k: &Child) -> bool { let Some(child_str) = orig.get(k.start..k.end) else { return false }; - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let Some(open_end) = tag_end(child_str).map(|e| e + 1) else { return false }; let Some(open_tag) = child_str.get(..open_end) else { return false }; let mut xml = String::with_capacity(root.len() + open_tag.len() + 64); @@ -758,11 +752,8 @@ fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> } fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + tag_str.len() + 32); xml.push_str(root); xml.push_str(tag_str); @@ -798,11 +789,8 @@ fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { } fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + compat_open.len() + child_str.len() + 32); xml.push_str(root); xml.push_str(compat_open); @@ -837,11 +825,8 @@ fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool } fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { - let root = if root_tag.starts_with('<') { - root_tag - } else { - r#""# - }; + let root = + if root_tag.starts_with('<') { root_tag } else { r#""# }; let mut xml = String::with_capacity(root.len() + compat_tag.len() + 32); xml.push_str(root); xml.push_str(compat_tag); From 87528f2fb96b40d55b23b3ab42ae31fd1e512fce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:11:06 -0800 Subject: [PATCH 041/154] Preferences: PreferencesWindow::page_steps adds Previous and Next to the footer With page_steps, the window's footer starts with Previous and Next buttons. They show the page before and after the shown one among the pages the search lists, and each is disabled at its end of the list. Only the paged layout shows them; a window of cards scrolls from page to page and keeps its narrower minimum width. PreferencesPageOutput::listed reports the ids of the listed pages, which the window reads to find the neighbors of the shown page. --- .../src/patterns/preferences/page.rs | 15 ++-- .../src/patterns/preferences/window.rs | 56 +++++++++++- .../src/patterns/preferences/words.rs | 2 + .../ui-patterns/tests/it/preferences/mod.rs | 1 + .../ui-patterns/tests/it/preferences/steps.rs | 90 +++++++++++++++++++ 5 files changed, 155 insertions(+), 9 deletions(-) create mode 100644 crates/ui-patterns/tests/it/preferences/steps.rs diff --git a/crates/ui-patterns/src/patterns/preferences/page.rs b/crates/ui-patterns/src/patterns/preferences/page.rs index f3371fc6db..3092d0fd74 100644 --- a/crates/ui-patterns/src/patterns/preferences/page.rs +++ b/crates/ui-patterns/src/patterns/preferences/page.rs @@ -74,6 +74,8 @@ pub struct PreferencesPageOutput { /// The id of the page shown, `None` when the search lists no page. With [`PreferencesLayout::Cards`], the picked /// page while the search lists it, else the first card. pub page: Option, + /// The ids of the pages the search lists, in order: the page list's rows, or the cards. + pub listed: Vec, } impl Outcome for PreferencesPageOutput { @@ -99,6 +101,7 @@ struct PageRun { work: PreferencesState, out: BodyOut, page: Option, + listed: Vec, } impl<'a> PreferencesPage<'a> { @@ -127,20 +130,20 @@ impl<'a> PreferencesPage<'a> { } let matcher = Matcher::new(&env.folder(), work.search.trim()); let mut out = BodyOut::default(); - let page = match layout { + let (page, listed) = match layout { PreferencesLayout::Paged => { let snap = snapshot(&*host, &matcher, &work.selected); show_body(ui, &mut *host, &snap, &mut work, &words, &units, &mut out); - snap.shown.map(|page| page.id) + (snap.shown.map(|page| page.id), snap.list.into_iter().map(|entry| entry.id).collect()) } PreferencesLayout::Cards => { let snap = cards_snapshot(&*host, &matcher); show_cards(ui, &mut *host, &snap, &mut work, &words, &units, &mut out); let shown = snap.shown.iter().find(|page| page.id == work.selected).or(snap.shown.first()); - shown.map(|page| page.id.clone()) + (shown.map(|page| page.id.clone()), snap.shown.into_iter().map(|page| page.id).collect()) } }; - PageRun { before, work, out, page } + PageRun { before, work, out, page, listed } }); let pick_color = shown .settle(|cx, run| { @@ -161,8 +164,8 @@ impl<'a> PreferencesPage<'a> { run.out.rows.pick_color.take() }) .flatten(); - let page = shown.inner.and_then(|run| run.page); - PreferencesPageOutput { response: shown.output, pick_color, page } + let (page, listed) = shown.inner.map_or((None, Vec::new()), |run| (run.page, run.listed)); + PreferencesPageOutput { response: shown.output, pick_color, page, listed } } } diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index 5aac4deae9..9171866e2c 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -9,10 +9,13 @@ use super::model::PreferencesModel; use super::model::{Closed, PreferencesDraft, PreferencesOutput}; use super::page::{PreferencesLayout, PreferencesPage}; use super::words::PreferencesWords; -use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _}; +use crate::buttons::Button; +use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _, clicked}; use crate::dialog::{Dialog, DialogOutput}; +use crate::layout_components::Row; use crate::notices::{Notice, NoticeLayout}; use crate::runtime::env::{Env, Label}; +use crate::runtime::frame::request_repaint; use crate::runtime::memory::StageAccess; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; @@ -78,6 +81,9 @@ pub struct PreferencesState { /// opens narrower, as it needs no room for a page list. /// - **Live mode.** [`PreferencesMode::Live`] applies changes as they occur and shows only OK, which closes without /// applying again. Closing the window does not cancel changes. A failed apply shows its message until another edit. +/// - **Page steps.** [`page_steps`](PreferencesWindow::page_steps) adds Previous and Next to the footer. They pick the +/// page before and after the shown one among the pages the search lists, and each is disabled at its end of the +/// list. A window of cards, which scrolls from page to page, does not show them. /// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to /// close; [`PreferencesModel::nested`] draws the nested dialogs with the body's `Ui`, inside the window's own /// viewport. @@ -109,6 +115,10 @@ pub struct PreferencesWindow<'a> { /// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing. #[prop(flag)] escape_keeps_typing: bool, + /// Adds Previous and Next to the footer, which pick the listed page before and after the shown one. Only + /// [`PreferencesLayout::Paged`] shows them. + #[prop(flag)] + page_steps: bool, } /// What the body, the footer and the buttons' guard share during one pass: the host, the window's state as the pass @@ -121,6 +131,8 @@ struct Session<'h, 'b, H: ?Sized> { before: PreferencesState, work: PreferencesState, page: Option, + /// The listed pages before and after the shown one, which Previous and Next pick. + steps: (Option, Option), applied: bool, } @@ -158,6 +170,21 @@ impl Session<'_, '_, H> { self.commit(cx); ok } + + /// Picks the page `page` (Previous or Next) and writes the state, so the next pass shows it. + fn step(&mut self, cx: &mut impl StageAccess, page: Option) { + if let Some(page) = page { + self.work.selected = page; + self.commit(cx); + } + } +} + +/// The pages of `listed` before and after `shown`. +fn neighbors(listed: &[String], shown: Option<&str>) -> (Option, Option) { + let Some(at) = listed.iter().position(|id| Some(id.as_str()) == shown) else { return (None, None) }; + let before = at.checked_sub(1).and_then(|at| listed.get(at)); + (before.cloned(), listed.get(at + 1).cloned()) } impl<'a> PreferencesWindow<'a> { @@ -171,12 +198,14 @@ impl<'a> PreferencesWindow<'a> { mode: PreferencesMode::Staged, layout: PreferencesLayout::Paged, escape_keeps_typing: false, + page_steps: false, } } /// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it. pub fn show(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput { - let PreferencesWindow { state, title, embedded, remember, mode, layout, escape_keeps_typing } = self; + let PreferencesWindow { state, title, embedded, remember, mode, layout, escape_keeps_typing, page_steps } = self; + let page_steps = page_steps && layout == PreferencesLayout::Paged; let env = Env::of(ui); let words = env.words::(); let common = env.words::(); @@ -207,6 +236,7 @@ impl<'a> PreferencesWindow<'a> { before: PreferencesState::default(), work: PreferencesState::default(), page: None, + steps: (None, None), applied: false, }); let mut dialog = Dialog::new(title.clone()) @@ -228,7 +258,24 @@ impl<'a> PreferencesWindow<'a> { dialog = dialog.remember(key); } let shown = dialog - .footer(|ui, _| { + .footer(|ui, cx| { + if page_steps { + let (before, after) = session.borrow().steps.clone(); + let mut picked = None; + Row::new().show(ui, |ui, _| { + for (label, key, page) in [(&words.previous, "previous", &before), (&words.next, "next", &after)] { + let button = Button::new(label.clone()).enabled(page.is_some() && !nested).id_salt(key).show(ui); + if clicked(&button) { + picked.clone_from(page); + } + } + }); + // The footer is measured in a sizing pass before it is shown; only the shown pass steps. + if !ui.is_sizing_pass() && picked.is_some() { + session.borrow_mut().step(cx.dialog(), picked); + request_repaint(ui.ctx()); + } + } let message = session.borrow().work.error.clone(); if let Some(message) = message { Notice::new(Tone::Bad, Label::from(message)).layout(NoticeLayout::Inline).show(ui); @@ -249,6 +296,9 @@ impl<'a> PreferencesWindow<'a> { if mode == PreferencesMode::Live && session.work.error.is_none() && session.host.differs() { session.apply(cx); } + if page_steps { + session.steps = neighbors(&shown.listed, shown.page.as_deref()); + } session.page = shown.page; session.commit(cx); }); diff --git a/crates/ui-patterns/src/patterns/preferences/words.rs b/crates/ui-patterns/src/patterns/preferences/words.rs index 47c137b7b4..76d3a35aca 100644 --- a/crates/ui-patterns/src/patterns/preferences/words.rs +++ b/crates/ui-patterns/src/patterns/preferences/words.rs @@ -15,6 +15,8 @@ craft_ui::words! { no_matches: "preferences.noMatches" = "No matching settings"; empty_page: "preferences.emptyPage" = "These settings aren't available yet."; apply: "preferences.apply" = "Apply"; + previous: "preferences.previous" = "Previous"; + next: "preferences.next" = "Next"; reset_section: "preferences.resetSection" = "Reset Section"; hex_label: "preferences.hexLabel" = "Hex color"; default_hint: "preferences.defaultHint" = "Default"; diff --git a/crates/ui-patterns/tests/it/preferences/mod.rs b/crates/ui-patterns/tests/it/preferences/mod.rs index 600067679f..8be62c1ec4 100644 --- a/crates/ui-patterns/tests/it/preferences/mod.rs +++ b/crates/ui-patterns/tests/it/preferences/mod.rs @@ -5,3 +5,4 @@ pub(crate) mod live; pub(crate) mod model; pub(crate) mod page; pub(crate) mod path_setting; +pub(crate) mod steps; diff --git a/crates/ui-patterns/tests/it/preferences/steps.rs b/crates/ui-patterns/tests/it/preferences/steps.rs new file mode 100644 index 0000000000..3ee161691f --- /dev/null +++ b/crates/ui-patterns/tests/it/preferences/steps.rs @@ -0,0 +1,90 @@ +//! Previous and Next in the preferences window's footer. + +use craft_ui::contract::Bind; +use craft_ui::patterns::preferences::{ + PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec, +}; +use craft_ui::testing::{Fixture, trial}; +use egui::Ui; +use std::cell::RefCell; +use std::rc::Rc; + +struct Model; + +impl PreferencesModel for Model { + fn pages(&self) -> Vec> { + ["General", "Type", "Units"] + .into_iter() + .map(|title| PageSpec::new(title, title, vec![RowSpec::new(title, title, RowKind::Bool(false))])) + .collect() + } + fn set(&mut self, _: &str, _: PrefValue) {} + fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn reset_page(&mut self, _: &str) {} +} + +impl PreferencesDraft for Model { + fn differs(&self) -> bool { + false + } + fn apply(&mut self) -> Result<(), String> { + Ok(()) + } + fn cancel(&mut self) {} +} + +/// A window with Previous and Next, and the page it shows after each pass. +fn window() -> (Fixture, Rc>>) { + let page = Rc::new(RefCell::new(None)); + let seen = page.clone(); + let mut state = PreferencesState::default(); + let fixture = Fixture::new(move |ui| { + let shown = PreferencesWindow::new(Bind::bound(&mut state)).page_steps().embedded().show(ui, &mut Model); + *seen.borrow_mut() = shown.page; + }); + (fixture, page) +} + +/// Whether the footer button `label` is disabled. +fn disabled(fixture: &Fixture, label: &str) -> bool { + let button = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} button")); + fixture.tree().is_disabled_key(button.node) +} + +#[trial] +fn next_and_previous_step_through_the_pages() { + let (mut fixture, page) = window(); + fixture.settle(); + assert_eq!(page.borrow().as_deref(), Some("General")); + assert!(disabled(&fixture, "Previous"), "the first page has no page before it"); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Type"), "Next shows the next page"); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Units")); + assert!(disabled(&fixture, "Next"), "the last page has no page after it"); + let previous = fixture.by_label("Previous").expect("the Previous button"); + fixture.click(&previous).settle(); + assert_eq!(page.borrow().as_deref(), Some("Type"), "Previous shows the page before"); +} + +#[trial] +fn the_steps_follow_the_pages_the_search_lists() { + let (mut fixture, page) = window(); + fixture.settle(); + let search = fixture.by_label("Search settings").expect("the search field"); + fixture.click(&search).settle(); + // Lists General and Units, not Type. + fixture.type_text("n").settle(); + assert_eq!(page.borrow().as_deref(), Some("General")); + let next = fixture.by_label("Next").expect("the Next button"); + fixture.click(&next).settle(); + assert_eq!(page.borrow().as_deref(), Some("Units"), "Next passes over the page the search hides"); + assert!(disabled(&fixture, "Next"), "Units is the last listed page"); +} From ff5bb9b5c781ae8438058d5080ff9a321110e85c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:36:27 -0800 Subject: [PATCH 042/154] Preferences: PreferencesWindow::size sets the size the window opens at The window opened at DEFAULT_SIZE (1040 by 800) with the page list, or the cards' own size, and a host had no way to choose another. `size` opens it at the given size until the user resizes it. The window's least size still applies, and a size that is not finite is ignored. Without `size` the window opens as before. --- .../src/patterns/preferences/window.rs | 13 +++- .../ui-patterns/tests/it/preferences/mod.rs | 1 + .../ui-patterns/tests/it/preferences/size.rs | 64 +++++++++++++++++++ 3 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 crates/ui-patterns/tests/it/preferences/size.rs diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index 9171866e2c..0de80126e9 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -90,8 +90,8 @@ pub struct PreferencesState { /// - **App-modal.** While the window is open the app's other windows take no input, show the blocked cursor and /// refuse to close, and a press on one raises the window. /// - **Placement.** The window opens in its own OS window where there are any, else as a modal dialog layer -/// ([`embedded`](PreferencesWindow::embedded) forces the layer). [`remember`](PreferencesWindow::remember) keeps -/// its place and size across runs. +/// ([`embedded`](PreferencesWindow::embedded) forces the layer). [`size`](PreferencesWindow::size) sets the size it +/// opens at. [`remember`](PreferencesWindow::remember) keeps its place and size across runs. #[must_use = "show the window with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] pub struct PreferencesWindow<'a> { @@ -111,6 +111,11 @@ pub struct PreferencesWindow<'a> { /// Lays the page out as `layout` says ([`PreferencesPage::layout`]); the default is [`PreferencesLayout::Paged`]. #[prop] layout: PreferencesLayout, + /// The size the window opens at until the user resizes it, in place of the layout's own ([`DEFAULT_SIZE`] for + /// pages, a narrower one for cards). A size under the layout's least ([`MIN_SIZE`] for pages) opens at the least; + /// a size that is not finite is ignored. + #[prop] + size: Option, /// Escape keeps the typing in the focused field ([`Dialog::escape_keeps_typing`]): in [`PreferencesMode::Live`] /// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing. #[prop(flag)] @@ -197,6 +202,7 @@ impl<'a> PreferencesWindow<'a> { remember: None, mode: PreferencesMode::Staged, layout: PreferencesLayout::Paged, + size: None, escape_keeps_typing: false, page_steps: false, } @@ -204,7 +210,7 @@ impl<'a> PreferencesWindow<'a> { /// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it. pub fn show(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput { - let PreferencesWindow { state, title, embedded, remember, mode, layout, escape_keeps_typing, page_steps } = self; + let PreferencesWindow { state, title, embedded, remember, mode, layout, size: asked, escape_keeps_typing, page_steps } = self; let page_steps = page_steps && layout == PreferencesLayout::Paged; let env = Env::of(ui); let words = env.words::(); @@ -226,6 +232,7 @@ impl<'a> PreferencesWindow<'a> { PreferencesLayout::Paged => (DEFAULT_SIZE, MIN_SIZE), PreferencesLayout::Cards => (CARDS_SIZE, CARDS_MIN_SIZE), }; + let size = asked.filter(|asked| asked.is_finite()).unwrap_or(size); let mut open = true; // Filed by a swatch press in this pass. let mut pick_color = None; diff --git a/crates/ui-patterns/tests/it/preferences/mod.rs b/crates/ui-patterns/tests/it/preferences/mod.rs index 8be62c1ec4..74c6b85008 100644 --- a/crates/ui-patterns/tests/it/preferences/mod.rs +++ b/crates/ui-patterns/tests/it/preferences/mod.rs @@ -5,4 +5,5 @@ pub(crate) mod live; pub(crate) mod model; pub(crate) mod page; pub(crate) mod path_setting; +pub(crate) mod size; pub(crate) mod steps; diff --git a/crates/ui-patterns/tests/it/preferences/size.rs b/crates/ui-patterns/tests/it/preferences/size.rs new file mode 100644 index 0000000000..17512925f4 --- /dev/null +++ b/crates/ui-patterns/tests/it/preferences/size.rs @@ -0,0 +1,64 @@ +//! The size the preferences window opens at. + +use craft_ui::contract::{Bind, Role}; +use craft_ui::patterns::preferences::{ + MIN_SIZE, PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec, +}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Rect, Ui, Vec2, vec2}; + +struct Model; + +impl PreferencesModel for Model { + fn pages(&self) -> Vec> { + ["General", "Type"].into_iter().map(|title| PageSpec::new(title, title, vec![RowSpec::new(title, title, RowKind::Bool(false))])).collect() + } + fn set(&mut self, _: &str, _: PrefValue) {} + fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool { + false + } + fn reset_page(&mut self, _: &str) {} +} + +impl PreferencesDraft for Model { + fn differs(&self) -> bool { + false + } + fn apply(&mut self) -> Result<(), String> { + Ok(()) + } + fn cancel(&mut self) {} +} + +/// The bounds of the window opened with `size`, or at its own size without it, in a room larger than either. +fn opened(size: Option) -> Rect { + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + let mut window = PreferencesWindow::new(Bind::bound(&mut state)).embedded(); + if let Some(size) = size { + window = window.size(size); + } + let _ = window.show(ui, &mut Model); + }); + fixture.room(vec2(1600.0, 1200.0)).settle(); + fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect).unwrap_or_else(|| panic!("the preferences window")) +} + +#[trial] +fn the_window_opens_at_the_size_the_host_gives() { + let own = opened(None); + let asked = (own.size() + MIN_SIZE) / 2.0; + let smaller = opened(Some(asked)); + assert!(smaller.width() < own.width() && smaller.height() < own.height(), "{smaller:?} is not smaller than {own:?}"); + let larger = opened(Some(own.size() + vec2(100.0, 100.0))); + assert!(larger.width() > own.width() && larger.height() > own.height(), "{larger:?} is not larger than {own:?}"); +} + +#[trial] +fn a_size_that_is_not_finite_is_ignored() { + let endless = opened(Some(vec2(f32::INFINITY, f32::NAN))); + assert_eq!(endless.size(), opened(None).size(), "a size that is not finite opens the window at its own size"); +} From b0fac2df714610fc8535b9dd737630f17a20d9a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 21:37:28 -0800 Subject: [PATCH 043/154] Tool cursors: a tool's icon on the pointer is white over its halo, not tinted in the overlay color PaintedCursor::Tool and PaintedCursor::PointerTool painted the tool's icon as a silhouette in overlay.stroke, the color of canvas overlay marks. In a theme whose overlay color is an accent tint (#ffa492 in one of the bundled themes), every tool pointer drawn from an app's icon showed in that tint. The icon now paints in overlay.handle_fill, which is white in every theme, over the same overlay.halo copies. The marks the pointer art draws itself (hand, magnifier, rotate, distort, skew, type, locator, arrow, path text, badges and the brush outline) keep overlay.stroke, which the token documents for cursor marks drawn over the halo. Test: a_tool_icon_on_the_pointer_takes_no_overlay_tint renders a Tool and a crosshair PointerTool cursor image and finds no tinted pixel. It fails with the icon painted in overlay.stroke. --- .../ui-contract/src/primitives/pointer_art.rs | 22 ++++++++++++++----- crates/ui-contract/tests/it/runtime/cursor.rs | 19 ++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index 3c8b40a6cc..e9aaa7122f 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -34,6 +34,7 @@ pub(crate) fn pointer_art(env: &Env, cursor: &PaintedCursor, closed: bool, marks art: RefCell::new(Art::default()), fill: crate::style::rgba_color(overlay.stroke), 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(), }; @@ -186,12 +187,14 @@ 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 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 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). pub(crate) struct Pen { pub art: RefCell, pub fill: Color32, pub halo: Color32, + pub icon: Color32, pub thin: f32, pub rtl: bool, } @@ -342,7 +345,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 mark +/// A tool's `icon` of `side` points with `hotspot` (a point of the icon's 24-unit box) on the pointer, in the icon /// 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) { @@ -355,7 +358,7 @@ pub(crate) fn tool(pen: &Pen, icon: Option, hotspot: Vec2, badge: Optio } } -/// `icon` in `rect` in the mark colour, over copies of it a hairline off in each of eight directions in the halo. +/// `icon` in `rect` in the icon 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] { @@ -364,7 +367,7 @@ fn icon_on_halo(pen: &Pen, rect: Rect, icon: SvgIcon) { } } } - pen.push(Mark::Icon(rect, icon, pen.fill)); + pen.push(Mark::Icon(rect, icon, pen.icon)); } /// The I-beam centred on the pointer: its stem and two serifs, as rules so each lies on whole device pixels and the @@ -496,7 +499,14 @@ 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, thin: tokens.stroke.thin, rtl: direction.is_rtl() }; + let pen = Pen { + art: RefCell::new(Art::default()), + fill: ink, + halo: Color32::TRANSPARENT, + icon: ink, + 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 6787aacba4..47575a5d19 100644 --- a/crates/ui-contract/tests/it/runtime/cursor.rs +++ b/crates/ui-contract/tests/it/runtime/cursor.rs @@ -244,6 +244,25 @@ 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. +#[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"); + } +} + /// An unchanged pointer hands the window the same image, so the integration uploads it to the OS once; a new size or /// scale makes a new one; a frame whose winner is a system cursor, or that asks for nothing, clears it (egui keeps an /// image until it is replaced). From 36f3188816ba48b9fc441825acb3c03ae8f327e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:22:39 -0800 Subject: [PATCH 044/154] 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 045/154] 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 7e3945ec4e0face57a57afeb86867d0d8cfc2fde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:47:57 -0800 Subject: [PATCH 046/154] 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 4bb8e364291a0686833613acfdd8d8cfe1d83082 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:22:08 -0800 Subject: [PATCH 047/154] 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 048/154] 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 ebb483f68d5ff38f05a73ad5648c0676eab8b6c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:05:18 -0800 Subject: [PATCH 049/154] ui-widgets: a focused tab strip rings the tab the keyboard is on Tab, Shift-Tab and the arrow keys move the keyboard to a tab in a tab strip, but no focus ring marked it. A strip's tabs are members of the collection's run and have no focus step of their own, and the paint step rings a collection only around a focused part or itself, so nothing painted a ring for the lead tab. - Collection::rings_lead (ui-contract, off by default) asks the item step to set the collection's focus shape to the lead item's rect, or to the collection's own rect while it has no lead or its lead is not shown. paint_focus rings a collection around the shape it declared. - TabStrip turns it on. The ring follows the lead as the arrow keys move it; how the arrows move between tabs and which tab is shown do not change. --- .../ui-contract/src/contract/items/hooks.rs | 14 +++- crates/ui-contract/src/contract/mod.rs | 7 ++ .../ui-contract/src/contract/steps/paint.rs | 5 +- crates/ui-widgets/src/tabs/strip.rs | 8 ++- crates/ui-widgets/tests/it/tabs.rs | 72 +++++++++++++++++++ 5 files changed, 102 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index a274babf17..eb57004a60 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -333,7 +333,19 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.requested_reveal(comp, &layout); self.type_ahead(comp, cx, &layout, lead_at); self.rest_lead(cx, &layout, seen); - request::record_lead(&cx.core.ctx, cx.core.id, self.lead.key.as_ref().and_then(|key| self.index_of(key))); + let lead_now = self.lead.key.as_ref().and_then(|key| self.index_of(key)); + request::record_lead(&cx.core.ctx, cx.core.id, lead_now); + // A collection whose lead item shows the focus ring takes the ring around that item while it is shown, and + // around itself while it has no lead or its lead is not shown, so its focus always shows. + if comp.rings_lead() { + cx.core.focus_shape = Some(match lead_now.filter(|&at| layout.shown(at)) { + Some(at) => { + let row = self.screen(&layout, rect, at, offset, rtl); + focus::FocusShape::Polygon(vec![row.left_top(), row.right_top(), row.right_bottom(), row.left_bottom()]) + } + None => focus::FocusShape::Rect, + }); + } if let Some(at) = self.page_reveal.take().filter(|&at| layout.shown(at)) { cx.core.reveal = Some(self.screen(&layout, rect, at, ScrollPos::default(), rtl)); } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 60c7bfd0c1..4d734f3554 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -688,6 +688,13 @@ pub trait Collection: Component + HasProps + Meta { None } + /// Whether the focus ring goes around the lead item while the collection has keyboard-visible focus: the item step + /// gives the ring the lead's rect (`Cx::focus_shape`), or the collection's own rect while it has no lead or its + /// lead is not shown. Off by default. + fn rings_lead(&self) -> bool { + false + } + /// Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this /// makes, under the row-hook contract on `ItemCx`. fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r> { diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 0360b61534..083f7c1616 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -114,7 +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, and never around a collection (`whole` false), whose lead item shows the focus. +/// on `Well` surfaces. A collection (`whole` false) shows a ring only around the shape it declared +/// (`Collection::rings_lead`). 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(); @@ -125,7 +126,7 @@ pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView, who 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 whole && FocusRing::visible(flags) && !well { + } else if (whole || core.focus_shape.is_some()) && 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/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 97dce4ce93..76d89c3590 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -122,7 +122,8 @@ 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: the focus ring of its end items; its row is as high as its tabs. +/// The look of a strip: the focus ring of its end items and of the tab the keyboard is on; its row is as high as its +/// tabs. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct TabStripStyle { @@ -1072,6 +1073,11 @@ impl Collection StripLayout::new(count, Vec2::new(width, cx.tokens.size.bar.tab), tab_gap, fitting, self.report.clone(), cx.frame_ctx().clone()) } + /// The tab the keyboard is on shows the focus ring, not the whole strip. + fn rings_lead(&self) -> bool { + true + } + /// Every tab takes the strip's kind, panel look and size. fn dress<'r>(&self, tab: Self::Item<'r>, _: &RowState) -> Self::Item<'r> { let tab = tab.kind(self.kind).panel_look(self.panel_look); diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index 46c6e6a41c..54e09dc946 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -206,6 +206,78 @@ fn an_arrow_moves_the_focus_and_enter_shows_the_tab() { assert_eq!(shown.get(), 1, "Enter shows the focused tab"); } +/// The rects of the focus rings in `shapes`: rect strokes and closed outlines at least two points wide. +fn rings(shapes: &[egui::Shape]) -> Vec { + shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + egui::Shape::Path(path) if path.closed && path.stroke.width >= 2.0 => Some(Rect::from_points(&path.points)), + _ => None, + }) + .collect() +} + +/// Whether a ring in `rings` goes around `target` and no other tab: it holds the target and is not much wider. +fn ringed(rings: &[Rect], target: Rect) -> bool { + rings.iter().any(|ring| ring.expand(1.0).contains_rect(target) && ring.width() < target.width() * 1.5) +} + +/// Tab to a strip rings its lead tab, not the whole strip, whether or not a press on a tab takes the focus; an arrow +/// moves the ring with the lead and leaves the shown tab as it is. +#[trial] +fn the_focused_strip_rings_its_lead_tab() { + for keeps in [false, true] { + let mut fixture = Fixture::new(move |ui| { + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + let strip = TabStrip::new("Documents").shown(0); + let strip = if keeps { strip.keeps_focus() } else { strip }; + let _ = strip.show_items(ui, &source, &mut |key, _| Tab::new(TITLES[*key])); + }); + fixture.settle(); + let rect = |fixture: &Fixture, label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the tab {label}")).rect; + let (one, two) = (rect(&fixture, "One"), rect(&fixture, "Two")); + let strip = fixture.by_role(Role::TAB_LIST).first().map(|node| node.rect).expect("the strip's node"); + assert!(rings(&fixture.frame_shapes()).is_empty(), "no ring before the keyboard reaches the strip (keeps_focus {keeps})"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let shown = rings(&fixture.frame_shapes()); + assert!(ringed(&shown, one), "Tab rings the lead tab (keeps_focus {keeps}): {shown:?}, tab {one:?}"); + assert!(!ringed(&shown, two), "the other tabs are not ringed (keeps_focus {keeps}): {shown:?}"); + assert!(!shown.iter().any(|ring| ring.expand(1.0).contains_rect(strip)), "no ring goes around the strip (keeps_focus {keeps}): {shown:?}"); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + let moved = rings(&fixture.frame_shapes()); + assert!(ringed(&moved, two) && !ringed(&moved, one), "the ring follows the lead (keeps_focus {keeps}): {moved:?}"); + } +} + +/// A focused strip whose lead tab the overflow menu holds rings the strip, so the focus still shows. +#[trial] +fn a_focused_strip_whose_lead_tab_is_hidden_rings_the_strip() { + let mut fixture = Fixture::new(|ui| { + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + let _ = TabStrip::new("Documents").shown(0).show_items(ui, &source, &mut |key, _| Tab::new(TITLES[*key])); + }); + fixture.room(egui::vec2(600.0, 100.0)).settle(); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + let three = fixture.by_label("Three").expect("the tab Three").rect; + assert!(ringed(&rings(&fixture.frame_shapes()), three), "the lead tab is ringed while it is shown"); + fixture.room(egui::vec2(120.0, 100.0)).settle(); + let strip = fixture.by_role(Role::TAB_LIST).first().map(|node| node.rect).expect("the strip's node"); + assert!( + fixture.by_label("More tabs").is_some() && fixture.by_label("Three").is_none_or(|node| !strip.contains_rect(node.rect)), + "the narrow strip sends the lead tab to the overflow menu" + ); + let shown = rings(&fixture.frame_shapes()); + assert!( + shown.iter().any(|ring| ring.expand(1.0).contains_rect(strip)), + "the strip is ringed while its lead is hidden: {shown:?}, strip {strip:?}" + ); +} + /// A click on a tab's close button closes the tab, and the close button is a node under its tab's node that an /// AccessKit Click closes. #[trial] From 170e0924b68021c1ad95596de096bf3fd4542d07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:39:44 -0800 Subject: [PATCH 050/154] dock: a narrow group's drag band leaves room for the host's header items The room a docked group's header keeps for the shown tab did not count the items the host adds before the tab strip (DockGroup::extra). The header parts are sized before the header runs, so in a narrow group the band kept its full width and the shown tab got what the host items left: 12.3 pt of the 44.4 pt a shrunk tab keeps in a 72 pt compact group with one host button. - ui-contract: layout_memory::emit_width and layout_memory::width hand forward a measured width as emit_text and text hand forward a text. It serves the rest of the pass, comes back with a kept measurement, and a memoized view that replays emits it again. - ui-panels: DockGroup's header hands forward the width its host items take, and the header parts add it to the room they keep before the band narrows. Until the header has handed it forward, and in groups without host items, the band narrows as before. Tests: a_narrow_groups_drag_band_leaves_room_for_the_hosts_header_items (both densities, both directions, one and two host items, one and two tabs), a_replayed_view_hands_forward_the_width_its_run_measured --- .../ui-contract/src/runtime/layout_memory.rs | 25 +++++++ .../tests/it/runtime/layout_memory.rs | 40 +++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + crates/ui-panels/src/docking/group.rs | 23 +++++- crates/ui-panels/tests/it/dock_group.rs | 72 +++++++++++++++++++ docs/contract-api.md | 2 + docs/craft-framework.md | 2 +- 7 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 crates/ui-contract/tests/it/runtime/layout_memory.rs diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index dbea6d3e98..2b09e02c69 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -100,6 +100,8 @@ enum Recorded { /// The width a row's shrink step gave a unit, as a measure, and whether it narrowed the unit or dropped it. Shrink(Measured, ShrinkGiven), Text(Option>), + /// A width a run measured that a step outside the run sizes by (`emit_width`). + Width(f32), } /// One thing a measuring run handed forward, in the order it did. @@ -536,6 +538,28 @@ pub fn text(ctx: &Context, id: Id) -> Option> { }) } +/// Hands forward a width a run measured under `id` that a step outside the content that measured it sizes by, as +/// [`emit_text`] hands forward a text (the room a container's header parts leave for items its host adds, for +/// example): it serves the rest of this pass, and a later pass that takes the kept measurement of a body it ran in +/// gets it with that measurement. A real run emits it too: a width that differs by more than the measuring tolerance +/// from the one a kept transcript gave the pass shows that transcript changed. +/// +/// A memoized view that replays emits it again. +pub fn emit_width(ctx: &Context, id: Id, width: f32) { + emit(ctx, id, Recorded::Width(width)); + super::replay::journal(ctx, || (id, width), |ctx, (id, width)| emit(ctx, *id, Recorded::Width(*width))); +} + +/// The width a run of this pass handed forward under `id` ([`emit_width`]), or a kept transcript gave this pass. +pub fn width(ctx: &Context, id: Id) -> Option { + let moment = Moment::of(ctx); + let pass = ctx.cumulative_pass_nr(); + with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass) { + Some(Found { recorded: Recorded::Width(width), .. }) => Some(*width), + _ => None, + }) +} + fn emit(ctx: &Context, id: Id, mut recorded: Recorded) { let moment = Moment::of(ctx); let pass = ctx.cumulative_pass_nr(); @@ -576,6 +600,7 @@ fn kept_differs(last: &Found, now: &Recorded, pass: u64, tolerance: f32) -> Opti let differs = match (was, now) { (Recorded::Measured(was), Recorded::Measured(now)) => measures(was, now, false), (Recorded::Shrink(was, was_given), Recorded::Shrink(now, now_given)) => measures(was, now, was_given != now_given), + (Recorded::Width(was), Recorded::Width(now)) => (was - now).abs() > tolerance, (was, now) => was != now, }; if *at != pass || !differs { diff --git a/crates/ui-contract/tests/it/runtime/layout_memory.rs b/crates/ui-contract/tests/it/runtime/layout_memory.rs new file mode 100644 index 0000000000..7c656d6347 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/layout_memory.rs @@ -0,0 +1,40 @@ +//! Layout memory's handoffs: what a run hands forward reaches code that reads it later in the pass. + +use craft_ui::contract::MemoView; +use craft_ui::runtime::layout_memory; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use egui::Id; +use std::cell::RefCell; +use std::rc::Rc; + +/// Where the view in these trials hands forward the width it measured. +fn handed() -> Id { + Id::NULL.with("handed width") +} + +/// A memoized view hands forward the width of what it shows. Code after the view reads that width in every pass, +/// the passes where the view replays included. +#[trial] +fn a_replayed_view_hands_forward_the_width_its_run_measured() { + let read: Rc>>> = Rc::default(); + let seen = Rc::clone(&read); + let mut fixture = Fixture::new(move |ui| { + let _ = MemoView::new("measuring", 1u32, |_: &mut u32, ui: &mut egui::Ui| { + let took = ui.label("Handed forward").rect.width(); + layout_memory::emit_width(ui.ctx(), handed(), took); + }) + .show(ui); + seen.borrow_mut().push(layout_memory::width(ui.ctx(), handed())); + }); + fixture.room(egui::Vec2::new(200.0, 100.0)); + fixture.settle(); + let ran = read.borrow().last().copied().flatten(); + assert!(ran.is_some_and(|width| width > 0.0), "the view's run hands forward its width: {ran:?}"); + for _ in 0..3 { + read.borrow_mut().clear(); + fixture.frame(Vec::new()); + let runs = last_frame_memo_runs(fixture.ctx()); + assert!(!runs.is_empty() && runs.iter().all(|(_, _, run)| *run == MemoRun::Replayed), "an idle frame replays the view: {runs:?}"); + assert!(read.borrow().iter().all(|width| *width == ran), "a replay hands forward the width the run measured: {:?}", read.borrow()); + } +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 1901607c05..573896b014 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod fingers; pub(crate) mod focus; pub(crate) mod frame; pub(crate) mod latch; +pub(crate) mod layout_memory; pub(crate) mod memory; pub(crate) mod part_request; pub(crate) mod paste; diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index a4426dbcdb..d991ea8952 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -19,6 +19,7 @@ use crate::primitives::{IconSpec, PaintShape}; use crate::runtime::commands::{self, CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusRequest, FocusTarget}; +use crate::runtime::layout_memory; use crate::runtime::memory::sub; use crate::sections::FooterBar; use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; @@ -230,6 +231,12 @@ fn grip_least(tokens: &Tokens) -> f32 { /// 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; +/// Where the header hands forward the width the host's items took before the tab strip, with the gap after them +/// (`layout_memory::emit_width`), keyed under the group's body id. +fn host_items_key(body: Id) -> Id { + sub(body, "host_items") +} + /// 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. @@ -720,11 +727,17 @@ impl Container for } /// 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. + /// them, the host's items and the shown tab's least room, the band narrows to an icon's room, so the shown tab stays + /// visible. The host's items count with the width the header last handed forward for them; before it has, they + /// count as none. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { 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)) } + if self.titled { + return parts; + } + let host = self.extra.as_ref().and_then(|_| layout_memory::width(cx.ui.ctx(), host_items_key(sub(cx.id, "body")))).unwrap_or(0.0); + parts.end_narrows(grip_least(cx.tokens) + button, host + self.shown_tab_least(cx)) } fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) { @@ -773,7 +786,13 @@ impl Container for } } if let Some(hook) = extra.as_mut() { + // The cursor moves past each item and the gap after it, so the distance it moves is the room the + // items take before the tab row. + let before = ui.cursor(); hook.run(ui, cx); + let after = ui.cursor(); + let took = if rtl { before.max.x - after.max.x } else { after.min.x - before.min.x }; + layout_memory::emit_width(ui.ctx(), host_items_key(cx.id), took.max(0.0)); } if titled { let close_name = cx.words::().close_panel.clone(); diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index 70e4217822..906f6ef7ae 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -345,6 +345,78 @@ fn a_narrow_groups_drag_band_narrows_before_the_shown_tab() { } } +// The host's items before the tab strip count in the room the header keeps: as a group with one or two of them narrows, +// at both densities and in both directions, the drag band narrows to its least before the shown tab goes below the +// width a shrunk tab keeps, and the host's items stay inside the group, clear of the band and the shown tab. +#[trial] +fn a_narrow_groups_drag_band_leaves_room_for_the_hosts_header_items() { + use craft_behavior::IconId; + use craft_theme::Size; + use craft_ui::buttons::IconButton; + use craft_ui::contract::Props as _; + use craft_ui::runtime::env::Direction; + const HOSTS: [&str; 2] = ["Host one", "Host two"]; + let tab = |width: f32, (density, direction): (Size, Direction), names: &'static [&'static str], hosts: usize| { + 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 group = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).extra(move |ui, _| { + for name in &HOSTS[..hosts] { + IconButton::new(IconId::new("settings")).label(*name).show(ui); + } + }); + let out = group.show_at(ui, group_rect, |_, _| ()); + seen.set(out.output.grip.map(|(rect, _)| rect)); + }); + fixture.density(density).direction(direction).settle(); + let host = HOSTS[..hosts].iter().map(|name| fixture.by_label(name).map(|node| node.rect)).collect::>(); + (fixture.by_label("Tools").map(|node| node.rect), grip.get(), host) + }; + for density in [Size::Compact, Size::Comfortable] { + // The least a tab shows, found as the trial above finds it, with no host items. + let least = (0..260) + .filter_map(|step| tab(300.0 - step as f32, (density, Direction::Ltr), &["Tools Options", "Tools"], 0).0) + .map(|rect| rect.width()) + .fold(f32::INFINITY, f32::min); + assert!(least.is_finite(), "the other tab shows shrunk in some group ({density:?})"); + let looks = [Direction::Ltr, Direction::Rtl].map(|direction| (density, direction)); + for (look, names) in looks.into_iter().flat_map(|look| [(look, &["Tools"][..]), (look, &["Tools", "Swatches"][..])]) { + for hosts in 1..=HOSTS.len() { + let (Some(natural), _, _) = tab(300.0, look, names, hosts) else { panic!("a wide group shows the tab ({look:?})") }; + let least = least.min(natural.width()); + let (_, Some(narrowest), _) = tab(40.0, look, names, 0) else { panic!("a 40 pt group shows the band ({look:?})") }; + for width in (0..17).map(|step| 40.0 + 8.0 * step as f32) { + let (shown, grip, host) = tab(width, look, names, hosts); + let case = format!("{width} pt, {look:?}, {names:?}, {hosts} host items"); + let Some(grip) = grip else { panic!("the band shows ({case})") }; + let group = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + // With no tab in the strip, the group's own node carries the shown panel's name. + let shown = shown.filter(|shown| shown.width() < group.width() - 0.5); + let shown_width = shown.map_or(0.0, |shown| shown.width()); + // A band above its least leaves the line room for the host's items. + if grip.width() > narrowest.width() + 0.5 { + for item in &host { + let Some(item) = item else { panic!("each host item shows ({case})") }; + assert!(group.contains_rect(*item), "the host item {item:?} lies inside the group ({case})"); + assert!(!grip.intersects(item.shrink(0.5)), "the band {grip:?} does not cover the host item {item:?} ({case})"); + } + if let Some(shown) = shown { + assert!(!grip.intersects(shown.shrink(0.5)), "the band {grip:?} does not cover the shown tab {shown:?} ({case})"); + } + } + assert!( + shown_width >= least - 1.0 || grip.width() <= narrowest.width() + 0.5, + "the band {grip:?} narrows to {} pt before the shown tab ({shown_width} pt) goes below {least} pt ({case})", + 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 2f49f3115d..5c7803afd6 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4167,9 +4167,11 @@ The key stage (spec 9.1, 9.2, 9.3, 9.7): the input hook strips the keys the runt Layout memory: sizes one pass measures and the next pass places by, the one discard pass a change asks for, what - `craft_ui::runtime::layout_memory::emit_text`: `pub fn emit_text(ctx: &Context, id: Id, text: Option<&str>)`. Hands forward a text a run found under `id` that content outside the body it runs in shows, as `emit_record` +- `craft_ui::runtime::layout_memory::emit_width`: `pub fn emit_width(ctx: &Context, id: Id, width: f32)`. Hands forward a width a run measured under `id` that a step outside the content that measured it sizes by, as - `craft_ui::runtime::layout_memory::forget_kept`: `pub fn forget_kept(ctx: &Context)`. Drops every kept measurement, so the next pass measures each body as a first pass would. - `craft_ui::runtime::layout_memory::kept_leaves`: `pub fn kept_leaves(ctx: &Context) -> usize`. How many component entries the valid kept measurements hold, each body counting only the components directly in - `craft_ui::runtime::layout_memory::text`: `pub fn text(ctx: &Context, id: Id) -> Option>`. The text a run of this pass handed forward under `id` ([`emit_text`]), or a kept transcript gave this pass. +- `craft_ui::runtime::layout_memory::width`: `pub fn width(ctx: &Context, id: Id) -> Option`. The width a run of this pass handed forward under `id` ([`emit_width`]), or a kept transcript gave this pass. ## `craft_ui::runtime::memory` diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 2c2af41391..5bb36f396b 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -326,7 +326,7 @@ Host code that does work once per shown frame (a frame count, a screenshot's set Content runs in every pass, and its sizes come from this pass. Layouts also read some state earlier passes left, for example a scroll area's offset and its last view and extent (step 4 and the scroll bars read them) and the sizes layout memory keeps (`runtime::layout_memory`; a changed size asks for a discard pass). The one exception to running in every pass is out-of-view content. -**Layout memory.** A record of layout memory holds a measure or a text. A body whose inputs did not change takes its kept measurement instead of running a measuring run. A text that a measuring run found for content outside the body (a value readout beside a story, for example) is kept with the measurement: `layout_memory::emit_text` hands it forward, `layout_memory::text` reads it, and a body that takes its kept measurement gives the text its measuring run found. A real run that finds another text marks the kept transcript as changed. +**Layout memory.** A record of layout memory holds a measure, a text or a width. A body whose inputs did not change takes its kept measurement instead of running a measuring run. A text that a measuring run found for content outside the body (a value readout beside a story, for example) is kept with the measurement: `layout_memory::emit_text` hands it forward, `layout_memory::text` reads it, and a body that takes its kept measurement gives the text its measuring run found. A real run that finds another text marks the kept transcript as changed. `layout_memory::emit_width` and `layout_memory::width` hand forward a measured width the same way, for a step that sizes by content it runs before (a dock group's header parts keep room for the items the host adds to its header). A real run that finds a width that differs by more than the measuring tolerance marks the kept transcript as changed. **Memoized views.** A memoized view (`MemoView::new(id, props, show).show(ui)`) runs only when one of its inputs changed, and otherwise adds its last real run to the pass again: its paint, widgets, accessibility nodes, focus stops and the other per-pass registrations, and the value its run returned. Its content is a `fn` that captures nothing, and its props (`#[derive(MemoProps)]`) hold every app input it reads, so the compiler checks that the framework sees them; large app data goes in a `Tracked`, which keys by revision. The view runs when its props key differs from its last run's, when its place or environment differs (room, clip, layer, scale, theme, density, language, the scope's inherited values), when a framework input it read moved (modifiers, pointer, keymap, focus, a bound value, a command state), when it is engaged (the pointer over it, focus in it, a press or drag in it, an intent routed to it), and while something in it still moves (an animation, a loading texture, a repaint asked in its run with `frame::request_repaint`, a wake time). Input elsewhere in the window and repaint requests outside every view run no view: what changed reaches a view through its props. Content outside every memoized view runs in every pass. From ca82fb0e805cc243118b6447ed25d6fc4f51413f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:19:28 -0800 Subject: [PATCH 051/154] ui-widgets: a segmented strip wider than its room moves segments to the next line Segmented measured the sum of its segments whatever the room and laid them all on one line, so in a narrow column it reached past the column and widened it. It now flows its segments into the room as WordRun does: a segment that does not fit what is left of a line starts the next, a segment wider than a line is cut to it and shows its label as its tooltip, and its least width is its widest segment. In a room the strip fits it keeps its one line. The segments stay one radio group with the same arrow keys. --- crates/ui-widgets/src/choice/segmented.rs | 88 ++++++++++++++++--- crates/ui-widgets/tests/it/layout/mod.rs | 1 + .../tests/it/layout/segmented_lines.rs | 82 +++++++++++++++++ 3 files changed, 157 insertions(+), 14 deletions(-) create mode 100644 crates/ui-widgets/tests/it/layout/segmented_lines.rs diff --git a/crates/ui-widgets/src/choice/segmented.rs b/crates/ui-widgets/src/choice/segmented.rs index 7cd4670485..aec1254177 100644 --- a/crates/ui-widgets/src/choice/segmented.rs +++ b/crates/ui-widgets/src/choice/segmented.rs @@ -1,6 +1,7 @@ //! `Segmented`: one of a few options as a strip of segments. A leaf with a part per segment; each segment wears a //! face that is flat and muted, with a hover fill, and takes the selection fill and edge while it is picked. The row is one Tab stop over its segments: arrows, Home and End move focus between them, Space, -//! Enter or a click picks the focused one. +//! Enter or a click picks the focused one. In a room narrower than the strip, the segments that do not fit move to +//! the next line. use crate::buttons::ActiveLook; use crate::buttons::face::{self, FaceLook, FaceSpec}; @@ -10,9 +11,9 @@ use crate::contract::{ use crate::primitives::IconSpec; use crate::runtime::env::Label; use crate::style::{ComponentStyle, Flags, FocusLook, IconLook, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens}; -use craft_behavior::{Flow, Metrics, NavShape, PartKey, PartRef, Roving, Sense, Value}; +use craft_behavior::{Flow, Metrics, NavShape, PartKey, PartRef, Proposal, Roving, Sense, Value}; use craft_theme::{Rgba, Stateful, States}; -use egui::{Rect, Vec2}; +use egui::{Rect, Vec2, pos2, vec2}; const SEGMENT: PartKey = PartKey::new("segment"); @@ -65,6 +66,67 @@ impl<'a, T: Value + 'static> Segmented<'a, T> { fn widths(&self, cx: &MeasureCx<'_, Self>) -> Vec { self.entries.iter().map(|entry| cx.face(Self::face(entry)).x).collect() } + + /// The segments measured and flowed into lines `room` wide. At the least proposal the room is the widest segment, + /// so each segment keeps its whole face. + fn arrange(&self, cx: &MeasureCx<'_, Self>, room: f32) -> Placement { + let wants = self.widths(cx); + let room = if cx.proposal == Proposal::Min { wants.iter().copied().fold(0.0, f32::max).min(room) } else { room }; + place(&wants, room, cx.style.gap) + } +} + +/// Where the segments sit: each segment's line and its start offset in the line, in reading order. +struct Placement { + /// The width each segment wants: its face's measure. + wants: Vec, + /// Each segment's width, cut to the line. + widths: Vec, + cells: Vec<(usize, f32)>, + lines: usize, + /// The extent of the longest line. + extent: f32, +} + +/// Flows segments `wants` wide into lines `room` wide, `gap` apart: a segment that does not fit what is left of a +/// line starts the next, and a segment wider than a line is cut to the line. With widths 36, 36 and 36 in a room of +/// 90 and a gap of 8 the first two share line 0 (at 0 and 44, ending at 80) and the third starts line 1 at 0. +fn place(wants: &[f32], room: f32, gap: f32) -> Placement { + let mut cells = Vec::with_capacity(wants.len()); + let mut widths = Vec::with_capacity(wants.len()); + let (mut line, mut at, mut extent) = (0, 0.0_f32, 0.0_f32); + for &want in wants { + let width = want.min(room); + if at > 0.0 && at + width > room { + line += 1; + at = 0.0; + } + cells.push((line, at)); + widths.push(width); + extent = extent.max(at + width); + at += width + gap; + } + let lines = if wants.is_empty() { 0 } else { line + 1 }; + Placement { wants: wants.to_vec(), widths, cells, lines, extent } +} + +impl Placement { + /// The strip's size: its longest line, and its lines `height` tall and `gap` apart. + fn size(&self, height: f32, gap: f32) -> Vec2 { + let lines = self.lines.max(1) as f32; + Vec2::new(self.extent, lines * height + (lines - 1.0) * gap) + } + + /// 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. + 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]) + } } impl Component for Segmented<'_, T> { @@ -83,26 +145,24 @@ impl Component for Segmented<'_, T> { } } + /// The lines the segments take in the column's room: one line when the strip fits it. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - let widths = self.widths(cx); - let gaps = widths.len().saturating_sub(1) as f32; - Vec2::new(widths.iter().sum::() + cx.style.gap * gaps, cx.style.height) + self.arrange(cx, cx.column_room().unwrap_or(f32::INFINITY)).size(cx.style.height, cx.style.gap) } fn sense(&self) -> Sense { Sense::HOVER } + /// A part per segment, flowed into the lines of `rect`. A segment with an icon, or one cut to its line, shows its + /// label as its tooltip. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { - let widths = self.widths(cx); - let gap = cx.style.gap; + let placement = self.arrange(cx, rect.width()); + let (gap, rtl) = (cx.style.gap, cx.flow.is_rtl()); let current = self.position_of(cx.value()); - let mut flow = Flow::new(rect, cx.flow.is_rtl()); - for (at, (entry, width)) in self.entries.iter().zip(widths).enumerate() { - let (cell, rest) = flow.take_start(width); - flow = rest.take_start(gap).1; - let mut part = cx.part(Self::part(at), cell); - if entry.icon_spec().is_some() { + 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] { part = part.tooltip(entry.label().clone()); } if !entry.is_enabled() { diff --git a/crates/ui-widgets/tests/it/layout/mod.rs b/crates/ui-widgets/tests/it/layout/mod.rs index 024eebd6bf..f2021638c3 100644 --- a/crates/ui-widgets/tests/it/layout/mod.rs +++ b/crates/ui-widgets/tests/it/layout/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod row_line; pub(crate) mod row_room; pub(crate) mod rtl_scroll; pub(crate) mod scroll_region; +pub(crate) mod segmented_lines; pub(crate) mod shrink_order; pub(crate) mod stack_header; pub(crate) mod stack_widths; diff --git a/crates/ui-widgets/tests/it/layout/segmented_lines.rs b/crates/ui-widgets/tests/it/layout/segmented_lines.rs new file mode 100644 index 0000000000..b92e42079b --- /dev/null +++ b/crates/ui-widgets/tests/it/layout/segmented_lines.rs @@ -0,0 +1,82 @@ +//! A segmented strip in a room narrower than its one line moves the segments that do not fit to the next line, so +//! it stays inside the room; in a room it fits it keeps one line. + +use craft_i18n::Direction; +use craft_ui::choice::Segmented; +use craft_ui::contract::{Bind, Entry, Show as _}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Rect, Vec2}; + +const MODES: [&str; 5] = ["New", "Add", "Subtract", "Intersect", "Exclude"]; + +/// The strip of the five modes, shown in a room `width` wide, laid out in `direction`. +fn strip(width: f32, direction: Direction) -> Fixture { + let mut fixture = Fixture::new(|ui| { + let entries: Vec> = (0..).zip(MODES).map(|(at, mode)| Entry::new(at, mode)).collect(); + let mut picked = 0_u8; + Segmented::new("Combine", Bind::bound(&mut picked), &entries).show(ui); + }); + fixture.direction(direction).room(Vec2::new(width, 300.0)).settle(); + fixture +} + +/// The strip's rect and each segment's, in reading order. +fn rects(fixture: &Fixture) -> (Rect, Vec) { + let group = fixture.by_label("Combine").expect("the strip").rect; + let segments = MODES.iter().map(|mode| fixture.by_label(mode).expect("a segment").rect).collect(); + (group, segments) +} + +/// The width the strip takes on one line, in a room much wider than it. +fn one_line_width() -> f32 { + let (group, segments) = rects(&strip(2000.0, Direction::Ltr)); + let tops: Vec = segments.iter().map(|segment| segment.top()).collect(); + assert!(tops.iter().all(|top| (top - tops[0]).abs() < 0.5), "in a wide room the segments share one line: {tops:?}"); + group.width() +} + +#[trial] +fn a_strip_wider_than_its_room_moves_segments_to_another_line() { + let line = one_line_width(); + let room = line * 0.6; + for direction in [Direction::Ltr, Direction::Rtl] { + let fixture = strip(room, direction); + let (group, segments) = rects(&fixture); + assert!(group.right() <= room + 0.5, "{direction:?}: the strip ({group:?}) stays inside the room {room}"); + for (mode, segment) in MODES.iter().zip(&segments) { + assert!(group.expand(0.5).contains_rect(*segment), "{direction:?}: {mode} ({segment:?}) is inside the strip ({group:?})"); + } + assert!(segments[4].top() > segments[0].bottom() - 0.5, "{direction:?}: the last segment is on a later line than the first"); + for (at, pair) in segments.windows(2).enumerate() { + let overlap = pair[0].intersect(pair[1]); + assert!(overlap.width() <= 0.0 || overlap.height() <= 0.0, "{direction:?}: segments {at} and {} do not overlap", at + 1); + } + // Each line starts at the strip's start edge: the left one, or the right one right to left. + let start = |segment: &Rect| if direction == Direction::Rtl { group.right() - segment.right() } else { segment.left() - group.left() }; + let first_of_later_line = segments.iter().find(|segment| segment.top() > segments[0].bottom() - 0.5).expect("a second line"); + assert!(start(&segments[0]).abs() < 0.5 && start(first_of_later_line).abs() < 0.5, "{direction:?}: every line starts at the start edge"); + } +} + +#[trial] +fn a_strip_that_fits_its_room_keeps_one_line() { + let line = one_line_width(); + let fixture = strip(line + 40.0, Direction::Ltr); + let (group, segments) = rects(&fixture); + assert!(segments.iter().all(|segment| (segment.top() - segments[0].top()).abs() < 0.5), "the segments share one line"); + assert!((group.width() - line).abs() < 0.5, "the strip is as wide as its one line ({} against {line})", group.width()); +} + +#[trial] +fn arrows_move_across_the_lines_of_a_wrapped_strip() { + let mut fixture = strip(one_line_width() * 0.6, Direction::Ltr); + let focused = |fixture: &Fixture| fixture.focused_stop().and_then(|(_, part)| part).and_then(|part| part.index); + fixture.key(Key::Tab, Modifiers::NONE); + assert_eq!(focused(&fixture), Some(0), "Tab enters the strip on the picked segment"); + for to in 1..MODES.len() as u64 { + fixture.key(Key::ArrowRight, Modifiers::NONE); + assert_eq!(focused(&fixture), Some(to), "each arrow moves to the next segment, across a line break too"); + } + fixture.key(Key::Home, Modifiers::NONE); + assert_eq!(focused(&fixture), Some(0), "Home goes to the first segment"); +} From b56f7f4a83745ad1bd209e558c467eaabac398d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 11:05:12 -0800 Subject: [PATCH 052/154] theme: link text reads at 4.5:1 on the page and the window background The contrast rule for accent.text covered the panel, raised and sunken surfaces only. Links on a start page stand on surface.page or surface.background, where accent.text read at 3.6 to 4.3:1 in several light themes. - The accent.text rule also covers surface.page and surface.background. - The pinned link colors that standard contrast keeps are darker, with their hue kept: #1062c4 to #025abc in the default and pro light themes, #004296 to #003184 in pro light gray, and in two app overrides of the default theme #b54b16 to #a43b00 and #3b6eab to #2c5f9a. - Classic's page is #808080, where no color reaches 7:1; in high contrast the page now takes the background color. - Token dumps are updated. --- 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 +- 39 files changed, 76 insertions(+), 44 deletions(-) diff --git a/crates/theme/src/semantic_tests.rs b/crates/theme/src/semantic_tests.rs index 958f6eef98..1e76ab627e 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 CONTROL_BGS: [T; 3] = [T::SurfacePanel, T::SurfaceRaised, T::SurfaceSunken]; +const LINK_BGS: [T; 5] = [T::SurfacePanel, T::SurfaceRaised, T::SurfaceSunken, T::SurfacePage, T::SurfaceBackground]; /// 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(CONTROL_BGS.map(|bg| (T::AccentText, bg, 4.5, 7.0))); + p.extend(LINK_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 dc77ea1382..5be41771a9 100644 --- a/crates/theme/src/values.rs +++ b/crates/theme/src/values.rs @@ -395,6 +395,9 @@ 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)]; @@ -418,7 +421,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], CONTROL_BGS, TEXT_MIN.0, TEXT_MIN.1), + rule(&[T::AccentText], LINK_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 8c597ec6ca..33ccc7ff75 100644 --- a/crates/theme/tests/dumps.rs +++ b/crates/theme/tests/dumps.rs @@ -170,6 +170,30 @@ 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 bfd4c2a4b7..e26b9222bb 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 = #034d98ff +accent.text = #00458cff 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 428f4679ef..d26c27ff9e 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 = #034d98ff +accent.text = #00458cff 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 7ae732239c..0d63ff97b6 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 = #004ea4ff +accent.text = #003f87ff 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 f4055162b0..86c74662c6 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 = #004ea4ff +accent.text = #003f87ff 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 5de1b1d40b..37c50f9c28 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 = #1062c4ff +accent.text = #025abcff 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 22c786c1bc..701f87b493 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 = #1062c4ff +accent.text = #025abcff 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 89a38d3fe0..c06e58e9ae 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 = #10537dff +accent.text = #004a72ff 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 1d3a65eee2..1b4164e3ef 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 = #10537dff +accent.text = #004a72ff 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 61cb69af23..d611d11ee7 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 = #808080ff +surface.page = #d4d0c8ff 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 0ca15ed942..0626f13b66 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 = #808080ff +surface.page = #d4d0c8ff 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 5af6b006e3..a293e3b041 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 = #0b225bff +accent.text = #021149ff 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 245919d79c..36c54d3725 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 = #0b225bff +accent.text = #021149ff 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 6cabc69b57..decfcb5ff1 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 = #2356aaff +accent.text = #1a4ea1ff 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 dec4dfff76..592302a2bb 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 = #2356aaff +accent.text = #1a4ea1ff 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 300b3802f1..1c0730a668 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 = #002964ff -accent.on_soft = #003a85ff +accent.text = #00113bff +accent.on_soft = #003184ff 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 27db441dd3..630edbe143 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 = #002964ff -accent.on_soft = #003a85ff +accent.text = #00113bff +accent.on_soft = #003184ff 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 4e2d60d87b..cb27453f77 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 = #004296ff -accent.on_soft = #004296ff +accent.text = #003184ff +accent.on_soft = #003184ff 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 da83865dea..b4b0cc5cd8 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 = #004296ff -accent.on_soft = #004296ff +accent.text = #003184ff +accent.on_soft = #003184ff 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 6ffb292cbd..966d049ddd 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 = #004ea4ff +accent.text = #003f87ff 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 ca70e2b4c7..624d323afa 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 = #004ea4ff +accent.text = #003f87ff 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 4255d49a8f..05de48efd2 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 = #1062c4ff +accent.text = #025abcff 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 35e3129d2d..25ecfd821d 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 = #1062c4ff +accent.text = #025abcff 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 586c299641..5543b49ee4 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 = #2e3a92ff +accent.text = #2e3991ff 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 1dd2cd15fc..5b81005fa7 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 = #2e3a92ff +accent.text = #2e3991ff 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 f786d932ac..4fb92a6269 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 = #4b3ac2ff +accent.text = #442eb7ff 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 097cc1014a..bcffef3733 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 = #4b3ac2ff +accent.text = #442eb7ff 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 2909929b10..3be9a72a1f 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 = #9e2613ff +accent.text = #951d09ff 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 deff824ff2..663d38a918 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 = #9e2613ff +accent.text = #951d09ff 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 13c9020bf3..225c67b63b 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 = #851200ff +accent.text = #750e00ff 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 e6da117635..6651453749 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 = #851200ff +accent.text = #750e00ff 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 eb6164ff38..46f01daf32 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 = #a42d1aff +accent.text = #a02916ff 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 9c39c4f922..4663c03c0f 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 = #a42d1aff +accent.text = #a02916ff 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 aec135debe..726d3f750e 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": "#1062c4", + "accent.text": "#025abc", "caption.close_hover": "#c42b1c", "caption.close_text": "#ffffff", "line.border": "#d6d6d6", @@ -143,7 +143,7 @@ "deckcraft": { "light": { "accent.solid": "#d95a1a", - "accent.text": "#b54b16", + "accent.text": "#a43b00", "text.on_accent": "#ffffff" }, "dark": { @@ -155,7 +155,7 @@ "soundcraft": { "light": { "accent.solid": "#3e74b4", - "accent.text": "#3b6eab", + "accent.text": "#2c5f9a", "text.on_accent": "#ffffff" }, "dark": { diff --git a/crates/theme/themes/classic.json b/crates/theme/themes/classic.json index c56d46aa42..8587311ce3 100644 --- a/crates/theme/themes/classic.json +++ b/crates/theme/themes/classic.json @@ -62,5 +62,10 @@ "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 852e5b38ca..7be3ca729d 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": "#004296", + "accent.text": "#003184", "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 0f721de17a..90d80b1792 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": "#1062c4", + "accent.text": "#025abc", "caption.close_hover": "#c42b1c", "caption.close_text": "#ffffff", "line.border": "#d6d6d6", From 292e4e46124b9cfc57c19d8cba8d3e40b6c479fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:57:25 -0800 Subject: [PATCH 053/154] Cloud: a page drawn after sign-out does not ask the service again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open and Save As call `start` on every frame. After a sign-out, `start` asked who is signed in and listed the root folder again. The sign-out has no answer and no order against those requests, so a provider that still held the session could answer with the departed account and its files, and the account answer also reset Share. `sign_out` now sets a flag that stops `start` from asking anything until the next `sign_in`, and the page header reads "Signed out" instead of "Connecting to your cloud account…" while it is set. --- crates/cloud-ui/src/cloud/conflict_tests.rs | 37 +++++++++++++++++++++ crates/cloud-ui/src/cloud/mod.rs | 15 ++++++++- crates/cloud-ui/src/cloud/pages.rs | 5 +++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/crates/cloud-ui/src/cloud/conflict_tests.rs b/crates/cloud-ui/src/cloud/conflict_tests.rs index 1e22e815fe..c1c3d820a7 100644 --- a/crates/cloud-ui/src/cloud/conflict_tests.rs +++ b/crates/cloud-ui/src/cloud/conflict_tests.rs @@ -235,6 +235,43 @@ fn a_late_reply_from_before_sign_out_is_dropped() { ); } +/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it +/// before a request the next frame sends. A provider that still holds the session answers that +/// request with the departed account, and the window must not show that account or its files. +#[test] +fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() { + let (mut app, held, _log) = two_tabs(); + start(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap(); + post.send(Event::Account(Ok(account("Previous Person")))); + held.take(|j| matches!(j, Job::List(_))).unwrap(); + drain(&mut app, &egui::Context::default()); + sign_out(&mut app); + start(&mut app); + // Whatever the frame asked is answered as a provider that has not yet ended the session would. + while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) { + match job { + Job::Account => post.send(Event::Account(Ok(account("Previous Person")))), + Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }), + _ => {} + } + } + drain(&mut app, &egui::Context::default()); + let r = report(&app); + assert!( + r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty), + "signed out, yet account={} entries={}", + r["account"], + r["entries"] + ); + sign_in(&mut app); + let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap(); + post.send(Event::Account(Ok(account("Ada")))); + drain(&mut app, &egui::Context::default()); + start(&mut app); + assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again"); +} + /// Save as 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 d988b3abb6..3f76377f0e 100644 --- a/crates/cloud-ui/src/cloud/mod.rs +++ b/crates/cloud-ui/src/cloud/mod.rs @@ -190,6 +190,11 @@ pub struct CloudFiles { pub account_fault: Option, /// The account is asked for once per run. A frame never asks again. asked_account: bool, + /// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the + /// pages ask the service nothing. [`Job::SignOut`] has no answer and no + /// order against a later job, so a provider that still holds the session + /// could answer an account or listing request with the departed account. + signed_out: bool, /// The folder being browsed. Shared by the Open and Save As pages, which /// are never on screen together. pub mine: Folder, @@ -243,6 +248,7 @@ impl CloudFiles { account: None, account_fault: None, asked_account: false, + signed_out: false, mine: Folder::default(), shared: Folder::default(), source: Source::default(), @@ -337,8 +343,10 @@ pub fn submit(app: &A, job: Job) { } /// Asks who is signed in, once per run, and lists the root folder. +/// +/// After [`sign_out`] it asks nothing until the next [`sign_in`]. pub fn start(app: &mut A) { - if !available(app) { + if !available(app) || app.cloud().signed_out { return; } if !app.cloud().asked_account { @@ -368,6 +376,7 @@ pub fn sign_in(app: &mut A) { // would then be swallowed by the guard that stops a frame asking twice. A // button that does nothing the second time reads as a broken button. cloud.asked_account = true; + cloud.signed_out = false; cloud.link = None; cloud.status = Some(working); // A new session. A job the previous one left outstanding may never @@ -389,6 +398,10 @@ pub fn sign_out(app: &mut A) { cloud.account = None; cloud.account_fault = None; cloud.asked_account = false; + // File › Open and Save As call `start` on every frame. Without this, the + // next frame would ask who is signed in and list the root folder while + // the sign-out may still be on its way. + cloud.signed_out = true; cloud.link = None; cloud.mine = Folder::default(); cloud.shared = Folder::default(); diff --git a/crates/cloud-ui/src/cloud/pages.rs b/crates/cloud-ui/src/cloud/pages.rs index 86e71d1c88..e1ce9b1ad4 100644 --- a/crates/cloud-ui/src/cloud/pages.rs +++ b/crates/cloud-ui/src/cloud/pages.rs @@ -42,6 +42,11 @@ fn header(app: &mut A, ui: &mut Ui) { let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() }; dim(ui, &style, &line); } + // Nothing is asked after a sign-out, so there is nothing to wait for. + (None, None) if app.cloud().signed_out => { + let signed_out = app.tr("Signed out"); + dim(ui, &style, &signed_out); + } (None, None) => { let waiting = app.tr("Connecting to your cloud account…"); dim(ui, &style, &waiting); From 8ed02d491090e391ff2e7ef902d9c4a110cd8fb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:15:48 -0800 Subject: [PATCH 054/154] ui-contract, behavior: a wheel that zooms carries its wheel lines A Ctrl+wheel on Windows and Linux reaches a taker as a zoom factor with no scroll, and a touchpad's fractional Ctrl+wheel there becomes a pinch step. A taker that steps a value by notches (VectorCraft's Quick Pen arc size) could only count them by working the lines back out of the factor with egui's zoom speed. - `Wheel::zoom_lines`: the motion that reached the share as `zoom`, in wheel lines: wheel events under the zoom modifier, measured before the user's wheel speed, and the Ctrl+wheel steps folded into pinch steps. It travels with the zoom share. A native pinch carries none. - `Wheel::zoom_gathered`: the running gesture's `zoom_lines`, gathered the way `gathered` gathers the scroll. --- crates/behavior/src/wheel.rs | 38 ++++++++++++++- crates/ui-contract/src/runtime/egui/input.rs | 50 +++++++++++++++++++ crates/ui-contract/src/runtime/wheel.rs | 27 ++++++++--- crates/ui-contract/tests/it/runtime/wheel.rs | 51 ++++++++++++++++++++ 4 files changed, 158 insertions(+), 8 deletions(-) diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 1985e4bf9c..12c36a01e3 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -66,6 +66,15 @@ pub struct Wheel { pub lines: Vec2, /// Zoom factor; 1 for none. pub zoom: f32, + /// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the + /// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line + /// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line + /// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that + /// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier. + pub zoom_lines: Vec2, + /// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture; + /// another taker's share gathers only itself, as with `gathered`. + pub zoom_gathered: Vec2, /// The modifiers held. pub mods: Mods, /// The unit the device reported. @@ -224,6 +233,8 @@ impl Wheel { scroll, lines: Vec2::ZERO, zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, mods, unit, phase, @@ -245,6 +256,13 @@ impl Wheel { self } + /// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). + #[must_use] + pub const fn zoom_lines(mut self, lines: Vec2) -> Self { + self.zoom_lines = lines; + self + } + /// The same gesture with the two-finger touch zoom factor `zoom`. pub const fn touch_zoom(mut self, zoom: f32) -> Self { self.touch_zoom = zoom; @@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool { /// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values. fn pinches(wheel: &Wheel) -> bool { - wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO + wheel.zoom != 1.0 + || wheel.zoom_lines != Vec2::ZERO + || wheel.touch_zoom != 1.0 + || wheel.rotation != 0.0 + || wheel.touch_rotation != 0.0 + || wheel.touch_pan != Vec2::ZERO } /// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region /// never reads one. const fn scroll_only(wheel: Wheel) -> Wheel { - Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel } + Wheel { + zoom: 1.0, + zoom_lines: Vec2::ZERO, + zoom_gathered: Vec2::ZERO, + touch_zoom: 1.0, + rotation: 0.0, + touch_rotation: 0.0, + touch_pan: Vec2::ZERO, + zooms: false, + ..wheel + } } /// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes @@ -715,6 +748,7 @@ fn split_at( Some((_, share)) => { share.scroll += part.scroll; share.zoom *= part.zoom; + share.zoom_lines += part.zoom_lines; share.touch_zoom *= part.touch_zoom; share.rotation += part.rotation; share.touch_rotation += part.touch_rotation; diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index ae62f7c0e0..f6a8be252e 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -571,6 +571,51 @@ pub(crate) fn wheel_read(ctx: &Context, line: f32, page: f32) -> Option<(Vec2, W }) } +/// The wheel motion of the pass that zooms instead of scrolling, in wheel lines (`Wheel::zoom_lines`): its wheel events +/// under egui's zoom modifier, which `pointer_read` turns into the pass's zoom factor and `wheel_read` leaves out of the +/// scroll, and the Ctrl+wheel steps `fold_legacy_pinch` turned into pinch steps in the same input. A line event counts +/// its lines, a point event its points over egui's line scroll speed and a page event its page's points over it. Zero +/// when there were none; a delta that is not finite is left out. +pub(crate) fn zoom_wheel_lines(ctx: &Context) -> Vec2 { + let (zoom_modifier, line) = ctx.options(|options| (options.input_options.zoom_modifier, options.input_options.line_scroll_speed)); + let page = ctx.content_rect().height(); + let speed = crate::runtime::frame::root_input(ctx).wheel; + let folded = PerViewport::::with(ctx, super::pass::current_viewport(ctx), |state| state.folded_lines); + ctx.input(|input| { + input.raw.events.iter().fold(folded, |sum, event| match event { + Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.matches_any(zoom_modifier) => { + sum + wheel_lines(*unit, unscaled(*unit, *delta, modifiers, speed), line, page) + } + _ => sum, + }) + }) +} + +/// `delta` of a wheel event in `unit` with `modifiers` as the device sent it, before `scale_wheel` multiplied it by the +/// user's `speed`. +fn unscaled(unit: MouseWheelUnit, delta: Vec2, modifiers: &egui::Modifiers, speed: crate::runtime::env::WheelSpeed) -> Vec2 { + if modifiers.ctrl || modifiers.command || modifiers.mac_cmd { + return delta; + } + let factor = match unit { + MouseWheelUnit::Line => speed.line, + MouseWheelUnit::Point => speed.point, + MouseWheelUnit::Page => return delta, + }; + if factor.is_finite() && factor > 0.0 { delta / factor } else { delta } +} + +/// `delta` of a wheel event in `unit` as wheel lines of `line` points, pages being `page` points; zero when it is not +/// finite. +fn wheel_lines(unit: MouseWheelUnit, delta: Vec2, line: f32, page: f32) -> Vec2 { + let lines = match unit { + MouseWheelUnit::Line => delta, + MouseWheelUnit::Point => delta / line, + MouseWheelUnit::Page => delta * page / line, + }; + if lines.is_finite() { lines } else { Vec2::ZERO } +} + /// Removes the events a modal layer in another viewport blocks: button and key presses, wheel, text, clipboard and /// touch. Pointer moves and releases stay, so the pointer position stays right and no press or key sticks down. The /// events `keep` admits stay too (the canvas the modal leaves open, `runtime::sampler`); `pointer` is where the pointer @@ -716,6 +761,7 @@ pub(crate) fn fold_legacy_pinch(ctx: &Context, input: &mut RawInput) { } let points = if unit == MouseWheelUnit::Line { delta * line } else { delta }; *event = Event::Zoom((speed * (points.x + points.y)).exp()); + state.folded_lines += wheel_lines(unit, delta, line, 0.0); state.last_pinch = now.or(state.last_pinch); } }); @@ -726,6 +772,8 @@ pub(crate) fn fold_legacy_pinch(ctx: &Context, input: &mut RawInput) { pub(crate) struct RawState { /// The input time of the last Ctrl+wheel folded into a pinch step. last_pinch: Option, + /// The wheel lines of the Ctrl+wheel events folded into pinch steps in the running pass's input (`zoom_wheel_lines`). + folded_lines: Vec2, control_click: ControlClick, /// The Alt+numpad entry in progress. alt_code: super::alt_code::AltCodeEntry, @@ -744,6 +792,8 @@ pub(crate) struct RawState { pub(crate) fn prepare(ctx: &Context, input: &mut RawInput) { // This frame's `RootEnv`, which `set_input` stored before egui ran the input hook. let root = crate::runtime::frame::root_input(ctx); + // Each pass's input folds its own steps: a later pass of the frame, whose input holds no events, reads none. + PerViewport::::with(ctx, input.viewport_id, |state| state.folded_lines = Vec2::ZERO); if root.ctrl_wheel_pinch { fold_legacy_pinch(ctx, input); } diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 5565fe76d7..96957c62f9 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -28,6 +28,8 @@ pub(crate) struct State { gesture: WheelGesture, /// The running gesture's gathered scroll in its owner's points, reset when the gesture closes. gathered: Vec2, + /// The running gesture's gathered zoom-modifier wheel motion in the device's unit, reset when the gesture closes. + zoom_gathered: Vec2, /// Whether the owner marked the running gesture moved, reset when the gesture closes. moved: bool, /// The last gesture the device ended, which a momentum run of the same owner within `GESTURE_GAP` resumes. @@ -42,6 +44,7 @@ struct Ended { owner: Id, at: f64, gathered: Vec2, + zoom_gathered: Vec2, moved: bool, } @@ -100,6 +103,7 @@ impl State { let ended = self.gesture.end(if pressed { f64::INFINITY } else { now }); if open && !self.gesture.last.is_finite() { self.gathered = Vec2::ZERO; + self.zoom_gathered = Vec2::ZERO; self.moved = false; } ended @@ -113,7 +117,8 @@ impl State { return None; } let swipe = self.device_ended.filter(|ended| source == WheelSource::Momentum && now - ended.at < GESTURE_GAP); - (self.gathered, self.moved) = swipe.map_or((Vec2::ZERO, false), |ended| (ended.gathered, ended.moved)); + (self.gathered, self.zoom_gathered, self.moved) = + swipe.map_or((Vec2::ZERO, Vec2::ZERO, false), |ended| (ended.gathered, ended.zoom_gathered, ended.moved)); swipe.map(|ended| ended.owner) } @@ -128,10 +133,13 @@ impl State { } if self.gesture.owner == Some(owner) { self.gathered += share.scroll; + self.zoom_gathered += share.zoom_lines; share.gathered = self.gathered; + share.zoom_gathered = self.zoom_gathered; share.moved = self.moved; } else { share.gathered = share.scroll; + share.zoom_gathered = share.zoom_lines; } } @@ -190,6 +198,7 @@ pub(crate) fn begin(ctx: &Context) { let pass_pointer = pointer::pass_pointer(ctx); let frame = pass_pointer.frame.clone(); let wheel_in = input::wheel_read(ctx, 1.0, 1.0); + let zoom_lines = input::zoom_wheel_lines(ctx); let now = crate::runtime::frame::clock(ctx); let focused = focus::focused_stop(ctx).map(|(owner, _)| owner); // A text field the app drew itself holds key focus: it reads its own wheel. @@ -250,12 +259,18 @@ pub(crate) fn begin(ctx: &Context) { let zoom = frame.zoom; // A device's end reaches the gesture's owner even when it moves nothing. let device_end = wheel_in.is_some() && matches!(phase, WheelPhase::End | WheelPhase::Cancel); - let moves = - scroll != Vec2::ZERO || zoom != 1.0 || touch_zoom != 1.0 || frame.rotation != 0.0 || touch_rotation != 0.0 || touch_pan != Vec2::ZERO; + let moves = scroll != Vec2::ZERO + || zoom != 1.0 + || zoom_lines != Vec2::ZERO + || touch_zoom != 1.0 + || frame.rotation != 0.0 + || touch_rotation != 0.0 + || touch_pan != Vec2::ZERO; if moves || device_end { let share = Wheel::new(scroll, mods, unit, phase) .source(source) .zoom(zoom) + .zoom_lines(zoom_lines) .touch_zoom(touch_zoom) .rotation(frame.rotation) .touch_rotation(touch_rotation) @@ -277,7 +292,7 @@ pub(crate) fn begin(ctx: &Context) { let shares = split(&eligible, at, share, focus, state.armed, &mut state.gesture, now); // A momentum run resumes its swipe only on the swipe's owner; any split drops the ended swipe. if swipe.is_some() && state.gesture.owner != swipe { - (state.gathered, state.moved) = (Vec2::ZERO, false); + (state.gathered, state.zoom_gathered, state.moved) = (Vec2::ZERO, Vec2::ZERO, false); } state.device_ended = None; // The device's lines and pages become points of each taker: the notch is the scroll owner's to choose. @@ -293,8 +308,8 @@ pub(crate) fn begin(ctx: &Context) { state.shares.push((owner, share)); } if device_end { - let (gathered, moved) = (state.gathered, state.moved); - state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, moved }); + let (gathered, zoom_gathered, moved) = (state.gathered, state.zoom_gathered, state.moved); + state.device_ended = state.gesture.owner.map(|owner| Ended { owner, at: now, gathered, zoom_gathered, moved }); } } } diff --git a/crates/ui-contract/tests/it/runtime/wheel.rs b/crates/ui-contract/tests/it/runtime/wheel.rs index 992d6e3725..d89e09fd57 100644 --- a/crates/ui-contract/tests/it/runtime/wheel.rs +++ b/crates/ui-contract/tests/it/runtime/wheel.rs @@ -114,6 +114,57 @@ fn a_fractional_ctrl_wheel_is_a_pinch_and_a_whole_notch_stays_a_scroll() { } } +#[trial] +fn a_wheel_that_zooms_carries_its_lines_and_the_gesture_gathers_them() { + // egui reports the Ctrl key as `ctrl` and `command` off macOS; Ctrl is egui's zoom modifier there. + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let ctrl_lines = |dy: f32| wheel_event(MouseWheelUnit::Line, Vec2::new(0.0, dy), TouchPhase::Move, ctrl); + let seen = Rc::new(RefCell::new(Vec::new())); + let shares = Rc::clone(&seen); + let view = Id::unique("zoom_lines_view"); + let mut fixture = Fixture::new(move |ui| { + register(ui.ctx(), WheelTaker::new(view, Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0))).vertical(true).zoom(true)); + shares.borrow_mut().extend(take_share(ui.ctx(), view)); + }); + fixture.os(Os::Windows); + fixture.settle(); + fixture.frame(vec![pointer::moved(Pos2::new(200.0, 150.0))]); + seen.borrow_mut().clear(); + let step = |fixture: &mut Fixture, events: Vec| -> Vec { + fixture.frame(events); + std::mem::take(&mut *seen.borrow_mut()) + }; + let near = |a: Vec2, b: Vec2| (a - b).length() < 1e-4; + + // Two notches in one pass zoom as one factor and count as two lines; the next notch of the gesture gathers on. + let two = step(&mut fixture, vec![ctrl_lines(1.0), ctrl_lines(1.0)]); + assert!(two.len() == 1 && two[0].zoom > 1.0 && two[0].scroll == Vec2::ZERO, "two notches zoom: {two:?}"); + assert_eq!((two[0].zoom_lines, two[0].zoom_gathered), (Vec2::new(0.0, 2.0), Vec2::new(0.0, 2.0)), "{two:?}"); + let down = step(&mut fixture, vec![ctrl_lines(-1.0)]); + assert_eq!((down[0].zoom_lines, down[0].zoom_gathered), (Vec2::new(0.0, -1.0), Vec2::new(0.0, 1.0)), "{down:?}"); + + // A touchpad driver's fractional Ctrl+wheel reaches the view as a pinch step and carries its lines too. + fixture.advance(1.0); + let folded = step(&mut fixture, vec![ctrl_lines(0.4)]); + assert!(folded.len() == 1 && folded[0].zoom > 1.0, "a pinch step: {folded:?}"); + assert!(near(folded[0].zoom_lines, Vec2::new(0.0, 0.4)) && near(folded[0].zoom_gathered, Vec2::new(0.0, 0.4)), "a new gesture: {folded:?}"); + + // A native pinch and a wheel without the modifier carry none. + fixture.advance(1.0); + let native = step(&mut fixture, vec![Event::Zoom(1.1)]); + assert!(native.len() == 1 && native[0].zoom_lines == Vec2::ZERO, "a native pinch: {native:?}"); + fixture.advance(1.0); + let plain = step(&mut fixture, vec![pointer::wheel_lines(1.0)]); + assert!(plain.len() == 1 && plain[0].zoom_lines == Vec2::ZERO && plain[0].zoom == 1.0, "a plain wheel: {plain:?}"); + + // With Alt as the zoom modifier, the user's wheel speed scales the notch it zooms by but not the lines it counts. + fixture.ctx().options_mut(|options| options.input_options.zoom_modifier = Modifiers::ALT); + fixture.root(RootEnv::default().wheel_speed(WheelSpeed::new(3.0, 3.0))); + fixture.advance(1.0); + let alt = step(&mut fixture, vec![wheel_event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), TouchPhase::Move, Modifiers::ALT)]); + assert!(alt.len() == 1 && near(alt[0].zoom_lines, Vec2::new(0.0, 1.0)), "one notch at three times the speed: {alt:?}"); +} + #[trial] fn a_wheel_gesture_ends_for_a_value_control_in_any_wheel_scope_and_not_for_a_scroll_region_or_the_canvas() { let panel = Id::unique("gesture_panel"); From 4cd6d53b69fcccb2fd956c9af2ef62df7a4c26f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:46:20 -0800 Subject: [PATCH 055/154] ui-canvas rulers: the units menu lists unit names, not their symbols The rows of the rulers' units menu were labeled with Units::symbol, so they read "pt", "pica", "in" and "mm". They now use Units::name, the names the other unit lists and the rulers' unit commands show ("Points", "Picas", "Inches", "Millimetres"). --- crates/ui-canvas/src/canvas/rulers/mod.rs | 2 +- crates/ui-canvas/tests/it/canvas/rulers.rs | 30 ++++++++++++++++++++++ 2 files changed, 31 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..bbf8e20af4 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -497,7 +497,7 @@ impl Component for Rulers<'_> { let words = cx.words::(); let shown = self.published().x.kind; let mut entries: Vec> = - units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), Label::from(numbers.symbol(kind))).checked(kind == shown)).collect(); + units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), numbers.name(kind)).checked(kind == shown)).collect(); entries.push(Entry::separator()); entries.push(Entry::new(MenuRow::ResetZero, Label::from(words.ruler_reset_zero.as_str().to_owned())).enabled(!self.origin_locked)); let name = Label::from(words.ruler_menu.as_str().to_owned()); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 5fe156210e..a567117c5e 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -238,6 +238,36 @@ fn with_rulers_on_the_tool_and_a_canvas_control_paint_inside_the_view_and_the_ru assert!(strips_keep_the_canvas, "the rulers paint inside the top strip under the canvas's rect: {strip:?} in {shapes:?}"); } +/// The units menu names each unit as a list of units does ("Points", "Millimetres"), not by the symbol a number +/// carries ("pt", "mm"). +#[trial] +fn the_units_menu_names_each_unit() { + const UNITS: [UnitKind; 4] = [UnitKind::Points, UnitKind::Picas, UnitKind::Inches, UnitKind::Millimetres]; + let zero = Rc::new(RefCell::new(Point::ZERO)); + let shown_zero = Rc::clone(&zero); + let room = Rc::new(Cell::new(Rect::NOTHING)); + let shown_room = Rc::clone(&room); + let mut fixture = Fixture::new(move |ui| { + let at = ui.available_rect_before_wrap(); + shown_room.set(at); + let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0); + let mut zero = shown_zero.borrow_mut(); + let _ = + Canvas::new("Document").view(view).with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut *zero)).units(&UNITS))).show(ui, |_, _| {}); + }); + fixture.room(Vec2::new(500.0, 400.0)).settle(); + let at = egui::pos2(room.get().center().x, room.get().min.y + 4.0); + fixture.frame(vec![craft_ui::testing::pointer::moved(at)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]); + fixture.settle(); + assert!(fixture.by_label("Reset Zero Point").is_some(), "the units menu is open"); + for (name, symbol) in [("Points", "pt"), ("Picas", "pica"), ("Inches", "in"), ("Millimetres", "mm")] { + assert!(fixture.by_label(name).is_some(), "the menu lists {name}"); + assert!(fixture.by_label(symbol).is_none(), "no row reads {symbol}"); + } +} + /// A drag of the rulers' corner with one move past the drag threshold, released there, moves the zero point to where it /// was released: the drag proposes its landing at its start and at its release, not only on the moves between. #[trial] From e543c98007ec66b1baa04d0fc20a9c817ad39fc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:04:59 -0800 Subject: [PATCH 056/154] Swatch: drag(Some(payload)) makes the well a drag source A primary drag that starts on the well carries the payload through the drag session, with a ghost the size of the well, for the drop targets of the payload's type. The swatch keeps its click; None drags nothing, as a SwatchPair well without a payload does. A panel can then let its gradient thumbnail be dragged onto art or a swatch list. --- crates/ui-widgets/src/choice/swatch.rs | 33 +++++++++++++--- crates/ui-widgets/tests/it/pickers/swatch.rs | 40 +++++++++++++++++++- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/ui-widgets/src/choice/swatch.rs b/crates/ui-widgets/src/choice/swatch.rs index 7743cabaa9..46b6c1c684 100644 --- a/crates/ui-widgets/src/choice/swatch.rs +++ b/crates/ui-widgets/src/choice/swatch.rs @@ -5,17 +5,18 @@ use super::radio::RadioKind; use super::words::ChoiceWords; use crate::contract::{ - Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role, - Sizing, Styled as _, WordSetCx as _, + Access, Activation, Common, Component, Cx, DisabledLook, DragPreview, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, + Props as _, Role, Sizing, Styled as _, WordSetCx as _, }; use crate::primitives::textures::UNTINTED; use crate::primitives::{Checker, ContentPainterCx, DataWidth, Draw, FacePaint, IconSpec, PaintShape, StrokeWidth, TextureCache, WellFill}; use crate::runtime::focus::FocusShape; use crate::runtime::requests::ColorRequest; use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style}; -use craft_behavior::{IconId, Metrics, Mixed, Sense, Value}; +use craft_behavior::{IconId, Metrics, Mixed, PointerButton, PressPhase, Sense, Value}; use craft_theme::{Hsb, Rgba, Srgba, Stateful, States, over}; use egui::{Color32, ColorImage, CornerRadius, Mesh, Pos2, Rect, Response, Shape, Vec2, pos2}; +use std::any::Any; use std::sync::Arc; #[cfg(feature = "suite")] @@ -231,7 +232,8 @@ impl crate::contract::ItemOutput for SwatchOutput { /// `activation`. A swatch with a `picker` key also files a `ColorRequest` for that key, opened at the swatch's colour /// and titled with its label, as `pick_color`; the host opens its colour picker and answers with the picked colour. A /// `Mixed` swatch files a request with no colour: the host's picker opens empty and the first pick sets the colour. -/// The host writes the pick to every target. +/// The host writes the pick to every target. A swatch given a payload with [`drag`](Swatch::drag) drags it to the +/// drop targets that take its type. /// /// AccessKit reports a colour well named by the label, whose value is the colour as `#rrggbb` (`#rrggbbaa` when /// translucent) and whose colour value is the colour; a mixed well has the value "Mixed" and no colour value. A split @@ -279,6 +281,8 @@ pub struct Swatch { picker: Option, /// The glyph an icon cell paints over its empty well, in place of a colour. icon: Option, + /// The payload a drag from the well carries, set by [`drag`](Swatch::drag). + drag: Option>, checked: bool, activation: Option, } @@ -303,6 +307,7 @@ impl Swatch<()> { shape: SwatchShape::default(), picker: None, icon: None, + drag: None, checked: false, activation: None, } @@ -335,10 +340,20 @@ impl Swatch { shape: self.shape, picker: self.picker, icon: self.icon, + drag: self.drag, checked: false, activation: None, } } + + /// A primary drag that starts on the well carries `payload` through the drag session, with a ghost as large as the + /// well, for the drop targets of type `P` (a gradient thumbnail dropped on art or on a swatch list); `None` drags + /// nothing, as a `SwatchPair` well without a payload does. The swatch keeps its click. + #[must_use] + pub fn drag(mut self, payload: 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 057/154] 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 064/154] 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 065/154] 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 066/154] 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 49c56041ca0cfbb2dad9c4b518813181c6e12e92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:55:50 -0800 Subject: [PATCH 067/154] 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 c94a5f795d1d07868baa9d495a6763a56cfeb289 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:06:26 -0800 Subject: [PATCH 068/154] 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 069/154] 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 070/154] 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 6cdbd0af0655671e1cb26233421c8d87c2f5494b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:38:53 -0800 Subject: [PATCH 071/154] 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 09d11fef0a6076de8e00da2c225d4b615aa3b90f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:12:52 -0800 Subject: [PATCH 072/154] 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 073/154] 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 37031ecda2c66a5fda8806efb1d127497b6a7e5a Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:45:38 +0530 Subject: [PATCH 074/154] font-manager: a right-click on a glyph cell names that cell The host hangs the menu from the grid response. The panel does not open it. Co-authored-by: Cursor --- crates/font-manager/src/glyphs.rs | 28 ++++++++++++++++++++++++-- crates/font-manager/tests/it/glyphs.rs | 22 +++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index aa0ae75021..77ac77f458 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -1,6 +1,8 @@ //! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation, //! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used //! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert. +//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens +//! the menu from the grid response. #[cfg(feature = "suite")] pub(crate) mod stories; @@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput { pub alternate: Option, /// The family or style changed in the panel's own pickers. pub font_changed: bool, + /// The grid cell a context menu was asked for, with the grid response the menu hangs from. + /// Reported on the secondary click and on every later pass while that menu stays open. + pub menu: Option, +} + +/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from. +#[derive(Debug)] +#[non_exhaustive] +pub struct GlyphCellMenu { + /// The cell. + pub cell: GlyphCell, + /// The grid the menu hangs from. + pub opener: Response, } /// The cell whose popup was used and the picked glyph. @@ -483,12 +498,13 @@ impl<'a> GlyphsPanel<'a> { }); }); craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS); - return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false }; + return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None }; } let ctx = ui.ctx().clone(); let mut activated_out: Option = None; let mut picked: Option = None; let mut font_changed = false; + let mut menu: Option = None; let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| { cx.publish(GlyphsCommand::Alternates, CommandState::new()); let mut state = read_bind(&mut settings, cx).unwrap_or_default(); @@ -608,6 +624,14 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); + // The collection keeps the request while the menu hung from this response stays open. + let opener = shown_grid.response.response.clone(); + menu = shown_grid + .response + .menu + .as_ref() + .and_then(|request| cells.get(request.key).copied()) + .map(|cell| GlyphCellMenu { cell, opener }); for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), @@ -693,6 +717,6 @@ impl<'a> GlyphsPanel<'a> { write_bind(&mut settings, cx, state, "Glyphs panel"); } }); - GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed } + GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu } } } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 2a92952e90..787f780977 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -6,6 +6,7 @@ use std::rc::Rc; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; use craft_ui::contract::Bind; +use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -43,6 +44,8 @@ struct Seen { marked: Option, reveal: Option, picks: Vec<(GlyphCell, GlyphCell)>, + /// Cells a secondary click asked for a menu on, in order. + menu: Vec, } fn rig() -> (Fixture, Rc>) { @@ -62,9 +65,13 @@ fn rig() -> (Fixture, Rc>) { if let Some(cell) = reveal { panel = panel.reveal(cell); } - if let Some(pick) = panel.show(ui).alternate { + let out = panel.show(ui); + if let Some(pick) = out.alternate { shown.borrow_mut().picks.push((pick.cell, pick.glyph)); } + if let Some(menu) = out.menu { + shown.borrow_mut().menu.push(menu.cell); + } }); fx.in_room(Room::Window); fx.settle(); @@ -125,6 +132,19 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() { assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup"); } +#[trial] +fn a_secondary_click_reports_the_cell_the_menu_is_for() { + let (mut fx, seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + let menu = seen.borrow().menu.clone(); + assert!(!menu.is_empty(), "the secondary click names the cell"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 9219c6c0eb7da3cc3c31597eb02c168ca5edd615 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:01:17 -0800 Subject: [PATCH 075/154] 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 076/154] 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 077/154] 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 14:02:46 +0530 Subject: [PATCH 078/154] font-manager: an open glyph menu keeps the cell that was clicked A later pass remembers the glyph, not the row, so a same-length list cannot move the menu onto another glyph. Co-authored-by: Cursor --- crates/font-manager/src/glyphs.rs | 27 +++++++++--- crates/font-manager/tests/it/glyphs.rs | 60 +++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 77ac77f458..6eaf8bdd40 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -325,6 +325,11 @@ struct CellsCache { #[derive(Clone, Default)] struct Marked(Selection); +/// The glyph a context menu was opened on. Later passes keep this glyph: the grid remembers the row, and another +/// glyph of a same-length list must not take the menu over. +#[derive(Clone, Copy, Default)] +struct HeldMenu(Option); + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -624,14 +629,22 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); - // The collection keeps the request while the menu hung from this response stays open. + // The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a + // same-length list must not move the open menu onto whatever glyph is there now. + let clicked = shown_grid.response.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), + _ => None, + }); + let mut held = *cx.memory::(); + if let Some(cell) = clicked { + held = HeldMenu(Some(cell)); + } let opener = shown_grid.response.response.clone(); - menu = shown_grid - .response - .menu - .as_ref() - .and_then(|request| cells.get(request.key).copied()) - .map(|cell| GlyphCellMenu { cell, opener }); + menu = shown_grid.response.menu.is_some().then_some(held.0).flatten().map(|cell| GlyphCellMenu { cell, opener }); + if shown_grid.response.menu.is_none() { + held = HeldMenu(None); + } + *cx.memory::() = held; for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 787f780977..e4845907ef 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -3,9 +3,12 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -145,6 +148,61 @@ fn a_secondary_click_reports_the_cell_the_menu_is_for() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); } +/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the +/// panel reads the list again. +struct Swap(Arc); + +impl GlyphSource for Swap { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST }; + std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + u64::from(self.0.load(Ordering::Relaxed)) + } +} + +#[trial] +fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { + let swapped = Arc::new(AtomicBool::new(false)); + let source = Swap(Arc::clone(&swapped)); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui); + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell"); + + seen.borrow_mut().clear(); + swapped.store(true, Ordering::Relaxed); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(!menu.is_empty(), "the menu stays open"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 01d7016e1225f0e0ced1286c638048070f01322b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:27:16 -0800 Subject: [PATCH 079/154] SelectableText: report primary clicks through the response --- crates/ui-contract/src/contract/text.rs | 6 ++ crates/ui-widgets/src/text/selectable_text.rs | 10 ++- crates/ui-widgets/tests/it/text/selectable.rs | 64 ++++++++++++++++++- 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 5a855c7f06..ea1a9f7095 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -677,6 +677,12 @@ pub(crate) fn run( } impl Cx<'_, C> { + /// The response of a declared selection part after `paint` shows it, or `None` when the part has no widget. + pub fn selection_response(&self, part: impl Into) -> Option { + let part = part.into(); + self.core.selections.contains(&part).then(|| self.core.ctx.read_response(selection_id(self.core.id, part))).flatten() + } + /// Changes the text part's draft in the next pass: `Some(text)` puts `text` in as a change of the typing run (one /// that begins the run when none is under way), the caret at its end; `None` ends the run with the text from /// before it, without the run's Escape reaching the host. A combo box's keys in its open list put the active diff --git a/crates/ui-widgets/src/text/selectable_text.rs b/crates/ui-widgets/src/text/selectable_text.rs index acd10f9998..731d55b5ba 100644 --- a/crates/ui-widgets/src/text/selectable_text.rs +++ b/crates/ui-widgets/src/text/selectable_text.rs @@ -107,6 +107,14 @@ impl Component for SelectableText<'_> { } fn finish(self, cx: Cx<'_, Self>) -> Response { - cx.response.clone() + let mut response = cx.response.clone(); + if let Some(text) = cx.selection_response(TEXT) { + let clicked = cx.resolved.enabled && !cx.resolved.read_only && text.clicked_by(egui::PointerButton::Primary); + response.flags.set(egui::response::Flags::CLICKED, clicked); + if clicked { + response.interact_pointer_pos_or_nan = text.interact_pointer_pos_or_nan; + } + } + response } } diff --git a/crates/ui-widgets/tests/it/text/selectable.rs b/crates/ui-widgets/tests/it/text/selectable.rs index ecc76542bc..305839c039 100644 --- a/crates/ui-widgets/tests/it/text/selectable.rs +++ b/crates/ui-widgets/tests/it/text/selectable.rs @@ -13,7 +13,7 @@ use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable}; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::{SelectableText, TextField}; use egui::{Event, Id, Key, Modifiers, Rect, Sense, Vec2, ViewportId}; -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; fn stop(fixture: &Fixture) -> Option { @@ -53,6 +53,68 @@ fn painted(fixture: &Fixture, text: &str) -> Rect { fixture.texts().iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("{text:?} is painted")).rect } +#[trial] +fn selectable_text_response_reports_its_clicks_and_modifiers() { + let clicks = Rc::new(RefCell::new(Vec::new())); + let seen = clicks.clone(); + let mut fixture = Fixture::new(move |ui| { + let response = SelectableText::new("Length", "234 pt").show(ui); + assert_eq!(craft_ui::contract::clicked(&response), response.clicked()); + if response.clicked() { + seen.borrow_mut().push((response.double_clicked(), craft_ui::runtime::pointer::frame(ui.ctx()).pick_mods)); + } + }); + fixture.settle(); + let at = painted(&fixture, "234 pt").center(); + fixture.click_at(at); + assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods::NONE)]); + clicks.borrow_mut().clear(); + fixture.advance(1.0); + let button = |pressed, modifiers| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + fixture.frame_through(vec![ + button(true, Modifiers::NONE), + button(false, Modifiers::NONE), + button(true, Modifiers::NONE), + button(false, Modifiers::NONE), + ]); + assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods::NONE), (true, craft_keymap::Mods::NONE)]); + clicks.borrow_mut().clear(); + fixture.advance(1.0); + fixture.frame_through(vec![button(true, Modifiers::SHIFT), button(false, Modifiers::SHIFT), Event::ModifiersChanged(Modifiers::NONE)]); + assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods { shift: true, ..craft_keymap::Mods::NONE })]); + clicks.borrow_mut().clear(); + let rect = painted(&fixture, "234 pt"); + fixture.drag_at(rect.left_center() + Vec2::new(1.0, 0.0), Vec2::new(rect.width() * 0.75, 0.0)); + assert!(clicks.borrow().is_empty()); + fixture.frame_through(vec![ + Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }, + ]); + assert!(clicks.borrow().is_empty()); +} + +#[trial] +fn read_only_selectable_text_keeps_selection_without_reporting_activation() { + for inherited in [false, true] { + let clicked = Rc::new(Cell::new(false)); + let seen = clicked.clone(); + let mut fixture = Fixture::new(move |ui| { + craft_ui::runtime::env::with_env( + ui, + |scope| scope.read_only = Some(inherited), + |ui| { + let response = SelectableText::new("Length", "234 pt").read_only(!inherited).show(ui); + seen.set(seen.get() || response.clicked()); + }, + ); + }); + fixture.settle(); + fixture.click_at(painted(&fixture, "234 pt").center()); + assert!(!clicked.get(), "inherited read-only: {inherited}"); + assert_eq!(copy_all(&mut fixture), ["234 pt"]); + } +} + /// Select All then Copy in the focused text. fn copy_all(fixture: &mut Fixture) -> Vec { fixture.key(Key::A, Modifiers::COMMAND); From cbe89553af911ef5c550686b88f0ef5c4e051b63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:38:34 -0800 Subject: [PATCH 080/154] Save for Web: show when the selected colors are web-shifted --- .../form_dialogs/save_for_web/model.rs | 3 ++ .../form_dialogs/save_for_web/options.rs | 18 ++++--- .../form_dialogs/save_for_web/stories.rs | 1 + .../tests/it/form_dialogs/save_for_web.rs | 48 +++++++++++++++++-- 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs index 7f34928759..b435e100bc 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs @@ -238,6 +238,9 @@ pub struct TableMarks { pub transparent: Vec<[u8; 3]>, /// The shifted colours, from and to. pub shifted: Vec<([u8; 3], [u8; 3])>, + /// Web-shifted colours, identified by the same RGB entries the host supplies in the palette. + /// `None` keeps separate Shift and Unshift controls for a host that does not report this state. + pub web_shifted: Option>, } /// What the dialog is for: a raster document or a vector one. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs index 96b3ebc464..a8f40838bd 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs @@ -417,16 +417,20 @@ fn color_table_section(ui: &mut Ui, kit: &Kit<'_>, live: &mut Live, asked: &mut if !deleted.is_empty() { asked.table.push(ColorTableEvent { edit: ColorTableEdit::Delete, colors: deleted }); } + let web_shifted = marks.and_then(|marks| marks.web_shifted.as_deref()); + let unshift = !selected.is_empty() && web_shifted.is_some_and(|shifted| selected.iter().all(|color| shifted.contains(color))); + let (web_icon, web_label, web_edit) = + if unshift { ("undo", &words.unshift, ColorTableEdit::Unshift) } else { ("web_colors", &words.web_shift, ColorTableEdit::WebShift) }; let tools = [ - ("web_colors", &words.web_shift, ColorTableEdit::WebShift), - ("undo", &words.unshift, ColorTableEdit::Unshift), - ("lock", &words.lock, ColorTableEdit::Lock), - ("grid", &words.make_transparent, ColorTableEdit::Transparent), - ("trash", &words.delete_color, ColorTableEdit::Delete), + Some(("web_colors", web_icon, web_label, web_edit)), + web_shifted.is_none().then_some(("undo", "undo", &words.unshift, ColorTableEdit::Unshift)), + Some(("lock", "lock", &words.lock, ColorTableEdit::Lock)), + Some(("grid", "grid", &words.make_transparent, ColorTableEdit::Transparent)), + Some(("trash", "trash", &words.delete_color, ColorTableEdit::Delete)), ]; Row::new().id_salt("table-tools").show(ui, |ui, _| { - for (icon, label, edit) in &tools { - let button = IconButton::new(IconId::new(icon)).label((*label).clone()).enabled(!selected.is_empty()).id_salt(*icon).show(ui); + for (id, icon, label, edit) in tools.iter().flatten() { + let button = IconButton::new(IconId::new(icon)).label((*label).clone()).enabled(!selected.is_empty()).id_salt(*id).show(ui); if clicked(&button) { asked.table.push(ColorTableEvent { edit: edit.clone(), colors: selected.clone() }); } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs index 2bfee2e34b..91a7591ec5 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs @@ -99,6 +99,7 @@ fn story_marks() -> &'static TableMarks { locked: vec![[20, 20, 20]], transparent: vec![[240, 240, 240]], shifted: vec![([138, 111, 77], [132, 112, 82])], + web_shifted: None, }) } diff --git a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs index c1d12cdfd9..29ecdaeeed 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs @@ -5,8 +5,8 @@ use craft_theme::Srgba; use craft_ui::contract::Bind; use craft_ui::dialog::{DialogHost, DialogResult, StackDialog}; use craft_ui::patterns::form_dialogs::{ - Animation, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, WebFormat, - WebPictures, WebPreset, WebSlice, WebSlices, WebVariant, + Animation, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, TableMarks, + WebFormat, WebPictures, WebPreset, WebSlice, WebSlices, WebVariant, }; use craft_ui::testing::{Fixture, trial}; use egui::load::SizedTexture; @@ -172,22 +172,60 @@ fn gif(colors: u16) -> SaveForWebOptions { /// The colours of the palette the shown encode reports. const PALETTE: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; -/// Answers the encode the dialog asked for with `PALETTE` and selects the Optimized pane, which shows the Color Table. -fn show_palette(host: &Rc>, fixture: &mut Fixture) { +/// Answers the encode with the given colours and selects the Optimized pane, which shows the Color Table. +fn show_palette_with(host: &Rc>, fixture: &mut Fixture, palette: &[[u8; 3]]) { let wanted = host.borrow_mut().get_mut::().map(HostedSaveForWeb::wanted_variants).expect("open"); let revision = wanted.first().map_or(1, |want| want.request.revision); - let variant = WebVariant::new(0, revision, texture(), 1000).colors(4).palette(PALETTE.to_vec()); + let variant = WebVariant::new(0, revision, texture(), 1000).colors(palette.len() as u16).palette(palette.to_vec()); host.borrow_mut().get_mut::().expect("open").set_variant(variant); fixture.settle(); select_optimized_pane(fixture); } +fn show_palette(host: &Rc>, fixture: &mut Fixture) { + show_palette_with(host, fixture, &PALETTE); +} + /// The colour table events the dialog filed since the last call. fn table_events(host: &Rc>) -> Vec<(ColorTableEdit, Vec<[u8; 3]>)> { let events = host.borrow_mut().get_mut::().map(HostedSaveForWeb::take_table_events).expect("the dialog is open"); events.into_iter().map(|event: ColorTableEvent| (event.edit, event.colors)).collect() } +#[trial] +fn the_web_shift_button_follows_the_selected_colors_reported_by_the_host() { + let web = HostedSaveForWeb::new("poster.psd", IMAGE, texture()).options(gif(8)); + let (host, mut fixture) = open(web); + let set_web_shifted = |colors| { + let mut marks = TableMarks::default(); + marks.web_shifted = Some(colors); + host.borrow_mut().get_mut::().expect("open").set_marks(marks); + }; + set_web_shifted(Vec::new()); + let mut palette = PALETTE; + let source = [220, 210, 196]; + palette[1] = source; + show_palette_with(&host, &mut fixture, &palette); + let cell = fixture.by_label("1 #dcd2c4").expect("the unshifted entry"); + fixture.click(&cell).settle(); + + assert!(fixture.by_label("Unshift Colors").is_none(), "an unshifted selection offers Shift"); + let shift = fixture.by_label("Shift to Web Palette").expect("the Shift button"); + fixture.click(&shift).settle(); + assert_eq!(table_events(&host), [(ColorTableEdit::WebShift, vec![source])]); + + let shifted = [204, 204, 204]; + palette[1] = shifted; + set_web_shifted(vec![shifted]); + show_palette_with(&host, &mut fixture, &palette); + let cell = fixture.by_label("1 #cccccc").expect("the shifted entry"); + fixture.click(&cell).settle(); + assert!(fixture.by_label("Shift to Web Palette").is_none(), "a shifted selection offers Unshift"); + let unshift = fixture.by_label("Unshift Colors").expect("the Unshift button"); + fixture.click(&unshift).settle(); + assert_eq!(table_events(&host), [(ColorTableEdit::Unshift, vec![shifted])]); +} + #[trial] fn a_slice_warning_appears_once_below_the_preview_captions() { let warning = "5 stored slices past the first 10000 were ignored"; From 169fd17da39715c4cd342bd749c60577c6e6e9f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:48:43 -0800 Subject: [PATCH 081/154] Forms: let a field require more than one enabled condition --- crates/ui-panels/src/sections/footer.rs | 16 +++ .../src/patterns/form_dialogs/dialog.rs | 108 +++++++++++++----- .../src/patterns/form_dialogs/param.rs | 15 ++- .../tests/it/form_dialogs/dialog.rs | 82 +++++++++++++ .../tests/it/form_dialogs/params.rs | 32 ++++++ 5 files changed, 220 insertions(+), 33 deletions(-) diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index 40427888a3..b3eb2a3824 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -444,6 +444,7 @@ impl DialogRole { pub struct FooterButton { label: Label, role: DialogRole, + tag: Option, letter: Option, chord: Option, enabled: bool, @@ -478,6 +479,7 @@ impl FooterButton { FooterButton { label: label.into(), role, + tag: None, letter: None, chord: None, enabled: true, @@ -488,6 +490,20 @@ impl FooterButton { } } + /// Associates a generated button with the dialog body that handles it. + #[doc(hidden)] + #[must_use] + pub const fn tagged(mut self, tag: Id) -> Self { + self.tag = Some(tag); + self + } + + /// The generated button's identity, preserved through footer settlement and picking. + #[doc(hidden)] + pub const fn tag(&self) -> Option { + self.tag + } + /// The letter that activates the button while its dialog holds focus and no text part owns the keys. On Windows /// and Linux, Alt with the letter also activates it while its dialog is the top modal, whatever has the focus. The /// button reports the letter as its `access_key`. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 46f9ed81dc..57e8bc93cc 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -36,7 +36,7 @@ use crate::runtime::env::{Env, Label}; use crate::text::RangeAlert; use craft_behavior::{CanvasTransform, DisplayOrder, EditEvent, ItemSource, Mixed, SelectionChange}; -use crate::runtime::memory::{Lifetime, MemoryStage, with_session}; +use crate::runtime::memory::{Lifetime, MemoryStage}; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; @@ -45,10 +45,11 @@ use crate::sections::{DialogRole, FooterButton}; use crate::contract::{CaptionColumn, LabelScheme}; use craft_theme::Srgba; use craft_theme::variant::Tone; -use egui::{Context, Pos2, Rect, Response, Ui}; +use egui::{Context, Id, Pos2, Rect, Response, Ui}; use serde_json::Value; use std::borrow::Cow; +use std::collections::HashMap; use std::sync::Arc; #[cfg(feature = "suite")] @@ -471,14 +472,6 @@ impl<'a> ParamPresets<'a> { } } -/// The footer rows of a [`ParamDialog`] between passes: whether each was on when the last pass ended, which its -/// button label shows, and the key of the row whose button was pressed, which the next pass flips. -#[derive(Clone, Debug, Default)] -struct FooterRows { - on: Vec, - flip: Option, -} - /// What `ParamDialog::below` draws under the rows. pub struct BelowRows<'a>(BelowRowsFn<'a>); @@ -719,17 +712,11 @@ impl<'a> ParamDialog<'a> { } // The pane shows only in a dialog that previews. let preview = preview.filter(|_| previews); - // The footer rows' buttons follow the extra buttons. A button's label cannot change inside the pass that - // draws it, so it shows the state the previous pass left. + // The footer rows' buttons follow the extra buttons; the body settles them by tag after it reads the fields. let footer_rows: Vec<&Param> = params.iter().filter(|param| param.footer_on().is_some()).collect(); - let footer_id = crate::runtime::memory::unique(("paramDialog.footer", key.as_str())); - let footer_states: Vec = - if footer_rows.is_empty() { Vec::new() } else { with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.on.clone()) }; - let footer_buttons = footer_rows.iter().enumerate().map(|(at, param)| { - let on = footer_states.get(at).copied().unwrap_or(false); - let label = param.footer_on().filter(|_| on).unwrap_or_else(|| param.label.clone()); - FooterButton::new(label, DialogRole::Other).stays_open(true) - }); + let footer_buttons = footer_rows.iter().map(|param| footer_toggle(param, false, true)); + let footer_owner = crate::runtime::overlay::running_dialog(ui.ctx()).unwrap_or_else(|| ui.scope_id()); + let footer_owner = crate::runtime::memory::unique(("paramDialog.footer.owner", footer_owner, key.as_str())); let buttons: Vec = extra_buttons.iter().map(|(_, button)| button.clone()).chain(footer_buttons).collect(); if !buttons.is_empty() { form = form.extra_buttons(buttons); @@ -807,7 +794,8 @@ impl<'a> ParamDialog<'a> { // A footer row pressed in the previous pass flips once; a measuring run leaves it for the real one. if !footer_rows.is_empty() && !crate::runtime::measure::active(ui.ctx()) - && let Some(flip) = with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.flip.take()) + && let Some(flip) = footer_flips(ui.ctx(), |flips| flips.ready.remove(&footer_owner)) + && footer_rows.iter().any(|param| param.key == flip && param.enabled(values)) { let on = values.bool(&flip).unwrap_or(false); values.set(flip, FieldValue::Bool(!on)); @@ -883,10 +871,13 @@ impl<'a> ParamDialog<'a> { } } *cx.memory::() = live.clone(); - if !footer_rows.is_empty() { - let states: Vec = footer_rows.iter().map(|param| values.bool(¶m.key).unwrap_or(false)).collect(); - with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.on = states); - } + *cx.memory::() = FooterToggles { + owner: Some(footer_owner), + buttons: footer_rows + .iter() + .map(|param| (param.key.clone(), footer_toggle(param, values.bool(¶m.key).unwrap_or(false), param.enabled(values)))) + .collect(), + }; // OK and Enter wait while a row's text does not parse. rows.as_ref().is_none_or(|rows| !rows.unparsed) }); @@ -897,12 +888,6 @@ impl<'a> ParamDialog<'a> { Some(ResetPick::Extra(at)) => extra_buttons.get(at).map(|(id, _)| id.clone()), _ => None, }; - if let Some(ResetPick::Extra(at)) = pick - && let Some(param) = at.checked_sub(extra_buttons.len()).and_then(|at| footer_rows.get(at)) - { - with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.flip = Some(param.key.clone())); - crate::runtime::frame::request_repaint(ui.ctx()); - } // Footer and row buttons share one channel. The rows' own slot is emptied, so a host that absorbs the rows // files the press once. let action = rows.as_mut().and_then(|rows: &mut ParamRowsOutput| rows.action.take()).or(pressed); @@ -1020,6 +1005,48 @@ struct Footing { ok: Option, } +/// The current labels and enablement of the generated footer buttons, from this dialog's body. +#[derive(Clone, Default)] +struct FooterToggles { + owner: Option, + buttons: Vec<(String, FooterButton)>, +} + +/// One pass of queued flips, keyed by dialog instance. Flips whose dialogs do not show on the next pass expire. +#[derive(Default)] +struct FooterFlips { + ready: HashMap, + next: HashMap, +} + +impl crate::runtime::frame::Stored for FooterFlips {} + +fn footer_flips(ctx: &Context, f: impl FnOnce(&mut FooterFlips) -> R) -> R { + use crate::runtime::frame::{PassStep, PerViewport, Stamped, running}; + let (viewport, pass) = if let Some(facts) = running(ctx) { + (facts.viewport, facts.pass_nr) + } else { + let viewport = ctx.viewport_id(); + (viewport, ctx.cumulative_pass_nr_for(viewport)) + }; + PerViewport::>::with_pass( + ctx, + viewport, + pass, + |flips, step| match step { + PassStep::Next => flips.ready = std::mem::take(&mut flips.next), + PassStep::Skipped => *flips = FooterFlips::default(), + }, + f, + ) +} + +fn footer_toggle(param: &Param, on: bool, enabled: bool) -> FooterButton { + let label = param.footer_on().filter(|_| on).unwrap_or_else(|| param.label.clone()); + let tag = crate::runtime::memory::unique(("paramDialog.footer", ¶m.key)); + FooterButton::new(label, DialogRole::Other).tagged(tag).stays_open(true).enabled(enabled) +} + /// What a footer with a Reset alternative answered with. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -1117,12 +1144,31 @@ impl ResetFooter { if let (Some(ok), Some(accept)) = (footing.ok, buttons.first_mut()) { accept.set_enabled(ok); } + let toggles = &cx.memory::().buttons; + for button in buttons { + if let Some(tag) = button.tag() + && let Some((_, toggle)) = toggles.iter().find(|(_, toggle)| toggle.tag() == Some(tag)) + { + *button = toggle.clone(); + } + } }) .on_pick(move |button, cx| { if pick.resetting() && button.role() == DialogRole::Other && *button.label() == pick.reset { restore(cx); crate::runtime::frame::request_repaint(cx.memory.ctx()); } + let toggles = cx.memory::(); + if let (Some(owner), Some(tag)) = (toggles.owner, button.tag()) + && let Some((key, _)) = toggles.buttons.iter().find(|(_, toggle)| toggle.tag() == Some(tag)) + { + let key = key.clone(); + let ctx = cx.memory.ctx(); + footer_flips(ctx, |flips| { + flips.next.insert(owner, key); + }); + crate::runtime::frame::request_repaint(ctx); + } }) } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index f83dbadd15..0b404e8254 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -621,6 +621,8 @@ pub(crate) struct RowOptions { resets: Vec, /// The row takes input only while the number under the key is above the bound ([`Param::enabled_above`]). enabled_above: Option<(String, f64)>, + /// Additional field conditions that must all hold ([`Param::and_enabled_when_in`]). + enabled_when_also: Vec<(String, Vec)>, /// The row takes input only while the values under the two keys differ ([`Param::enabled_when_differs`]). enabled_when_differs: Option<(String, String)>, /// The value the row shows while it is disabled ([`Param::disabled_value`]). @@ -914,6 +916,14 @@ impl Param { self } + /// Adds a condition: the row takes input only while `fields[key]` equals one of `values` and every other + /// enable condition holds. A missing field does not satisfy it. + #[must_use] + pub fn and_enabled_when_in(mut self, key: impl Into, values: impl IntoIterator>) -> Self { + self.options.get_or_insert_default().enabled_when_also.push((key.into(), values.into_iter().map(Into::into).collect())); + self + } + /// The row takes input only while the number `fields[key]` is above `bound` (an int reads as a number); otherwise /// it is shown disabled. #[must_use] @@ -1500,8 +1510,7 @@ impl Param { self.shown && self.visible_when.iter().all(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held))) } - /// Whether the row takes input with `fields`: every condition its `enabled_when`, - /// [`enabled_above`](Param::enabled_above) and [`enabled_when_differs`](Param::enabled_when_differs) set holds. + /// Whether the row takes input with `fields`: every enable condition must hold. pub fn enabled(&self, fields: &DialogFields) -> bool { let options = self.options.as_deref(); let enabled = match &self.enable { @@ -1510,6 +1519,8 @@ impl Param { Enable::Off => false, }; enabled + && options + .is_none_or(|options| options.enabled_when_also.iter().all(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held)))) && options.and_then(|options| options.enabled_above.as_ref()).is_none_or(|(key, bound)| fields.number(key).is_some_and(|n| n > *bound)) && options.and_then(|options| options.enabled_when_differs.as_ref()).is_none_or(|(a, b)| fields.get(a) != fields.get(b)) } diff --git a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs index ee63330c0e..8770d17ef9 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs @@ -1139,6 +1139,88 @@ fn a_footer_row_flips_its_value_and_automation_sets_it() { assert!(!ParamDialog::remembered(&footer_params(), &fields).contains("grid"), "the footer key is not remembered"); } +#[trial] +fn a_footer_toggle_takes_input_only_while_all_its_conditions_hold() { + let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false))); + let mut fixture = host_fixture(&host, &twice); + let ctx = fixture.ctx().clone(); + fn build(fields: &mut DialogFields) -> ParamDialog<'_> { + let rows = vec![ + Param::new("custom", "Custom", ParamKind::bool(false)), + Param::new("advanced", "Advanced", ParamKind::bool(false)), + Param::new("grid", "Show Grid", ParamKind::bool(false)) + .enabled_when("custom", true) + .and_enabled_when_in("advanced", [true]) + .in_footer("Hide Grid"), + ]; + ParamDialog::new("conditional-grid", "Grid", rows).values(Bind::bound(fields)) + } + let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "conditional-grid", DialogFields::new(), build)); + let grid = || on_dialog(&host, |dialog| dialog.fields().bool("grid")).flatten(); + fixture.idle(6); + assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "custom", json!(true)), Ok(())); + fixture.idle(6); + let button = fixture.by_label("Show Grid").expect("the footer button stays visible"); + assert!(fixture.tree().is_disabled_key(button.node)); + fixture.click(&button).idle(6); + assert_ne!(grid(), Some(true), "a disabled footer button does not flip the value"); + assert!(host.borrow_mut().set_json_field(&ctx, id, "grid", json!(true)).is_err()); + + assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(true)), Ok(())); + fixture.idle(6); + let button = fixture.by_label("Show Grid").expect("the footer button"); + assert!(!fixture.tree().is_disabled_key(button.node)); + fixture.press(&button).release(&button); + assert_ne!(grid(), Some(true), "the flip waits for the next pass"); + assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(false)), Ok(())); + fixture.idle(6); + assert_ne!(grid(), Some(true), "a queued flip is dropped once its condition no longer holds"); + + assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(true)), Ok(())); + fixture.idle(6); + let button = fixture.by_label("Show Grid").expect("the footer button is enabled again"); + fixture.click(&button).idle(6); + assert_eq!(grid(), Some(true)); + assert!(fixture.by_label("Hide Grid").is_some()); +} + +#[trial] +fn a_queued_footer_press_follows_its_dialog_when_the_stack_changes() { + let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false))); + let mut fixture = host_fixture(&host, &twice); + let ctx = fixture.ctx().clone(); + let lower = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("lower")); + let top = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("top")); + fixture.idle(6); + let top_button = fixture.by_label("Show Grid").expect("the top dialog's toggle"); + fixture.press(&top_button).release(&top_button); + assert!(host.borrow_mut().cancel_by_id(&ctx, lower)); + let new = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("new")); + fixture.idle(6); + let grid = |id| host.borrow().get_by_id::(id).and_then(|dialog| dialog.fields().bool("grid")); + assert_eq!(grid(top), Some(true), "the press follows the original dialog"); + assert_eq!(grid(new), Some(false), "the new dialog does not inherit the press"); +} + +#[trial] +fn a_replacement_footer_button_keeps_its_own_enablement() { + let mut fixture = Fixture::new(|ui| { + ParamDialog::new("custom-footer", "Custom Footer", footer_params()) + .shaped(|dialog| { + dialog.buttons([ + FooterButton::new("OK", DialogRole::Accept), + FooterButton::new("Cancel", DialogRole::Cancel), + FooterButton::new("Unavailable", DialogRole::Other).enabled(false), + ]) + }) + .show(ui); + }); + fixture.settle(); + let replacement = fixture.by_label("Unavailable").expect("the caller's replacement button"); + assert!(fixture.tree().is_disabled_key(replacement.node)); + assert!(fixture.by_label("Show Grid").is_none()); +} + // The presets row lists the presets; a pick writes the preset's values as one edit, and a value edited after it // leaves the values matching no preset. #[trial] diff --git a/crates/ui-patterns/tests/it/form_dialogs/params.rs b/crates/ui-patterns/tests/it/form_dialogs/params.rs index ed2792b745..feb765491c 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/params.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/params.rs @@ -198,6 +198,38 @@ fn rows_follow_their_predicates_and_carry_their_tooltip() { assert!(fixture.tree().is_disabled_key(detail.node), "disabled for the third value"); } +#[trial] +fn a_row_checks_all_its_enable_conditions_on_screen_and_in_automation() { + let params = vec![ + Param::new("hyphenate", "Hyphenation", ParamKind::bool(false)), + Param::new("zone", "Hyphenation Zone", ParamKind::int(Some(0), None, 0)) + .enabled_when("hyphenate", true) + .and_enabled_when_in("composer", ["singleLine", "standardSingleLine"]), + ]; + let values = Rc::new(RefCell::new(DialogFields::new())); + let mut fixture = rows(params.clone(), &values); + for (hyphenate, composer, enabled) in [ + (true, None, false), + (false, Some("singleLine"), false), + (true, Some("everyLine"), false), + (true, Some("singleLine"), true), + (true, Some("standardSingleLine"), true), + ] { + { + let mut fields = values.borrow_mut(); + fields.set("hyphenate", hyphenate); + if let Some(composer) = composer { + fields.set("composer", composer); + } + } + fixture.settle(); + let zone = fixture.by_label("Hyphenation Zone").expect("the row stays visible"); + assert_eq!(!fixture.tree().is_disabled_key(zone.node), enabled, "{hyphenate}, {composer:?}"); + let mut fields = values.borrow().clone(); + assert_eq!(set_param_field(¶ms, &mut fields, "zone", json!(8)).is_ok(), enabled, "{hyphenate}, {composer:?}"); + } +} + // A row with two `visible_when` conditions is there only while both hold: the second call adds a condition, not // replaces the first. A `disabled` row takes no input whatever the fields hold, from a click or from automation. #[trial] From cb820a84ae94d3a2c8c70b91c262c35b21e5bc39 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:08:02 -0800 Subject: [PATCH 082/154] ui-widgets: let a slider step through a value ladder Keep the track's mapping and snapping when a caller supplies custom steps for the keyboard, wheel and accessibility actions. Report each available direction without advertising a fixed increment. --- crates/ui-contract/src/runtime/access.rs | 7 ++ crates/ui-contract/src/runtime/access/emit.rs | 28 ++++-- crates/ui-widgets/src/text/number/rule.rs | 5 +- crates/ui-widgets/src/value_drag/slider.rs | 87 +++++++++++++++++-- crates/ui-widgets/tests/it/value_drag.rs | 53 +++++++++++ 5 files changed, 162 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 3875e52017..c33b6d4522 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -293,6 +293,7 @@ pub struct Access { pub(crate) unit: Option, pub(crate) color: Option, pub(crate) numeric: Option, + pub(crate) variable_steps: Option<(bool, bool)>, pub(crate) expanded: Option, pub(crate) has_popup: Option, pub(crate) level: Option, @@ -363,6 +364,12 @@ impl Access { self } + /// Offers the available Increment and Decrement actions for a numeric value with no fixed step size. + pub fn variable_steps(&mut self, increment: bool, decrement: bool) -> &mut Self { + self.variable_steps = Some((increment, decrement)); + self + } + /// Whether a disclosure is open, when no flag says it. pub fn expanded(&mut self, on: bool) -> &mut Self { self.expanded = Some(on); diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 50c92339ae..c117a209c0 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -161,7 +161,14 @@ fn write_position(spec: &mut NodeSpec, position: Option, level: Opt } /// The actions the interaction and the numeric facts declare. -fn declare_actions(spec: &mut NodeSpec, focusable: bool, clickable: bool, context_menu: bool, numeric: Option<&Numeric>) { +fn declare_actions( + spec: &mut NodeSpec, + focusable: bool, + clickable: bool, + context_menu: bool, + numeric: Option<&Numeric>, + variable_steps: Option<(bool, bool)>, +) { // A read-only value offers no action that would change it. let numeric = numeric.filter(|_| !spec.read_only); if focusable { @@ -173,17 +180,22 @@ fn declare_actions(spec: &mut NodeSpec, focusable: bool, clickable: bool, contex if context_menu { spec.actions.push(NodeAction::ContextMenu); } - if let Some(numeric) = numeric.filter(|numeric| numeric.step.is_some()) { + if let Some(numeric) = numeric { // A step that cannot move the value is not offered: no Increment at the range's end, unless the value wraps. let stuck = |at_end: bool| at_end && !numeric.wraps; - if !stuck(numeric.value.is_some_and(|value| value >= *numeric.range.end())) { + let (increment, decrement) = variable_steps.unwrap_or_else(|| { + let has_step = numeric.step.is_some(); + ( + has_step && !stuck(numeric.value.is_some_and(|value| value >= *numeric.range.end())), + has_step && !stuck(numeric.value.is_some_and(|value| value <= *numeric.range.start())), + ) + }); + if increment { spec.actions.push(NodeAction::Increment); } - if !stuck(numeric.value.is_some_and(|value| value <= *numeric.range.start())) { + if decrement { spec.actions.push(NodeAction::Decrement); } - } - if numeric.is_some() { spec.actions.push(NodeAction::SetValue); } } @@ -308,7 +320,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { if let Some(expanded) = expanded { spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand }); } - declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric); + declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric, access.variable_steps); declare_scroll_actions(&mut spec, (own.scrolls.0 || access.pans.0, own.scrolls.1 || access.pans.1)); custom_actions(&mut spec, &access.custom_actions); write_node(ctx, own.id, &spec); @@ -404,7 +416,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { spec.sort = node.sort; spec.sortable = node.sortable; write_states(&mut spec, flags, None, decl.enabled, false); - declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric); + declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric, None); if node.steps && numeric.is_none() { spec.actions.extend([NodeAction::Increment, NodeAction::Decrement]); } diff --git a/crates/ui-widgets/src/text/number/rule.rs b/crates/ui-widgets/src/text/number/rule.rs index 4368203c97..62056b348f 100644 --- a/crates/ui-widgets/src/text/number/rule.rs +++ b/crates/ui-widgets/src/text/number/rule.rs @@ -8,8 +8,7 @@ use std::borrow::Cow; use std::marker::PhantomData; use std::ops::RangeInclusive; -/// The value one step from a value in a direction: the up arrow, the wheel and the Page keys of a field whose values -/// lie on a ladder instead of a grid (`NumberField::stepper`). The direction is `1` up and `-1` down. +/// A custom step for a number field or slider whose values lie on a ladder instead of a grid. pub struct NumberStepper<'a>(Box f64 + 'a>); impl<'a> NumberStepper<'a> { @@ -19,7 +18,7 @@ impl<'a> NumberStepper<'a> { NumberStepper(Box::new(next)) } - pub(super) fn next(&self, from: f64, direction: i32, scale: f64) -> f64 { + pub(crate) fn next(&self, from: f64, direction: i32, scale: f64) -> f64 { (self.0)(from, direction, scale) } } diff --git a/crates/ui-widgets/src/value_drag/slider.rs b/crates/ui-widgets/src/value_drag/slider.rs index e2dc3e183d..d7089cba0e 100644 --- a/crates/ui-widgets/src/value_drag/slider.rs +++ b/crates/ui-widgets/src/value_drag/slider.rs @@ -12,6 +12,9 @@ use crate::contract::{ use crate::runtime::env::Label; use crate::runtime::focus::{ActivateKeys, KeepKeys, KeyUse}; use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceStyle, TextLook, TrackLook}; +use crate::text::NumberStepper; +use craft_behavior::intent::{MoveMods, NavMove}; +use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps, step_value}; use craft_behavior::{Flow, HitLevel, HitPriority, Metrics, PartKey, PressPhase, Proposal, Sense, WheelPhase}; use craft_theme::Stateful; use egui::{Pos2, Rect, Vec2}; @@ -70,6 +73,13 @@ pub struct Slider<'a> { /// no stops. #[prop(quantity = "step")] step: Option, + /// Where keys, accessibility actions and the wheel step from the current value. The direction is 1 or -1; + /// the magnitude counts steps. A ladder steps in that direction without wrapping. The callback is also + /// queried for the available accessibility actions. + /// It takes precedence over the fixed key and wheel steps. Pointer placement, including snapping, + /// still uses the track's scale. + #[prop(func = "Fn(f64, i32, f64) -> f64")] + stepper: Option>, /// How positions along the track map to values. #[prop] scale: SliderScale, @@ -82,7 +92,7 @@ pub struct Slider<'a> { marks: Marks, /// The change of one wheel notch where it is coarser than the step (an offset of 0.0001 steps that wants 0.01 a /// notch); the step by default. Shift and Alt scale it as they scale the step. A logarithmic track with no step - /// moves along the track and ignores it. + /// moves along the track and ignores it. A custom stepper also overrides it. #[prop(quantity = "step")] wheel_step: Option, /// When a press on the track sets the value: on its release or drag (the default), or as the primary button goes @@ -90,8 +100,8 @@ pub struct Slider<'a> { #[prop] track_press: TrackPress, /// The value as the caller words it ("50 %"), in place of the slider's own value text: the number in the step's - /// decimals, or in one decimal without a step. Assistive technology reads it, and so does a viewer that - /// shows the value beside the slider. + /// decimals, in one decimal without a step, or at the local step's precision with a custom stepper. Assistive + /// technology reads it, and so does a viewer that shows the value beside the slider. #[prop(into)] value_text: 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::

{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 b3663dae2b27901addc6d6b6781db8b8047b43f8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 26 Nov 2026 21:56:04 -0500 Subject: [PATCH 121/154] feat(update): default update checks to signed getartcraft.com catalog with GitHub fallback --- Cargo.lock | 3 + crates/update/Cargo.toml | 3 + .../assets/launcher-catalog-public-key.pem | 3 + crates/update/src/catalog.rs | 373 ++++++++++++++++++ crates/update/src/lib.rs | 23 +- crates/update/src/protocol.rs | 2 +- crates/update/src/source.rs | 70 ++++ 7 files changed, 475 insertions(+), 2 deletions(-) create mode 100644 crates/update/assets/launcher-catalog-public-key.pem create mode 100644 crates/update/src/catalog.rs diff --git a/Cargo.lock b/Cargo.lock index 2e14ca9825..7a2f52f116 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4659,11 +4659,13 @@ dependencies = [ name = "craft-update" version = "0.1.0" dependencies = [ + "base64 0.22.1", "chrono", "craft-host", "craft-theme", "craft-ui", "dunce", + "ed25519-dalek 2.2.0", "egui", "flate2", "image", @@ -4676,6 +4678,7 @@ dependencies = [ "sha2 0.10.9", "tar", "tempfile", + "toml", "ureq", "verifysign", "winreg", diff --git a/crates/update/Cargo.toml b/crates/update/Cargo.toml index c9a33bd7f6..fdace6226c 100644 --- a/crates/update/Cargo.toml +++ b/crates/update/Cargo.toml @@ -41,6 +41,9 @@ serde_json = { workspace = true } log = "0.4" tempfile = "3" sha2 = "0.10" +base64 = "0.22" +ed25519-dalek = { version = "2.2", default-features = false, features = ["std", "fast", "pem"] } +toml = { version = "=1.1.8", default-features = false, features = ["parse", "serde", "std"] } ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "_ring", "gzip", "platform-verifier"] } chrono = { workspace = true } semver = { version = "1", features = ["serde"] } diff --git a/crates/update/assets/launcher-catalog-public-key.pem b/crates/update/assets/launcher-catalog-public-key.pem new file mode 100644 index 0000000000..458f762668 --- /dev/null +++ b/crates/update/assets/launcher-catalog-public-key.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEArvYP9xTYyIXT+nJ3kRzhHtkTqbC1UnDCHPvO8iP/qRs= +-----END PUBLIC KEY----- diff --git a/crates/update/src/catalog.rs b/crates/update/src/catalog.rs new file mode 100644 index 0000000000..26482a8185 --- /dev/null +++ b/crates/update/src/catalog.rs @@ -0,0 +1,373 @@ +//! Signed release catalog hosted at `https://getartcraft.com/launcher-catalog.toml`. +//! +//! Verified against the compiled-in Ed25519 public key before parsing. Used as the primary +//! update source so apps don't each poll `api.github.com` (60 unauthenticated requests/hour), +//! with GitHub as the automatic fallback when the catalog is unavailable, stale, or omits an app. + +use std::collections::BTreeMap; + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use ed25519_dalek::{Signature, VerifyingKey, pkcs8::DecodePublicKey}; +use serde::Deserialize; + +use crate::app::App; +use crate::http::Http; +use crate::release::{self, Asset, Release}; +use crate::time::parse_rfc3339; +use crate::version; + +/// Where the signed release catalog lives. +pub const CATALOG_URL: &str = "https://getartcraft.com/launcher-catalog.toml"; +/// Detached Ed25519 signature over [`CATALOG_URL`]. +pub const SIGNATURE_URL: &str = "https://getartcraft.com/launcher-catalog.toml.sig"; +/// Pinned SPKI PEM public key corresponding to `LAUNCHER_CATALOG_SIGNING_KEY`. +pub const PUBLIC_KEY_PEM: &str = include_str!("../assets/launcher-catalog-public-key.pem"); +/// Maximum accepted catalog size (1 MiB). +pub const MAX_CATALOG_BYTES: usize = 1 << 20; +/// Maximum accepted base64 signature size. +pub const MAX_SIGNATURE_BYTES: usize = 128; +/// How long a signed catalog snapshot is trusted before falling back to GitHub (24 hours). +pub const MAX_AGE: i64 = 24 * 3600; + +/// Verified release metadata extracted from `launcher-catalog.toml`. +#[derive(Clone, Debug, Default)] +pub struct SignedCatalog { + /// When the website build generated this catalog (Unix seconds). + pub generated_at: Option, + apps: BTreeMap, +} + +#[derive(Clone, Debug)] +struct CatalogEntry { + repo: Option, + stable: Option, + prerelease: Option, + nightly: Option, +} + +#[derive(Deserialize, Default)] +struct Document { + #[serde(default)] + generated_at: Option, + #[serde(default)] + launcher: Option, + #[serde(default)] + apps: Vec, +} + +#[derive(Deserialize, Default)] +struct RawApp { + #[serde(default)] + id: Option, + #[serde(default)] + repo: Option, + #[serde(default)] + releases: Option, +} + +#[derive(Deserialize, Default)] +struct RawChannels { + #[serde(default)] + stable: Option, + #[serde(default)] + prerelease: Option, + #[serde(default)] + nightly: Option, +} + +#[derive(Clone, Debug, Deserialize, Default)] +struct RawRelease { + #[serde(default)] + tag: Option, + #[serde(default)] + name: Option, + #[serde(default)] + published_at: Option, + #[serde(default)] + html_url: Option, + #[serde(default)] + prerelease: bool, + #[serde(default)] + notes_markdown: Option, + #[serde(default)] + assets: Vec, +} + +#[derive(Clone, Debug, Deserialize, Default)] +struct RawAsset { + #[serde(default)] + name: Option, + #[serde(default)] + size_bytes: u64, + #[serde(default)] + download_url: Option, + #[serde(default)] + sha256: Option, +} + +impl SignedCatalog { + /// Fetches and verifies the signed catalog from `getartcraft.com`. + pub fn fetch(http: &Http) -> Result { + Self::fetch_from(http, CATALOG_URL, SIGNATURE_URL) + } + + /// Fetches and verifies the signed catalog from explicit URLs. + pub fn fetch_from(http: &Http, catalog_url: &str, signature_url: &str) -> Result { + let catalog = http.get_bytes(catalog_url, MAX_CATALOG_BYTES)?.ok_or("catalog not published")?; + let signature = http.get_bytes(signature_url, MAX_SIGNATURE_BYTES)?.ok_or("catalog signature not published")?; + Self::verify(&catalog, &signature) + } + + /// Verifies `signature` over `bytes` with the pinned Ed25519 key, then parses the TOML. + pub fn verify(bytes: &[u8], signature: &[u8]) -> Result { + let key = VerifyingKey::from_public_key_pem(PUBLIC_KEY_PEM).map_err(|_| "invalid compiled catalog key")?; + Self::verify_with_key(bytes, signature, &key) + } + + /// Verifies `signature` over `bytes` with an explicit key, then parses the TOML. + pub fn verify_with_key(bytes: &[u8], signature: &[u8], key: &VerifyingKey) -> Result { + if bytes.len() > MAX_CATALOG_BYTES || signature.len() > MAX_SIGNATURE_BYTES { + return Err("signed catalog or signature exceeds byte limit".into()); + } + let encoded = std::str::from_utf8(signature).map_err(|_| "signature is not UTF-8")?.trim(); + let decoded = STANDARD.decode(encoded).map_err(|_| "invalid base64 signature")?; + let sig = Signature::from_slice(&decoded).map_err(|_| "invalid Ed25519 signature length")?; + key.verify_strict(bytes, &sig).map_err(|_| "catalog signature does not match the pinned key")?; + + let text = std::str::from_utf8(bytes).map_err(|_| "catalog is not UTF-8")?; + let doc: Document = toml::from_str(text).map_err(|e| format!("invalid catalog TOML: {e}"))?; + let generated_at = doc.generated_at.as_deref().and_then(parse_rfc3339); + + let mut apps = BTreeMap::new(); + if let Some(launcher) = doc.launcher + && let Some(channels) = launcher.releases + { + let id = launcher.id.unwrap_or_else(|| "artcraft-launcher".into()).to_lowercase(); + apps.insert( + id, + CatalogEntry { repo: launcher.repo, stable: channels.stable, prerelease: channels.prerelease, nightly: channels.nightly }, + ); + } + for app in doc.apps { + let Some(id) = app.id.filter(|s| !s.is_empty()) else { continue }; + let Some(channels) = app.releases else { continue }; + apps.insert( + id.to_lowercase(), + CatalogEntry { repo: app.repo, stable: channels.stable, prerelease: channels.prerelease, nightly: channels.nightly }, + ); + } + Ok(Self { generated_at, apps }) + } + + /// The latest release for `app` at `now` (stable, or the higher of stable/prerelease when + /// `prereleases` is true). Returns `None` if the catalog is stale, omits `app`, or the repo + /// does not match `app.repo`. + pub fn latest_for(&self, app: &App, prereleases: bool, now: i64) -> Option { + let entry = self.fresh_entry(app.id, app.repo, now)?; + let stable = entry.stable.as_ref().and_then(|r| r.to_release(app.repo)); + if !prereleases { + return stable; + } + let pre = entry.prerelease.as_ref().and_then(|r| r.to_release(app.repo)); + match (stable, pre) { + (Some(s), Some(p)) => { + let pick_pre = match (&p.version, &s.version) { + (Some(pv), Some(sv)) => version::is_newer(pv, sv), + _ => false, + }; + Some(if pick_pre { p } else { s }) + } + (Some(s), None) => Some(s), + (None, Some(p)) => Some(p), + (None, None) => None, + } + } + + /// Looks up a release by `repo` (`owner/repo`), for callers that implement [`crate::source::ReleaseSource`]. + pub fn latest_for_repo(&self, repo: &str, prereleases: bool, now: i64) -> Option { + let generated_at = self.generated_at?; + if now.saturating_sub(generated_at) > MAX_AGE { + return None; + } + let entry = self.apps.values().find(|e| e.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(repo)))?; + let stable = entry.stable.as_ref().and_then(|r| r.to_release(repo)); + if !prereleases { + return stable; + } + let pre = entry.prerelease.as_ref().and_then(|r| r.to_release(repo)); + match (stable, pre) { + (Some(s), Some(p)) => { + let pick_pre = match (&p.version, &s.version) { + (Some(pv), Some(sv)) => version::is_newer(pv, sv), + _ => false, + }; + Some(if pick_pre { p } else { s }) + } + (Some(s), None) => Some(s), + (None, Some(p)) => Some(p), + (None, None) => None, + } + } + + /// The newest nightly release for `app` at `now`, if listed. + pub fn nightly_for(&self, app: &App, now: i64) -> Option { + let entry = self.fresh_entry(app.id, app.repo, now)?; + entry.nightly.as_ref().and_then(|r| r.to_release(app.repo)) + } + + fn fresh_entry(&self, id: &str, repo: &str, now: i64) -> Option<&CatalogEntry> { + let generated_at = self.generated_at?; + if now.saturating_sub(generated_at) > MAX_AGE { + return None; + } + let entry = self.apps.get(&id.to_lowercase())?; + if let Some(entry_repo) = &entry.repo + && !entry_repo.eq_ignore_ascii_case(repo) + { + return None; + } + Some(entry) + } +} + +impl RawRelease { + fn to_release(&self, repo: &str) -> Option { + let tag = self.tag.as_deref().filter(|t| !t.is_empty() && t.len() <= 64 && release::valid_tag(t))?; + let version = version::parse(tag)?; + let prefix = release::download_prefix(repo); + let assets = self + .assets + .iter() + .filter_map(|a| { + let name = a.name.as_deref().filter(|n| release::valid_file_name(n))?; + let url = a.download_url.as_deref()?; + let expected = format!("{prefix}{tag}/{name}"); + if url != expected || !release::download_url_under(url, &prefix) { + return None; + } + let sha256 = a + .sha256 + .as_deref() + .filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())) + .map(str::to_ascii_lowercase); + Some(Asset { name: name.to_string(), size: a.size_bytes, url: url.to_string(), sha256 }) + }) + .take(300) + .collect(); + let fallback_url = format!("https://github.com/{repo}/releases/tag/{tag}"); + let html_url = self + .html_url + .as_deref() + .and_then(|u| release::safe_release_html_url(repo, u)) + .or_else(|| release::safe_release_html_url(repo, &fallback_url)) + .unwrap_or_else(|| format!("https://github.com/{repo}/releases")); + Some(Release { + repo: repo.to_string(), + tag: tag.to_string(), + version: Some(version), + name: self.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(tag).to_string(), + published_at: self.published_at.as_deref().and_then(parse_rfc3339), + html_url, + notes: self.notes_markdown.clone().unwrap_or_default(), + prerelease: self.prerelease, + assets, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::{Signer as _, SigningKey}; + + const NOW: i64 = 1_795_728_600; // 2026-11-26T21:30:00Z + const HASH: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + fn sample_toml() -> String { + format!( + r#"generated_at = "2026-11-26T21:00:00Z" + +[launcher] +id = "artcraft-launcher" +repo = "storytold/craft-launcher" +[launcher.releases.stable] +tag = "v0.20.4" +version = "0.20.4" +html_url = "https://github.com/storytold/craft-launcher/releases/tag/v0.20.4" +prerelease = false +[[launcher.releases.stable.assets]] +name = "artcraft-launcher-0.20.4-macos-universal.dmg" +download_url = "https://github.com/storytold/craft-launcher/releases/download/v0.20.4/artcraft-launcher-0.20.4-macos-universal.dmg" +sha256 = "{HASH}" + +[[apps]] +id = "photocraft" +repo = "storytold/photocraft" +[apps.releases.stable] +tag = "v0.23.1" +version = "0.23.1" +html_url = "https://github.com/storytold/photocraft/releases/tag/v0.23.1" +prerelease = false +[[apps.releases.stable.assets]] +name = "photocraft-0.23.1-macos-universal.dmg" +download_url = "https://github.com/storytold/photocraft/releases/download/v0.23.1/photocraft-0.23.1-macos-universal.dmg" +sha256 = "{HASH}" +[[apps.releases.stable.assets]] +name = "evil.dmg" +download_url = "https://evil.example/evil.dmg" +sha256 = "{HASH}" +[apps.releases.prerelease] +tag = "v0.24.0-rc.1" +version = "0.24.0-rc.1" +html_url = "https://github.com/storytold/photocraft/releases/tag/v0.24.0-rc.1" +prerelease = true +[apps.releases.nightly] +tag = "v0.24.0-nightly.20261126.1.1" +version = "0.24.0-nightly.20261126.1.1" +html_url = "https://github.com/storytold/photocraft/releases/tag/v0.24.0-nightly.20261126.1.1" +prerelease = true +"# + ) + } + + fn sign(toml: &str) -> (SigningKey, String) { + let key = SigningKey::from_bytes(&[7; 32]); + let sig = STANDARD.encode(key.sign(toml.as_bytes()).to_bytes()); + (key, sig) + } + + #[test] + fn verifies_signed_catalog_and_extracts_stable_prerelease_and_nightly() { + let toml = sample_toml(); + let (key, sig) = sign(&toml); + let catalog = SignedCatalog::verify_with_key(toml.as_bytes(), sig.as_bytes(), &key.verifying_key()).unwrap(); + let photo = App::by_id("photocraft").unwrap(); + + let stable = catalog.latest_for(photo, false, NOW).unwrap(); + assert_eq!(stable.tag, "v0.23.1"); + assert_eq!(stable.assets.len(), 1, "evil.example asset must be dropped"); + assert_eq!(stable.assets[0].sha256.as_deref(), Some(HASH)); + + let pre = catalog.latest_for(photo, true, NOW).unwrap(); + assert_eq!(pre.tag, "v0.24.0-rc.1"); + + let nightly = catalog.nightly_for(photo, NOW).unwrap(); + assert_eq!(nightly.tag, "v0.24.0-nightly.20261126.1.1"); + + let by_repo = catalog.latest_for_repo("storytold/craft-launcher", false, NOW).unwrap(); + assert_eq!(by_repo.tag, "v0.20.4"); + } + + #[test] + fn rejects_tampering_wrong_key_and_stale_catalog() { + let toml = sample_toml(); + let (key, sig) = sign(&toml); + let wrong_key = SigningKey::from_bytes(&[9; 32]); + assert!(SignedCatalog::verify_with_key(toml.as_bytes(), sig.as_bytes(), &wrong_key.verifying_key()).is_err()); + assert!(SignedCatalog::verify_with_key(format!("{toml}\n").as_bytes(), sig.as_bytes(), &key.verifying_key()).is_err()); + + let catalog = SignedCatalog::verify_with_key(toml.as_bytes(), sig.as_bytes(), &key.verifying_key()).unwrap(); + let photo = App::by_id("photocraft").unwrap(); + assert!(catalog.latest_for(photo, false, NOW + MAX_AGE + 3600).is_none()); + } +} diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index ced3e0503a..31786a0a47 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -3,6 +3,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod app; +pub mod catalog; pub mod desktop_entry; pub mod detect; pub mod distro; @@ -88,11 +89,31 @@ impl From<&str> for CheckError { } } -/// Checks for an update against GitHub releases for the given app. +/// Checks for an update: defaults to the signed `getartcraft.com` catalog, falling back to +/// GitHub releases when the catalog is unavailable, fails verification, is stale, or omits `app`. pub fn check_for_update(app: &App, http: &Http, current_version: &str) -> Result, CheckError> { + let version = self_update::current_version(app, current_version).map(|v| v.to_string()); + let effective_version = version.as_deref().unwrap_or(current_version); + match catalog::SignedCatalog::fetch(http) { + Ok(signed) => { + if let Some(latest) = signed.latest_for(app, false, now()) { + return Ok(offer_if_newer(latest, effective_version)); + } + } + Err(why) => { + log::debug!("signed catalog unavailable ({why}); falling back to GitHub"); + } + } check_releases_at(&format!("https://api.github.com/repos/{}/releases?per_page=30", app.repo), app, http, current_version) } +/// Returns `Some(release)` when [`version::offers_update`] says `current_version` should update to it. +fn offer_if_newer(release: Release, current_version: &str) -> Option { + let running = crate::version::parse(current_version)?; + let rel_v = release.version.as_ref()?; + crate::version::offers_update(rel_v, &running).then_some(release) +} + /// [`check_for_update`] against the release list at `url` (a loopback server in tests). fn check_releases_at(url: &str, app: &App, http: &Http, current_version: &str) -> Result, CheckError> { let version = self_update::current_version(app, current_version).map(|v| v.to_string()); diff --git a/crates/update/src/protocol.rs b/crates/update/src/protocol.rs index 90831d5b85..6a4b3c5dca 100644 --- a/crates/update/src/protocol.rs +++ b/crates/update/src/protocol.rs @@ -76,7 +76,7 @@ pub const INSTALL_CANCELLED: &str = "install cancelled"; /// Where release information came from. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Source { - /// ArtCraft's release feed (storyteller-web), which polls GitHub for everyone. + /// ArtCraft's signed release catalog (`getartcraft.com/launcher-catalog.toml`). Feed, /// The GitHub REST API. GitHubApi, diff --git a/crates/update/src/source.rs b/crates/update/src/source.rs index 81db2953f0..76a335cc72 100644 --- a/crates/update/src/source.rs +++ b/crates/update/src/source.rs @@ -212,6 +212,76 @@ impl ReleaseSource for GitHubSource { } } +/// Release source that defaults to the signed `getartcraft.com` catalog and falls back to +/// `fallback` (typically [`GitHubSource`]) when the catalog is unavailable, stale, or omits a repo. +pub struct CatalogSource { + http: Http, + fallback: F, + cached: Mutex>, +} + +impl CatalogSource { + /// Creates a release source that checks the signed `getartcraft.com` catalog first and falls + /// back to `fallback` (typically [`GitHubSource`]). + pub fn new(http: Http, fallback: F) -> Self { + Self { http, fallback, cached: Mutex::new(None) } + } + + fn catalog(&self) -> Option { + let now = crate::now(); + { + let guard = self.cached.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(c) = guard.as_ref() + && c.generated_at.is_some_and(|t| now.saturating_sub(t) <= crate::catalog::MAX_AGE) + { + return Some(c.clone()); + } + } + match crate::catalog::SignedCatalog::fetch(&self.http) { + Ok(fresh) => { + *self.cached.lock().unwrap_or_else(PoisonError::into_inner) = Some(fresh.clone()); + Some(fresh) + } + Err(why) => { + log::debug!("signed catalog unavailable ({why}); falling back to GitHub"); + None + } + } + } +} + +impl ReleaseSource for CatalogSource { + fn latest(&self, repo: &str, prereleases: bool) -> Answer { + if let Some(catalog) = self.catalog() + && let Some(release) = catalog.latest_for_repo(repo, prereleases, crate::now()) + { + return Answer { latest: LatestRelease::Found(release), source: Source::Feed }; + } + self.fallback.latest(repo, prereleases) + } + + fn cached(&self, repo: &str, prereleases: bool) -> Option { + if let Some(c) = self.cached.lock().unwrap_or_else(PoisonError::into_inner).as_ref() + && let Some(r) = c.latest_for_repo(repo, prereleases, crate::now()) + { + return Some(LatestRelease::Found(r)); + } + self.fallback.cached(repo, prereleases) + } + + fn newest_tag(&self, repo: &str) -> Option { + self.fallback.newest_tag(repo) + } + + fn rate_limited_until(&self) -> Option { + self.fallback.rate_limited_until() + } + + fn save(&self) { + self.fallback.save(); + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; From e11dc10b538aad54ab5aef65f45b40dfcca2de55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:58:29 -0800 Subject: [PATCH 122/154] 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 408de2e176f3a7cebde281c26894951a2b1acf61 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 26 Nov 2026 21:59:44 -0500 Subject: [PATCH 123/154] test(update): register signed catalog unit tests with #[trial] --- crates/update/src/catalog.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/update/src/catalog.rs b/crates/update/src/catalog.rs index 26482a8185..97d49a51bb 100644 --- a/crates/update/src/catalog.rs +++ b/crates/update/src/catalog.rs @@ -276,8 +276,9 @@ impl RawRelease { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + use craft_ui::testing::trial; use ed25519_dalek::{Signer as _, SigningKey}; const NOW: i64 = 1_795_728_600; // 2026-11-26T21:30:00Z @@ -336,7 +337,7 @@ prerelease = true (key, sig) } - #[test] + #[trial] fn verifies_signed_catalog_and_extracts_stable_prerelease_and_nightly() { let toml = sample_toml(); let (key, sig) = sign(&toml); @@ -358,7 +359,7 @@ prerelease = true assert_eq!(by_repo.tag, "v0.20.4"); } - #[test] + #[trial] fn rejects_tampering_wrong_key_and_stale_catalog() { let toml = sample_toml(); let (key, sig) = sign(&toml); From ad46e895fb18432d5081497d6600ceaa5e6cef26 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 03:11:45 +0000 Subject: [PATCH 124/154] 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 125/154] 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 126/154] 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 127/154] 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 128/154] 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 129/154] 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 130/154] 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 131/154] 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; From 86bb6407565748f3e33197511054ea1d0dc54e20 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 12:32:02 +0530 Subject: [PATCH 132/154] fix(zip): index virtual names from the central directory and require UTF-8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `virtual_entry_name` and `virtual_entry_size` went through `by_index_raw`, which seeks the local header, so one part with a damaged local header stopped `Package::open` and `LazyPackage::open` before any part was read. They now read only the central-directory record (`by_index_data`); a damaged part fails only when it is read, as before the hardening. `ZipFile::name()` decodes a non-UTF-8 name as CP437, so `\x82.xml` was admitted as `é.xml`. The virtual name now requires the raw bytes to be UTF-8. Co-Authored-By: Claude Opus 5.5 --- crates/opc/tests/package.rs | 14 ++++++++++++++ crates/zip/src/archive.rs | 18 ++++++++++------- crates/zip/tests/it/archive.rs | 35 ++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/opc/tests/package.rs b/crates/opc/tests/package.rs index 73857b27e6..2ce4f5526d 100644 --- a/crates/opc/tests/package.rs +++ b/crates/opc/tests/package.rs @@ -225,6 +225,20 @@ fn traversal_zip_entry_names_are_not_parts() { assert_eq!(lazy.read("evil.xml").unwrap(), None); } +/// Indexing part names reads only the central directory: one part whose local header is +/// damaged leaves the others readable. +#[test] +fn a_damaged_local_header_does_not_stop_the_package_opening() { + let mut z = zip_of(&[("a.xml", b"
".to_vec()), ("bad.xml", b"".to_vec())]); + let local = z.windows(7).position(|w| w == b"bad.xml").unwrap() - 30; + assert_eq!(&z[local..local + 4], b"PK\x03\x04"); + z[local] = b'X'; + let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.get("a.xml"), Some(&b""[..])); + let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap(); + assert_eq!(lazy.read("a.xml").unwrap().as_deref(), Some(&b""[..])); +} + #[test] fn xml_parts_are_read_with_the_callers_options() { let z = zip_of(&[("a.xml", b"".to_vec()), ("bad.xml", b"".to_vec())]); diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 7c09ac4f9c..6e8577d910 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -122,26 +122,30 @@ impl<'a> Archive<'a> { /// legacy writer's `/docProps/core.xml` is `docProps/core.xml`. Names that still contain /// traversal components (`..`, a drive prefix, a NUL) after that, and names that are not /// UTF-8, return `None`. A caller that extracts entries to disk uses [`Self::entry_name`]. + /// + /// Only the central directory is read, so an entry whose local header is damaged still has + /// a name here; reading it is what fails. pub fn virtual_entry_name(&mut self, index: usize) -> Result, Error> { - if index >= self.zip.len() { + let Ok(file) = self.zip.by_index_data(index) else { return Ok(None); - } - let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + }; let raw = file.name_raw(); let start = raw.iter().position(|b| *b != b'/' && *b != b'\\').unwrap_or(raw.len()); if raw[start..].is_empty() || has_traversal_component_bytes(&raw[start..]) { return Ok(None); } - let Ok(name) = file.name() else { return Ok(None) }; - Ok(sanitize_path(&name).map(str::to_string)) + // `zip` decodes a non-UTF-8 name as CP437, which would admit a name no writer spelled. + let Ok(name) = std::str::from_utf8(raw) else { return Ok(None) }; + Ok(sanitize_path(name).map(str::to_string)) } - /// The size the entry at `index` declares, when it has a [`Self::virtual_entry_name`]. + /// The size the entry at `index` declares, when it has a [`Self::virtual_entry_name`]. Like + /// the name, it comes from the central directory alone. pub fn virtual_entry_size(&mut self, index: usize) -> Result, Error> { if self.virtual_entry_name(index)?.is_none() { return Ok(None); } - let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + let file = self.zip.by_index_data(index).map_err(|error| Error::NotZip(error.to_string()))?; Ok(Some(file.size())) } diff --git a/crates/zip/tests/it/archive.rs b/crates/zip/tests/it/archive.rs index 1ef0d81a34..cec83f0d73 100644 --- a/crates/zip/tests/it/archive.rs +++ b/crates/zip/tests/it/archive.rs @@ -368,3 +368,38 @@ fn virtual_names_strip_a_leading_separator_and_still_refuse_traversal() { assert_eq!(archive.read_virtual_index(index, 100).unwrap(), None, "entry {index}"); } } + +#[test] +fn virtual_names_come_from_the_central_directory_and_must_be_utf8() { + use std::io::Write as _; + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + for (name, data) in [("good.xml", &b"good"[..]), ("Xcp437.xml", b"cp437"), ("bad.xml", b"bad")] { + zip.start_file(name, opts).unwrap(); + zip.write_all(data).unwrap(); + } + let mut bytes = zip.finish().unwrap().into_inner(); + // A byte that is not UTF-8: `zip` would decode it as CP437 `é`. + let mut at = 0; + while let Some(found) = bytes[at..].windows(10).position(|w| w == b"Xcp437.xml") { + bytes[at + found] = 0x82; + at += found + 10; + } + // Break the local header of `bad.xml`; its central-directory record stays intact. + let local = find(&bytes, b"bad.xml", 0) - 30; + assert_eq!(&bytes[local..local + 4], b"PK\x03\x04"); + bytes[local] = b'X'; + let mut archive = Archive::open(&bytes, ROOMY).unwrap(); + + assert_eq!(archive.virtual_entry_name(0).unwrap().as_deref(), Some("good.xml")); + assert_eq!(archive.virtual_entry_name(1).unwrap(), None); + assert_eq!(archive.virtual_entry_size(1).unwrap(), None); + assert_eq!(archive.read_virtual_index(1, 100).unwrap(), None); + + // The damaged entry is still named and sized; only reading it fails. + assert_eq!(archive.virtual_entry_name(2).unwrap().as_deref(), Some("bad.xml")); + assert_eq!(archive.virtual_entry_size(2).unwrap(), Some(3)); + assert!(archive.read_virtual_index(2, 100).is_err()); + assert_eq!(archive.read_virtual_index(0, 100).unwrap().as_deref(), Some(&b"good"[..])); +} From 33fb95c7189686cab2fc0a6dbc1882ce7237e2c2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:40:29 +0100 Subject: [PATCH 133/154] fcproj-format: schema v19 for FilmCraft Script items (#3782) A no-op v18 -> v19 step so FilmCraft can save Script Project items (script lines, slates with linked takes, marks and thumbnail positions) and older builds refuse such projects instead of dropping them on save. Library part of storytold/filmcraft#2726, which until now bumped an app-local schema number that clashed with the shared v18 (camera raw). --- crates/fcproj-format/src/lib.rs | 37 ++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs index 11f7e5013f..10c8348811 100644 --- a/crates/fcproj-format/src/lib.rs +++ b/crates/fcproj-format/src/lib.rs @@ -15,7 +15,7 @@ pub type Migration = fn(Value) -> Result; /// edit a shipped one. pub const MIGRATIONS: &[Migration] = &[ v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14, - v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, + v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19, ]; /// The schema version this build writes (and the newest it reads). @@ -262,6 +262,13 @@ fn v17_to_v18(doc: Value) -> Result { Ok(doc) } +/// v18 → v19: Script Project items (`ItemKind::Script`: script lines, slates with linked takes, +/// marks and independently positioned thumbnails). Existing data needs no change; older builds +/// must refuse such projects instead of failing on or dropping the Script items when saving. +fn v18_to_v19(doc: Value) -> Result { + Ok(doc) +} + #[cfg(test)] mod tests { use super::*; @@ -272,10 +279,10 @@ mod tests { let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]}); assert_eq!(detect_version(&bare).unwrap(), 1); let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap(); - assert_eq!(migrated["schema_version"], 18); + assert_eq!(migrated["schema_version"], SCHEMA_VERSION); assert_eq!(migrated["project"]["extra"], json!([1, 2])); assert_eq!(migrated["generator"], "FilmCraft (schema v1)"); - assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 18); + assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), SCHEMA_VERSION); let parsed: EnvelopeIn = serde_json::from_value(migrated).unwrap(); assert!(parsed.view.is_none()); assert_eq!(parsed.project["extra"], json!([1, 2])); @@ -303,20 +310,40 @@ mod tests { let item = json!({"Media": {"interpret": {"par": [1, 1]}}}); let v17 = json!({"format": FORMAT_ID, "schema_version": 17, "project": {"items": {"1": {"kind": item}}, "root": {}}}); let up = migrate_with(MIGRATIONS, v17.clone(), 17).unwrap(); - assert_eq!(up["schema_version"], 18); + assert_eq!(up["schema_version"], SCHEMA_VERSION); assert_eq!(up["project"], v17["project"]); let raw = json!({"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}}, "exposure": -0.75}); let mut v18 = up; + v18["schema_version"] = json!(18); v18["project"]["items"]["1"]["kind"]["Media"]["interpret"]["raw"] = raw.clone(); let bytes = serde_json::to_vec(&v18).unwrap(); let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); assert_eq!(version, 18); assert_eq!(file.project["items"]["1"]["kind"]["Media"]["interpret"]["raw"], raw); } + /// Schema 19 (Script items): a v18 project upgrades with its data untouched, and a v19 project + /// with a Script item is read rather than refused as too new. + #[test] + fn v18_upgrades_and_v19_script_items_are_read() { + let media = json!({"Media": {"interpret": {"par": [1, 1]}}}); + let v18 = json!({"format": FORMAT_ID, "schema_version": 18, "project": {"items": {"1": {"kind": media}}, "root": {}}}); + let up = migrate_with(MIGRATIONS, v18.clone(), 18).unwrap(); + assert!(up["schema_version"].as_u64().unwrap() > 18); + assert_eq!(up["project"], v18["project"]); + let script = json!({"Script": {"lines": [{"id": 1, "text": "one"}], "slates": [{"id": 2, "takes": [{"id": 3, "source": 1}]}], "next_id": 4}}); + let mut v19 = up; + v19["schema_version"] = json!(19); + v19["project"]["items"]["2"] = json!({"kind": script.clone()}); + let bytes = serde_json::to_vec(&v19).unwrap(); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, 19); + assert_eq!(file.project["items"]["2"]["kind"], script); + assert_eq!(file.project["items"]["1"]["kind"], media); + } #[test] fn rejects_wrong_future_and_damaged_envelopes() { assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_)))); - assert!(matches!(detect_bytes(br#"{"schema_version":19}"#), Err(FormatError::TooNew { found: 19, supported: 18 }))); + assert!(matches!(detect_bytes(br#"{"schema_version":20}"#), Err(FormatError::TooNew { found: 20, supported: 19 }))); assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 }))); assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_)))); assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. }))); From b0370f22982c8052164ddf24d6c1cbee2d1839f6 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 15:49:20 +0700 Subject: [PATCH 134/154] Revert "Merge pull request #3855 from dotCooCoo/fix/web-export-web-shift-state" This reverts commit e707caf24585028f3de76ae9e99060b3f8ed4667, reversing changes made to f66ed91a3400744b3431721a147023542825f082. --- .../src/patterns/form_dialogs/save_for_web.rs | 6 -- .../form_dialogs/save_for_web/model.rs | 3 - .../form_dialogs/save_for_web/options.rs | 50 ++-------- .../form_dialogs/save_for_web/stories.rs | 1 - .../tests/it/form_dialogs/save_for_web.rs | 96 +------------------ 5 files changed, 12 insertions(+), 144 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web.rs index 8f31b18a7f..3299039583 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web.rs @@ -328,10 +328,6 @@ struct Live { reported: u64, /// The selection of the Color Table's cells. table: Selection, - /// The Shift and Unshift focus targets from the table's last frame. - table_actions: [Option; 2], - /// Restore focus on the next frame if a palette action disappeared while focused. - recover_table_focus: bool, /// The colour of the palette entry whose colour request is out. editing: Option<[u8; 3]>, /// The Download speed of the captions in Kbps; not remembered. @@ -355,8 +351,6 @@ impl Default for Live { revision: 1, reported: 0, table: Selection::default(), - table_actions: [None; 2], - recover_table_focus: false, editing: None, speed: OPENING_SPEED, preset: PresetState::new(), diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs index b435e100bc..7f34928759 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/model.rs @@ -238,9 +238,6 @@ pub struct TableMarks { pub transparent: Vec<[u8; 3]>, /// The shifted colours, from and to. pub shifted: Vec<([u8; 3], [u8; 3])>, - /// Web-shifted colours, identified by the same RGB entries the host supplies in the palette. - /// `None` keeps separate Shift and Unshift controls for a host that does not report this state. - pub web_shifted: Option>, } /// What the dialog is for: a raster document or a vector one. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs index 80f777fe62..96b3ebc464 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs @@ -25,7 +25,6 @@ use crate::patterns::presets::{ use crate::pickers::{Select, UnitSelect}; use crate::runtime::env::{Env, Label, UnitKind, Units}; -use crate::runtime::focus::{self, FocusTarget}; use crate::sections::Section; use crate::style::TypeRole; @@ -418,56 +417,21 @@ fn color_table_section(ui: &mut Ui, kit: &Kit<'_>, live: &mut Live, asked: &mut if !deleted.is_empty() { asked.table.push(ColorTableEvent { edit: ColorTableEdit::Delete, colors: deleted }); } - let web_shifted = marks.and_then(|marks| marks.web_shifted.as_deref()); - let shifted_count = web_shifted.map(|shifted| selected.iter().filter(|color| shifted.contains(color)).count()); - // A mixed selection offers both actions. Each keeps its identity when the other appears or disappears. - let show_shift = shifted_count.is_none_or(|count| count == 0 || count < selected.len()); - let show_unshift = shifted_count.is_none_or(|count| count > 0); let tools = [ - show_shift.then_some(("web_colors", &words.web_shift, ColorTableEdit::WebShift)), - show_unshift.then_some(("undo", &words.unshift, ColorTableEdit::Unshift)), - Some(("lock", &words.lock, ColorTableEdit::Lock)), - Some(("grid", &words.make_transparent, ColorTableEdit::Transparent)), - Some(("trash", &words.delete_color, ColorTableEdit::Delete)), + ("web_colors", &words.web_shift, ColorTableEdit::WebShift), + ("undo", &words.unshift, ColorTableEdit::Unshift), + ("lock", &words.lock, ColorTableEdit::Lock), + ("grid", &words.make_transparent, ColorTableEdit::Transparent), + ("trash", &words.delete_color, ColorTableEdit::Delete), ]; Row::new().id_salt("table-tools").show(ui, |ui, _| { - let interactive = !crate::runtime::measure::active(ui.ctx()); - let focused_action = live.table_actions.iter().position(|id| id.is_some_and(|id| focus::is_focused(ui.ctx(), id))); - let mut targets = [None; 2]; - for (index, tool) in tools.iter().enumerate() { - let Some((icon, label, edit)) = tool else { continue }; + for (icon, label, edit) in &tools { let button = IconButton::new(IconId::new(icon)).label((*label).clone()).enabled(!selected.is_empty()).id_salt(*icon).show(ui); - if !selected.is_empty() - && let Some(target) = targets.get_mut(index) - { - *target = Some(button.response.id); - } if clicked(&button) { - let colors = match (edit, web_shifted) { - (ColorTableEdit::Unshift, Some(shifted)) => selected.iter().copied().filter(|color| shifted.contains(color)).collect(), - _ => selected.clone(), - }; - asked.table.push(ColorTableEvent { edit: edit.clone(), colors }); + asked.table.push(ColorTableEvent { edit: edit.clone(), colors: selected.clone() }); } } let more = IconButton::new(IconId::new("more")).label(words.table_menu.clone()).id_salt("menu").show(ui); - if interactive { - let mut recover = focused_action.is_some_and(|index| targets[index].is_none()); - // Recover on the following frame so presses can finish choosing their own focus. - if live.recover_table_focus && ui.memory(|memory| memory.focused().is_none()) { - if ui.input(|input| input.pointer.any_pressed() || input.key_pressed(egui::Key::Tab)) { - recover = true; - } else { - let target = targets.into_iter().flatten().next().unwrap_or(more.response.id); - focus::request(ui.ctx(), FocusTarget::Id(target)); - } - } - live.recover_table_focus = recover; - live.table_actions = targets; - if recover { - crate::runtime::frame::request_repaint(ui.ctx()); - } - } let orders = [ (&words.order_unsorted, TableOrder::Unsorted), (&words.order_hue, TableOrder::Hue), diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs index 91a7591ec5..2bfee2e34b 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs @@ -99,7 +99,6 @@ fn story_marks() -> &'static TableMarks { locked: vec![[20, 20, 20]], transparent: vec![[240, 240, 240]], shifted: vec![([138, 111, 77], [132, 112, 82])], - web_shifted: None, }) } diff --git a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs index 27c505588c..c1d12cdfd9 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs @@ -5,11 +5,9 @@ use craft_theme::Srgba; use craft_ui::contract::Bind; use craft_ui::dialog::{DialogHost, DialogResult, StackDialog}; use craft_ui::patterns::form_dialogs::{ - Animation, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, TableMarks, - WebFormat, WebPictures, WebPreset, WebSlice, WebSlices, WebVariant, + Animation, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, PALETTE_COLOR_KEY, SAVE_PATH_KEY, SaveForWebDialog, SaveForWebOptions, WebFormat, + WebPictures, WebPreset, WebSlice, WebSlices, WebVariant, }; -use craft_ui::testing::access::NodeKey; -use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, trial}; use egui::load::SizedTexture; use egui::{Key, Modifiers, Pos2, Rect, Vec2, pos2, vec2}; @@ -174,106 +172,22 @@ fn gif(colors: u16) -> SaveForWebOptions { /// The colours of the palette the shown encode reports. const PALETTE: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; -/// Answers the encode with the given colours and selects the Optimized pane, which shows the Color Table. -fn show_palette_with(host: &Rc>, fixture: &mut Fixture, palette: &[[u8; 3]]) { +/// Answers the encode the dialog asked for with `PALETTE` and selects the Optimized pane, which shows the Color Table. +fn show_palette(host: &Rc>, fixture: &mut Fixture) { let wanted = host.borrow_mut().get_mut::().map(HostedSaveForWeb::wanted_variants).expect("open"); let revision = wanted.first().map_or(1, |want| want.request.revision); - let variant = WebVariant::new(0, revision, texture(), 1000).colors(palette.len() as u16).palette(palette.to_vec()); + let variant = WebVariant::new(0, revision, texture(), 1000).colors(4).palette(PALETTE.to_vec()); host.borrow_mut().get_mut::().expect("open").set_variant(variant); fixture.settle(); select_optimized_pane(fixture); } -fn show_palette(host: &Rc>, fixture: &mut Fixture) { - show_palette_with(host, fixture, &PALETTE); -} - /// The colour table events the dialog filed since the last call. fn table_events(host: &Rc>) -> Vec<(ColorTableEdit, Vec<[u8; 3]>)> { let events = host.borrow_mut().get_mut::().map(HostedSaveForWeb::take_table_events).expect("the dialog is open"); events.into_iter().map(|event: ColorTableEvent| (event.edit, event.colors)).collect() } -#[trial] -fn the_web_shift_button_follows_the_selected_colors_reported_by_the_host() { - let web = HostedSaveForWeb::new("poster.psd", IMAGE, texture()).options(gif(8)); - let (host, mut fixture) = open(web); - let set_web_shifted = |colors| { - let mut marks = TableMarks::default(); - marks.web_shifted = Some(colors); - host.borrow_mut().get_mut::().expect("open").set_marks(marks); - }; - set_web_shifted(Vec::new()); - let mut palette = PALETTE; - let source = [220, 210, 196]; - palette[1] = source; - show_palette_with(&host, &mut fixture, &palette); - let cell = fixture.by_label("1 #dcd2c4").expect("the unshifted entry"); - fixture.click(&cell).settle(); - - assert!(fixture.by_label("Unshift Colors").is_none(), "an unshifted selection offers Shift"); - let shift = fixture.by_label("Shift to Web Palette").expect("the Shift button"); - fixture.click(&shift).settle(); - assert_eq!(table_events(&host), [(ColorTableEdit::WebShift, vec![source])]); - - let shifted = [204, 204, 204]; - palette[1] = shifted; - set_web_shifted(vec![shifted]); - show_palette_with(&host, &mut fixture, &palette); - let cell = fixture.by_label("1 #cccccc").expect("the shifted entry"); - fixture.click(&cell).settle(); - assert!(fixture.by_label("Shift to Web Palette").is_none(), "a shifted selection offers Unshift"); - let unshift = fixture.by_label("Unshift Colors").expect("the Unshift button"); - fixture.click(&unshift).settle(); - assert_eq!(table_events(&host), [(ColorTableEdit::Unshift, vec![shifted])]); - - // With a hand-shifted swatch in the selection, both web actions are still available. - let hand_shifted = palette[2]; - let mut marks = TableMarks::default(); - marks.web_shifted = Some(vec![shifted]); - marks.shifted = vec![([0x99, 0x88, 0x77], hand_shifted)]; - host.borrow_mut().get_mut::().expect("open").set_marks(marks); - fixture.settle(); - let set_selection = |fixture: &Fixture, colors| { - host.borrow_mut().get_mut::().expect("open").set_json_field(fixture.ctx(), "colorSelection", colors).unwrap(); - }; - let unshift = fixture.by_label("Unshift Colors").expect("the shifted selection offers Unshift"); - fixture.access(AccessActionKind::Focus, &unshift).idle(1); - set_selection(&fixture, serde_json::json!(["#cccccc", "#0000ff"])); - fixture.settle(); - assert!(fixture.by_label("Shift to Web Palette").is_some(), "a mixed selection still offers Shift"); - let unshift = fixture.by_label("Unshift Colors").expect("a mixed selection also offers Unshift"); - assert_eq!(fixture.focused().map(NodeKey::of), Some(unshift.node), "Unshift keeps focus as Shift appears"); - fixture.key(Key::Space, Modifiers::NONE).settle(); - assert_eq!(table_events(&host), [(ColorTableEdit::Unshift, vec![shifted])]); - assert_eq!(fixture.focused().map(NodeKey::of), Some(unshift.node), "Unshift keeps focus while the host still shows it"); - - set_web_shifted(Vec::new()); - fixture.settle(); - assert!(fixture.by_label("Unshift Colors").is_none()); - let shift = fixture.by_label("Shift to Web Palette").expect("Shift stays in the toolbar"); - assert_eq!(fixture.focused().map(NodeKey::of), Some(shift.node), "keyboard focus stays in the palette toolbar"); - - set_web_shifted(vec![shifted]); - fixture.settle(); - let unshift = fixture.by_label("Unshift Colors").expect("mixed selection restored"); - fixture.access(AccessActionKind::Focus, &unshift).idle(1); - set_selection(&fixture, serde_json::json!([])); - fixture.settle(); - let menu = fixture.by_label("Color Table Menu").expect("the menu remains available"); - assert_eq!(fixture.focused().map(NodeKey::of), Some(menu.node), "clearing the selection keeps focus in the toolbar"); - - set_web_shifted(Vec::new()); - set_selection(&fixture, serde_json::json!(["#cccccc"])); - fixture.settle(); - let shift = fixture.by_label("Shift to Web Palette").expect("the unshifted selection offers Shift"); - fixture.access(AccessActionKind::Focus, &shift).idle(1); - set_selection(&fixture, serde_json::json!([])); - fixture.settle(); - let menu = fixture.by_label("Color Table Menu").expect("the menu remains available"); - assert_eq!(fixture.focused().map(NodeKey::of), Some(menu.node), "disabling a focused Shift keeps focus in the toolbar"); -} - #[trial] fn a_slice_warning_appears_once_below_the_preview_captions() { let warning = "5 stored slices past the first 10000 were ignored"; From 72ddff0c18f9d4359e53ae804af76ea559eddd49 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 15:49:25 +0700 Subject: [PATCH 135/154] Revert "Merge pull request #3738 from dotCooCoo/fix/selectable-text-click-response" This reverts commit 205995c95ccd283deffee7d5e955e79912483912, reversing changes made to 85d26f43e039d89a7a9e1f2efc07cf62f5ffa9da. --- crates/ui-contract/src/contract/text.rs | 6 -- crates/ui-widgets/src/text/selectable_text.rs | 10 +-- crates/ui-widgets/tests/it/text/selectable.rs | 64 +------------------ 3 files changed, 2 insertions(+), 78 deletions(-) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index dd9ec76963..9bbf1478ab 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -682,12 +682,6 @@ pub(crate) fn run( } impl Cx<'_, C> { - /// The response of a declared selection part after `paint` shows it, or `None` when the part has no widget. - pub fn selection_response(&self, part: impl Into) -> Option { - let part = part.into(); - self.core.selections.contains(&part).then(|| self.core.ctx.read_response(selection_id(self.core.id, part))).flatten() - } - /// Changes the text part's draft in the next pass: `Some(text)` puts `text` in as a change of the typing run (one /// that begins the run when none is under way), the caret at its end; `None` ends the run with the text from /// before it, without the run's Escape reaching the host. A combo box's keys in its open list put the active diff --git a/crates/ui-widgets/src/text/selectable_text.rs b/crates/ui-widgets/src/text/selectable_text.rs index 731d55b5ba..acd10f9998 100644 --- a/crates/ui-widgets/src/text/selectable_text.rs +++ b/crates/ui-widgets/src/text/selectable_text.rs @@ -107,14 +107,6 @@ impl Component for SelectableText<'_> { } fn finish(self, cx: Cx<'_, Self>) -> Response { - let mut response = cx.response.clone(); - if let Some(text) = cx.selection_response(TEXT) { - let clicked = cx.resolved.enabled && !cx.resolved.read_only && text.clicked_by(egui::PointerButton::Primary); - response.flags.set(egui::response::Flags::CLICKED, clicked); - if clicked { - response.interact_pointer_pos_or_nan = text.interact_pointer_pos_or_nan; - } - } - response + cx.response.clone() } } diff --git a/crates/ui-widgets/tests/it/text/selectable.rs b/crates/ui-widgets/tests/it/text/selectable.rs index 305839c039..ecc76542bc 100644 --- a/crates/ui-widgets/tests/it/text/selectable.rs +++ b/crates/ui-widgets/tests/it/text/selectable.rs @@ -13,7 +13,7 @@ use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable}; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::{SelectableText, TextField}; use egui::{Event, Id, Key, Modifiers, Rect, Sense, Vec2, ViewportId}; -use std::cell::{Cell, RefCell}; +use std::cell::Cell; use std::rc::Rc; fn stop(fixture: &Fixture) -> Option { @@ -53,68 +53,6 @@ fn painted(fixture: &Fixture, text: &str) -> Rect { fixture.texts().iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("{text:?} is painted")).rect } -#[trial] -fn selectable_text_response_reports_its_clicks_and_modifiers() { - let clicks = Rc::new(RefCell::new(Vec::new())); - let seen = clicks.clone(); - let mut fixture = Fixture::new(move |ui| { - let response = SelectableText::new("Length", "234 pt").show(ui); - assert_eq!(craft_ui::contract::clicked(&response), response.clicked()); - if response.clicked() { - seen.borrow_mut().push((response.double_clicked(), craft_ui::runtime::pointer::frame(ui.ctx()).pick_mods)); - } - }); - fixture.settle(); - let at = painted(&fixture, "234 pt").center(); - fixture.click_at(at); - assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods::NONE)]); - clicks.borrow_mut().clear(); - fixture.advance(1.0); - let button = |pressed, modifiers| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; - fixture.frame_through(vec![ - button(true, Modifiers::NONE), - button(false, Modifiers::NONE), - button(true, Modifiers::NONE), - button(false, Modifiers::NONE), - ]); - assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods::NONE), (true, craft_keymap::Mods::NONE)]); - clicks.borrow_mut().clear(); - fixture.advance(1.0); - fixture.frame_through(vec![button(true, Modifiers::SHIFT), button(false, Modifiers::SHIFT), Event::ModifiersChanged(Modifiers::NONE)]); - assert_eq!(&*clicks.borrow(), &[(false, craft_keymap::Mods { shift: true, ..craft_keymap::Mods::NONE })]); - clicks.borrow_mut().clear(); - let rect = painted(&fixture, "234 pt"); - fixture.drag_at(rect.left_center() + Vec2::new(1.0, 0.0), Vec2::new(rect.width() * 0.75, 0.0)); - assert!(clicks.borrow().is_empty()); - fixture.frame_through(vec![ - Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, - Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }, - ]); - assert!(clicks.borrow().is_empty()); -} - -#[trial] -fn read_only_selectable_text_keeps_selection_without_reporting_activation() { - for inherited in [false, true] { - let clicked = Rc::new(Cell::new(false)); - let seen = clicked.clone(); - let mut fixture = Fixture::new(move |ui| { - craft_ui::runtime::env::with_env( - ui, - |scope| scope.read_only = Some(inherited), - |ui| { - let response = SelectableText::new("Length", "234 pt").read_only(!inherited).show(ui); - seen.set(seen.get() || response.clicked()); - }, - ); - }); - fixture.settle(); - fixture.click_at(painted(&fixture, "234 pt").center()); - assert!(!clicked.get(), "inherited read-only: {inherited}"); - assert_eq!(copy_all(&mut fixture), ["234 pt"]); - } -} - /// Select All then Copy in the focused text. fn copy_all(fixture: &mut Fixture) -> Vec { fixture.key(Key::A, Modifiers::COMMAND); From 1eb6a92ade797b5c1f2a51a9d8540d242670d3e0 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 15:52:35 +0700 Subject: [PATCH 136/154] Clear the design-lint findings on main Mark TransformBox::handle_side and PreferencesWindow::size as point quantities the host supplies, and make CheckContext #[non_exhaustive]. #3855 and #3738 are reverted above: they read egui memory, raw keys and pointer clicks outside runtime::egui. --- crates/draw/src/ui/transform/transform_box.rs | 2 +- crates/ui-patterns/src/patterns/preferences/window.rs | 2 +- crates/update/src/updater.rs | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 6b6594715b..a7c7230f99 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -494,7 +494,7 @@ pub struct TransformBox<'a> { 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] + #[prop(quantity = "points, from the host's handle size preference")] 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 diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index e07e5ea76a..fc6a85df6b 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -116,7 +116,7 @@ pub struct PreferencesWindow<'a> { /// The size the window opens at until the user resizes it, in place of the layout's own ([`DEFAULT_SIZE`] for /// pages, a narrower one for cards). A size under the layout's least ([`MIN_SIZE`] for pages) opens at the least; /// a size that is not finite is ignored. - #[prop] + #[prop(quantity = "points, the window's opening size")] size: Option, /// Escape keeps the typing in the focused field ([`Dialog::escape_keeps_typing`]): in [`PreferencesMode::Live`] /// the typed value stays applied when Escape closes the window. Off by default: Escape cancels the typing. diff --git a/crates/update/src/updater.rs b/crates/update/src/updater.rs index d09cb52062..cd6cec580f 100644 --- a/crates/update/src/updater.rs +++ b/crates/update/src/updater.rs @@ -37,6 +37,7 @@ pub type ContextSource = Arc Result, Ch /// What a check runs for: the app, and the version the running copy reports. #[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct CheckContext { /// The app the check is for. pub app: &'static App, From 2476cd83402e5a85da52ce3c8af91c2bc619dbe0 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 14:46:04 +0530 Subject: [PATCH 137/154] proof: the mixed-spans proptest draws every language again Adding Gujarati grew the language list in mixed_spans_never_panic to 16, but the index range stayed 0..15, so the last entry, ProofLang::Other, was never drawn. The range is now 0..16. Co-Authored-By: Claude Opus 5.5 --- crates/proof/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/proof/src/tests.rs b/crates/proof/src/tests.rs index 46131db25d..76797d8c17 100644 --- a/crates/proof/src/tests.rs +++ b/crates/proof/src/tests.rs @@ -628,7 +628,7 @@ fn mixed_language_paragraphs_check_each_run_in_its_language() { proptest::proptest! { #[test] - fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..15), 0..6)) { + fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..16), 0..6)) { let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect(); for i in check_text(&s, &spans) { From 2573a919396193b0407a938853d1c274ef7704ba Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:47:13 +0530 Subject: [PATCH 138/154] font-manager: an open glyph menu lets go of its cell when the face changes A glyph id names a glyph only in the face it was clicked in. The held menu cell now keeps its family and style, and a pass in another face drops it, so the menu never reports the same id against a different glyph. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 30 ++++++++++----- crates/font-manager/tests/it/glyphs.rs | 51 ++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 6eaf8bdd40..14eee5ac87 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -325,10 +325,19 @@ struct CellsCache { #[derive(Clone, Default)] struct Marked(Selection); -/// The glyph a context menu was opened on. Later passes keep this glyph: the grid remembers the row, and another -/// glyph of a same-length list must not take the menu over. -#[derive(Clone, Copy, Default)] -struct HeldMenu(Option); +/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid +/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph +/// only in its own face, so the menu holds the cell only while that face is shown. +#[derive(Clone, Default)] +struct HeldMenu(Option); + +/// A held menu's cell and the family and style it was clicked in. +#[derive(Clone)] +struct MenuCell { + cell: GlyphCell, + family: String, + style: String, +} /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. @@ -635,15 +644,18 @@ impl<'a> GlyphsPanel<'a> { CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), _ => None, }); - let mut held = *cx.memory::(); + let mut held = std::mem::take(cx.memory::()); if let Some(cell) = clicked { - held = HeldMenu(Some(cell)); + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned() })); } - let opener = shown_grid.response.response.clone(); - menu = shown_grid.response.menu.is_some().then_some(held.0).flatten().map(|cell| GlyphCellMenu { cell, opener }); - if shown_grid.response.menu.is_none() { + // A closed menu lets go of its cell, and so does another face: the same glyph id there is + // another glyph. + let other_face = held.0.as_ref().is_some_and(|held| (held.family.as_str(), held.style.as_str()) != face); + if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } + let opener = shown_grid.response.response.clone(); + menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener }); *cx.memory::() = held; for event in shown_grid.response.events { match event { diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index e4845907ef..b4fd930390 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -203,6 +203,57 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } +/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. +struct Unencoded; + +impl GlyphSource for Unencoded { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + (1..=300).map(GlyphCell::Glyph).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &Unencoded, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + + seen.borrow_mut().clear(); + *family.borrow_mut() = "Other".to_owned(); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 9b4e1134d536caeb1fdbc2b8a0a875be8afccb9b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 27 Nov 2026 16:18:46 +0700 Subject: [PATCH 139/154] platform: the inherit-only test checks the Users entry apart from the runner's On a GitHub Windows runner the temp folder's Administrators entry is inherited and comes first, so the folder check reported it before the Users entry the test adds and the assertion on Users failed. --- crates/platform/src/owner_only.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index fcfdad684e..b37ecdf9f7 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -778,9 +778,17 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap(); assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); let sddl = sddl_of(&dir).unwrap(); - assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}"); + let users = sddl + .split('(') + .filter_map(|ace| ace.split(')').next()) + .find(|ace| ace.split(';').nth(1).is_some_and(|flags| flags.contains("IO")) && ace.ends_with(";S-1-5-32-545")); + let users = users.unwrap_or_else(|| panic!("the inherit-only entry for Users is read: {sddl}")); + // The folder also inherits the temp folder's entries (Administrators on a CI runner), which the check reports + // first, so it is asked about the Users entry alone. let me = current_user_sid().unwrap(); - assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}"); + let only_users = format!("O:{}D:({users})", section(&sddl, "O:").unwrap()); + assert!(foreign_folder_access(&only_users, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}"); + assert_eq!(foreign_access(&only_users, &me), None, "a file's check skips the inherit-only entry: {sddl}"); let _ = std::fs::remove_dir_all(&dir); } From a885cd5f384f835b672bd8248508af9cfbc325af Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 27 Nov 2026 12:14:56 +0100 Subject: [PATCH 140/154] ui-contract: the pointer-move gate compares each root's hover and press winners Overlapping shapes of one root can hit both points of a move while the nearest centre picks another winner; the move now runs a pass then. Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/runtime/pointer.rs | 34 ++++++++++++------- .../ui-contract/tests/it/runtime/pointer.rs | 19 +++++++++++ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 5ab0a02679..37f2f59501 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -695,32 +695,40 @@ pub fn move_needs_pass(ctx: &Context, viewport: ViewportId, from: Option, follows || ctx.widgets_at(viewport, from) != ctx.widgets_at(viewport, to) || shapes_under(ctx, viewport, from) != shapes_under(ctx, viewport, to) } -/// The layer under `at` and the component shapes there that hit it, as the last finished pass of `viewport` recorded -/// them: each as its root and its index in the root's record. -fn shapes_under(ctx: &Context, viewport: ViewportId, at: Pos2) -> (Option, Vec<(Id, usize)>) { +/// The layer under `at` and, for each root with component shapes there that hit it as the last finished pass of +/// `viewport` recorded them, the root, the indices of those shapes in the root's record and the ones that win its hover +/// and its press: overlapping shapes can hit both points while the nearest centre picks another winner. +fn shapes_under(ctx: &Context, viewport: ViewportId, at: Pos2) -> (Option, Vec) { let Some(layer) = areas::layer_at(ctx, at) else { return (None, Vec::new()) }; let point = areas::layer_map(ctx, layer).map_or(at, |map| map.to_layer(at)); let hit = PerViewport::::with(ctx, viewport, |record| { record.this.get(&layer).map_or_else(Vec::new, |roots| { - let mut hit: Vec<(Id, usize)> = roots + let mut hit: Vec = roots .iter() - .flat_map(|(root, entry)| { - entry - .shapes - .iter() - .zip(&entry.placed) - .enumerate() - .filter(|(_, (shape, placed))| placed.clip.contains(point) && shape.hits(point)) - .map(move |(index, _)| (*root, index)) + .filter_map(|(root, entry)| { + let indices: Vec = (0..entry.shapes.len().min(entry.placed.len())) + .filter(|&index| entry.placed[index].clip.contains(point) && entry.shapes[index].hits(point)) + .collect(); + if indices.is_empty() { + return None; + } + let shapes: Vec> = indices.iter().map(|&index| entry.shapes[index].clone()).collect(); + let winner = |kind| resolve(&shapes, point, kind).and_then(|winner| indices.get(winner.index).copied()); + let (hover, press) = (winner(ResolveFor::Hover), winner(ResolveFor::Press)); + Some((*root, indices, hover, press)) }) .collect(); - hit.sort_unstable_by_key(|(root, index)| (root.value(), *index)); + hit.sort_unstable_by_key(|(root, ..)| root.value()); hit }) }); (Some(layer), hit) } +/// A root with shapes under a point ([`shapes_under`]): the root, the indices of its shapes that hit the point, and +/// the indices of the ones that win its hover and its press there. +type UnderRoot = (Id, Vec, Option, Option); + /// Records that `layer` shows the transformed body of the root `root`, which is itself shown on `parent`: a press on /// the body layer reaches the root's own shapes beneath the body's. pub(crate) fn record_body_layer(ctx: &Context, layer: Layer, parent: Layer, root: Id) { diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index 282b8e153c..ac0c06eef2 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -889,3 +889,22 @@ fn a_move_that_changes_nothing_under_the_pointer_needs_no_pass() { assert!(needs(Some(follow.center()), follow.center() + Vec2::new(5.0, 0.0)), "a move in a rect that follows the pointer runs a pass"); assert!(needs(None, inside), "the pointer coming in runs a pass"); } + +/// Two overlapping parts of one root that hit both points of a move, where the nearest centre picks another part at +/// the end: the hover changes, so the move runs a pass. +#[trial] +fn a_move_that_changes_the_nearest_part_needs_a_pass() { + use craft_ui::runtime::pointer::move_needs_pass; + use egui::ViewportId; + const LEFT: PartKey = PartKey::new("left"); + const RIGHT: PartKey = PartKey::new("right"); + let root = ProbeRoot::new("parts", rect(0.0, 0.0, 140.0, 100.0), Sense::empty()) + .part(ProbePart::new(LEFT, rect(0.0, 0.0, 100.0, 100.0), Sense::CLICK)) + .part(ProbePart::new(RIGHT, rect(40.0, 0.0, 100.0, 100.0), Sense::CLICK)); + let (mut show, _) = scene(vec![root]); + let mut frames = Frames::new(); + frames.idle(2, &mut show); + let needs = |from: Pos2, to: Pos2| move_needs_pass(&frames.ctx, ViewportId::ROOT, Some(from), to); + assert!(!needs(Pos2::new(60.0, 50.0), Pos2::new(65.0, 50.0)), "both points nearer the left part's centre"); + assert!(needs(Pos2::new(60.0, 50.0), Pos2::new(80.0, 50.0)), "the right part's centre is nearer at the end"); +} From 0f525a505d904582053f801e9dec6d0f8f241ea0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:17:25 +0700 Subject: [PATCH 141/154] test(update): cover the signed-catalog source and signature failure paths Sonar's new-code coverage gate was 71.4% (needs 80%): CatalogSource and the signature/document refusal paths had no tests. Add tests with a fake fallback source and a fresh signed catalog; no network is used. --- crates/update/src/catalog.rs | 48 ++++++++++++++++++++++++-- crates/update/src/source.rs | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 3 deletions(-) diff --git a/crates/update/src/catalog.rs b/crates/update/src/catalog.rs index 9c5f12c623..b1015b204b 100644 --- a/crates/update/src/catalog.rs +++ b/crates/update/src/catalog.rs @@ -270,7 +270,7 @@ pub(crate) mod tests { const NOW: i64 = 1_795_728_600; // 2026-11-26T21:30:00Z const HASH: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - fn sample_toml() -> String { + pub(crate) fn sample_toml() -> String { format!( r#"generated_at = "2026-11-26T21:00:00Z" @@ -317,7 +317,7 @@ prerelease = true ) } - fn sign(toml: &str) -> (SigningKey, String) { + pub(crate) fn sign(toml: &str) -> (SigningKey, String) { let key = SigningKey::from_bytes(&[7; 32]); let sig = STANDARD.encode(key.sign(toml.as_bytes()).to_bytes()); (key, sig) @@ -358,7 +358,7 @@ prerelease = true assert!(catalog.latest_for(photo, false, NOW + MAX_AGE + 3600).is_none()); } - fn signed(toml: &str) -> SignedCatalog { + pub(crate) fn signed(toml: &str) -> SignedCatalog { let (key, sig) = sign(toml); SignedCatalog::verify_with_key(toml.as_bytes(), sig.as_bytes(), &key.verifying_key()).unwrap() } @@ -413,4 +413,46 @@ sha256 = "{HASH}" let older_pre = sample_toml().replace("v0.24.0-rc.1", "v0.22.0-rc.1").replace("0.24.0-rc.1", "0.22.0-rc.1"); assert_eq!(signed(&older_pre).latest_for(photo, true, NOW).unwrap().tag, "v0.23.1"); } + + /// The sample catalog, generated "now" so it is fresh for code that reads the real clock. + pub(crate) fn fresh_signed_catalog() -> SignedCatalog { + let generated = chrono::DateTime::from_timestamp(crate::now(), 0).expect("a valid time").to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + signed(&sample_toml().replace("2026-11-26T21:00:00Z", &generated)) + } + + #[trial] + fn a_bad_signature_or_document_is_refused_with_a_reason() { + let toml = sample_toml(); + let (key, sig) = sign(&toml); + let verifying = key.verifying_key(); + let refused = |bytes: &[u8], signature: &[u8]| SignedCatalog::verify_with_key(bytes, signature, &verifying).unwrap_err(); + assert!(refused(toml.as_bytes(), &[0xff, 0xfe]).contains("UTF-8")); + assert!(refused(toml.as_bytes(), b"not base64!").contains("base64")); + assert!(refused(toml.as_bytes(), STANDARD.encode([1u8; 8]).as_bytes()).contains("length")); + assert!(refused(&[b'a'; MAX_CATALOG_BYTES + 1], sig.as_bytes()).contains("byte limit")); + assert!(refused(toml.as_bytes(), &[b'a'; MAX_SIGNATURE_BYTES + 1]).contains("byte limit")); + // Signed but not TOML: the signature holds, the document is refused. + let garbage = "this is = = not toml"; + let (garbage_key, garbage_sig) = sign(garbage); + let reason = SignedCatalog::verify_with_key(garbage.as_bytes(), garbage_sig.as_bytes(), &garbage_key.verifying_key()).unwrap_err(); + assert!(reason.contains("invalid catalog TOML"), "{reason}"); + // The pinned production key does not accept a signature made with a test key. + assert!(SignedCatalog::verify(toml.as_bytes(), sig.as_bytes()).is_err()); + } + + #[trial] + fn a_catalog_without_a_generation_time_is_never_fresh() { + let toml = sample_toml().replace("generated_at = \"2026-11-26T21:00:00Z\"", ""); + let catalog = signed(&toml); + let photo = App::by_id("photocraft").unwrap(); + assert!(catalog.latest_for(photo, false, NOW).is_none()); + assert!(catalog.latest_for_repo("storytold/photocraft", false, NOW).is_none()); + assert!(catalog.nightly_for(photo, NOW).is_none()); + } + + #[trial] + fn an_entry_for_another_repository_is_not_used_for_the_app() { + let toml = sample_toml().replace("repo = \"storytold/photocraft\"", "repo = \"someone/else\""); + assert!(signed(&toml).latest_for(App::by_id("photocraft").unwrap(), false, NOW).is_none()); + } } diff --git a/crates/update/src/source.rs b/crates/update/src/source.rs index 76a335cc72..63cd458842 100644 --- a/crates/update/src/source.rs +++ b/crates/update/src/source.rs @@ -302,4 +302,70 @@ pub(crate) mod tests { assert_eq!(retry_at(Some(i64::MAX), 1_000), 1_000 + 60 * 60); assert_eq!(retry_at(Some(99_999_999_999), 1_000), 1_000 + 60 * 60); } + + /// A fallback that answers "no release" and records nothing, so a test sees which source answered. + struct Fallback; + + impl ReleaseSource for Fallback { + fn latest(&self, _repo: &str, _prereleases: bool) -> Answer { + Answer { latest: LatestRelease::None, source: Source::GitHubApi } + } + + fn cached(&self, _repo: &str, _prereleases: bool) -> Option { + Some(LatestRelease::RateLimited) + } + + fn newest_tag(&self, _repo: &str) -> Option { + Some("v9.9.9".into()) + } + + fn rate_limited_until(&self) -> Option { + Some(42) + } + + fn save(&self) {} + } + + fn catalog_source() -> CatalogSource { + let source = CatalogSource::new(Http::new("craft-update-test/0.0").expect("an HTTP client"), Fallback); + *source.cached.lock().expect("lock") = Some(crate::catalog::tests::fresh_signed_catalog()); + source + } + + #[trial] + fn the_catalog_answers_for_a_repo_it_lists_and_marks_the_answer_as_the_feed() { + let answer = catalog_source().latest("storytold/photocraft", false); + assert_eq!(answer.source, Source::Feed); + assert!(matches!(&answer.latest, LatestRelease::Found(release) if release.tag == "v0.23.1"), "{:?}", answer.latest); + } + + #[trial] + fn a_repo_the_catalog_omits_falls_back_to_the_other_source() { + let answer = catalog_source().latest("storytold/unlisted", false); + assert_eq!(answer.source, Source::GitHubApi); + assert_eq!(answer.latest, LatestRelease::None); + } + + #[trial] + fn the_saved_answer_comes_from_the_catalog_or_else_the_fallback() { + let source = catalog_source(); + assert!(matches!(source.cached("storytold/photocraft", true), Some(LatestRelease::Found(release)) if release.tag == "v0.24.0-rc.1")); + assert_eq!(source.cached("storytold/unlisted", false), Some(LatestRelease::RateLimited)); + } + + #[trial] + fn tags_quota_and_saving_are_the_fallbacks_business() { + let source = catalog_source(); + assert_eq!(source.newest_tag("storytold/photocraft").as_deref(), Some("v9.9.9")); + assert_eq!(source.rate_limited_until(), Some(42)); + source.save(); + } + + #[trial] + fn a_stale_cached_catalog_is_not_used() { + let source = CatalogSource::new(Http::new("craft-update-test/0.0").expect("an HTTP client"), Fallback); + let stale = crate::catalog::tests::sample_toml().replace("2026-11-26T21:00:00Z", "2020-01-01T00:00:00Z"); + *source.cached.lock().expect("lock") = Some(crate::catalog::tests::signed(&stale)); + assert_eq!(source.cached("storytold/photocraft", false), Some(LatestRelease::RateLimited)); + } } From 079da658b332194d566c1dd7837d4591531178c9 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 17:32:06 +0530 Subject: [PATCH 142/154] Keep vendor markup on deduplicated switches and drop bare compat blocks and all relationship attributes - An enabled compat switch that appears more than once now keeps the occurrences carrying markup the model doesn't write (e.g. x:vendor) and drops only plain duplicates; with none, the first stays. - A bare self-closing follows the empty-block rule, like ; one with unmodeled attributes is still kept. - Compat retention and pruning treat every attribute in the relationship namespace (r:embed, r:link, ...) as a reference, not only r:id; vendor attributes of the same local name stay. Each change has a regression test that fails without it. Co-Authored-By: Claude Opus 5.5 --- crates/docx/src/write/settings_merge.rs | 85 ++++++++++++++++++++----- 1 file changed, 69 insertions(+), 16 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 9ab1d8201b..9a4ab2efef 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -648,6 +648,12 @@ fn updated_switch(elem_str: &str, root_tag: &str, compat_s: &str, enabled: bool) elem_str.to_string() } +/// Does the switch element carry attributes or content besides its value? A disabled switch keeps +/// its element only then, so [`updated_switch`] answers this when asked to turn it off. +fn switch_has_extensions(elem_str: &str, root_tag: &str, compat_s: &str) -> bool { + !updated_switch(elem_str, root_tag, compat_s, false).is_empty() +} + fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generated: &str, sw_local: &str) -> Option<()> { let gen_sw = children(generated, "w:compat").and_then(|(_, _, _, g_kids)| { g_kids.into_iter().find(|k| is_wml_switch_child(root_tag, generated, k, sw_local)).and_then(|k| generated.get(k.start..k.end)) @@ -676,13 +682,19 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat orig.insert_str(at, &child); } (matches, Some(_g_text)) => { - for &(a, b) in matches[1..].iter().rev() { - orig.replace_range(a..b, ""); + // Drop plain duplicates but never one carrying markup the model doesn't write; with + // no such occurrence, the first one stays. + let compat: &str = orig; + let extended: Vec = matches.iter().map(|&(a, b)| switch_has_extensions(&compat[a..b], root_tag, compat)).collect(); + let first_kept = extended.iter().position(|&e| e).unwrap_or(0); + for (i, (&(a, b), &keeps_markup)) in matches.iter().zip(&extended).enumerate().rev() { + if i == first_kept || keeps_markup { + let updated = updated_switch(&orig[a..b], root_tag, orig, true); + orig.replace_range(a..b, &updated); + } else { + orig.replace_range(a..b, ""); + } } - let (first_a, first_b) = matches[0]; - let orig_elem = &orig[first_a..first_b]; - let updated = updated_switch(orig_elem, root_tag, orig, true); - orig.replace_range(first_a..first_b, &updated); } } Some(()) @@ -710,7 +722,8 @@ fn merge_compat(root_tag: &str, orig: &str, orig_tag: &str, generated: &str) -> let gen_modes = mode_spans(generated, "w:compat"); if is_self_closing && gen_modes.is_empty() && !has_any_gen_switch { - return Some(orig.to_string()); + // An empty block goes, as `` does below, unless it carries markup. + return Some(if compat_has_unmodeled_attrs(root_tag, compat_open) { orig.to_string() } else { String::new() }); } let mut out = if is_self_closing { @@ -789,9 +802,8 @@ fn tag_has_rel_id(root_tag: &str, tag_str: &str) -> bool { depth += 1; if depth == 2 { for attr in e.attributes().with_checks(false).flatten() { - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { return true; @@ -823,9 +835,8 @@ fn child_has_rel_id(root_tag: &str, compat_open: &str, child_str: &str) -> bool depth += 1; if depth >= 3 { for attr in e.attributes().with_checks(false).flatten() { - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { return true; @@ -866,9 +877,8 @@ fn compat_has_unmodeled_attrs(root_tag: &str, compat_tag: &str) -> bool { if key.starts_with(b"xmlns:") || key == b"xmlns" { continue; } - let (res, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"id" - && let quick_xml::name::ResolveResult::Bound(ns) = res + let (res, _) = reader.resolver().resolve_attribute(attr.key); + if let quick_xml::name::ResolveResult::Bound(ns) = res && is_rel_ns(ns.as_ref()) { continue; @@ -1366,4 +1376,47 @@ mod tests { assert!(merged.contains(""), "{merged}"); assert!(!merged.contains("rId8"), "expected Strict r:id to be omitted: {merged}"); } + + #[test] + fn deduplicating_an_enabled_switch_keeps_the_occurrence_with_vendor_markup() { + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:vendor="kept""#), "{merged}"); + assert_eq!(merged.matches("doNotExpandShiftReturn").count(), 1, "{merged}"); + assert!(merged.contains(""), "{merged}"); + } + + #[test] + fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() { + let gen_xml = r#""#; + let merged_with = |compat: &str| { + let orig = format!( + r#"{compat}"# + ); + String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap() + }; + let self_closing = merged_with(""); + assert!(!self_closing.contains("compat"), "{self_closing}"); + assert!(self_closing.contains(r#""#), "{self_closing}"); + assert_eq!(self_closing, merged_with("")); + } + + #[test] + fn compat_drops_every_relationship_attribute_but_keeps_vendor_ones_of_the_same_name() { + let gen_xml = r#""#; + let decls = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x="urn:vendor""#; + // On a child of the block. + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(!merged.contains("rId9"), "{merged}"); + assert!(merged.contains(r#"x:embed="keep""#) && merged.contains(""), "{merged}"); + // On the block itself. + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(!merged.contains("rId4"), "{merged}"); + let orig = format!(r#""#); + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + assert!(merged.contains(r#"x:link="keep""#), "{merged}"); + } } From b8bda06c2c12ccf247ceb770a1fa5efd99ee6510 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 27 Nov 2026 14:58:00 +0100 Subject: [PATCH 143/154] Pin egui at storytold/egui#65's merge commit 932a73b2 (photocraft#17148) Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 28 ++++++++++++++-------------- crates/craft/src/egui_fork.rs | 2 +- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fd6ffc831e..c99367b053 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5656,7 +5656,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "emath", @@ -5712,7 +5712,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5747,7 +5747,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "accesskit", "ahash", @@ -5766,7 +5766,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5785,7 +5785,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5805,7 +5805,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", "egui", @@ -5818,7 +5818,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "eframe", "egui", @@ -5895,7 +5895,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "bytemuck", ] @@ -5968,7 +5968,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" dependencies = [ "ahash", "bytemuck", @@ -5994,7 +5994,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[package]] name = "equator" @@ -15317,19 +15317,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=9952df2fb315a5c07d200ce09e19cf176c417206#9952df2fb315a5c07d200ce09e19cf176c417206" +source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index 3aebf53d07..3af86eaf40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -321,20 +321,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -emath = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "9952df2fb315a5c07d200ce09e19cf176c417206" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 1ec410e0ff..e10d75f9e0 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "9952df2fb315a5c07d200ce09e19cf176c417206"; +pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ From c2d8c9e2e3963d658f01affbddd7b7e7c53e5c95 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:48:08 +0530 Subject: [PATCH 144/154] font-manager: an open glyph menu lets go of a glyph id when the source changes The source may replace a face under the same family and style, and its revision is the signal. The held menu cell now keeps the revision it was clicked at, and a glyph id is dropped at a new revision; a character still names the same character there, so it stays held. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 17 +++++--- crates/font-manager/tests/it/glyphs.rs | 54 +++++++++++++++++++------- 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 14eee5ac87..232b94c641 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -327,16 +327,18 @@ struct Marked(Selection); /// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid /// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph -/// only in its own face, so the menu holds the cell only while that face is shown. +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and for +/// a glyph id the same source revision, since the source may replace a face under the same names. #[derive(Clone, Default)] struct HeldMenu(Option); -/// A held menu's cell and the family and style it was clicked in. +/// A held menu's cell, the family and style it was clicked in, and the source's revision then. #[derive(Clone)] struct MenuCell { cell: GlyphCell, family: String, style: String, + revision: u64, } /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when @@ -644,13 +646,18 @@ impl<'a> GlyphsPanel<'a> { CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), _ => None, }); + let revision = source.revision(); let mut held = std::mem::take(cx.memory::()); if let Some(cell) = clicked { - held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned() })); + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); } // A closed menu lets go of its cell, and so does another face: the same glyph id there is - // another glyph. - let other_face = held.0.as_ref().is_some_and(|held| (held.family.as_str(), held.style.as_str()) != face); + // another glyph. A new revision may be another face under the same names; a character still + // names the same character there, a glyph id does not. + let other_face = held.0.as_ref().is_some_and(|held| { + (held.family.as_str(), held.style.as_str()) != face + || (matches!(held.cell, GlyphCell::Glyph(_)) && held.revision != revision) + }); if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index b4fd930390..51bace6c19 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -4,7 +4,7 @@ use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; @@ -203,8 +203,9 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } -/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. -struct Unencoded; +/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. Its revision is the +/// shared counter, so a test can replace the faces under the same names. +struct Unencoded(Arc); impl GlyphSource for Unencoded { fn cells(&self, _: &str, _: &str, _: &str) -> Vec { @@ -214,19 +215,32 @@ impl GlyphSource for Unencoded { fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { None } + + fn revision(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } } -#[trial] -fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { +/// The host's family and the source's revision, which a test changes between passes, and the cells the panel +/// reported a menu for. +struct OpenMenu { + fx: Fixture, + family: Rc>, + revision: Arc, + seen: Rc>>, +} + +/// A panel over [`Unencoded`] whose host hangs a menu from every menu it reports, with that menu opened on glyph 1. +fn open_menu_on_glyph_1() -> OpenMenu { let family = Rc::new(RefCell::new("Plain".to_owned())); - let host_family = Rc::clone(&family); + let revision = Arc::new(AtomicU64::new(0)); let seen = Rc::new(RefCell::new(Vec::::new())); - let shown = Rc::clone(&seen); + let (host_family, source, shown) = (Rc::clone(&family), Unencoded(Arc::clone(&revision)), Rc::clone(&seen)); let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); let mut fx = Fixture::new(move |ui| { let out = { let mut family = host_family.borrow_mut(); - GlyphsPanel::new("Glyphs", &Unencoded, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) .can_insert(true) .show(ui) }; @@ -245,15 +259,29 @@ fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { fx.frame(vec![pointer::secondary(at, false)]); fx.settle(); assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); - seen.borrow_mut().clear(); - *family.borrow_mut() = "Other".to_owned(); - fx.frame(Vec::new()); - fx.settle(); - let menu = seen.borrow().clone(); + OpenMenu { fx, family, revision, seen } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let mut open = open_menu_on_glyph_1(); + *open.family.borrow_mut() = "Other".to_owned(); + open.fx.frame(Vec::new()); + open.fx.settle(); + let menu = open.seen.borrow().clone(); assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); } +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_a_replaced_face() { + let mut open = open_menu_on_glyph_1(); + open.revision.fetch_add(1, Ordering::Relaxed); + open.fx.frame(Vec::new()); + open.fx.settle(); + let menu = open.seen.borrow().clone(); + assert!(menu.is_empty(), "the same names and ids at a new revision may be another face, so the menu reports none: {menu:?}"); +} #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From 323db9809e3b2a2ebd2e08e2cd038c07d02c67b5 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:49:28 +0530 Subject: [PATCH 145/154] font-manager: an open glyph menu lets go of a glyph id when the source replaces its faces The source can replace a face under the same family and style, and says so through its revision. The held menu cell now keeps the revision it was clicked at, and a glyph id is dropped once the revision changes. A character names the same glyph in the read-again face, so it stays held. Co-Authored-By: Claude Opus 5.5 --- crates/font-manager/src/glyphs.rs | 24 +++--- crates/font-manager/tests/it/glyphs.rs | 100 +++++++++++++------------ 2 files changed, 67 insertions(+), 57 deletions(-) diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 232b94c641..692c7fcb03 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -327,12 +327,12 @@ struct Marked(Selection); /// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid /// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph -/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and for -/// a glyph id the same source revision, since the source may replace a face under the same names. +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and +/// for a glyph id the same source revision, since the source can replace a face under the same names. #[derive(Clone, Default)] struct HeldMenu(Option); -/// A held menu's cell, the family and style it was clicked in, and the source's revision then. +/// A held menu's cell, the family and style it was clicked in, and the source revision then. #[derive(Clone)] struct MenuCell { cell: GlyphCell, @@ -341,6 +341,14 @@ struct MenuCell { revision: u64, } +impl MenuCell { + /// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same + /// glyph after the source reads its faces again; a glyph id may not. + fn holds_in(&self, face: (&str, &str), revision: u64) -> bool { + (self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision) + } +} + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -651,13 +659,9 @@ impl<'a> GlyphsPanel<'a> { if let Some(cell) = clicked { held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); } - // A closed menu lets go of its cell, and so does another face: the same glyph id there is - // another glyph. A new revision may be another face under the same names; a character still - // names the same character there, a glyph id does not. - let other_face = held.0.as_ref().is_some_and(|held| { - (held.family.as_str(), held.style.as_str()) != face - || (matches!(held.cell, GlyphCell::Glyph(_)) && held.revision != revision) - }); + // A closed menu lets go of its cell, and so does another face, or a glyph id after the source + // replaced its faces: the same id there is another glyph. + let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision)); if shown_grid.response.menu.is_none() || other_face { held = HeldMenu(None); } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index 51bace6c19..4972047be6 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -203,8 +203,8 @@ fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); } -/// Unencoded glyphs 1 to 300 in every face: the same id names another glyph in another face. Its revision is the -/// shared counter, so a test can replace the faces under the same names. +/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face, +/// or in a face the source replaced under the same names. struct Unencoded(Arc); impl GlyphSource for Unencoded { @@ -221,67 +221,73 @@ impl GlyphSource for Unencoded { } } -/// The host's family and the source's revision, which a test changes between passes, and the cells the panel -/// reported a menu for. -struct OpenMenu { +/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change. +struct GlyphMenu { fx: Fixture, family: Rc>, revision: Arc, seen: Rc>>, } -/// A panel over [`Unencoded`] whose host hangs a menu from every menu it reports, with that menu opened on glyph 1. -fn open_menu_on_glyph_1() -> OpenMenu { - let family = Rc::new(RefCell::new("Plain".to_owned())); - let revision = Arc::new(AtomicU64::new(0)); - let seen = Rc::new(RefCell::new(Vec::::new())); - let (host_family, source, shown) = (Rc::clone(&family), Unencoded(Arc::clone(&revision)), Rc::clone(&seen)); - let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); - let mut fx = Fixture::new(move |ui| { - let out = { - let mut family = host_family.borrow_mut(); - GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) - .can_insert(true) - .show(ui) - }; - if let Some(menu) = out.menu { - shown.borrow_mut().push(menu.cell); - Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { - MenuItem::new("Insert Glyph").show(ui); - }); - } - }); - fx.in_room(Room::Window); - fx.settle(); - let cell = fx.by_label("1, glyph 1").expect("the first glyph"); - let at = cell.center(); - fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); - fx.frame(vec![pointer::secondary(at, false)]); - fx.settle(); - assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); - seen.borrow_mut().clear(); - OpenMenu { fx, family, revision, seen } +impl GlyphMenu { + fn open() -> Self { + let revision = Arc::new(AtomicU64::new(0)); + let source = Unencoded(Arc::clone(&revision)); + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + seen.borrow_mut().clear(); + GlyphMenu { fx, family, revision, seen } + } + + /// The cells the menu reported over the next passes. + fn reported(&mut self) -> Vec { + self.fx.frame(Vec::new()); + self.fx.settle(); + self.seen.borrow().clone() + } } #[trial] fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { - let mut open = open_menu_on_glyph_1(); + let mut open = GlyphMenu::open(); *open.family.borrow_mut() = "Other".to_owned(); - open.fx.frame(Vec::new()); - open.fx.settle(); - let menu = open.seen.borrow().clone(); + let menu = open.reported(); assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); } #[trial] -fn an_open_menu_does_not_report_a_glyph_id_from_a_replaced_face() { - let mut open = open_menu_on_glyph_1(); - open.revision.fetch_add(1, Ordering::Relaxed); - open.fx.frame(Vec::new()); - open.fx.settle(); - let menu = open.seen.borrow().clone(); - assert!(menu.is_empty(), "the same names and ids at a new revision may be another face, so the menu reports none: {menu:?}"); +fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() { + let mut open = GlyphMenu::open(); + open.revision.store(1, Ordering::Relaxed); + let menu = open.reported(); + assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}"); } + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); From d14a23d33b74f0b43e77e2348fc036dffe44fb79 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 19:53:19 +0530 Subject: [PATCH 146/154] proof: hyphenate Gujarati between aksharas Gujarati words fell to the English rules and got no break. They now break only between orthographic syllables (aksharas): never inside a conjunct, never before a vowel sign or mark, and never before a dead final consonant. The rules come from the script's Unicode encoding (the shared Brahmic block layout), so no pattern file is read. A `gu` Language pack's patterns still come first. The new `indic` module also carries the Devanagari table, so Hindi and the other Devanagari languages need only a `Script::of` mapping. Part of storytold/vectorcraft#4947. Co-Authored-By: Claude Opus 5.5 --- crates/proof/README.md | 1 + crates/proof/src/gu/mod.rs | 2 +- crates/proof/src/hyphen.rs | 12 +- crates/proof/src/hyphen/tests.rs | 15 +++ crates/proof/src/indic.rs | 225 +++++++++++++++++++++++++++++++ crates/proof/src/lang.rs | 4 +- crates/proof/src/lib.rs | 1 + 7 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 crates/proof/src/indic.rs diff --git a/crates/proof/README.md b/crates/proof/README.md index bbf39f7be8..661b246cf0 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -19,6 +19,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) | | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | +| Gujarati | the installed Hunspell dictionary | generic checks | akshara rules (or a Language pack) | Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every build. diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index e72089a4ca..619f75ab58 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -1,6 +1,6 @@ //! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled). //! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati -//! messages; hyphenation keeps the existing fallback. +//! messages. Hyphenation is by akshara ([`crate::indic`]). pub mod grammar; pub(crate) mod suggest; diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index 862526bb58..f62cd7b027 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -15,6 +15,9 @@ //! //! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list. //! +//! **Gujarati**: breaks between aksharas, never inside a conjunct or between a consonant and its +//! vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no pattern file. +//! //! **German**: the TeX German patterns for the reformed spelling ([`Patterns::de`]), also for //! Swiss text, whose `ss` the patterns split like any double consonant (`Stras-se`). //! @@ -116,7 +119,7 @@ pub enum Source { Patterns, /// A heuristic for a language without a dictionary or patterns. Heuristic, - /// A language's syllable rules (Bulgarian, [`crate::bg`]). + /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati [`crate::indic`]). Rules, /// No break points: the word is too short or no source applies. None, @@ -156,6 +159,13 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) { return (crate::bg::points(core), Source::Rules); } + // Gujarati words break between aksharas ([`crate::indic`]); other words in a Gujarati run + // (`WordCraft`) are hyphenated as English. + if let Some(script) = crate::indic::Script::of(lang) + && core.iter().all(|&c| script.is_letter(c)) + { + return (crate::indic::points(script, core), Source::Rules); + } // A suffix written after an apostrophe (`Ankara'dan`, `Türkiye'nin`) is hyphenated part by // part; no break goes next to the apostrophe ([`word_breaks_in`] drops those). if lang == ProofLang::Tr && core.iter().all(|&c| c == '\'' || crate::tr::hyphen::is_letter(c)) { diff --git a/crates/proof/src/hyphen/tests.rs b/crates/proof/src/hyphen/tests.rs index d8f8cf4318..9fa483fab3 100644 --- a/crates/proof/src/hyphen/tests.rs +++ b/crates/proof/src/hyphen/tests.rs @@ -194,3 +194,18 @@ fn gujarati_pack_patterns_fit_checks_script_and_exceptions() { let en_word: Vec = "hyphenation".chars().collect(); assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word)); } + +/// storytold/vectorcraft#4947: Gujarati text breaks between aksharas, within the paragraph's +/// limits, where it used to fall to the English rules and get no break at all; a Latin word in +/// a Gujarati run is still hyphenated as English. +#[test] +fn gujarati_breaks_between_aksharas_within_the_limits() { + let lim = Limits::default(); + let gu = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Gu); + assert_eq!(gu("વિદ્યાર્થી"), "વિ-દ્યા-ર્થી", "a conjunct is never split"); + assert_eq!(word_breaks_in("વિદ્યાર્થી", ProofLang::Gu).1, Source::Rules); + // A lone consonant at either end is fewer letters than `after_first`/`before_last` allow. + assert_eq!(gu("અમદાવાદ"), "અમ-દા-વાદ"); + assert_eq!(gu("«ગુજરાતી»"), "«ગુ-જ-રા-તી»", "punctuation around the word"); + assert_eq!(gu("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); +} diff --git a/crates/proof/src/indic.rs b/crates/proof/src/indic.rs new file mode 100644 index 0000000000..d333d6ec53 --- /dev/null +++ b/crates/proof/src/indic.rs @@ -0,0 +1,225 @@ +//! Hyphenation of Indic scripts by rule: a word breaks only between its orthographic syllables +//! (aksharas), never inside one. +//! +//! An akshara is a consonant with what is written on it — its vowel sign, nukta, anusvara, +//! candrabindu or visarga — and the consonants joined to it by a virama (a conjunct: `દ્ય`, `ર્થ`, +//! `न्द`), or an independent vowel with its marks. So a break goes only before a consonant or an +//! independent vowel that does not follow a virama: `ગુ-જ-રા-તી`, `વિ-દ્યા-ર્થી`, `સં-સ્કૃત`, +//! `हि-न्दी`. A vowel sign, a mark or the second consonant of a conjunct never starts a line. +//! Nor does a dead consonant — one ending in a virama with no consonant after it (`વાક્`) — since +//! it has no vowel of its own and is the end of the syllable before. +//! +//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is +//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a +//! script is its block's start and a few script-specific code points ([`Script::kind`]). +//! Gujarati ([`ProofLang::Gu`](crate::ProofLang::Gu)) uses them; Devanagari is ready for Hindi +//! and the other Devanagari languages: map the language to [`Script::Devanagari`] in +//! [`Script::of`]. +//! +//! A single akshara left at the end or start of a line is ruled out by the paragraph's +//! [`Limits`](crate::hyphen::Limits), which count letters (vowel signs and anusvara count, +//! viramas and nuktas don't), so a bare consonant (`…-ત`) is not carried over with the default +//! limits but a consonant with its vowel sign (`…-તી`) is. + +use crate::ProofLang; + +/// An Indic script hyphenated by [`points`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Script { + /// Devanagari (U+0900..=U+097F): Hindi, Marathi, Nepali… + Devanagari, + /// Gujarati (U+0A80..=U+0AFF). + Gujarati, +} + +/// What a code point is in an akshara. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// An independent vowel: starts an akshara. + Vowel, + /// A consonant: starts an akshara, unless a virama joins it to the consonant before. + Consonant, + /// The virama: joins the consonant before it to the next one, or kills its vowel. + Virama, + /// A vowel sign, nukta, anusvara, candrabindu, visarga or other mark (and the avagraha): + /// belongs to the akshara before it. + Mark, +} + +impl Script { + /// The script whose rules hyphenate `lang`'s words, if any. + pub fn of(lang: ProofLang) -> Option

::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 092/154] 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 093/154] 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 094/154] 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 095/154] 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 33424a99c7b17c99d8e4b6d33bab70897692137b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:16:12 -0800 Subject: [PATCH 096/154] 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 097/154] 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".to_vec()), ("docProps/core.xml", b"".to_vec())]); + // A legacy writer's leading `/` stays a readable part: part names are never filesystem paths. + let mut z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"".to_vec()), ("xdocProps/core.xml", b"".to_vec())]); + rename_entries(&mut z, b"xdocProps/core.xml", b"/docProps/core.xml"); let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.get("docProps/core.xml"), Some(&b""[..])); assert!(p.get("ppt/slides/slide1.xml").is_some()); assert_eq!(p.canonical("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml")); assert_eq!(p.canonical("docprops/core.xml"), Some("docProps/core.xml")); @@ -195,6 +209,20 @@ fn backslash_zip_entry_names_are_found() { assert_eq!(lazy.canonical("/DOCPROPS/core.xml").as_deref(), Some("docProps/core.xml")); assert_eq!(lazy.canonical("nothing"), None); assert_eq!(lazy.read("PPT/slides/slide1.xml").unwrap().as_deref(), Some(&b""[..])); + assert_eq!(lazy.read("docProps/core.xml").unwrap().as_deref(), Some(&b""[..])); +} + +#[test] +fn traversal_zip_entry_names_are_not_parts() { + let mut z = zip_of(&[("a.xml", b"".to_vec()), ("xx/evil.xml", b"".to_vec()), ("C_/evil2.xml", b"".to_vec())]); + rename_entries(&mut z, b"xx/evil.xml", b"../evil.xml"); + rename_entries(&mut z, b"C_/evil2.xml", b"C:/evil2.xml"); + let p = Package::open(&z, &LIMITS).unwrap(); + assert_eq!(p.names().collect::>(), ["a.xml"]); + let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap(); + assert_eq!(lazy.names(), ["a.xml"]); + assert_eq!(lazy.read("../evil.xml").unwrap(), None); + assert_eq!(lazy.read("evil.xml").unwrap(), None); } #[test] diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 04939a71ea..7c09ac4f9c 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -4,7 +4,7 @@ use std::borrow::Cow; use std::io::{Cursor, Read}; use std::sync::Arc; -use crate::entry::{has_traversal_component, has_traversal_component_bytes}; +use crate::entry::{has_traversal_component, has_traversal_component_bytes, sanitize_path}; use crate::preflight::{ReadError, read_entry}; use crate::{Budget, Error, check_entry_count}; @@ -117,6 +117,34 @@ impl<'a> Archive<'a> { Ok(Some(name.into_owned())) } + /// The name at `index` in a virtual namespace, for a format whose entry names are never + /// joined to a filesystem path (OPC part names, for one): leading `/` and `\` removed, so a + /// legacy writer's `/docProps/core.xml` is `docProps/core.xml`. Names that still contain + /// traversal components (`..`, a drive prefix, a NUL) after that, and names that are not + /// UTF-8, return `None`. A caller that extracts entries to disk uses [`Self::entry_name`]. + pub fn virtual_entry_name(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + let raw = file.name_raw(); + let start = raw.iter().position(|b| *b != b'/' && *b != b'\\').unwrap_or(raw.len()); + if raw[start..].is_empty() || has_traversal_component_bytes(&raw[start..]) { + return Ok(None); + } + let Ok(name) = file.name() else { return Ok(None) }; + Ok(sanitize_path(&name).map(str::to_string)) + } + + /// The size the entry at `index` declares, when it has a [`Self::virtual_entry_name`]. + pub fn virtual_entry_size(&mut self, index: usize) -> Result, Error> { + if self.virtual_entry_name(index)?.is_none() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(file.size())) + } + /// Whether the entry at `index` is a directory according to ZIP filename conventions. pub fn entry_is_dir(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { @@ -264,15 +292,29 @@ impl<'a> Archive<'a> { self.read_index_named(index, &name, max) } + /// Read the entry at `index` under the same size, checksum and budget rules as [`Self::read`], + /// when it has a [`Self::virtual_entry_name`]; `None` otherwise. + pub fn read_virtual_index(&mut self, index: usize, max: u64) -> Result>, Error> { + let Some(name) = self.virtual_entry_name(index)? else { + return Ok(None); + }; + self.read_at(index, &name, max).map(Some) + } + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { if has_traversal_component(name) { return Ok(None); } + self.read_at(index, name, max).map(Some) + } + + /// The entry at `index`, whose name the caller has already checked; `name` is for errors. + fn read_at(&mut self, index: usize, name: &str, max: u64) -> Result, Error> { let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); match read_entry(f, declared, max, &mut self.budget) { - Ok(data) => Ok(Some(data)), + Ok(data) => Ok(data), Err(ReadError::DeclaredTooLarge { limit, .. }) | Err(ReadError::Overrun { limit }) => { Err(Error::EntryTooLarge { name: name.to_string(), limit }) } diff --git a/crates/zip/tests/it/archive.rs b/crates/zip/tests/it/archive.rs index 9cc5e111d8..1ef0d81a34 100644 --- a/crates/zip/tests/it/archive.rs +++ b/crates/zip/tests/it/archive.rs @@ -340,3 +340,31 @@ fn raw_bytes_with_traversal_and_invalid_utf8_are_flagged() { assert_eq!(seekable.entry_sizes(0).unwrap(), None); assert_eq!(seekable.read_index(0, 10).unwrap(), None); } + +#[test] +fn virtual_names_strip_a_leading_separator_and_still_refuse_traversal() { + use std::io::Write as _; + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + for (name, data) in [("/docProps/core.xml", &b"core"[..]), ("../evil.xml", b"evil"), ("C:/drive.xml", b"drive"), ("/", b"")] { + zip.start_file(name, opts).unwrap(); + zip.write_all(data).unwrap(); + } + let bytes = zip.finish().unwrap().into_inner(); + let mut archive = Archive::open(&bytes, ROOMY).unwrap(); + + // The named API stays closed to a leading separator; the virtual one reads it without it. + assert_eq!(archive.entry_name(0).unwrap(), None); + assert_eq!(archive.read("/docProps/core.xml", 100).unwrap(), None); + assert_eq!(archive.virtual_entry_name(0).unwrap().as_deref(), Some("docProps/core.xml")); + assert_eq!(archive.virtual_entry_size(0).unwrap(), Some(4)); + assert_eq!(archive.read_virtual_index(0, 100).unwrap().as_deref(), Some(&b"core"[..])); + + // Traversal, drive prefixes and an empty name stay unreadable either way. + for index in 1..archive.len() { + assert_eq!(archive.virtual_entry_name(index).unwrap(), None, "entry {index}"); + assert_eq!(archive.virtual_entry_size(index).unwrap(), None, "entry {index}"); + assert_eq!(archive.read_virtual_index(index, 100).unwrap(), None, "entry {index}"); + } +} From 830521eb00f98484e06adbba7b57ac2911da623a Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 27 Nov 2026 06:16:59 +0530 Subject: [PATCH 119/154] Match DOCX settings reader semantics and retain disabled switch extensions --- crates/docx/src/write/settings_merge.rs | 77 +++++++++++++++---------- crates/docx/tests/it/settings_merge.rs | 64 ++++++++++++++++++++ 2 files changed, 111 insertions(+), 30 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index d94cf5c7d4..9ab1d8201b 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -176,11 +176,20 @@ fn tag_end(s: &str) -> Option { /// The root start tag's span start, span end, close tag start, and the root's direct children, /// or `None` for anything the scanner doesn't expect (CDATA, DOCTYPE, a different root). fn children(xml: &str, root: &str) -> Option<(usize, usize, usize, Vec)> { - let open = xml.find(&format!("<{root}"))?; - let open_end = open + tag_end(xml.get(open..)?)? + 1; - if xml.get(open_end - 2..open_end)? == "/>" { - return None; - } + use quick_xml::events::Event; + let body = xml.strip_prefix('\u{feff}').unwrap_or(xml); + let mut reader = quick_xml::Reader::from_str(body); + let (open, open_end) = loop { + match reader.read_event().ok()? { + Event::Start(e) if e.name().as_ref() == root.as_bytes() => { + let end = xml.len() - body.len() + usize::try_from(reader.buffer_position()).ok()?; + break (end.checked_sub(e.len() + 2)?, end); + } + Event::Decl(_) | Event::PI(_) | Event::Comment(_) => {} + Event::Text(t) if t.iter().all(u8::is_ascii_whitespace) => {} + _ => return None, + } + }; let mut out = Vec::new(); let mut depth = 0usize; let mut i = open_end; @@ -338,15 +347,15 @@ fn is_compat_mode_child(root_tag: &str, compat_s: &str, k: &Child) -> bool { let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); if local.as_ref() == b"name" { - if is_wml { + if is_wml && w_name.is_none() { w_name = val; - } else if is_unbound { + } else if is_unbound && un_name.is_none() { un_name = val; } } else if local.as_ref() == b"uri" { - if is_wml { + if is_wml && w_uri.is_none() { w_uri = val; - } else if is_unbound { + } else if is_unbound && un_uri.is_none() { un_uri = val; } } @@ -546,7 +555,7 @@ fn qualify_wml_child(g_text: &str, root_tag: &str, compat_s: &str) -> String { } } -fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> String { +fn updated_switch(elem_str: &str, root_tag: &str, compat_s: &str, enabled: bool) -> String { let root = if root_tag.trim_start().starts_with('<') { root_tag } else { @@ -569,7 +578,9 @@ fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> Stri let mut reader = quick_xml::NsReader::from_str(&xml); let mut depth = 0; let mut root_w_ns = None; - let mut disabled_val_range: Option<(usize, usize)> = None; + let mut value_edit = None; + let mut has_extra = + tag_end(elem_str).and_then(|end| elem_str[end + 1..].rsplit_once(" Stri let root_w = root_w_ns.as_deref().unwrap_or(b""); for attr in e.attributes().with_checks(false).flatten() { let (ares, local) = reader.resolver().resolve_attribute(attr.key); - if local.as_ref() == b"val" { - let is_wml = match ares { - quick_xml::name::ResolveResult::Bound(ref ns) => is_wml_ns(ns.as_ref(), root_w), - _ => false, - }; - let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + let is_wml = matches!(&ares, quick_xml::name::ResolveResult::Bound(ns) if is_wml_ns(ns.as_ref(), root_w)); + let is_unbound = matches!(ares, quick_xml::name::ResolveResult::Unbound); + if local.as_ref() == b"val" && (is_wml || is_unbound) { let val_str = attr.normalized_value(quick_xml::XmlVersion::Explicit1_0).ok(); let start_in_xml = attr.value.as_ptr() as usize - xml.as_ptr() as usize; if start_in_xml >= elem_offset_in_xml { let start = start_in_xml - elem_offset_in_xml; let end = start + attr.value.len(); - if is_wml { + if is_wml && w_val.is_none() { w_val = Some((val_str, (start, end))); - } else if is_unbound { + } else if is_unbound && un_val.is_none() { un_val = Some((val_str, (start, end))); } } + } else if attr.key.as_ref() != b"xmlns" && !attr.key.as_ref().starts_with(b"xmlns:") { + has_extra = true; } } let chosen = w_val.or(un_val); - if let Some((Some(v), span)) = chosen - && crate::units::is_off_val(&v) - { - disabled_val_range = Some(span); + if let Some((Some(v), span)) = chosen { + if crate::units::is_off_val(&v) == enabled { + value_edit = Some((span, if enabled { "1".to_owned() } else { "0".to_owned() })); + } + } else if !enabled { + let name = e.name(); + let name = std::str::from_utf8(name.as_ref()).unwrap_or_default(); + let prefix = name.rfind(':').map_or("", |i| &name[..=i]); + let pos = 1 + name.len(); + value_edit = Some(((pos, pos), format!(" {prefix}val=\"0\""))); } break; } @@ -621,12 +637,12 @@ fn enable_switch_element(elem_str: &str, root_tag: &str, compat_s: &str) -> Stri } } - if let Some((start, end)) = disabled_val_range - && start < end - && end <= elem_str.len() - { + if !enabled && !has_extra { + return String::new(); + } + if let Some(((start, end), value)) = value_edit { let mut s = elem_str.to_string(); - s.replace_range(start..end, "1"); + s.replace_range(start..end, &value); return s; } elem_str.to_string() @@ -645,7 +661,8 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat ([], None) => {} (matches, None) => { for &(a, b) in matches.iter().rev() { - orig.replace_range(a..b, ""); + let updated = updated_switch(&orig[a..b], root_tag, orig, false); + orig.replace_range(a..b, &updated); } } ([], Some(g_text)) => { @@ -664,7 +681,7 @@ fn sync_compat_switch(root_tag: &str, orig: &mut String, orig_tag: &str, generat } let (first_a, first_b) = matches[0]; let orig_elem = &orig[first_a..first_b]; - let updated = enable_switch_element(orig_elem, root_tag, orig); + let updated = updated_switch(orig_elem, root_tag, orig, true); orig.replace_range(first_a..first_b, &updated); } } diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index 4fe770c6a4..167d55fa12 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -312,3 +312,67 @@ fn hidden_proofing_errors_round_trip() { let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); } + +#[test] +fn root_example_in_prolog_comment_is_preserved_when_zoom_changes() { + let comment = ""; + let original = format!("\u{feff}{}", SETTINGS.replace(" Vec { + with_settings( + &SETTINGS + .replace("", &format!(r#"{child}"#)), + ) +} + +#[test] +fn mode_merge_keeps_settings_whose_first_qualified_name_or_uri_is_vendor_owned() { + for child in [ + r#""#, + r#""#, + ] { + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert_eq!(doc.settings.compat_mode, Some(15)); + doc.settings.compat_mode = None; + let saved = craft_docx::write(&doc).unwrap(); + assert!(text(&unzip(&saved), "word/settings.xml").contains(child)); + assert_eq!(craft_docx::read(&saved).unwrap().settings.compat_mode, None); + } +} + +#[test] +fn enabling_switch_updates_first_qualified_value() { + let child = r#""#; + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert!(!doc.settings.do_not_expand_shift_return); + doc.settings.do_not_expand_shift_return = true; + let saved = craft_docx::write(&doc).unwrap(); + assert!(craft_docx::read(&saved).unwrap().settings.do_not_expand_shift_return); + assert!(text(&unzip(&saved), "word/settings.xml").contains(&child.replace("w:val=\"0\"", "w:val=\"1\""))); +} + +#[test] +fn disabled_switch_keeps_vendor_markup_on_save_and_after_an_edit() { + for (child, was_on) in [ + (r#""#, false), + (r#""#, true), + (r#""#, true), + ] { + let mut doc = craft_docx::read(&with_compat_child(child)).unwrap(); + assert_eq!(doc.settings.do_not_expand_shift_return, was_on); + doc.settings.do_not_expand_shift_return = false; + let saved = craft_docx::write(&doc).unwrap(); + let xml = text(&unzip(&saved), "word/settings.xml"); + let expected = + if child.contains("s:val") { child.replace("s:val=\"1\"", "s:val=\"0\"") } else { child.replace("Return> Date: Thu, 26 Nov 2026 17:53:52 -0800 Subject: [PATCH 120/154] Preserve non-XML whitespace when dropping indentation --- crates/xml/README.md | 2 +- crates/xml/src/read.rs | 10 +++++++--- crates/xml/tests/it/hostile.rs | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/xml/README.md b/crates/xml/README.md index a61a46832c..395f06196f 100644 --- a/crates/xml/README.md +++ b/crates/xml/README.md @@ -36,7 +36,7 @@ assert_eq!((rows, sheet.map(|s| s.children.len())), (3, Ok(0))); | `unknown_entity` | `Drop` | `Drop`, `Literal` (keep `&name;` as text) or `Error`. | | `doctype` | `Ignore` | `Ignore`, `RejectInternalSubset` or `Reject`. Never processed, whichever is chosen. | | `cdata`, `pis`, `comments` | `false` | Keep these as their own nodes. CDATA content is otherwise joined to the text around it. | -| `drop_blank_text` | `false` | Drop the text of an element with child elements when all of it is whitespace (indentation). | +| `drop_blank_text` | `false` | If an element has child elements and all its character data is XML whitespace, the reader drops its ordinary text nodes. CDATA nodes retained by `cdata` remain. | | `split_depth` | `2` | For streaming: how far below the root an element may be and still be handed out. | ### Limits diff --git a/crates/xml/src/read.rs b/crates/xml/src/read.rs index aaea862fc5..20c1f11d6a 100644 --- a/crates/xml/src/read.rs +++ b/crates/xml/src/read.rs @@ -202,8 +202,9 @@ pub struct Options<'a> { pub pis: bool, /// Keep comments inside the root element as [`Node::Comment`]. pub comments: bool, - /// Drop the text of an element that has child elements when all of it is whitespace: the - /// indentation of an indented document. + /// If an element has child elements and all of its character data consists of spaces, tabs, + /// carriage returns, or line feeds, the reader drops its ordinary text nodes. CDATA nodes retained + /// by [`Self::cdata`] remain. pub drop_blank_text: bool, /// For [`Options::parse_streaming`]: how far below the root an element may be and still be /// handed out. 2 by default: children and grandchildren of the root. @@ -889,7 +890,10 @@ impl Builder<'_, '_> { let (mark, attrs_mark, elements_mark) = self.marks.pop().unwrap_or((0, 0, 0)); if self.opts.drop_blank_text && el.children.iter().any(|n| matches!(n, Node::El(_))) { let is_text = |n: &Node| matches!(n, Node::Text(_)); - if el.children.iter().all(|n| !is_text(n) || matches!(n, Node::Text(t) if t.trim().is_empty())) { + if el.children.iter().all(|node| match node { + Node::Text(text) | Node::CData(text) => text.trim_matches([' ', '\t', '\r', '\n']).is_empty(), + _ => true, + }) { let before = el.children.len(); el.children.retain(|n| !is_text(n)); self.kept = self.kept.saturating_sub(before - el.children.len()); diff --git a/crates/xml/tests/it/hostile.rs b/crates/xml/tests/it/hostile.rs index ed1809c9fc..08ad805ba7 100644 --- a/crates/xml/tests/it/hostile.rs +++ b/crates/xml/tests/it/hostile.rs @@ -5,6 +5,27 @@ use craft_xml::{Canonical, Doctype, El, Error, Limits, Options, UnknownEntity, p const CANON: Canonical<'static> = Canonical::new(&[("w", "urn:w"), ("r", "urn:r")]); +#[test] +fn drop_blank_text_preserves_non_xml_whitespace() { + let options = Options { drop_blank_text: true, ..Options::default() }.strict(); + for character in ['\u{a0}', '\u{2003}', '\u{85}', '\u{2028}'] { + let text = format!(" {character} \n"); + let document = format!("