From d35666a71cb4507059d0b3093def6b1956c5666b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 19:37:31 -0800 Subject: [PATCH 01/33] image-codecs: the XMP decoy check reads the result instead of the time truncated_metadata_never_panics_and_falls_back passed its 50,000 repeated " tiff:ResolutionUnit>" decoys only when xmp_resolution returned within 2 s. The search lives in craft-metadata, where repeated_property_text_is_searched_once_for_each_property counts the bytes it reads. This test now checks that the decoys give no resolution, and keeps its clean-packet check. --- crates/image-codecs/tests/it/resolution.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/image-codecs/tests/it/resolution.rs b/crates/image-codecs/tests/it/resolution.rs index 14c682f8db..2a362eb29e 100644 --- a/crates/image-codecs/tests/it/resolution.rs +++ b/crates/image-codecs/tests/it/resolution.rs @@ -287,14 +287,11 @@ fn truncated_metadata_never_panics_and_falls_back() { let _ = xmp_with_resolution(x, (1.0, 1.0)); } - // Property-like text repeated inside the packet must not trigger a full-suffix rescan - // per occurrence (it used to be quadratic). With the cursor advancing past each located - // value, this completes well under a second even with many decoys; a timeout here would - // indicate the quadratic scan returned. A clean packet still extracts correctly. - let start = std::time::Instant::now(); + // Property-like text repeated inside the packet has no value. craft-metadata's + // `repeated_property_text_is_searched_once_for_each_property` counts the bytes this search + // reads. A clean packet still extracts correctly. let decoys = " tiff:ResolutionUnit>".repeat(50_000); - let _ = xmp_resolution(&decoys); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "xmp scan took too long: {:?}", start.elapsed()); + assert_eq!(xmp_resolution(&decoys), None); let clean = "300/1300/12"; near(xmp_resolution(clean), 300.0); } From ec4f2f8c1dee5a4bd28ac4d0478bed7692cc03fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:27:14 -0800 Subject: [PATCH 02/33] ui-contract: test fixtures read a paint chunk's members through their own transform and clip The test fixtures flattened a Shape::PaintChunk but dropped each member's transform_after_tessellation and clip_rect, and a top-level shape's transform as well. A retained chunk whose member moves, scales or has a narrower clip then read at its untransformed place, under the outer clip. flatten and flatten_ref now compose each member's transform after the chunk's and intersect its clip with the chunk's, as egui's tessellator does. Frames::frame_shapes, Fixture::frame_shapes and frame_clipped_shapes return the moved shapes with their own clips, and a frame's shape_bounds, overshoot and painted texts (rect and baseline) follow the same transform. --- .../ui-contract/src/runtime/egui/fixture.rs | 54 ++++++++---- crates/ui-contract/src/testing/fixture.rs | 14 +-- .../tests/it/paint/chunk_members.rs | 87 +++++++++++++++++++ crates/ui-contract/tests/it/paint/mod.rs | 2 + 4 files changed, 132 insertions(+), 25 deletions(-) create mode 100644 crates/ui-contract/tests/it/paint/chunk_members.rs diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c41f3cf1be..7f6c395ca3 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -1,5 +1,7 @@ //! The egui calls `craft_ui::testing` needs: frames, raw input and options that apps reach only through the runtime. +use egui::emath::TSTransform; +use egui::epaint::ClippedShape; use egui::{Context, Event, Key, Modifiers, Pos2, Rect, Shape, Ui, Vec2, ViewportCommand}; use std::sync::Arc; @@ -282,21 +284,19 @@ pub(crate) fn run_frame( } let mut flat = Vec::new(); for clipped in &output.shapes { - let mut shapes = Vec::new(); - flatten_ref(&clipped.shape, &mut shapes); - flat.extend(shapes.into_iter().map(|shape| (shape, clipped.clip_rect))); + flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, &mut flat); } // A shape shows only inside its clip rect. let (bounds, overshoot): (Vec, Vec) = flat .iter() - .filter(|(shape, _)| !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) - .map(|(shape, clip)| (shape.visual_bounding_rect().intersect(*clip), stroke_width(shape) / 2.0)) + .filter(|(shape, _, _)| !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) + .map(|(shape, transform, clip)| ((*transform * shape.visual_bounding_rect()).intersect(*clip), stroke_width(shape) * transform.scaling / 2.0)) .filter(|(rect, _)| rect.is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y) .unzip(); let mut painted_before: std::collections::HashMap = std::collections::HashMap::new(); let texts = flat .iter() - .filter_map(|(shape, clip)| match shape { + .filter_map(|(shape, transform, clip)| match shape { Shape::Text(text) => { let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0); let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth); @@ -306,8 +306,8 @@ pub(crate) fn run_frame( None => placed.pos.y + placed.row.size.y, }); Some(PaintedText { - rect: text.galley.rect.translate(text.pos.to_vec2()), - baseline: text.pos.y + baseline, + rect: *transform * text.galley.rect.translate(text.pos.to_vec2()), + baseline: transform.scaling * (text.pos.y + baseline) + transform.translation.y, elided: full.is_some(), text: full.unwrap_or_else(|| text.galley.job.text.clone()), clip: *clip, @@ -467,9 +467,9 @@ pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl output.textures_delta.clear(); let mut flat = Vec::new(); for clipped in output.shapes { - flatten(clipped.shape, &mut flat); + flatten(clipped, &mut flat); } - flat + flat.into_iter().map(|(shape, _)| shape).collect() } /// A blurred rect: the shadow of a surface. @@ -488,19 +488,37 @@ fn stroke_width(shape: &Shape) -> f32 { } } -fn flatten_ref<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) { +/// Pushes each shape in `shape`, nested shapes flattened, with the transform and clip rect egui paints it under: a paint +/// chunk's member moves by its own transform after the chunk's and shows only inside its own clip rect within the chunk's. +fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, out: &mut Vec<(&'a Shape, TSTransform, Rect)>) { match shape { - Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, out)), - Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten_ref(&clipped.shape, out)), - other => out.push(other), + Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { + flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip.intersect(transform * clipped.clip_rect), out); + }), + other => out.push((other, transform, clip)), } } -pub(crate) fn flatten(shape: Shape, out: &mut Vec) { +/// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with +/// the clip rect it shows inside. +pub(crate) fn flatten(clipped: ClippedShape, out: &mut Vec<(Shape, Rect)>) { + flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, out); +} + +fn flatten_owned(shape: Shape, transform: TSTransform, clip: Rect, out: &mut Vec<(Shape, Rect)>) { match shape { - Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten(shape, out)), - Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten(clipped.shape.clone(), out)), - other => out.push(other), + Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, out)), + Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { + let (transform, clip) = (transform * clipped.transform_after_tessellation, clip.intersect(transform * clipped.clip_rect)); + flatten_owned(clipped.shape.clone(), transform, clip, out); + }), + mut other => { + if transform != TSTransform::IDENTITY { + other.transform(transform); + } + out.push((other, clip)); + } } } diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index f662509a07..65d30d5567 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -528,11 +528,11 @@ impl Fixture { let Some(mut paint) = self.frames.take_paint() else { return out }; // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); + let mut shapes = Vec::new(); for clipped in paint.shapes { - let mut shapes = Vec::new(); - fixture::flatten(clipped.shape, &mut shapes); - out.extend(shapes.into_iter().map(|shape| (clipped.clip_rect, shape))); + fixture::flatten(clipped, &mut shapes); } + out.extend(shapes.into_iter().map(|(shape, clip)| (clip, shape))); out } @@ -541,14 +541,14 @@ impl Fixture { pub fn frame_shapes_with(&mut self, events: Vec) -> Vec { self.frames.record_paint(); self.frame(events); - let mut shapes = Vec::new(); - let Some(mut paint) = self.frames.take_paint() else { return shapes }; + let Some(mut paint) = self.frames.take_paint() else { return Vec::new() }; // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); + let mut shapes = Vec::new(); for clipped in paint.shapes { - fixture::flatten(clipped.shape, &mut shapes); + fixture::flatten(clipped, &mut shapes); } - shapes + shapes.into_iter().map(|(shape, _)| shape).collect() } /// `n` frames with no events. diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs new file mode 100644 index 0000000000..1f26bc11a9 --- /dev/null +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -0,0 +1,87 @@ +//! The test fixtures read a paint chunk's members where egui draws them: each member moves by its own transform after +//! the chunk's and shows only inside its own clip rect within the chunk's. + +use craft_ui::testing::{Fixture, Frames, trial}; +use egui::emath::TSTransform; +use egui::epaint::ClippedShape; +use egui::{Color32, FontId, Rect, Shape, Ui, Vec2, pos2, vec2}; +use std::cell::Cell; +use std::sync::Arc; + +const FILL: Color32 = Color32::from_rgb(200, 40, 40); +const BOX: Rect = Rect { min: pos2(10.0, 10.0), max: pos2(30.0, 20.0) }; +/// The member's own clip rect, narrower than the window on the left. +const MEMBER_CLIP: Rect = Rect { min: pos2(80.0, 0.0), max: pos2(390.0, 290.0) }; +const TEXT_AT: egui::Pos2 = pos2(10.0, 30.0); + +thread_local! { + /// The text run's size as laid out, before the member's transform. + static LAID_OUT: Cell = const { Cell::new(Vec2::ZERO) }; +} + +fn moved() -> TSTransform { + TSTransform::new(vec2(40.0, 30.0), 2.0) +} + +/// Paints one chunk whose members, a filled box and a text run, carry their own transform and clip rect. +fn paint_chunk(ui: &mut Ui) { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + LAID_OUT.set(galley.rect.size()); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: MEMBER_CLIP, + shape, + transform_after_tessellation: moved(), + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); +} + +/// Where the box is drawn: moved, then cut to the member's clip rect. +fn drawn_box() -> Rect { + (moved() * BOX).intersect(MEMBER_CLIP) +} + +fn the_box(shapes: &[Shape]) -> Rect { + let boxes: Vec = + shapes.iter().filter(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)).map(Shape::visual_bounding_rect).collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + boxes[0] +} + +#[trial] +fn a_fixture_reads_a_chunk_member_through_its_own_transform_and_clip() { + let mut fixture = Fixture::new(paint_chunk); + fixture.settle(); + + let clipped = fixture.frame_clipped_shapes(); + let boxes: Vec<(Rect, Rect)> = clipped + .iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (*clip, shape.visual_bounding_rect())) + .collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + let (clip, bounds) = boxes[0]; + assert_eq!(bounds, moved() * BOX, "frame_clipped_shapes: the box moves by the member's transform"); + assert!(MEMBER_CLIP.contains_rect(clip), "frame_clipped_shapes: the clip {clip:?} is within the member's"); + + assert_eq!(the_box(&fixture.frame_shapes()), moved() * BOX, "frame_shapes: the box moves by the member's transform"); + + fixture.frame(Vec::new()); + assert!(fixture.shape_bounds().contains(&drawn_box()), "shape_bounds holds the drawn box {:?}: {:?}", drawn_box(), fixture.shape_bounds()); + let text = fixture.texts().iter().find(|text| text.text == "chunk").expect("the text run is painted"); + assert_eq!(text.rect.min, moved() * TEXT_AT, "texts: the run moves by the member's transform"); + assert_eq!(text.rect.size(), LAID_OUT.get() * moved().scaling, "texts: the run scales by the member's transform"); + assert!( + text.baseline > text.rect.min.y && text.baseline < text.rect.max.y, + "texts: the baseline {} lies in the run {:?}", + text.baseline, + text.rect + ); + assert!(MEMBER_CLIP.contains_rect(text.clip), "texts: the clip {:?} is within the member's", text.clip); +} + +#[trial] +fn frames_read_a_chunk_member_through_its_own_transform() { + let mut frames = Frames::new(); + let shapes = frames.frame_shapes(paint_chunk); + assert_eq!(the_box(&shapes), moved() * BOX, "the box moves by the member's transform"); +} diff --git a/crates/ui-contract/tests/it/paint/mod.rs b/crates/ui-contract/tests/it/paint/mod.rs index 97f1508135..22c98b1b62 100644 --- a/crates/ui-contract/tests/it/paint/mod.rs +++ b/crates/ui-contract/tests/it/paint/mod.rs @@ -1,5 +1,7 @@ pub(crate) mod backdrop; +pub(crate) mod chunk_members; + pub(crate) mod draw_place; pub(crate) mod painters; From 17d50b9d650ee2da1d20fa11e769a93c10a3e668 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:54:58 -0800 Subject: [PATCH 03/33] ui-contract: test a nested paint chunk with its own transform and clip The new trial paints the chunk inside an outer chunk whose transform and clip rect are not the identity. It checks that frame_clipped_shapes, frame_shapes, shape_bounds and texts compose the member's transform first and the outer chunk's second, and that the clip is the member's clip moved by the outer transform, within the outer clip. The test fails when the multiplication order is reversed or when the outer transform is left off the member's clip. --- .../tests/it/paint/chunk_members.rs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index 1f26bc11a9..b38c995d8b 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -85,3 +85,61 @@ fn frames_read_a_chunk_member_through_its_own_transform() { let shapes = frames.frame_shapes(paint_chunk); assert_eq!(the_box(&shapes), moved() * BOX, "the box moves by the member's transform"); } + +/// The clip rect of the outer chunk that holds the nested one, inside the window. It cuts the drawn box on the right, +/// and the member's clip cuts it on the left. +const PARENT_CLIP: Rect = Rect { min: pos2(50.0, 20.0), max: pos2(140.0, 250.0) }; + +fn parent() -> TSTransform { + TSTransform::new(vec2(5.0, 8.0), 1.5) +} + +/// Paints the chunk of [`paint_chunk`] as the only member of an outer chunk with its own transform and clip rect. +fn paint_nested_chunk(ui: &mut Ui) { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + LAID_OUT.set(galley.rect.size()); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: MEMBER_CLIP, + shape, + transform_after_tessellation: moved(), + }); + let inner = ClippedShape { clip_rect: PARENT_CLIP, shape: Shape::PaintChunk(Arc::from(members)), transform_after_tessellation: parent() }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); +} + +/// The nested members' transform: the member's first, then the outer chunk's. +fn composed() -> TSTransform { + parent() * moved() +} + +/// The nested members' clip: the member's clip, moved by the outer chunk's transform, within the outer chunk's clip. +fn composed_clip() -> Rect { + PARENT_CLIP.intersect(parent() * MEMBER_CLIP) +} + +#[trial] +fn a_fixture_reads_a_nested_chunk_member_through_both_transforms_and_clips() { + let mut fixture = Fixture::new(paint_nested_chunk); + fixture.settle(); + + let clipped = fixture.frame_clipped_shapes(); + let boxes: Vec<(Rect, Rect)> = clipped + .iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (*clip, shape.visual_bounding_rect())) + .collect(); + assert_eq!(boxes.len(), 1, "one box is painted: {boxes:?}"); + let (clip, bounds) = boxes[0]; + assert_eq!(bounds, composed() * BOX, "frame_clipped_shapes: the box moves by the member's transform, then the outer chunk's"); + assert_eq!(clip, composed_clip(), "frame_clipped_shapes: the clip is the member's within the outer chunk's"); + + assert_eq!(the_box(&fixture.frame_shapes()), composed() * BOX, "frame_shapes: the box moves by both transforms"); + + fixture.frame(Vec::new()); + let drawn = (composed() * BOX).intersect(composed_clip()); + assert!(fixture.shape_bounds().contains(&drawn), "shape_bounds holds the drawn box {drawn:?}: {:?}", fixture.shape_bounds()); + let text = fixture.texts().iter().find(|text| text.text == "chunk").expect("the text run is painted"); + assert_eq!(text.rect.min, composed() * TEXT_AT, "texts: the run moves by both transforms"); + assert_eq!(text.rect.size(), LAID_OUT.get() * composed().scaling, "texts: the run scales by both transforms"); + assert_eq!(text.clip, composed_clip(), "texts: the clip is the member's within the outer chunk's"); +} From 179e63c5d223295a44d12ce110bc80120dbd18b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:16:39 -0800 Subject: [PATCH 04/33] ui-contract: fixtures skip chunk members with an empty clip and scale glyphs with their text A paint chunk member whose clip only touches its parent's clip has no area, and egui does not draw it; the fixtures now leave it out of shape bounds, texts and frame shapes. When a chunk scales a text run, the fixtures also scale each glyph's position, metrics and point-space UV rect, so baselines read from frame_shapes() match Fixture::texts(). --- .../ui-contract/src/runtime/egui/fixture.rs | 25 +++++- .../tests/it/paint/chunk_members.rs | 78 +++++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 7f6c395ca3..4c60f3f614 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -289,7 +289,7 @@ pub(crate) fn run_frame( // A shape shows only inside its clip rect. let (bounds, overshoot): (Vec, Vec) = flat .iter() - .filter(|(shape, _, _)| !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) + .filter(|(shape, _, clip)| clip.is_positive() && !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) .map(|(shape, transform, clip)| ((*transform * shape.visual_bounding_rect()).intersect(*clip), stroke_width(shape) * transform.scaling / 2.0)) .filter(|(rect, _)| rect.is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y) .unzip(); @@ -301,6 +301,9 @@ pub(crate) fn run_frame( let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0); let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth); *nth += 1; + if !clip.is_positive() { + return None; + } let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, @@ -507,6 +510,9 @@ pub(crate) fn flatten(clipped: ClippedShape, out: &mut Vec<(Shape, Rect)>) { } fn flatten_owned(shape: Shape, transform: TSTransform, clip: Rect, out: &mut Vec<(Shape, Rect)>) { + if !clip.is_positive() { + return; + } match shape { Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { @@ -516,6 +522,23 @@ fn flatten_owned(shape: Shape, transform: TSTransform, clip: Rect, out: &mut Vec mut other => { if transform != TSTransform::IDENTITY { other.transform(transform); + if transform.scaling != 1.0 + && let Shape::Text(text) = &mut other + { + for placed in &mut Arc::make_mut(&mut text.galley).rows { + for glyph in &mut Arc::make_mut(&mut placed.row).glyphs { + glyph.pos *= transform.scaling; + glyph.advance_width *= transform.scaling; + glyph.line_height *= transform.scaling; + glyph.font_ascent *= transform.scaling; + glyph.font_height *= transform.scaling; + glyph.font_face_ascent *= transform.scaling; + glyph.font_face_height *= transform.scaling; + glyph.uv_rect.offset *= transform.scaling; + glyph.uv_rect.size *= transform.scaling; + } + } + } } out.push((other, clip)); } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index b38c995d8b..a0ea7e3175 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -143,3 +143,81 @@ fn a_fixture_reads_a_nested_chunk_member_through_both_transforms_and_clips() { assert_eq!(text.rect.size(), LAID_OUT.get() * composed().scaling, "texts: the run scales by both transforms"); assert_eq!(text.clip, composed_clip(), "texts: the clip is the member's within the outer chunk's"); } + +#[trial] +fn chunk_members_with_empty_effective_clips_are_not_reported() { + let parent_clip = Rect::from_min_max(pos2(20.0, 20.0), pos2(120.0, 120.0)); + for min in [pos2(120.0, 20.0), pos2(20.0, 120.0), pos2(120.0, 120.0), pos2(130.0, 20.0)] { + let member_clip = Rect::from_min_max(min, pos2(200.0, 200.0)); + let hidden_bounds = parent_clip.intersect(member_clip); + let mut fixture = Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("hidden".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [ + Shape::rect_filled(Rect::from_min_max(egui::Pos2::ZERO, pos2(200.0, 200.0)), 0.0, FILL), + Shape::galley(TEXT_AT, galley, Color32::WHITE), + ] + .map(|shape| ClippedShape { clip_rect: member_clip, shape, transform_after_tessellation: TSTransform::IDENTITY }); + let inner = ClippedShape { + clip_rect: parent_clip, + shape: Shape::PaintChunk(Arc::from(members)), + transform_after_tessellation: TSTransform::IDENTITY, + }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); + ui.painter().text(pos2(30.0, 40.0), egui::Align2::LEFT_TOP, "visible", FontId::proportional(14.0), Color32::WHITE); + }); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&hidden_bounds)); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden")); + assert!(fixture.texts().iter().any(|text| text.text == "visible")); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden"))); + assert!(shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "visible"))); + } + } +} + +#[trial] +fn scaled_chunk_text_glyphs_match_reported_baselines() { + let mut fixture = Fixture::new(|ui| { + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, composed()].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }); + fixture.settle(); + + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, scaled) = (texts[0], texts[1]); + let scale = composed().scaling; + assert_eq!(scaled.pos, composed() * original.pos); + assert_eq!(scaled.galley.rows.len(), original.galley.rows.len()); + for (row, source) in scaled.galley.rows.iter().zip(&original.galley.rows) { + assert_eq!(row.row.glyphs.len(), source.row.glyphs.len()); + assert!(!row.row.glyphs.is_empty()); + for (glyph, source) in row.row.glyphs.iter().zip(&source.row.glyphs) { + assert_eq!(glyph.pos, source.pos * scale); + assert_eq!(glyph.advance_width, source.advance_width * scale); + assert_eq!(glyph.line_height, source.line_height * scale); + assert_eq!(glyph.font_ascent, source.font_ascent * scale); + assert_eq!(glyph.font_height, source.font_height * scale); + assert_eq!(glyph.font_face_ascent, source.font_face_ascent * scale); + assert_eq!(glyph.font_face_height, source.font_face_height * scale); + assert_eq!(glyph.uv_rect.offset, source.uv_rect.offset * scale); + assert_eq!(glyph.uv_rect.size, source.uv_rect.size * scale); + assert_eq!(glyph.uv_rect.min, source.uv_rect.min); + assert_eq!(glyph.uv_rect.max, source.uv_rect.max); + } + } + let first = &scaled.galley.rows[0]; + let baseline = scaled.pos.y + first.pos.y + first.row.glyphs[0].pos.y; + let reported = fixture.texts().iter().find(|text| text.rect.min == scaled.pos).expect("the scaled text is reported"); + assert!((baseline - reported.baseline).abs() < 0.001); + } +} From 07a4c415a0e73ed80b0abda00d0cbb2575a5632b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:24:49 -0800 Subject: [PATCH 05/33] ui-contract: fixtures report negatively scaled shapes exactly where egui's tessellator draws them Under a negative scale egui culls a shape against its clip mapped back through the inverse transform, which comes out inverted, so it draws only shapes whose bounds enclose that clip, mirrored into place. Fixtures now ask egui's own Tessellator, with the frame's pixels per point and tessellation options, whether such a shape is drawn, report it with its corners in order, and skip members whose transform is not valid. --- .../ui-contract/src/runtime/egui/fixture.rs | 80 +++++- crates/ui-contract/src/testing/fixture.rs | 6 +- .../tests/it/paint/chunk_members.rs | 241 +++++++++++++++++- 3 files changed, 309 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 4c60f3f614..21d8981b54 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -286,11 +286,28 @@ pub(crate) fn run_frame( for clipped in &output.shapes { flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, &mut flat); } + let (pixels_per_point, options) = (output.pixels_per_point, ctx.tessellation_options(|options| *options)); // A shape shows only inside its clip rect. let (bounds, overshoot): (Vec, Vec) = flat .iter() - .filter(|(shape, _, clip)| clip.is_positive() && !is_shadow(shape) && shape.visual_bounding_rect().is_finite()) - .map(|(shape, transform, clip)| ((*transform * shape.visual_bounding_rect()).intersect(*clip), stroke_width(shape) * transform.scaling / 2.0)) + .filter_map(|(shape, transform, clip)| { + if !transform.is_valid() || !clip.is_positive() || is_shadow(shape) { + return None; + } + if transform.scaling < 0.0 && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { + return None; + } + let rect = shape.visual_bounding_rect(); + if !rect.is_finite() { + return None; + } + let moved = *transform * rect; + // egui mirrors the vertices of a shape it draws under a negative scale, so its drawn rect is the moved one's + // corners in order. A callback keeps the moved rect as egui passes it on. + let flipped = transform.scaling < 0.0 && !matches!(shape, Shape::Callback(_)); + let moved = if flipped { Rect::from_two_pos(moved.min, moved.max) } else { moved }; + Some((moved.intersect(*clip), stroke_width(shape) * transform.scaling.abs() / 2.0)) + }) .filter(|(rect, _)| rect.is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y) .unzip(); let mut painted_before: std::collections::HashMap = std::collections::HashMap::new(); @@ -301,7 +318,10 @@ pub(crate) fn run_frame( let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0); let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth); *nth += 1; - if !clip.is_positive() { + if !transform.is_valid() || !clip.is_positive() { + return None; + } + if transform.scaling < 0.0 && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { return None; } let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { @@ -309,7 +329,10 @@ pub(crate) fn run_frame( None => placed.pos.y + placed.row.size.y, }); Some(PaintedText { - rect: *transform * text.galley.rect.translate(text.pos.to_vec2()), + rect: { + let moved = *transform * text.galley.rect.translate(text.pos.to_vec2()); + Rect::from_two_pos(moved.min, moved.max) + }, baseline: transform.scaling * (text.pos.y + baseline) + transform.translation.y, elided: full.is_some(), text: full.unwrap_or_else(|| text.galley.job.text.clone()), @@ -469,12 +492,26 @@ pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl let mut output = drive(|| run_ui(ctx, input, &children, ui)); output.textures_delta.clear(); let mut flat = Vec::new(); + let options = ctx.tessellation_options(|options| *options); for clipped in output.shapes { - flatten(clipped, &mut flat); + flatten(clipped, output.pixels_per_point, options, &mut flat); } flat.into_iter().map(|(shape, _)| shape).collect() } +/// Whether egui's tessellator draws `shape` moved by `transform` inside `clip`. Under a negative scale, egui tessellates +/// the shape against the clip mapped back through the inverse transform, which comes out inverted, so its coarse culling +/// keeps only shapes whose bounds enclose that clip. This asks the tessellator itself. +fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_point: f32, options: egui::epaint::TessellationOptions) -> bool { + if matches!(shape, Shape::Callback(_)) { + return true; + } + let clipped = ClippedShape { clip_rect: clip, shape: shape.clone(), transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { debug_paint_clip_rects: false, ..options }; + let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()); + !tessellator.tessellate_shapes(vec![clipped]).is_empty() +} + /// A blurred rect: the shadow of a surface. fn is_shadow(shape: &Shape) -> bool { matches!(shape, Shape::Rect(rect) if rect.blur_width > 0.0) @@ -497,7 +534,8 @@ fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, out: &m match shape { Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { - flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip.intersect(transform * clipped.clip_rect), out); + let clip = clip.intersect(transform * clipped.clip_rect); + flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip, out); }), other => out.push((other, transform, clip)), } @@ -505,23 +543,39 @@ fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, out: &m /// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with /// the clip rect it shows inside. -pub(crate) fn flatten(clipped: ClippedShape, out: &mut Vec<(Shape, Rect)>) { - flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, out); +pub(crate) fn flatten(clipped: ClippedShape, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>) { + flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, pixels_per_point, options, out); } -fn flatten_owned(shape: Shape, transform: TSTransform, clip: Rect, out: &mut Vec<(Shape, Rect)>) { - if !clip.is_positive() { +fn flatten_owned( + shape: Shape, + transform: TSTransform, + clip: Rect, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, + out: &mut Vec<(Shape, Rect)>, +) { + if !transform.is_valid() || !clip.is_positive() { return; } match shape { - Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, out)), + Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, pixels_per_point, options, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { - let (transform, clip) = (transform * clipped.transform_after_tessellation, clip.intersect(transform * clipped.clip_rect)); - flatten_owned(clipped.shape.clone(), transform, clip, out); + let clip = clip.intersect(transform * clipped.clip_rect); + let transform = transform * clipped.transform_after_tessellation; + flatten_owned(clipped.shape.clone(), transform, clip, pixels_per_point, options, out); }), mut other => { + if transform.scaling < 0.0 && !egui_draws(&other, transform, clip, pixels_per_point, options) { + return; + } if transform != TSTransform::IDENTITY { other.transform(transform); + if transform.scaling < 0.0 + && let Shape::Rect(rect) = &mut other + { + rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); + } if transform.scaling != 1.0 && let Shape::Text(text) = &mut other { diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 65d30d5567..ada546df7e 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -529,8 +529,9 @@ impl Fixture { // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); let mut shapes = Vec::new(); + let options = self.ctx().tessellation_options(|options| *options); for clipped in paint.shapes { - fixture::flatten(clipped, &mut shapes); + fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes); } out.extend(shapes.into_iter().map(|(shape, clip)| (clip, shape))); out @@ -545,8 +546,9 @@ impl Fixture { // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. paint.textures_delta.clear(); let mut shapes = Vec::new(); + let options = self.ctx().tessellation_options(|options| *options); for clipped in paint.shapes { - fixture::flatten(clipped, &mut shapes); + fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes); } shapes.into_iter().map(|(shape, _)| shape).collect() } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index a0ea7e3175..473d6d1084 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -3,7 +3,7 @@ use craft_ui::testing::{Fixture, Frames, trial}; use egui::emath::TSTransform; -use egui::epaint::ClippedShape; +use egui::epaint::{ClippedShape, PaintCallback}; use egui::{Color32, FontId, Rect, Shape, Ui, Vec2, pos2, vec2}; use std::cell::Cell; use std::sync::Arc; @@ -144,11 +144,52 @@ fn a_fixture_reads_a_nested_chunk_member_through_both_transforms_and_clips() { assert_eq!(text.clip, composed_clip(), "texts: the clip is the member's within the outer chunk's"); } +#[trial] +fn nested_chunk_members_under_negative_parent_scales_are_not_reported() { + let parent = TSTransform::new(vec2(180.0, 160.0), -2.0); + let parent_clip = Rect::from_min_max(pos2(115.0, 105.0), pos2(160.0, 145.0)); + let member_clip = Rect::from_min_max(pos2(15.0, 5.0), pos2(45.0, 40.0)); + let transformed_clip = Rect::from_two_pos(parent * member_clip.min, parent * member_clip.max); + let expected_clip = parent_clip.intersect(transformed_clip); + for member_scale in [-0.5, 0.5] { + let member = TSTransform::new(vec2(40.0, 30.0), member_scale); + let bounds = (parent * member) * BOX; + let paint = move |ui: &mut Ui| { + let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: member_clip, + shape, + transform_after_tessellation: member, + }); + let inner = ClippedShape { clip_rect: parent_clip, shape: Shape::PaintChunk(Arc::from(members)), transform_after_tessellation: parent }; + ui.painter().add(Shape::PaintChunk(Arc::from([inner]))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(expected_clip.is_positive()); + assert!(!fixture.shape_bounds().contains(&bounds.intersect(expected_clip))); + assert!(!fixture.texts().iter().any(|text| text.text == "chunk")); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "chunk"))); + } + } +} + #[trial] fn chunk_members_with_empty_effective_clips_are_not_reported() { let parent_clip = Rect::from_min_max(pos2(20.0, 20.0), pos2(120.0, 120.0)); - for min in [pos2(120.0, 20.0), pos2(20.0, 120.0), pos2(120.0, 120.0), pos2(130.0, 20.0)] { - let member_clip = Rect::from_min_max(min, pos2(200.0, 200.0)); + for member_clip in [ + Rect::NOTHING, + Rect::from_min_max(pos2(120.0, 20.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(20.0, 120.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(120.0, 120.0), pos2(200.0, 200.0)), + Rect::from_min_max(pos2(130.0, 20.0), pos2(200.0, 200.0)), + ] { let hidden_bounds = parent_clip.intersect(member_clip); let mut fixture = Fixture::new(move |ui| { let galley = ui.painter().layout_no_wrap("hidden".to_owned(), FontId::proportional(14.0), Color32::WHITE); @@ -178,6 +219,200 @@ fn chunk_members_with_empty_effective_clips_are_not_reported() { } } +#[trial] +fn inverted_source_bounds_are_not_reported() { + for bounds in [ + Rect::from_min_max(pos2(140.0, 100.0), pos2(100.0, 140.0)), + Rect::from_min_max(pos2(100.0, 140.0), pos2(140.0, 100.0)), + Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)), + ] { + let mut fixture = Fixture::new(move |ui| { + ui.painter().add(Shape::rect_filled(bounds, 0.0, FILL)); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }); + fixture.settle(); + + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&Rect::from_two_pos(bounds.min, bounds.max))); + } + + let bounds = Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)); + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + let drawn = transform * bounds; + let paint = move |ui: &mut Ui| { + let member = ClippedShape { clip_rect: clip, shape: Shape::rect_filled(bounds, 0.0, FILL), transform_after_tessellation: transform }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(drawn.is_positive()); + assert!(clip.contains_rect(drawn)); + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&drawn)); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert_eq!(the_box(&shapes), BOX); + } +} + +#[trial] +fn negatively_scaled_callbacks_with_inverted_source_bounds_are_reported() { + let bounds = Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)); + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(170.0, 150.0), pos2(210.0, 210.0)); + let drawn = transform * bounds; + let paint = move |ui: &mut Ui| { + let member = ClippedShape { + clip_rect: clip, + shape: Shape::Callback(PaintCallback { rect: bounds, callback: Arc::new(()) }), + transform_after_tessellation: transform, + }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(drawn.is_positive()); + let callbacks: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter_map(|(clip, shape)| if let Shape::Callback(callback) = shape { Some((clip, callback.rect)) } else { None }) + .collect(); + assert_eq!(callbacks.len(), 1); + let (actual_clip, actual_bounds) = callbacks[0]; + assert_eq!(actual_bounds, drawn); + assert_eq!(actual_clip, clip); + + fixture.frame(Vec::new()); + assert!(fixture.shape_bounds().contains(&actual_bounds.intersect(actual_clip))); + for shapes in [fixture.frame_shapes(), Frames::new().frame_shapes(paint)] { + let callbacks: Vec<_> = + shapes.iter().filter_map(|shape| if let Shape::Callback(callback) = shape { Some(callback.rect) } else { None }).collect(); + assert_eq!(callbacks, vec![drawn]); + } +} + +#[trial] +fn negatively_scaled_chunk_members_are_not_reported_in_shape_bounds() { + let transform = TSTransform::new(vec2(180.0, 160.0), -2.0); + let clip = Rect::from_min_max(pos2(130.0, 0.0), pos2(170.0, 180.0)); + let stroke = egui::Stroke::new(3.0, FILL); + let box_shape = Shape::rect_stroke(BOX, 0.0, stroke, egui::StrokeKind::Outside); + let bounds = box_shape.visual_bounding_rect(); + let drawn = Rect::from_two_pos(transform * bounds.min, transform * bounds.max).intersect(clip); + let paint = move |ui: &mut Ui| { + let galley = ui.painter().layout_no_wrap("hidden".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [box_shape.clone(), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: clip, + shape, + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + ui.painter().add(Shape::rect_filled(BOX, 0.0, FILL)); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + assert!(drawn.is_positive()); + assert!(fixture.shape_bounds().contains(&BOX)); + assert!(!fixture.shape_bounds().contains(&drawn)); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden")); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert_eq!(the_box(&shapes), BOX); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.stroke == stroke))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden"))); + } +} + +/// The rects egui's tessellator fills for `shape`, each cut to its primitive's clip rect. +fn tessellated(shape: ClippedShape) -> Vec { + let mut tessellator = egui::epaint::Tessellator::new(1.0, egui::epaint::TessellationOptions::default(), [1, 1], Vec::new()); + tessellator + .tessellate_shapes(vec![shape]) + .into_iter() + .filter_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => Some(mesh.calc_bounds().intersect(primitive.clip_rect)), + egui::epaint::Primitive::Callback(_) => None, + }) + .collect() +} + +#[trial] +fn negatively_scaled_members_that_egui_draws_are_reported_where_egui_draws_them() { + let enclosing = Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)); + let flip = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + // A member whose bounds enclose its clip mapped back through its negative scale, and a nested member whose inverted + // clip the parent's negative scale turns into the whole plane. + for (parent, parent_clip, member, member_clip) in + [(TSTransform::IDENTITY, Rect::EVERYTHING, flip, clip), (flip, clip, TSTransform::IDENTITY, Rect::NOTHING)] + { + let chunk = move || { + let inner = + ClippedShape { clip_rect: member_clip, shape: Shape::rect_filled(enclosing, 0.0, FILL), transform_after_tessellation: member }; + let outer = ClippedShape { clip_rect: parent_clip, shape: Shape::PaintChunk(Arc::from([inner])), transform_after_tessellation: parent }; + Shape::PaintChunk(Arc::from([outer])) + }; + let window = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let expected = tessellated(ClippedShape { clip_rect: window, shape: chunk(), transform_after_tessellation: TSTransform::IDENTITY }); + assert_eq!(expected, vec![clip], "egui draws the member inside the clip"); + let paint = move |ui: &mut Ui| { + ui.painter().add(chunk()); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(fixture.shape_bounds().contains(&clip), "{:?}", fixture.shape_bounds()); + for shapes in [fixture.frame_shapes(), Frames::new().frame_shapes(paint)] { + let boxes: Vec = + shapes.iter().filter(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)).map(Shape::visual_bounding_rect).collect(); + assert_eq!(boxes.len(), 1, "the member is painted: {boxes:?}"); + assert_eq!(boxes[0].intersect(clip), clip); + } + let boxes: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter(|(_, shape)| matches!(shape, Shape::Rect(rect) if rect.fill == FILL)) + .map(|(clip, shape)| (clip, shape.visual_bounding_rect().intersect(clip))) + .collect(); + assert_eq!(boxes, vec![(clip, clip)]); + } +} + +#[trial] +fn chunk_members_with_invalid_transforms_are_not_reported() { + for scale in [0.0, -0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let transform = TSTransform::new(vec2(100.0, 100.0), scale); + let mut fixture = + Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("shared".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE)] + .map(|shape| ClippedShape { clip_rect: MEMBER_CLIP, shape, transform_after_tessellation: transform }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + ui.painter().galley(TEXT_AT, galley, Color32::WHITE); + }); + fixture.settle(); + + let texts: Vec<_> = fixture.texts().iter().filter(|text| text.text == "shared").collect(); + assert_eq!(texts.len(), 1, "only the later valid run is reported for scale {scale}"); + assert_eq!(texts[0].rect.min, TEXT_AT); + let hidden = Rect::from_min_max(pos2(100.0, 100.0), pos2(100.0, 100.0)); + assert!(!fixture.shape_bounds().contains(&hidden)); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].pos, TEXT_AT); + } + } +} + #[trial] fn scaled_chunk_text_glyphs_match_reported_baselines() { let mut fixture = Fixture::new(|ui| { From cfe20059f862c8723c880bd6d036173edba0172a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:33:50 -0800 Subject: [PATCH 06/33] ui-contract: mirrored fixture shapes keep positive radii and stroke widths Shape::transform scales radii, stroke widths and corner radii by the signed scale, so a shape egui draws under a negative scale came back with negative dimensions. Fixtures now mirror positions only and scale dimensions by the scale's magnitude. The visibility check runs a member through tessellate_clipped_shape, the path egui takes for paint chunk members, so parallel tessellation of a lone shape does not change the answer. --- .../ui-contract/src/runtime/egui/fixture.rs | 50 ++++++-- .../tests/it/paint/chunk_members.rs | 115 +++++++++++++++++- 2 files changed, 157 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 21d8981b54..a704d7eb15 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -509,7 +509,48 @@ fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_poin let clipped = ClippedShape { clip_rect: clip, shape: shape.clone(), transform_after_tessellation: transform }; let options = egui::epaint::TessellationOptions { debug_paint_clip_rects: false, ..options }; let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()); - !tessellator.tessellate_shapes(vec![clipped]).is_empty() + let mut primitives = Vec::new(); + tessellator.tessellate_clipped_shape(clipped, &mut primitives); + primitives.into_iter().any(|primitive| { + primitive.clip_rect.is_positive() + && match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => !mesh.is_empty(), + egui::epaint::Primitive::Callback(_) => true, + } + }) +} + +fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { + let corner_radius = if let Shape::Rect(rect) = shape { Some(rect.corner_radius) } else { None }; + shape.transform(transform); + if transform.scaling >= 0.0 { + return; + } + match shape { + Shape::Circle(circle) => { + circle.radius = -circle.radius; + circle.stroke.width = -circle.stroke.width; + } + Shape::Ellipse(ellipse) => { + ellipse.radius = -ellipse.radius; + ellipse.stroke.width = -ellipse.stroke.width; + } + Shape::LineSegment { stroke, .. } => stroke.width = -stroke.width, + Shape::Path(path) => path.stroke.width = -path.stroke.width, + Shape::QuadraticBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, + Shape::CubicBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, + Shape::Band(band) => band.stroke.width = -band.stroke.width, + Shape::Rect(rect) => { + rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); + if let Some(corner_radius) = corner_radius { + rect.corner_radius = corner_radius * transform.scaling.abs(); + } + rect.stroke.width = -rect.stroke.width; + rect.blur_width = -rect.blur_width; + } + Shape::Text(text) => text.underline.width = -text.underline.width, + _ => {} + } } /// A blurred rect: the shadow of a surface. @@ -570,12 +611,7 @@ fn flatten_owned( return; } if transform != TSTransform::IDENTITY { - other.transform(transform); - if transform.scaling < 0.0 - && let Shape::Rect(rect) = &mut other - { - rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); - } + transform_fixture_shape(&mut other, transform); if transform.scaling != 1.0 && let Shape::Text(text) = &mut other { diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index 473d6d1084..4c0449d209 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -332,7 +332,11 @@ fn negatively_scaled_chunk_members_are_not_reported_in_shape_bounds() { /// The rects egui's tessellator fills for `shape`, each cut to its primitive's clip rect. fn tessellated(shape: ClippedShape) -> Vec { - let mut tessellator = egui::epaint::Tessellator::new(1.0, egui::epaint::TessellationOptions::default(), [1, 1], Vec::new()); + tessellated_with_options(shape, egui::epaint::TessellationOptions::default()) +} + +fn tessellated_with_options(shape: ClippedShape, options: egui::epaint::TessellationOptions) -> Vec { + let mut tessellator = egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()); tessellator .tessellate_shapes(vec![shape]) .into_iter() @@ -343,6 +347,115 @@ fn tessellated(shape: ClippedShape) -> Vec { .collect() } +#[trial] +fn mirrored_chunk_members_preserve_radii_and_stroke_widths() { + let transform = TSTransform::new(vec2(480.0, 480.0), -2.0); + let clip = Rect::from_min_max(pos2(200.0, 200.0), pos2(240.0, 240.0)); + for source in [ + Shape::circle_filled(pos2(120.0, 120.0), 80.0, FILL), + Shape::line_segment([pos2(80.0, 80.0), pos2(160.0, 160.0)], egui::Stroke::new(3.0, FILL)), + ] { + let chunk = Shape::PaintChunk(Arc::from([ClippedShape { clip_rect: clip, shape: source.clone(), transform_after_tessellation: transform }])); + let expected = + tessellated(ClippedShape { clip_rect: Rect::EVERYTHING, shape: chunk.clone(), transform_after_tessellation: TSTransform::IDENTITY }); + assert_eq!(expected, vec![clip], "egui draws the mirrored member"); + let paint = move |ui: &mut Ui| { + ui.painter().add(chunk.clone()); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + assert!(fixture.shape_bounds().contains(&expected[0])); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint.clone()), + ] { + let members: Vec<_> = shapes + .iter() + .filter(|shape| { + matches!(shape, Shape::Circle(circle) if circle.fill == FILL) + || matches!(shape, Shape::LineSegment { stroke, .. } if stroke.color == FILL) + }) + .collect(); + assert_eq!(members.len(), 1); + let member = members[0]; + match (&source, member) { + (Shape::Circle(source), Shape::Circle(circle)) => { + assert_eq!(circle.center, transform * source.center); + assert_eq!(circle.radius, source.radius * transform.scaling.abs()); + assert!(circle.radius > 0.0); + } + (Shape::LineSegment { points: source_points, stroke: source_stroke }, Shape::LineSegment { points, stroke }) => { + assert_eq!(*points, source_points.map(|point| transform * point)); + assert_eq!(stroke.width, source_stroke.width * transform.scaling.abs()); + assert!(stroke.width > 0.0); + } + _ => panic!("the fixture preserves the member's shape type"), + } + assert!(member.visual_bounding_rect().is_positive()); + assert_eq!(member.visual_bounding_rect().intersect(clip), expected[0]); + } + let members: Vec<_> = fixture + .frame_clipped_shapes() + .into_iter() + .filter(|(_, shape)| { + matches!(shape, Shape::Circle(circle) if circle.fill == FILL) + || matches!(shape, Shape::LineSegment { stroke, .. } if stroke.color == FILL) + }) + .map(|(clip, shape)| (clip, shape.visual_bounding_rect().intersect(clip))) + .collect(); + assert_eq!(members, vec![(clip, expected[0])]); + } +} + +#[trial] +fn mirrored_rotated_ellipses_follow_chunk_culling_with_parallel_tessellation() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(150.0, 150.0), pos2(210.0, 210.0)); + for parallel in [false, true] { + for (radius, visible) in [(vec2(80.0, 10.0), false), (vec2(80.0, 80.0), true)] { + let ellipse = egui::epaint::EllipseShape { + center: pos2(120.0, 120.0), + radius, + fill: FILL, + stroke: egui::Stroke::NONE, + angle: std::f32::consts::FRAC_PI_2, + }; + let chunk = Shape::PaintChunk(Arc::from([ClippedShape { + clip_rect: clip, + shape: Shape::Ellipse(ellipse), + transform_after_tessellation: transform, + }])); + let options = egui::epaint::TessellationOptions { parallel_tessellation: parallel, ..Default::default() }; + let expected = tessellated_with_options( + ClippedShape { clip_rect: Rect::EVERYTHING, shape: chunk.clone(), transform_after_tessellation: TSTransform::IDENTITY }, + options, + ); + assert_eq!(!expected.is_empty(), visible, "egui chunk culling with parallel tessellation {parallel}"); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.parallel_tessellation = parallel); + ui.painter().add(chunk.clone()); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + let bounds = Rect::from_two_pos(transform * ellipse.visual_bounding_rect().min, transform * ellipse.visual_bounding_rect().max); + assert_eq!(fixture.shape_bounds().contains(&bounds.intersect(clip)), visible); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint.clone()), + ] { + let ellipses: Vec<_> = shapes.iter().filter(|shape| matches!(shape, Shape::Ellipse(ellipse) if ellipse.fill == FILL)).collect(); + assert_eq!(!ellipses.is_empty(), visible, "fixture chunk culling with parallel tessellation {parallel}"); + if visible { + assert_eq!(ellipses.len(), 1); + assert_eq!(ellipses[0].visual_bounding_rect().intersect(clip), expected[0]); + } + } + } + } +} + #[trial] fn negatively_scaled_members_that_egui_draws_are_reported_where_egui_draws_them() { let enclosing = Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)); From 4649d8c3d3f6f60c31b1109c65c1c8706fa38c37 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:00:03 -0800 Subject: [PATCH 07/33] ui-contract: fixtures leave out transformed chunk members that their clip hides A chunk member moved or scaled entirely outside a nonempty clip was still returned by Fixture::frame_shapes, frame_clipped_shapes and Frames::frame_shapes, although egui's tessellator culls it and shape_bounds leaves it out. Every transformed member is now kept exactly when egui's Tessellator draws it. --- .../ui-contract/src/runtime/egui/fixture.rs | 2 +- .../tests/it/paint/chunk_members.rs | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index a704d7eb15..4e19e11ea4 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -607,7 +607,7 @@ fn flatten_owned( flatten_owned(clipped.shape.clone(), transform, clip, pixels_per_point, options, out); }), mut other => { - if transform.scaling < 0.0 && !egui_draws(&other, transform, clip, pixels_per_point, options) { + if transform != TSTransform::IDENTITY && !egui_draws(&other, transform, clip, pixels_per_point, options) { return; } if transform != TSTransform::IDENTITY { diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index 4c0449d209..fc60ea7e56 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -219,6 +219,27 @@ fn chunk_members_with_empty_effective_clips_are_not_reported() { } } +#[trial] +fn positively_scaled_chunk_members_outside_their_clip_are_not_reported() { + let transform = TSTransform::new(vec2(400.0, 0.0), 2.0); + let paint = move |ui: &mut Ui| { + let member = ClippedShape { clip_rect: MEMBER_CLIP, shape: Shape::rect_filled(BOX, 0.0, FILL), transform_after_tessellation: transform }; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + ui.painter().text(pos2(30.0, 40.0), egui::Align2::LEFT_TOP, "visible", FontId::proportional(14.0), Color32::WHITE); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&(transform * BOX))); + assert!(fixture.texts().iter().any(|text| text.text == "visible")); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "visible"))); + } +} + #[trial] fn inverted_source_bounds_are_not_reported() { for bounds in [ From a945bc835a64498c1aa4e8854341b1e0f927473b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:09:48 -0800 Subject: [PATCH 08/33] ui-contract: fixtures match egui for clipped text and mirrored bands, text and corners - Text moved or scaled entirely outside its clip is left out of texts(), as egui's tessellator culls it. - A transformed mesh that lies outside its clip is not reported, also with coarse culling off. - A mirrored band keeps its samples in x order with ordered y ranges. - Mirrored text keeps ordered galley and row bounds. - A mirrored rectangle moves each corner radius to the opposite corner. --- .../ui-contract/src/runtime/egui/fixture.rs | 27 ++- .../tests/it/paint/chunk_members.rs | 177 ++++++++++++++++++ 2 files changed, 199 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 4e19e11ea4..30ecab5494 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -321,7 +321,7 @@ pub(crate) fn run_frame( if !transform.is_valid() || !clip.is_positive() { return None; } - if transform.scaling < 0.0 && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { + if *transform != TSTransform::IDENTITY && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { return None; } let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { @@ -514,7 +514,7 @@ fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_poin primitives.into_iter().any(|primitive| { primitive.clip_rect.is_positive() && match primitive.primitive { - egui::epaint::Primitive::Mesh(mesh) => !mesh.is_empty(), + egui::epaint::Primitive::Mesh(mesh) => !mesh.is_empty() && mesh.calc_bounds().intersects(primitive.clip_rect), egui::epaint::Primitive::Callback(_) => true, } }) @@ -539,16 +539,33 @@ fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { Shape::Path(path) => path.stroke.width = -path.stroke.width, Shape::QuadraticBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, Shape::CubicBezier(bezier) => bezier.stroke.width = -bezier.stroke.width, - Shape::Band(band) => band.stroke.width = -band.stroke.width, + Shape::Band(band) => { + band.points.reverse(); + for point in &mut band.points { + std::mem::swap(&mut point.y.min, &mut point.y.max); + } + band.stroke.width = -band.stroke.width; + } Shape::Rect(rect) => { rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); if let Some(corner_radius) = corner_radius { - rect.corner_radius = corner_radius * transform.scaling.abs(); + rect.corner_radius = egui::CornerRadius { nw: corner_radius.se, ne: corner_radius.sw, sw: corner_radius.ne, se: corner_radius.nw } + * transform.scaling.abs(); } rect.stroke.width = -rect.stroke.width; rect.blur_width = -rect.blur_width; } - Shape::Text(text) => text.underline.width = -text.underline.width, + Shape::Text(text) => { + text.underline.width = -text.underline.width; + let galley = Arc::make_mut(&mut text.galley); + galley.rect = Rect::from_two_pos(galley.rect.min, galley.rect.max); + galley.mesh_bounds = Rect::from_two_pos(galley.mesh_bounds.min, galley.mesh_bounds.max); + for placed in &mut galley.rows { + let row = Arc::make_mut(&mut placed.row); + let bounds = &mut row.visuals.mesh_bounds; + *bounds = Rect::from_two_pos(bounds.min, bounds.max); + } + } _ => {} } } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index fc60ea7e56..c8deb439d3 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -280,6 +280,183 @@ fn inverted_source_bounds_are_not_reported() { } } +#[trial] +fn positively_transformed_text_outside_its_clip_is_not_reported() { + for transform in [TSTransform::from_translation(vec2(400.0, 0.0)), TSTransform::from_scaling(20.0)] { + let mut fixture = Fixture::new(move |ui| { + let galley = ui.painter().layout_no_wrap("shared".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let hidden = ClippedShape { + clip_rect: MEMBER_CLIP, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }; + assert!(tessellated(hidden.clone()).is_empty()); + ui.painter().add(Shape::PaintChunk(Arc::from([hidden]))); + ui.painter().galley(TEXT_AT, galley, Color32::WHITE); + }); + fixture.settle(); + + let texts: Vec<_> = fixture.texts().iter().filter(|text| text.text == "shared").collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].rect.min, TEXT_AT); + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].pos, TEXT_AT); + } + } +} + +#[trial] +fn transformed_meshes_outside_the_clip_are_not_reported_without_coarse_culling() { + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, ..Default::default() }; + let transform = TSTransform::from_translation(vec2(400.0, 0.0)); + let member = ClippedShape { clip_rect: MEMBER_CLIP, shape: Shape::rect_filled(BOX, 0.0, FILL), transform_after_tessellation: transform }; + let expected = tessellated_with_options(member.clone(), options); + assert_eq!(expected.len(), 1, "egui produces a mesh before renderer clipping"); + assert!(!expected[0].is_positive()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + assert!(!fixture.shape_bounds().contains(&expected[0])); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + } +} + +#[trial] +fn mirrored_bands_keep_ordered_samples_and_vertical_ranges() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let source = egui::epaint::BandShape::filled( + vec![ + egui::epaint::BandPoint::new(80.0, 80.0..=140.0), + egui::epaint::BandPoint::new(120.0, 90.0..=160.0), + egui::epaint::BandPoint::new(160.0, 100.0..=150.0), + ], + FILL, + ); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let member = ClippedShape { clip_rect: clip, shape: Shape::Band(source.clone()), transform_after_tessellation: transform }; + let expected = tessellated_with_options(member.clone(), options); + assert_eq!(expected.len(), 1); + assert!(expected[0].is_positive()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let bands: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Band(band) = shape { Some(band) } else { None }).collect(); + assert_eq!(bands.len(), 1); + let band = bands[0]; + assert!(band.points.windows(2).all(|pair| pair[0].x < pair[1].x)); + for (point, original) in band.points.iter().zip(source.points.iter().rev()) { + assert!(point.y.min <= point.y.max); + assert_eq!(pos2(point.x, point.y.min), transform * pos2(original.x, original.y.max)); + assert_eq!(pos2(point.x, point.y.max), transform * pos2(original.x, original.y.min)); + } + assert_eq!(band.visual_bounding_rect().intersect(clip), expected[0]); + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Band(band.clone())), options), expected); + } +} + +#[trial] +fn mirrored_text_has_ordered_layout_bounds_and_preserves_glyph_positions() { + let transform = TSTransform::new(vec2(300.0, 300.0), -2.0); + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels: false, ..Default::default() }; + let mut fixture = Fixture::new(move |ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: clip, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }); + fixture.settle(); + + for shapes in [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect()] { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + let expected = tessellated_with_options( + ClippedShape { clip_rect: clip, shape: Shape::Text(original.clone()), transform_after_tessellation: transform }, + options, + ); + assert_eq!(expected.len(), 1); + assert!(expected[0].is_positive()); + assert!(mirrored.galley.rect.is_positive()); + assert_eq!(mirrored.galley.size(), original.galley.size() * transform.scaling.abs()); + let reported = fixture.texts().iter().find(|text| text.rect.max == mirrored.pos).expect("the mirrored text is reported"); + assert_eq!(mirrored.galley.rect.translate(mirrored.pos.to_vec2()), reported.rect); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + assert_eq!(row.pos, source.pos * transform.scaling); + for (glyph, source) in row.row.glyphs.iter().zip(&source.row.glyphs) { + assert_eq!(glyph.pos, source.pos * transform.scaling); + } + for (vertex, source) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + assert_eq!(vertex.pos, source.pos * transform.scaling); + } + } + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Text(mirrored.clone())), options), expected); + } +} + +#[trial] +fn mirrored_rectangles_move_asymmetric_radii_to_opposite_corners() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let radius = egui::CornerRadius { nw: 24, ne: 0, sw: 0, se: 0 }; + let source = Shape::rect_filled(Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)), radius, FILL); + let member = ClippedShape { clip_rect: clip, shape: source, transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let positions = |shape| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| vertex.pos).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let expected = positions(member.clone()); + assert!(!expected.is_empty()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let rects: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); + assert_eq!(rects.len(), 1); + let rect = rects[0]; + assert_eq!(rect.corner_radius, egui::CornerRadius { nw: radius.se, ne: radius.sw, sw: radius.ne, se: radius.nw }); + let actual = positions(ClippedShape::new(clip, Shape::Rect(rect.clone()))); + assert_eq!(actual.len(), expected.len()); + for point in &expected { + assert!(actual.iter().any(|actual| actual.distance(*point) < 0.001), "the transformed outline contains {point:?}"); + } + } +} + #[trial] fn negatively_scaled_callbacks_with_inverted_source_bounds_are_reported() { let bounds = Rect::from_min_max(pos2(140.0, 140.0), pos2(100.0, 100.0)); From 4ab22ea60b3d79b4bd1598964c0ae2ba766a22d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:22:38 -0800 Subject: [PATCH 09/33] ui-contract: fixtures use one egui visibility rule for every chunk member - shape_bounds(), texts(), frame_shapes() and frame_clipped_shapes() keep a chunk member, or a transformed top-level shape, exactly when egui's Tessellator draws it, also when the member's composed transform is the identity. - A mirrored textured rectangle reverses its brush UVs, so it tessellates as egui draws it. - Mirrored text rows keep ordered row rectangles. --- .../ui-contract/src/runtime/egui/fixture.rs | 65 +++++-- .../tests/it/paint/chunk_members.rs | 179 +++++++++++++++++- 2 files changed, 219 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 30ecab5494..365f2ec808 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -284,17 +284,14 @@ pub(crate) fn run_frame( } let mut flat = Vec::new(); for clipped in &output.shapes { - flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, &mut flat); + flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, &mut flat); } let (pixels_per_point, options) = (output.pixels_per_point, ctx.tessellation_options(|options| *options)); // A shape shows only inside its clip rect. let (bounds, overshoot): (Vec, Vec) = flat .iter() - .filter_map(|(shape, transform, clip)| { - if !transform.is_valid() || !clip.is_positive() || is_shadow(shape) { - return None; - } - if transform.scaling < 0.0 && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { + .filter_map(|(shape, transform, clip, in_chunk)| { + if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) || is_shadow(shape) { return None; } let rect = shape.visual_bounding_rect(); @@ -313,15 +310,12 @@ pub(crate) fn run_frame( let mut painted_before: std::collections::HashMap = std::collections::HashMap::new(); let texts = flat .iter() - .filter_map(|(shape, transform, clip)| match shape { + .filter_map(|(shape, transform, clip, in_chunk)| match shape { Shape::Text(text) => { let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0); let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth); *nth += 1; - if !transform.is_valid() || !clip.is_positive() { - return None; - } - if *transform != TSTransform::IDENTITY && !egui_draws(shape, *transform, *clip, pixels_per_point, options) { + if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) { return None; } let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { @@ -520,6 +514,19 @@ fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_poin }) } +fn fixture_draws( + shape: &Shape, + transform: TSTransform, + clip: Rect, + in_chunk: bool, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, +) -> bool { + transform.is_valid() + && clip.is_positive() + && ((!in_chunk && transform == TSTransform::IDENTITY) || egui_draws(shape, transform, clip, pixels_per_point, options)) +} + fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { let corner_radius = if let Shape::Rect(rect) = shape { Some(rect.corner_radius) } else { None }; shape.transform(transform); @@ -548,6 +555,10 @@ fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { } Shape::Rect(rect) => { rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max); + if let Some(brush) = &mut rect.brush { + let uv = &mut Arc::make_mut(brush).uv; + std::mem::swap(&mut uv.min, &mut uv.max); + } if let Some(corner_radius) = corner_radius { rect.corner_radius = egui::CornerRadius { nw: corner_radius.se, ne: corner_radius.sw, sw: corner_radius.ne, se: corner_radius.nw } * transform.scaling.abs(); @@ -588,27 +599,28 @@ fn stroke_width(shape: &Shape) -> f32 { /// Pushes each shape in `shape`, nested shapes flattened, with the transform and clip rect egui paints it under: a paint /// chunk's member moves by its own transform after the chunk's and shows only inside its own clip rect within the chunk's. -fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, out: &mut Vec<(&'a Shape, TSTransform, Rect)>) { +fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, in_chunk: bool, out: &mut Vec<(&'a Shape, TSTransform, Rect, bool)>) { match shape { - Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, out)), + Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, in_chunk, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { let clip = clip.intersect(transform * clipped.clip_rect); - flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip, out); + flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip, true, out); }), - other => out.push((other, transform, clip)), + other => out.push((other, transform, clip, in_chunk)), } } /// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with /// the clip rect it shows inside. pub(crate) fn flatten(clipped: ClippedShape, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>) { - flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, pixels_per_point, options, out); + flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, pixels_per_point, options, out); } fn flatten_owned( shape: Shape, transform: TSTransform, clip: Rect, + in_chunk: bool, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>, @@ -617,14 +629,14 @@ fn flatten_owned( return; } match shape { - Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, pixels_per_point, options, out)), + Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, in_chunk, pixels_per_point, options, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { let clip = clip.intersect(transform * clipped.clip_rect); let transform = transform * clipped.transform_after_tessellation; - flatten_owned(clipped.shape.clone(), transform, clip, pixels_per_point, options, out); + flatten_owned(clipped.shape.clone(), transform, clip, true, pixels_per_point, options, out); }), mut other => { - if transform != TSTransform::IDENTITY && !egui_draws(&other, transform, clip, pixels_per_point, options) { + if !fixture_draws(&other, transform, clip, in_chunk, pixels_per_point, options) { return; } if transform != TSTransform::IDENTITY { @@ -633,7 +645,8 @@ fn flatten_owned( && let Shape::Text(text) = &mut other { for placed in &mut Arc::make_mut(&mut text.galley).rows { - for glyph in &mut Arc::make_mut(&mut placed.row).glyphs { + let row = Arc::make_mut(&mut placed.row); + for glyph in &mut row.glyphs { glyph.pos *= transform.scaling; glyph.advance_width *= transform.scaling; glyph.line_height *= transform.scaling; @@ -644,6 +657,18 @@ fn flatten_owned( glyph.uv_rect.offset *= transform.scaling; glyph.uv_rect.size *= transform.scaling; } + if transform.scaling < 0.0 { + let offset = row.size; + placed.pos += offset; + row.size = -offset; + for glyph in &mut row.glyphs { + glyph.pos -= offset; + } + for vertex in &mut row.visuals.mesh.vertices { + vertex.pos -= offset; + } + row.visuals.mesh_bounds = row.visuals.mesh_bounds.translate(-offset); + } } } } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index c8deb439d3..c6a7944dfc 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -403,12 +403,13 @@ fn mirrored_text_has_ordered_layout_bounds_and_preserves_glyph_positions() { let reported = fixture.texts().iter().find(|text| text.rect.max == mirrored.pos).expect("the mirrored text is reported"); assert_eq!(mirrored.galley.rect.translate(mirrored.pos.to_vec2()), reported.rect); for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { - assert_eq!(row.pos, source.pos * transform.scaling); - for (glyph, source) in row.row.glyphs.iter().zip(&source.row.glyphs) { - assert_eq!(glyph.pos, source.pos * transform.scaling); + for (glyph, original_glyph) in row.row.glyphs.iter().zip(&source.row.glyphs) { + let expected = (source.pos + original_glyph.pos.to_vec2()) * transform.scaling; + assert!((row.pos + glyph.pos.to_vec2()).distance(expected) < 0.001); } - for (vertex, source) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { - assert_eq!(vertex.pos, source.pos * transform.scaling); + for (vertex, original_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let expected = (source.pos + original_vertex.pos.to_vec2()) * transform.scaling; + assert!((row.pos + vertex.pos.to_vec2()).distance(expected) < 0.001); } } assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Text(mirrored.clone())), options), expected); @@ -724,6 +725,174 @@ fn chunk_members_with_invalid_transforms_are_not_reported() { } } +#[trial] +fn identity_chunk_members_outside_their_clip_are_not_reported() { + let clip = Rect::from_min_max(pos2(200.0, 100.0), pos2(300.0, 200.0)); + for nested in [false, true] { + for coarse_culling in [false, true] { + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.coarse_tessellation_culling = coarse_culling); + let galley = ui.painter().layout_no_wrap("hidden identity".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let parent = if nested { TSTransform::new(vec2(40.0, 20.0), 2.0) } else { TSTransform::IDENTITY }; + let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { + clip_rect: parent.inverse() * clip, + shape: Shape::Vec(vec![shape]), + transform_after_tessellation: parent.inverse(), + }); + let chunk = Shape::PaintChunk(Arc::from(members)); + let chunk = if nested { + Shape::PaintChunk(Arc::from([ClippedShape { clip_rect: clip, shape: chunk, transform_after_tessellation: parent }])) + } else { + chunk + }; + let expected = tessellated_with_options(ClippedShape::new(clip, chunk.clone()), ui.ctx().tessellation_options(|options| *options)); + assert!(expected.iter().all(|bounds| !bounds.is_positive())); + ui.painter().add(chunk); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + assert!(!fixture.texts().iter().any(|text| text.text == "hidden identity")); + assert!(!fixture.shape_bounds().contains(&BOX)); + for shapes in [ + fixture.frame_shapes(), + fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), + Frames::new().frame_shapes(paint), + ] { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == FILL))); + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Text(text) if text.galley.job.text == "hidden identity"))); + } + } + } +} + +#[trial] +fn positively_transformed_culled_ellipses_are_excluded_from_bounds() { + let transform = TSTransform::new(vec2(20.0, 10.0), 1.5); + let source_clip = Rect::from_min_max(pos2(115.0, 170.0), pos2(125.0, 180.0)); + let clip = transform * source_clip; + let ellipse = egui::epaint::EllipseShape { + center: pos2(120.0, 120.0), + radius: vec2(80.0, 10.0), + fill: FILL, + stroke: egui::Stroke::NONE, + angle: std::f32::consts::FRAC_PI_2, + }; + let bounds = (transform * ellipse.visual_bounding_rect()).intersect(clip); + assert!(bounds.is_positive()); + let member = ClippedShape { clip_rect: clip, shape: Shape::Ellipse(ellipse), transform_after_tessellation: transform }; + assert!(tessellated(member.clone()).is_empty()); + for in_chunk in [false, true] { + let member = member.clone(); + let paint = move |ui: &mut Ui| { + if in_chunk { + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + } else { + let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("culled ellipse")); + let painter = egui::Painter::new(ui.ctx().clone(), layer, source_clip); + painter.add(member.shape.clone()); + ui.ctx().transform_layer_shapes_after_rounding(layer, transform); + } + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + assert!(!fixture.shape_bounds().contains(&bounds)); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + assert!(!shapes.iter().any(|shape| matches!(shape, Shape::Ellipse(ellipse) if ellipse.fill == FILL))); + } + } +} + +#[trial] +fn mirrored_textured_rectangles_preserve_tessellated_positions_and_uvs() { + let transform = TSTransform::new(vec2(300.0, 300.0), -1.0); + let clip = Rect::from_min_max(pos2(100.0, 100.0), pos2(260.0, 260.0)); + let uv = Rect::from_min_max(pos2(0.125, 0.25), pos2(0.75, 0.875)); + let source = egui::epaint::RectShape::filled(Rect::from_min_max(pos2(80.0, 80.0), pos2(160.0, 160.0)), 0.0, Color32::WHITE) + .with_texture(egui::TextureId::User(7), uv); + let member = ClippedShape { clip_rect: clip, shape: Shape::Rect(source), transform_after_tessellation: transform }; + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, feathering: false, ..Default::default() }; + let vertices = |shape| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| (vertex.pos, vertex.uv)).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let expected = vertices(member.clone()); + assert!(!expected.is_empty()); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + ui.painter().add(Shape::PaintChunk(Arc::from([member.clone()]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let rects: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); + assert_eq!(rects.len(), 1); + let actual = vertices(ClippedShape::new(clip, Shape::Rect(rects[0].clone()))); + assert_eq!(actual.len(), expected.len()); + for vertex in &expected { + assert!(actual.contains(vertex), "the mirrored rectangle preserves position and UV {vertex:?}"); + } + } +} + +#[trial] +fn mirrored_text_rows_have_ordered_rects_and_unchanged_tessellation() { + let transform = TSTransform::new(vec2(300.0, 300.0), -2.0); + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels: false, ..Default::default() }; + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\n\nsecond\n".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: clip, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + assert_eq!(mirrored.galley.rows.len(), original.galley.rows.len()); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + let expected = transform.scaling * source.rect(); + assert_eq!(row.rect(), Rect::from_two_pos(expected.min, expected.max)); + assert!(row.rect().min.x <= row.rect().max.x && row.rect().min.y <= row.rect().max.y); + assert_eq!(row.glyphs.len(), source.glyphs.len()); + assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); + for (glyph, source_glyph) in row.glyphs.iter().zip(&source.glyphs) { + let expected = (source.pos + source_glyph.pos.to_vec2()) * transform.scaling; + assert!((row.pos + glyph.pos.to_vec2()).distance(expected) < 0.001); + } + for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let expected = (source.pos + source_vertex.pos.to_vec2()) * transform.scaling; + assert!((row.pos + vertex.pos.to_vec2()).distance(expected) < 0.001); + assert_eq!(vertex.uv, source_vertex.uv); + } + } + let expected = tessellated_with_options( + ClippedShape { clip_rect: clip, shape: Shape::Text(original.clone()), transform_after_tessellation: transform }, + options, + ); + assert!(!expected.is_empty()); + assert_eq!(tessellated_with_options(ClippedShape::new(clip, Shape::Text(mirrored.clone())), options), expected); + } +} + #[trial] fn scaled_chunk_text_glyphs_match_reported_baselines() { let mut fixture = Fixture::new(|ui| { From 6951680cf4d0dd1014a9b5f8b13884a37f6e595a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:36:16 -0800 Subject: [PATCH 10/33] ui-contract: fixtures snap text origins and keep mirrored underlines where egui draws them - texts() rounds the text origin to pixels before the paint transform when round_text_to_pixels is on, as egui's tessellator does. - Mirrored text returns its visible underlines as separate line segments after the text, placed where egui draws them. --- .../ui-contract/src/runtime/egui/fixture.rs | 36 +++++- .../tests/it/paint/chunk_members.rs | 112 ++++++++++++++++++ 2 files changed, 146 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 365f2ec808..8096efcd90 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -322,12 +322,13 @@ pub(crate) fn run_frame( Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, }); + let pos = if options.round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) } else { text.pos }; Some(PaintedText { rect: { - let moved = *transform * text.galley.rect.translate(text.pos.to_vec2()); + let moved = *transform * text.galley.rect.translate(pos.to_vec2()); Rect::from_two_pos(moved.min, moved.max) }, - baseline: transform.scaling * (text.pos.y + baseline) + transform.translation.y, + baseline: transform.scaling * (pos.y + baseline) + transform.translation.y, elided: full.is_some(), text: full.unwrap_or_else(|| text.galley.job.text.clone()), clip: *clip, @@ -474,6 +475,7 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions { } /// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened. +/// Mirrored text returns its visible underlines as separate line segments immediately after the text, whose underline is `Stroke::NONE`. pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec { let screen = Rect::from_min_size(Pos2::ZERO, screen); let children = open_children(ctx, egui::ViewportId::ROOT); @@ -612,6 +614,7 @@ fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, in_chun /// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with /// the clip rect it shows inside. +/// Mirrored text with a visible underline uses `Stroke::NONE`. Its transformed underlines follow it as separate line segments under the same clip. pub(crate) fn flatten(clipped: ClippedShape, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>) { flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, pixels_per_point, options, out); } @@ -639,6 +642,34 @@ fn flatten_owned( if !fixture_draws(&other, transform, clip, in_chunk, pixels_per_point, options) { return; } + let mut underlines = Vec::new(); + if transform.scaling < 0.0 + && let Shape::Text(text) = &mut other + && !text.underline.is_empty() + && !text.galley.is_empty() + && text.opacity_factor > 0.0 + { + let pos = if options.round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) } else { text.pos }; + let rotation = egui::emath::Rot2::from_angle(text.angle); + let source_clip = transform.inverse() * clip; + for row in &text.galley.rows { + if row.visuals.mesh.is_empty() { + continue; + } + let mut rect = row.visuals.mesh_bounds; + if text.angle != 0.0 { + rect = rect.rotate_bb(rotation); + } + rect = rect.translate((pos + rotation * row.pos.to_vec2()).to_vec2()); + if options.coarse_tessellation_culling && !source_clip.intersects(rect) { + continue; + } + let points = [transform * rect.left_bottom(), transform * rect.right_bottom()]; + let stroke = egui::Stroke { width: text.underline.width * transform.scaling.abs(), color: text.underline.color }; + underlines.push(Shape::LineSegment { points, stroke }); + } + text.underline = egui::Stroke::NONE; + } if transform != TSTransform::IDENTITY { transform_fixture_shape(&mut other, transform); if transform.scaling != 1.0 @@ -673,6 +704,7 @@ fn flatten_owned( } } out.push((other, clip)); + out.extend(underlines.into_iter().map(|shape| (shape, clip))); } } } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index c6a7944dfc..661ef363c7 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -6,6 +6,7 @@ use egui::emath::TSTransform; use egui::epaint::{ClippedShape, PaintCallback}; use egui::{Color32, FontId, Rect, Shape, Ui, Vec2, pos2, vec2}; use std::cell::Cell; +use std::rc::Rc; use std::sync::Arc; const FILL: Color32 = Color32::from_rgb(200, 40, 40); @@ -893,6 +894,117 @@ fn mirrored_text_rows_have_ordered_rects_and_unchanged_tessellation() { } } +#[trial] +fn painted_text_origins_are_snapped_before_the_paint_transform() { + let origin = pos2(10.2, 30.2); + let pixels_per_point = 1.5; + for round_text_to_pixels in [false, true] { + for scale in [1.0, 2.0, -2.0] { + let transform = TSTransform::new(vec2(200.25, 150.25), scale); + let expected = Rc::new(Cell::new((Rect::NOTHING, 0.0))); + let recorded = expected.clone(); + let mut fixture = Fixture::new(move |ui| { + let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, round_text_to_pixels, ..Default::default() }; + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("snapped origin".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let pos = if round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(origin, pixels_per_point) } else { origin }; + let moved = transform * galley.rect.translate(pos.to_vec2()); + let row = &galley.rows[0]; + let baseline = transform * pos2(0.0, pos.y + (row.pos.y + row.glyphs[0].pos.y)); + recorded.set((Rect::from_two_pos(moved.min, moved.max), baseline.y)); + let shape = Shape::galley(origin, galley.clone(), Color32::WHITE); + let member = ClippedShape { clip_rect: Rect::EVERYTHING, shape, transform_after_tessellation: transform }; + let snapped = ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(pos, galley, Color32::WHITE), + transform_after_tessellation: transform, + }; + let vertices = |shape, options| { + egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()) + .tessellate_shapes(vec![shape]) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => mesh.vertices.into_iter().map(|vertex| vertex.pos).collect::>(), + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let actual = vertices(member.clone(), options); + assert!(!actual.is_empty()); + assert_eq!(actual, vertices(snapped, egui::epaint::TessellationOptions { round_text_to_pixels: false, ..options })); + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }); + fixture.pixels_per_point(pixels_per_point); + fixture.settle(); + let text = fixture.texts().iter().find(|text| text.text == "snapped origin").expect("the text is painted"); + let (rect, baseline) = expected.get(); + assert_eq!(text.rect, rect, "rounding {round_text_to_pixels}, scale {scale}"); + assert_eq!(text.baseline, baseline, "rounding {round_text_to_pixels}, scale {scale}"); + } + } +} + +#[trial] +fn mirrored_text_underlines_match_egui_vertices() { + let clip = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 300.0)); + for scale in [-1.0, -2.0] { + for angle in [0.0, 0.35] { + let transform = TSTransform::new(vec2(300.0, 250.0), scale); + let options = egui::epaint::TessellationOptions { + coarse_tessellation_culling: false, + feathering: scale == -1.0, + round_line_segments_to_pixels: scale == -1.0, + ..Default::default() + }; + let underline_vertices = |shapes| { + egui::epaint::Tessellator::new(1.0, options, [1, 1], Vec::new()) + .tessellate_shapes(shapes) + .into_iter() + .flat_map(|primitive| match primitive.primitive { + egui::epaint::Primitive::Mesh(mesh) => { + mesh.vertices.into_iter().filter(|vertex| vertex.color == FILL).map(|vertex| vertex.pos).collect::>() + } + egui::epaint::Primitive::Callback(_) => Vec::new(), + }) + .collect::>() + }; + let source = Rc::new(std::cell::RefCell::new(Vec::new())); + let recorded = source.clone(); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|current| *current = options); + let galley = ui.painter().layout_no_wrap("first\n\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let mut text = egui::epaint::TextShape::new(TEXT_AT, galley, Color32::WHITE).with_underline(egui::Stroke::new(2.0, FILL)); + text.angle = angle; + let member = ClippedShape { clip_rect: clip, shape: Shape::Text(text), transform_after_tessellation: transform }; + *recorded.borrow_mut() = vec![member.clone()]; + ui.painter().add(Shape::PaintChunk(Arc::from([member]))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.settle(); + let expected = underline_vertices(source.borrow().clone()); + assert!(!expected.is_empty()); + let clipped = fixture.frame_clipped_shapes(); + let text_index = clipped.iter().position(|(_, shape)| matches!(shape, Shape::Text(_))).expect("the text is returned"); + assert!(matches!(&clipped[text_index].1, Shape::Text(text) if text.underline == egui::Stroke::NONE)); + for (line_clip, line) in &clipped[text_index + 1..text_index + 3] { + assert_eq!(*line_clip, clipped[text_index].0); + assert!(matches!(line, Shape::LineSegment { stroke, .. } if stroke.color == FILL)); + } + for shapes in [ + fixture.frame_shapes().into_iter().map(|shape| ClippedShape::new(clip, shape)).collect(), + clipped.into_iter().map(|(clip, shape)| ClippedShape::new(clip, shape)).collect(), + Frames::new().frame_shapes(paint).into_iter().map(|shape| ClippedShape::new(clip, shape)).collect(), + ] { + let actual = underline_vertices(shapes); + assert_eq!(actual.len(), expected.len()); + for vertex in &expected { + assert!(actual.iter().any(|actual| actual.distance(*vertex) < 0.001), "missing underline vertex {vertex:?}"); + } + } + } + } +} + #[trial] fn scaled_chunk_text_glyphs_match_reported_baselines() { let mut fixture = Fixture::new(|ui| { From 3c4020654a45262174318b3dee2f53f04f4a9c3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:48:16 -0800 Subject: [PATCH 11/33] ui-contract: fixtures snap transformed text in its own space and keep mirrored glyph rects ordered - shape_bounds() and the returned TextShape round a transformed text origin to pixels before the transform, as egui's tessellator does. - Mirrored glyphs keep nonnegative advance widths and heights, so Glyph::logical_rect() is ordered and covers the mirrored area. --- .../ui-contract/src/runtime/egui/fixture.rs | 24 ++++- .../tests/it/paint/chunk_members.rs | 99 ++++++++++++++++++- 2 files changed, 118 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 8096efcd90..2a69216ca2 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -294,7 +294,14 @@ pub(crate) fn run_frame( if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) || is_shadow(shape) { return None; } - let rect = shape.visual_bounding_rect(); + let rect = match shape { + Shape::Text(text) if *transform != TSTransform::IDENTITY && options.round_text_to_pixels => { + let mut text = text.clone(); + text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point); + text.visual_bounding_rect() + } + _ => shape.visual_bounding_rect(), + }; if !rect.is_finite() { return None; } @@ -671,6 +678,11 @@ fn flatten_owned( text.underline = egui::Stroke::NONE; } if transform != TSTransform::IDENTITY { + if options.round_text_to_pixels + && let Shape::Text(text) = &mut other + { + text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point); + } transform_fixture_shape(&mut other, transform); if transform.scaling != 1.0 && let Shape::Text(text) = &mut other @@ -687,6 +699,16 @@ fn flatten_owned( glyph.font_face_height *= transform.scaling; glyph.uv_rect.offset *= transform.scaling; glyph.uv_rect.size *= transform.scaling; + if transform.scaling < 0.0 { + let rect = glyph.logical_rect(); + glyph.advance_width = glyph.advance_width.abs(); + glyph.line_height = glyph.line_height.abs(); + glyph.font_ascent = glyph.font_ascent.abs(); + glyph.font_height = glyph.font_height.abs(); + glyph.font_face_ascent = glyph.font_face_ascent.abs(); + glyph.font_face_height = glyph.font_face_height.abs(); + glyph.pos = Rect::from_two_pos(rect.min, rect.max).min + egui::vec2(0.0, glyph.font_ascent); + } } if transform.scaling < 0.0 { let offset = row.size; diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index 661ef363c7..d948c97616 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -405,8 +405,10 @@ fn mirrored_text_has_ordered_layout_bounds_and_preserves_glyph_positions() { assert_eq!(mirrored.galley.rect.translate(mirrored.pos.to_vec2()), reported.rect); for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { for (glyph, original_glyph) in row.row.glyphs.iter().zip(&source.row.glyphs) { - let expected = (source.pos + original_glyph.pos.to_vec2()) * transform.scaling; - assert!((row.pos + glyph.pos.to_vec2()).distance(expected) < 0.001); + let expected = transform.scaling * original_glyph.logical_rect().translate(source.pos.to_vec2()); + let actual = glyph.logical_rect().translate(row.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001); + assert!(actual.max.distance(expected.min) < 0.001); } for (vertex, original_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { let expected = (source.pos + original_vertex.pos.to_vec2()) * transform.scaling; @@ -876,8 +878,10 @@ fn mirrored_text_rows_have_ordered_rects_and_unchanged_tessellation() { assert_eq!(row.glyphs.len(), source.glyphs.len()); assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); for (glyph, source_glyph) in row.glyphs.iter().zip(&source.glyphs) { - let expected = (source.pos + source_glyph.pos.to_vec2()) * transform.scaling; - assert!((row.pos + glyph.pos.to_vec2()).distance(expected) < 0.001); + let expected = transform.scaling * source_glyph.logical_rect().translate(source.pos.to_vec2()); + let actual = glyph.logical_rect().translate(row.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001); + assert!(actual.max.distance(expected.min) < 0.001); } for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { let expected = (source.pos + source_vertex.pos.to_vec2()) * transform.scaling; @@ -894,6 +898,93 @@ fn mirrored_text_rows_have_ordered_rects_and_unchanged_tessellation() { } } +#[trial] +fn transformed_text_shapes_and_bounds_snap_the_source_origin() { + let origin = pos2(10.4, 30.4); + let transform = TSTransform::new(vec2(0.3, 0.3), 1.5); + let pixels_per_point = 1.0; + let snapped = egui::emath::GuiRounding::round_to_pixels(origin, pixels_per_point); + let expected_bounds = Rc::new(Cell::new(Rect::NOTHING)); + let recorded = expected_bounds.clone(); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| options.round_text_to_pixels = true); + let galley = ui.painter().layout_no_wrap("source snapping".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let text = egui::epaint::TextShape::new(snapped, galley.clone(), Color32::WHITE); + recorded.set(transform * text.visual_bounding_rect()); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(origin, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint.clone()); + fixture.pixels_per_point(pixels_per_point); + fixture.settle(); + assert!(fixture.shape_bounds().contains(&expected_bounds.get()), "{:?}", fixture.shape_bounds()); + + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + assert_eq!(texts[0].pos, origin); + assert_eq!(texts[1].pos, transform * snapped); + } +} + +#[trial] +fn mirrored_glyph_logical_rects_are_ordered_and_cover_the_transformed_source() { + for scale in [-1.0, -1.5, -2.0] { + let transform = TSTransform::new(vec2(300.0, 250.0), scale); + let paint = move |ui: &mut Ui| { + ui.ctx().tessellation_options_mut(|options| { + options.coarse_tessellation_culling = false; + options.round_text_to_pixels = false; + }); + let galley = ui.painter().layout_no_wrap("first\nsecond".to_owned(), FontId::proportional(14.0), Color32::WHITE); + let members = [TSTransform::IDENTITY, transform].map(|transform| ClippedShape { + clip_rect: Rect::EVERYTHING, + shape: Shape::galley(TEXT_AT, galley.clone(), Color32::WHITE), + transform_after_tessellation: transform, + }); + ui.painter().add(Shape::PaintChunk(Arc::from(members))); + }; + let mut fixture = Fixture::new(paint); + fixture.settle(); + for shapes in + [fixture.frame_shapes(), fixture.frame_clipped_shapes().into_iter().map(|(_, shape)| shape).collect(), Frames::new().frame_shapes(paint)] + { + let texts: Vec<_> = shapes.iter().filter_map(|shape| if let Shape::Text(text) = shape { Some(text) } else { None }).collect(); + assert_eq!(texts.len(), 2); + let (original, mirrored) = (texts[0], texts[1]); + assert_eq!(mirrored.galley.rows.len(), original.galley.rows.len()); + for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { + assert!(!row.glyphs.is_empty()); + assert_eq!(row.glyphs.len(), source.glyphs.len()); + for (glyph, source_glyph) in row.glyphs.iter().zip(&source.glyphs) { + assert!(glyph.advance_width >= 0.0 && glyph.line_height >= 0.0 && glyph.font_ascent >= 0.0); + assert!(glyph.font_height >= 0.0 && glyph.font_face_ascent >= 0.0 && glyph.font_face_height >= 0.0); + let rect = glyph.logical_rect(); + assert!(rect.min.x <= rect.max.x && rect.min.y <= rect.max.y); + let actual = rect.translate(mirrored.pos.to_vec2() + row.pos.to_vec2()); + let expected = transform * source_glyph.logical_rect().translate(original.pos.to_vec2() + source.pos.to_vec2()); + assert!(actual.min.distance(expected.max) < 0.001, "{actual:?} versus {expected:?}"); + assert!(actual.max.distance(expected.min) < 0.001, "{actual:?} versus {expected:?}"); + } + assert!(!row.visuals.mesh.vertices.is_empty()); + assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); + for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { + let actual = mirrored.pos + row.pos.to_vec2() + vertex.pos.to_vec2(); + let expected = transform * (original.pos + source.pos.to_vec2() + source_vertex.pos.to_vec2()); + assert!(actual.distance(expected) < 0.001); + assert_eq!(vertex.uv, source_vertex.uv); + } + } + } + } +} + #[trial] fn painted_text_origins_are_snapped_before_the_paint_transform() { let origin = pos2(10.2, 30.2); From 131dbeec7d3fb45d39fbfa3fc47e879e4680a9d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:33:51 -0800 Subject: [PATCH 12/33] ui-contract: fixtures tessellate mirrored underlines in source space A scaled underline was returned as a LineSegment with a scaled width, so feathering ran after the transform and the opaque edges moved. The fixture now tessellates each underline before the paint transform, as egui's tessellate_text does, and returns the transformed mesh. The vertex comparison now runs with feathering at scale -2 too. --- crates/ui-contract/src/runtime/egui/fixture.rs | 14 +++++++++++--- crates/ui-contract/tests/it/paint/chunk_members.rs | 4 ++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 2a69216ca2..43a9fc0708 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -671,9 +671,17 @@ fn flatten_owned( if options.coarse_tessellation_culling && !source_clip.intersects(rect) { continue; } - let points = [transform * rect.left_bottom(), transform * rect.right_bottom()]; - let stroke = egui::Stroke { width: text.underline.width * transform.scaling.abs(), color: text.underline.color }; - underlines.push(Shape::LineSegment { points, stroke }); + let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new()); + tessellator.set_clip_rect(source_clip); + let mut mesh = egui::epaint::Mesh::default(); + tessellator.tessellate_line_segment([rect.left_bottom(), rect.right_bottom()], text.underline, &mut mesh); + if mesh.is_empty() { + continue; + } + for vertex in &mut mesh.vertices { + vertex.pos = transform * vertex.pos; + } + underlines.push(Shape::Mesh(Arc::new(mesh))); } text.underline = egui::Stroke::NONE; } diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index d948c97616..b42ef667c2 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -1043,7 +1043,7 @@ fn mirrored_text_underlines_match_egui_vertices() { let transform = TSTransform::new(vec2(300.0, 250.0), scale); let options = egui::epaint::TessellationOptions { coarse_tessellation_culling: false, - feathering: scale == -1.0, + feathering: true, round_line_segments_to_pixels: scale == -1.0, ..Default::default() }; @@ -1079,7 +1079,7 @@ fn mirrored_text_underlines_match_egui_vertices() { assert!(matches!(&clipped[text_index].1, Shape::Text(text) if text.underline == egui::Stroke::NONE)); for (line_clip, line) in &clipped[text_index + 1..text_index + 3] { assert_eq!(*line_clip, clipped[text_index].0); - assert!(matches!(line, Shape::LineSegment { stroke, .. } if stroke.color == FILL)); + assert!(matches!(line, Shape::Mesh(mesh) if mesh.vertices.iter().any(|vertex| vertex.color == FILL))); } for shapes in [ fixture.frame_shapes().into_iter().map(|shape| ClippedShape::new(clip, shape)).collect(), From 744812cbf94730c0971c1b5dfb5ac99db037f76c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:31:57 -0800 Subject: [PATCH 13/33] ui-contract: an Alt code types its character once with winit 0dfcec0e The winit patch rev moves from a517b384 to 0dfcec0e, the head of storytold/winit craft/0.30.13. It adds native touchpad pinch and rotation on Wayland (storytold/winit#20), which egui-winit reports as Event::Zoom and Event::Rotate, and the Windows change that reports an Alt + keypad code's character as a key press with that text after the Alt release. That press has no physical key. For a character egui names a key for (backslash, pipe, letters, digits), egui-winit sends a key press before the text, and the Alt-code fold took the press for a key the user pressed: it dropped the echo of the character it had typed, so the character was typed twice, and the press reached egui, where a single-key shortcut could take it. The fold now leaves that press and its release out, so the text that follows meets the echo. Only a press whose key names the code's character, or for a code above 255 the character of the byte Windows reduces it to, counts; another key with no physical key still types. --- Cargo.lock | 2 +- Cargo.toml | 2 +- .../ui-contract/src/runtime/egui/alt_code.rs | 40 ++++++- .../ui-contract/tests/it/runtime/alt_code.rs | 101 ++++++++++++++++++ 4 files changed, 141 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c319ea1631..aab3d2ddd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14711,7 +14711,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "android-activity", "atomic-waker", diff --git a/Cargo.toml b/Cargo.toml index f8bc4506d5..e664d72fdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -342,7 +342,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid # 32-bit stream the prediction can leave the i32 range while the sum does not, so a debug build diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs index 0639e31fa8..985d77e5a9 100644 --- a/crates/ui-contract/src/runtime/egui/alt_code.rs +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -25,6 +25,8 @@ pub(crate) struct AltCodeEntry { swallow_text: bool, /// What the last code typed, for the character a platform composes itself and sends after it. echo: Option, + /// The key of the press that carries the platform's composed character, whose release is left out with it. + carrier: Option, } /// The character an Alt code typed, kept until the next key or pointer press. @@ -33,6 +35,26 @@ struct Echo { /// The code names a byte of the code pages (1–255): the platform's own character for it wins over ours, since it /// knows the system's code pages (double-byte ones too) better than the app's locale guess. byte_code: bool, + /// The keys egui names the platform's character by, for the press that can carry it on Windows: the key of our + /// character, and for a code above 255 the key of the character of the byte Windows reduces it to. + carriers: Vec, +} + +impl Echo { + /// The echo of `typed`, the character `code` names in `pages`. + fn new(typed: char, code: &str, pages: AltCodePages) -> Self { + let value = code.trim_start_matches('0').parse::().ok(); + let byte_code = value.is_some_and(|value| value <= 255); + let mut carriers: Vec = Key::from_name(&typed.to_string()).into_iter().collect(); + if let Some(value) = value.filter(|value| *value > 255) { + let byte = value % 256; + let byte_digits = if code.starts_with('0') { format!("0{byte}") } else { byte.to_string() }; + if let Some(key) = craft_codepage::alt_code_char(&byte_digits, pages.ansi, pages.oem).and_then(|c| Key::from_name(&c.to_string())) { + carriers.push(key); + } + } + Echo { typed: typed.to_string(), byte_code, carriers } + } } /// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. `os` is the platform the events @@ -49,6 +71,20 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt let mut out = Vec::with_capacity(events.len() + 1); for event in events.drain(..) { match &event { + // On Windows the composed character can come on a press of its own after the Alt release, with no + // physical key and the key egui names the character by (`\` is `Key::Backslash`). It is no key the user + // pressed: the press and its release are left out, and the text that follows meets the echo. A press of + // another key with no physical key (one egui does not map, such as a JIS key) is the user's. + Event::Key { key, physical_key: None, pressed: true, repeat: false, .. } + if composes && entry.echo.as_ref().is_some_and(|echo| echo.carriers.contains(key)) => + { + entry.carrier = Some(*key); + continue; + } + Event::Key { key, physical_key: None, pressed: false, .. } if entry.carrier == Some(*key) => { + entry.carrier = None; + continue; + } Event::Key { key, pressed: true, repeat, modifiers, .. } => { entry.swallow_text = false; entry.echo = None; @@ -103,6 +139,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt Event::WindowFocused(false) => { entry.code.clear(); entry.swallow_text = false; + entry.carrier = None; } _ => {} } @@ -117,8 +154,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // composed character or what is typed next. A digit that sent no text must not cost the next one. entry.swallow_text = false; if let Some(c) = craft_codepage::alt_code_char(&code, pages.ansi, pages.oem) { - let byte_code = code.trim_start_matches('0').parse::().is_ok_and(|value| value <= 255); - entry.echo = Some(Echo { typed: c.to_string(), byte_code }); + entry.echo = Some(Echo::new(c, &code, pages)); out.push(Event::Text(c.to_string())); } } diff --git a/crates/ui-contract/tests/it/runtime/alt_code.rs b/crates/ui-contract/tests/it/runtime/alt_code.rs index 560d7cd3a8..2c7d94eb7d 100644 --- a/crates/ui-contract/tests/it/runtime/alt_code.rs +++ b/crates/ui-contract/tests/it/runtime/alt_code.rs @@ -250,6 +250,107 @@ fn an_alt_numpad_code_types_its_character_once() { assert!(!option.lone_alt, "macOS has no lone Alt either"); } +/// The press, text and release that winit on Windows reports a composed Alt code's character with: the press has no +/// physical key, and its key is the one egui names the character by. +fn composed_on_key(key: Key, composed: &str) -> Vec { + let event = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + vec![event(true), text(composed), event(false)] +} + +/// On Windows the platform's character for a code can come on a key press of its own, with no physical key, after +/// the Alt release: in the release's frame or in the next one. For a character egui has a key for (`\` is +/// `Key::Backslash`, `A` is `Key::A`), that press is the platform's carrier of the character, not a key the user +/// pressed: the character is typed once and the press does not reach egui, where a single-key shortcut could take +/// it. Above 255 the carried character is the one of the byte Windows reduces the code to, and ours stays. A key the +/// user presses after a code still types as normal, also one with no physical key in egui. +#[trial] +fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() { + let typed = Rc::new(RefCell::new(String::new())); + let reached = Rc::new(RefCell::new(Vec::<(Key, bool)>::new())); + let mut show = { + let (typed, reached) = (Rc::clone(&typed), Rc::clone(&reached)); + move |ui: &mut egui::Ui| { + let keys: Vec<(Key, bool)> = ui.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + Event::Key { key, pressed, .. } => Some((*key, *pressed)), + _ => None, + }) + .collect() + }); + reached.borrow_mut().extend(keys); + Probe::new(&typed).label("Text").id_salt("alt_code_field").show_at(ui, AT); + } + }; + let mut frames = Frames::new(); + craft_ui::testing::windows::set_os(&frames.ctx, Os::Windows); + frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437))); + frames.idle(3, &mut show); + // Plays `sequence`, then a frame with none; returns the field's text and the key events that reached egui, each + // with whether it is a press. + let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec>| { + reached.borrow_mut().clear(); + typed.borrow_mut().clear(); + for events in sequence { + frames.frame(events, &mut *show); + } + frames.frame(Vec::new(), &mut *show); + (typed.take(), reached.take()) + }; + let next_frame = || { + let mut frames = code("0092"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + let same_frame = || { + let mut frames = code("65"); + if let Some(release) = frames.last_mut() { + release.extend(composed_on_key(Key::A, "A")); + } + frames + }; + let then_pressed = || { + let mut frames = code("0233"); + frames.push(vec![key_press(Key::A, Modifiers::NONE), text("a"), key_release(Key::A, Modifiers::NONE)]); + frames + }; + // Above 255 Windows reduces the code to a byte: 321 is 65, `A`, while ours is U+0141. + let reduced = || { + let mut frames = code("321"); + frames.push(composed_on_key(Key::A, "A")); + frames + }; + // A key egui has no physical key for (a JIS key typing `\`) pressed after a code whose character is `A`. + let unmapped = || { + let mut frames = code("65"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + + // With nothing focused, egui's input holds every key event no component took. The digits' releases reach it too. + let of = |keys: Vec<(Key, bool)>, key: Key| keys.into_iter().filter(|(k, _)| *k == key).collect::>(); + let (_, keys) = send(&mut frames, &mut show, next_frame()); + assert_eq!(of(keys, Key::Backslash), [], "a carrier press and its release in the next frame do not reach egui"); + let (_, keys) = send(&mut frames, &mut show, same_frame()); + assert_eq!(of(keys, Key::A), [], "a carrier press and its release in the release's frame do not reach egui"); + let (_, keys) = send(&mut frames, &mut show, then_pressed()); + assert_eq!(of(keys, Key::A), [(Key::A, true), (Key::A, false)], "a key the user presses after a code reaches egui"); + let (_, keys) = send(&mut frames, &mut show, reduced()); + assert_eq!(of(keys, Key::A), [], "the carrier of the byte a code above 255 reduces to does not reach egui"); + let (_, keys) = send(&mut frames, &mut show, unmapped()); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "another key with no physical key reaches egui"); + + click(&mut frames, AT.center(), &mut show); + frames.idle(1, &mut show); + assert_eq!(send(&mut frames, &mut show, reduced()).0, "\u{141}", "above 255 ours stays and the carried byte is dropped"); + assert_eq!(send(&mut frames, &mut show, unmapped()).0, "A\\", "another key with no physical key types as normal"); + assert_eq!(send(&mut frames, &mut show, next_frame()).0, "\\", "a carrier press in the next frame types nothing more"); + assert_eq!(send(&mut frames, &mut show, same_frame()).0, "A", "a carrier press in the release's frame types nothing more"); + assert_eq!(send(&mut frames, &mut show, then_pressed()).0, "éa", "a key the user presses after a code types as normal"); +} + /// Alt with the digit 3, which the host canvas of the next trial claims. const ALT_3: craft_keymap::Chord = craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num3); From b0f4dbea643e03b7dd818e7047ea08474015575b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:00:45 -0800 Subject: [PATCH 14/33] ui-contract: a dialog the host removes gives up the keyboard in that pass When a DialogHost removed a dialog after its body ran in the pass (a held OK the app accepted, a result returned from show), the dialog's layer stayed in that pass's overlay stack and its focus scope stayed open. The end hook kept the focus on the dialog's field and recorded a modal layer, so with one pass per frame the next frame's keys went to the closed dialog's field and were lost. end_stack_dialog now takes the dialog's layers off the running pass's stack and closes their focus scopes (focus::end_scope), so the end hook of the same pass returns the focus to the dialog's opener and records no modal for the next frame. Test: a_dialog_that_finishes_after_its_pass_ran_hands_the_next_keys_to_its_opener in craft-ui-panels' dialog tests. --- crates/ui-contract/src/runtime/focus.rs | 11 +++++ crates/ui-contract/src/runtime/overlay.rs | 12 +++-- crates/ui-panels/tests/it/dialogs.rs | 53 +++++++++++++++++++++++ 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 44e38d6e20..941f27be9e 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -702,6 +702,17 @@ fn opener(state: &State, id: Id, noted: Option, focused: Option) -> } } +/// The layer `id` ended its shown life in the running pass after its body ran (a dialog host removed the dialog it +/// showed): its scope plays its exit from now on, so the end hook of this pass moves the focus inside it to its opener, +/// or nowhere, as for a scope that went away. A scope this pass did not show is left as it is. +pub(crate) fn end_scope(ctx: &Context, id: Id) { + with(ctx, |state| { + if let Some(scope) = state.scopes.get_mut(&id) { + scope.closing = true; + } + }); +} + /// The innermost scope open in the running pass: the scope whose body is being shown. #[doc(hidden)] pub fn open_scope(ctx: &Context) -> Option { diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 295f149c5a..c94ce33edf 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -834,14 +834,20 @@ pub fn take_keys_for_new_dialog(ctx: &Context) { /// A dialog host removed `dialog`: the layers it showed for it (`stack_place`) in the running or the last pass end /// their shown life at once (`memory::end_shown`), as a container that shows nothing does, and forget the open state /// they kept for the session (`memory::open_slot`), so the next open of the dialog is a first pass and starts open: the -/// close that ended the dialog wrote that state closed. +/// close that ended the dialog wrote that state closed. The layers leave this pass's stack, so its end hook records no +/// modal and no top layer for them, and their focus scopes close (`focus::end_scope`): the end hook of this pass moves +/// the focus inside them back to the opener, and the next frame's keys go there. #[doc(hidden)] pub fn end_stack_dialog(ctx: &Context, dialog: Id) { - let shown: Vec = - with_pass(ctx, |pass| pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect()); + let shown: Vec = with_pass(ctx, |pass| { + let shown = pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect(); + pass.current.retain(|entry| entry.dialog != Some(dialog)); + shown + }); for id in shown { crate::runtime::memory::end_shown(ctx, id); crate::runtime::memory::forget(ctx, crate::runtime::memory::open_slot(id)); + crate::runtime::focus::end_scope(ctx, id); } } diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 5059c84c0e..70a22db8d8 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -1358,3 +1358,56 @@ fn an_alert_moves_by_its_title_row() { fixture.drag_at(at, vec2(40.0, 30.0)).idle(4); assert_eq!(dialog.get().min - before.min, vec2(40.0, 30.0), "the alert moved with the drag"); } + +/// A modal dialog with a name field that finishes in the pass after `finish` is set, as a held OK the app accepted does. +struct Renaming { + name: String, + finish: Arc, +} + +impl StackDialog for Renaming { + type Result = (); + + fn id(&self) -> DialogId { + dialog_id("renaming") + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + Dialog::new("Rename").id_salt("renaming").show(ui, |ui, _| { + TextField::new("New name", Bind::bound(&mut self.name)).show(ui); + }); + self.finish.load(Ordering::Relaxed).then_some(DialogResult::Ok(())) + } +} + +/// A dialog the host removes in the pass its body ran gives up the keyboard in that pass: the next frame's typing goes +/// to the field the dialog opened from, and that frame sees no modal layer. +#[trial] +fn a_dialog_that_finishes_after_its_pass_ran_hands_the_next_keys_to_its_opener() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let below = Rc::new(RefCell::new(String::new())); + let modal_seen = Rc::new(RefCell::new(Vec::new())); + let (shown, field, seen) = (Rc::clone(&host), Rc::clone(&below), Rc::clone(&modal_seen)); + let mut fixture = Fixture::new(move |ui| { + seen.borrow_mut().push(any_open(ui.ctx(), OpenFilter::Modal)); + TextField::new("Layer name", Bind::bound(&mut *field.borrow_mut())).show(ui); + shown.borrow_mut().run(ui); + }); + fixture.settle(); + let opener = fixture.by_label("Layer name").expect("the window's field shows"); + fixture.click(&opener).settle(); + let finish = Arc::new(AtomicBool::new(false)); + host.borrow_mut().open(Renaming { name: String::new(), finish: Arc::clone(&finish) }); + fixture.settle(); + let in_dialog = fixture.by_label("New name").expect("the dialog's field shows"); + assert_eq!(fixture.tree().focused_key(), in_dialog.node, "the dialog's field has the keyboard"); + finish.store(true, Ordering::Relaxed); + fixture.frame(Vec::new()); + assert!(!host.borrow().is_open::(), "the dialog finished"); + assert_eq!(fixture.passes(), 1, "the frame the dialog finished in ran one pass"); + modal_seen.borrow_mut().clear(); + fixture.frame(vec![egui::Event::Text("x".to_owned())]); + assert_eq!(modal_seen.borrow().first(), Some(&false), "the frame after the close sees no modal layer"); + fixture.idle(2); + assert_eq!(*below.borrow(), "x", "the typing of the frame after the close reached the opener's field"); +} From 9f649dc80d85129459f35fcfc83788238c0ca5e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:10:29 -0800 Subject: [PATCH 15/33] ui-contract: a lost carrier release and a focus loss end an Alt code's state A key press clears the carrier, so a carrier whose release never came does not take the release of a key pressed after it. A focus loss clears the echo as well as the carrier, so a key with no physical key pressed after focus returns is not taken for the platform's carrier. --- crates/ui-contract/src/runtime/egui/alt_code.rs | 8 +++++++- crates/ui-contract/tests/it/runtime/alt_code.rs | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs index 985d77e5a9..3b8b1b5d4c 100644 --- a/crates/ui-contract/src/runtime/egui/alt_code.rs +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -29,7 +29,7 @@ pub(crate) struct AltCodeEntry { carrier: Option, } -/// The character an Alt code typed, kept until the next key or pointer press. +/// The character an Alt code typed, kept until the next key or pointer press or a focus loss. struct Echo { typed: String, /// The code names a byte of the code pages (1–255): the platform's own character for it wins over ours, since it @@ -88,6 +88,11 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt Event::Key { key, pressed: true, repeat, modifiers, .. } => { entry.swallow_text = false; entry.echo = None; + // A carrier whose release never came (the platform dropped it with the held physical key's) does not + // take the release of a key pressed after it. + if !*repeat { + entry.carrier = None; + } match digit(*key).filter(|_| alt_only(modifiers) && !claimed(&event)) { Some(d) => { // A held digit's auto-repeat adds nothing, as on Windows. @@ -139,6 +144,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt Event::WindowFocused(false) => { entry.code.clear(); entry.swallow_text = false; + entry.echo = None; entry.carrier = None; } _ => {} diff --git a/crates/ui-contract/tests/it/runtime/alt_code.rs b/crates/ui-contract/tests/it/runtime/alt_code.rs index 2c7d94eb7d..2c4b4a5a52 100644 --- a/crates/ui-contract/tests/it/runtime/alt_code.rs +++ b/crates/ui-contract/tests/it/runtime/alt_code.rs @@ -341,6 +341,21 @@ fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() { assert_eq!(of(keys, Key::A), [], "the carrier of the byte a code above 255 reduces to does not reach egui"); let (_, keys) = send(&mut frames, &mut show, unmapped()); assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "another key with no physical key reaches egui"); + // The carrier's release never comes (the platform drops it with a held backslash key's), then the user presses + // that key with no physical key in egui: its release reaches egui with its press. + let mut lost_release = code("0092"); + lost_release.push(composed_on_key(Key::Backslash, "\\")[..2].to_vec()); + lost_release.push(composed_on_key(Key::Backslash, "\\")); + let (_, keys) = send(&mut frames, &mut show, lost_release); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a carrier with no release keeps no later release"); + // A code the platform sends nothing after, then focus leaves the window and comes back: a key with no physical key + // in egui that types the code's character is the user's. + let mut refocused = code("0092"); + refocused.push(vec![Event::WindowFocused(false)]); + refocused.push(vec![Event::WindowFocused(true)]); + refocused.push(composed_on_key(Key::Backslash, "\\")); + let (_, keys) = send(&mut frames, &mut show, refocused); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a focus loss ends the code's echo"); click(&mut frames, AT.center(), &mut show); frames.idle(1, &mut show); From 42f874c0f86365cf6fc68c5e943139807f6e393b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:14:58 -0800 Subject: [PATCH 16/33] ui-contract: fixtures report untransformed shapes as main does The fixture changes on this branch also changed how untransformed paint is reported, which broke 20 tests in crates that depend on craft-ui-contract (craft-draw, craft-menu, craft-ui-panels, craft-ui-patterns and craft-ui-widgets): - run_frame() snapped every text origin to pixels, so texts() moved untransformed text by up to half a pixel. Only a text under a paint transform is snapped now, as egui snaps it before the transform. - frame_shapes() and the shape bounds dropped top-level shapes whose clip rect is empty. A top-level shape with the identity transform is reported whatever its clip, as before. - A chunk member with the identity transform went through egui's tessellator, which drops fully transparent shapes, so a memoized view's replayed paint differed from the paint of a run. Such a member is now kept unless its clip hides its bounds. --- .../ui-contract/src/runtime/egui/fixture.rs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index 43a9fc0708..a5db36a176 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -329,7 +329,12 @@ pub(crate) fn run_frame( Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, }); - let pos = if options.round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) } else { text.pos }; + // egui snaps a text origin before a paint transform; an untransformed text is reported at its own origin. + let pos = if options.round_text_to_pixels && *transform != TSTransform::IDENTITY { + egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) + } else { + text.pos + }; Some(PaintedText { rect: { let moved = *transform * text.galley.rect.translate(pos.to_vec2()); @@ -531,9 +536,16 @@ fn fixture_draws( pixels_per_point: f32, options: egui::epaint::TessellationOptions, ) -> bool { - transform.is_valid() - && clip.is_positive() - && ((!in_chunk && transform == TSTransform::IDENTITY) || egui_draws(shape, transform, clip, pixels_per_point, options)) + // A top-level shape that egui paints untransformed is reported as before, whatever its clip rect. + if !in_chunk && transform == TSTransform::IDENTITY { + return true; + } + // An untransformed chunk member is reported like a top-level shape, invisible paint included, unless its clip hides it. + if transform == TSTransform::IDENTITY { + let bounds = shape.visual_bounding_rect(); + return clip.is_positive() && (!bounds.is_finite() || bounds.intersects(clip)); + } + transform.is_valid() && clip.is_positive() && egui_draws(shape, transform, clip, pixels_per_point, options) } fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) { @@ -635,9 +647,6 @@ fn flatten_owned( options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>, ) { - if !transform.is_valid() || !clip.is_positive() { - return; - } match shape { Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, in_chunk, pixels_per_point, options, out)), Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| { From 71d68251a1eb13a32c6f4af1b14827b4af11e568 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:21:27 -0800 Subject: [PATCH 17/33] craft-raster3d: average resolve blocks of more than 256 subsamples in f64 An f32 sum drops the low bits of each sample as it grows: a 17 x 17 block of 0.7 resolved outside 1e-6 of 0.7, and a 1024 x 1024 block to 0.6927. try_resolve now averages every block of more than 256 subsamples (k over 16) in f64, as it already did above 2^24. --- crates/raster3d/README.md | 10 ++++++---- crates/raster3d/src/resolve.rs | 27 ++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 4e0e9600ed..83bdd65269 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -86,7 +86,7 @@ Building a scene from an app's document (layers, cameras, models, text) stays in - **Resolve and encoding.** `try_resolve(&target, k)` averages each `k × k` block of premultiplied pixels with equal weights, and takes the mean depth of the block's covered pixels, infinity where none is covered; a pixel whose `f32` sums overflow, and every pixel when a block holds more than - 2^24 subsamples, is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer + 256 subsamples (`k` over 16), is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer function of CSS Color 4 (), a linear segment up to a magnitude of 0.0031308 and a 1/2.4 power above it, with a negative color keeping its sign, multiplies by alpha again and leaves alpha linear. `srgb_to_linear` decodes a negative @@ -140,7 +140,7 @@ far plane, where depth-range crossings lie within 1/4096 of an edge from its ins texture coordinates times the texture's width or height reach 2^23 in magnitude, where normals' squared lengths, squared distances from fragments to point and spot lights, or casters' light-space coordinates times a map's focal length overflow `f32`, where shadow-casting spot -lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 2^24 +lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 256 subsamples, where shadows-only materials do not receive shadows, where fragments under discarded opaque pixels leave the depth range, where blended casters have no base texture, where opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of @@ -198,8 +198,10 @@ Changes from those files: - A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps, as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest of the cone were not shadowed. -- A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of - covered subsamples stopped at 2^24, which raised the mean depth. +- A resolve block of more than 256 subsamples is averaged in `f64`. EffectCraft summed every block + in `f32`, which dropped the low bits of each sample as the sum grew (a 1024 × 1024 block of 0.7 + resolved to 0.6927), and its `f32` count of covered subsamples stopped at 2^24, which raised the + mean depth. - A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest values) is projected in `f64` instead of dropping its triangle, and a drawn pixel whose camera depth overflows is an error. diff --git a/crates/raster3d/src/resolve.rs b/crates/raster3d/src/resolve.rs index 1b348dca5f..f45a2550ce 100644 --- a/crates/raster3d/src/resolve.rs +++ b/crates/raster3d/src/resolve.rs @@ -18,6 +18,9 @@ pub struct Image { /// Alpha above 1 that [`try_encode`] accepts as rounding from blending. const ALPHA_SLACK: f32 = 1e-4; +/// The largest block [`try_resolve`] sums in `f32`. +const F32_SAMPLES: u64 = 256; + /// `w × h` as a length, when it fits `usize`. fn area(w: u32, h: u32) -> Option { usize::try_from(u64::from(w) * u64::from(h)).ok() @@ -26,7 +29,7 @@ fn area(w: u32, h: u32) -> Option { /// Box-filter a supersampled target down by `k` per side: each output pixel is the mean of its /// `k × k` premultiplied colors, and its depth is the mean of the covered subsamples' depths /// (infinity where none is covered). A pixel whose `f32` sums overflow, and every pixel when a -/// block holds more than 2^24 subsamples, is averaged in `f64`. +/// block holds more than 256 subsamples (`k` over 16), is averaged in `f64`. /// /// Returns [`RenderError::BadFactor`] when `k` is zero or does not divide both sides, and /// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height @@ -50,8 +53,9 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> return Ok((img, depth)); } let n = (u64::from(k) * u64::from(k)) as f32; - // An f32 count stops at 2^24, so a larger block is averaged in f64. - let wide = u64::from(k) * u64::from(k) > 1 << 24; + // An f32 sum drops the low bits of each sample as it grows, so a block of more than + // `F32_SAMPLES` subsamples is averaged in f64. + let wide = u64::from(k) * u64::from(k) > F32_SAMPLES; img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { for x in 0..w as usize { if wide { @@ -158,3 +162,20 @@ pub fn try_render_cpu(s: &Scene, limits: &Limits) -> Result<(Image, Vec), R } try_resolve(&try_render(s, limits)?, k) } + +#[cfg(test)] +mod tests { + use super::{Target, try_resolve}; + + #[test] + fn a_large_block_of_one_color_resolves_to_that_color() { + // An f32 sum of 17 × 17 samples of 0.7 drifts past the tolerance; 17 is the first factor + // averaged in f64. + let n = 17u32; + let len = (n * n) as usize; + let t = Target { width: n, height: n, color: vec![[0.7; 4]; len], depth: vec![0.5; len] }; + let (img, depth) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}")); + assert!(img.data[0].iter().all(|&c| (c - 0.7).abs() < 1e-6), "{:?}", img.data[0]); + assert!((depth[0] - 0.5).abs() < 1e-6, "{}", depth[0]); + } +} From c201908614dec94cf6670c3259cec0e2562e4662 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:27:18 -0800 Subject: [PATCH 18/33] overlay: a window raised after a carried raise comes in front of it A raise asked in the pass a floating window first shows is asked again in the next pass (Persist::raise_again). When another window was raised in that next pass, both went to the top of egui's area order together, and egui keeps the old order among the layers it raises in one pass. The window raised first had already gone above the second one, so it stayed in front: activating one document window and then another one frame later left the first in front. end_pass now compares egui's area order of the lifted layers with the raise order. When a carried raise stands above a raise asked in this pass, only this pass's raises go up, and every raise is asked again in the next pass, where the newer ones already stand above the carried ones. A root asked more than once in a pass is carried once, in its last place. Test: a_window_raised_after_a_carried_raise_comes_in_front_of_it. --- crates/ui-contract/src/runtime/egui/areas.rs | 6 +++ crates/ui-contract/src/runtime/overlay.rs | 47 ++++++++++++---- .../tests/it/shell/document_window.rs | 54 +++++++++++++++++++ 3 files changed, 98 insertions(+), 9 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index be31991ac3..d1d4c46eb9 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -449,6 +449,12 @@ pub(crate) fn move_to_top(ctx: &Context, layer: LayerId) { ctx.move_to_top(layer); } +/// egui's own area order as of the running pass, bottom first: the order of the last pass, with the layers that first +/// showed in this one at the end. +pub(crate) fn area_order(ctx: &Context) -> Vec { + ctx.memory(|memory| memory.layer_ids().collect()) +} + /// Whether egui showed `layer` in the last pass. pub(crate) fn visible_last_frame(ctx: &Context, layer: LayerId) -> bool { ctx.memory(|memory| memory.areas().visible_last_frame(&layer)) diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 295f149c5a..420b12633a 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -330,7 +330,8 @@ pub(crate) struct Persist { appeared: IdMap<(u64, u64)>, /// The roots whose asked raise ran in a pass where a floating window (re)appeared: egui raises every layer that /// shows again, and its area order keeps the old order among the layers raised in one pass, so the raise is asked - /// again in the next pass. + /// again in the next pass. Also the roots raised in a pass that moved only its own raises up, past a carried one + /// that stood above them, asked again in the order they were asked. raise_again: Vec, } @@ -922,8 +923,10 @@ pub(crate) fn end_pass(ctx: &Context) { }); let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); let now = pass::root_frame_nr(ctx); - let (order, to_top, floats, asked) = with_persist(ctx, viewport, |persist| { - let raise: Vec = std::mem::take(&mut persist.raise_again).into_iter().chain(raise).collect(); + let (order, lifted, floats, asked) = with_persist(ctx, viewport, |persist| { + let carried = std::mem::take(&mut persist.raise_again); + let carried_count = carried.len(); + let raise: Vec = carried.into_iter().chain(raise).collect(); let stamp = |id: Id, persist: &mut Persist| { persist.counter += 1; persist.raised.insert(id, persist.counter); @@ -935,6 +938,8 @@ pub(crate) fn end_pass(ctx: &Context) { .map(|entry| entry.id) .collect(); let mut asked: Vec = Vec::new(); + // The roots raised by this pass's own reasons, without the raises carried from the last pass. + let mut fresh: Vec = Vec::new(); for root in &roots { let shown = current.iter().find(|entry| entry.id == *root); // A root the last pass did not have appears, and so does one that faded out then and is open again @@ -949,9 +954,10 @@ pub(crate) fn end_pass(ctx: &Context) { // its area in the pass before, so it raises none. A root that first shows there is raised by egui itself. if reopened && shown.is_some_and(|entry| !entry.window && (entry.rank == Rank::Window || entry.among_windows)) { asked.push(*root); + fresh.push(*root); } } - for id in raise { + for (at_raise, id) in raise.into_iter().enumerate() { let mut at = current.iter().find(|entry| entry.id == id); while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) { at = Some(parent); @@ -959,8 +965,20 @@ pub(crate) fn end_pass(ctx: &Context) { if let Some(root) = at { stamp(root.id, persist); asked.push(root.id); + if at_raise >= carried_count { + fresh.push(root.id); + } } } + // A root asked more than once keeps its last place, so a raise asked again in every pass carries one entry. + let mut once: Vec = Vec::new(); + for id in asked.iter().rev() { + if !once.contains(id) { + once.push(*id); + } + } + once.reverse(); + let asked = once; persist.raised.retain(|id, _| roots.contains(id)); persist.appeared.retain(|id, _| current.iter().any(|entry| entry.id == *id)); let before = families(¤t, &persist.raised); @@ -976,7 +994,9 @@ pub(crate) fn end_pass(ctx: &Context) { let families = families(¤t, &persist.raised); let mut order: Vec = Vec::new(); let mut listed: Vec = Vec::new(); - let mut to_top: Vec = Vec::new(); + // The layers an asked raise moves to the top of egui's area order, in the raise order, each with whether this + // pass asked for it. + let mut lifted: Vec<(Layer, bool)> = Vec::new(); let mut floats: Vec = Vec::new(); persist.stack.clear(); for members in &families { @@ -996,9 +1016,9 @@ pub(crate) fn end_pass(ctx: &Context) { listed.push(member.id); } else if !member.window { floats.push(member.layer); - if members.first().is_some_and(|root| asked.contains(&root.id)) { + if let Some(root) = members.first().filter(|root| asked.contains(&root.id)) { // An asked raise of a layer left to egui's area order raises it there, as a press on it does. - to_top.push(member.layer); + lifted.push((member.layer, fresh.contains(&root.id))); } } persist.stack.push(member.id); @@ -1026,13 +1046,22 @@ pub(crate) fn end_pass(ctx: &Context) { .map(|(_, members)| { members.iter().flat_map(|member| std::iter::once(member.rect).chain(member.anchor).chain(member.peers.iter().copied())).collect() }); - (order, to_top, floats, asked) + (order, lifted, floats, asked) }); + // egui keeps the old order among the layers it moves to the top in one pass. When that order differs from the + // raise order, a raise carried from the last pass and a raise asked in this one cannot go up together: the carried + // one would stay above the newer one. Only this pass's raises go up then, and `held_back` asks every raise again in + // the next pass, where this pass's raises already stand above the carried ones. + let stacked = areas::area_order(ctx); + let place = |layer: &Layer| stacked.iter().position(|at| at == layer).unwrap_or(stacked.len()); + let in_order = lifted.windows(2).all(|pair| place(&pair[0].0) <= place(&pair[1].0)); + let held_back = !in_order && lifted.iter().any(|(_, fresh)| *fresh) && lifted.iter().any(|(_, fresh)| !fresh); + let to_top: Vec = lifted.into_iter().filter(|(_, fresh)| *fresh || !held_back).map(|(layer, _)| layer).collect(); areas::set_layer_order(ctx, &order); for layer in &to_top { areas::move_to_top(ctx, *layer); } - if !to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer)) { + if held_back || (!to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer))) { with_persist(ctx, viewport, |persist| persist.raise_again = asked); } // An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown. diff --git a/crates/ui-shell/tests/it/shell/document_window.rs b/crates/ui-shell/tests/it/shell/document_window.rs index 45e3832670..508e2d7536 100644 --- a/crates/ui-shell/tests/it/shell/document_window.rs +++ b/crates/ui-shell/tests/it/shell/document_window.rs @@ -306,3 +306,57 @@ fn a_window_raised_as_the_windows_show_again_comes_to_the_front() { fixture.frame(Vec::new()); assert_eq!(top.get(), first.get(), "the window raised as they showed again is in front"); } + +/// A document window raised in the passes after another one's raise was carried over (a window first showed in that +/// pass) comes in front of it, and the window raised first stays in front of the one that showed. egui keeps the old +/// order among the layers it moves to the top in one pass, so the carried raise and the newer one going up together +/// left the window raised first in front. +#[trial] +fn a_window_raised_after_a_carried_raise_comes_in_front_of_it() { + use craft_ui::testing::Fixture; + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + use std::rc::Rc; + + // First and Second overlap at `first_second`, First and Third (which shows later) at `first_third`. + let (first_second, first_third) = (pos2(300.0, 150.0), pos2(100.0, 220.0)); + let places = [("First.psd", pos2(40.0, 40.0)), ("Second.psd", pos2(200.0, 120.0)), ("Third.psd", pos2(40.0, 200.0))]; + let third_shows = Rc::new(Cell::new(false)); + let raised: Rc>> = Rc::new(Cell::new(None)); + let layers = Rc::new(RefCell::new(HashMap::new())); + let tops = Rc::new(Cell::new((None, None))); + let (shows, raise, seen, front) = (third_shows.clone(), raised.clone(), layers.clone(), tops.clone()); + let mut fixture = Fixture::new(move |ui| { + front.set((ui.ctx().layer_id_at(first_second), ui.ctx().layer_id_at(first_third))); + for (name, at) in places { + if name == "Third.psd" && !shows.get() { + continue; + } + let window = DocumentWindow::new(name).id_salt(name).first_placed(Rect::from_min_size(at, vec2(300.0, 200.0))); + if raise.get() == Some(name) { window.raise() } else { window }.show(ui, |ui, _| { + seen.borrow_mut().insert(name, ui.layer_id()); + }); + } + }); + fixture.settle(); + let layer = |name: &str| layers.borrow().get(name).copied(); + assert_eq!(tops.get().0, layer("Second.psd"), "the window opened last is in front"); + // Third shows in the pass First is raised in, so First's raise is carried to the next pass. + third_shows.set(true); + raised.set(Some("First.psd")); + fixture.frame(Vec::new()); + // Second is raised in three passes in a row, as a body that asks for it while it is current does. + // Each frame reads the order the pass before it left. + raised.set(Some("Second.psd")); + fixture.frame(Vec::new()); + fixture.frame(Vec::new()); + assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last is in front of the one raised before it"); + fixture.frame(Vec::new()); + assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last stays in front"); + assert_eq!(tops.get().1, layer("First.psd"), "the carried raise goes up while Second is still raised in every pass"); + raised.set(None); + fixture.frame(Vec::new()); + fixture.frame(Vec::new()); + assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last stays in front once its raise ends"); + assert_eq!(tops.get().1, layer("First.psd"), "the window raised first is in front of the one that showed as it was raised"); +} From 4b1d442bb97e0b84dcf8ed76988a9d67e52983d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:34:24 -0800 Subject: [PATCH 19/33] ui-contract: a top-row Alt code leaves the next key press alone on Windows Windows composes Alt codes from keypad digits only. After a top-row code it sends no character of its own, so the next key press with no physical key in egui (a JIS backslash key) and the next text are the user's. The entry notes a digit whose physical key is a top-row one, and only a keypad code filters a carrier press or lets the platform's text replace ours. --- .../ui-contract/src/runtime/egui/alt_code.rs | 41 ++++++++++++------ .../ui-contract/tests/it/runtime/alt_code.rs | 43 ++++++++++++++++--- 2 files changed, 66 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs index 3b8b1b5d4c..4d6b7f4730 100644 --- a/crates/ui-contract/src/runtime/egui/alt_code.rs +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -18,6 +18,9 @@ const MAX_DIGITS: usize = 8; pub(crate) struct AltCodeEntry { /// The digits typed while Alt is held. code: String, + /// A digit of the code came from the top row (its physical key is `Num0`…`Num9`, a keypad digit's is + /// `Numpad0`…`Numpad9`). Windows composes keypad codes only, so it sends no character of its own for this code. + top_row: bool, /// A digit was typed in this Alt hold, also when the code was then dropped (a focus loss): the Alt release is no /// lone Alt, since the key stage never saw the digits. digits_typed: bool, @@ -35,14 +38,18 @@ struct Echo { /// The code names a byte of the code pages (1–255): the platform's own character for it wins over ours, since it /// knows the system's code pages (double-byte ones too) better than the app's locale guess. byte_code: bool, + /// The platform composes this code itself and sends its character after it: Windows, for a code typed on the + /// keypad. + native: bool, /// The keys egui names the platform's character by, for the press that can carry it on Windows: the key of our /// character, and for a code above 255 the key of the character of the byte Windows reduces it to. carriers: Vec, } impl Echo { - /// The echo of `typed`, the character `code` names in `pages`. - fn new(typed: char, code: &str, pages: AltCodePages) -> Self { + /// The echo of `typed`, the character `code` names in `pages`. `native` tells whether the platform composes the + /// code too. + fn new(typed: char, code: &str, pages: AltCodePages, native: bool) -> Self { let value = code.trim_start_matches('0').parse::().ok(); let byte_code = value.is_some_and(|value| value <= 255); let mut carriers: Vec = Key::from_name(&typed.to_string()).into_iter().collect(); @@ -53,12 +60,12 @@ impl Echo { carriers.push(key); } } - Echo { typed: typed.to_string(), byte_code, carriers } + Echo { typed: typed.to_string(), byte_code, native, carriers } } } /// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. `os` is the platform the events -/// come from: on Windows (a browser on Windows too) the platform composes the code itself and sends its character +/// come from: on Windows (a browser on Windows too) the platform composes a keypad code itself and sends its character /// after the Alt release. Returns whether an Alt release in `events` ended a hold in which digits were typed (a code, /// or one a focus loss dropped), so the key stage does not take it for a lone Alt. The caller does not call it on macOS, where Option+digit types its own characters. /// @@ -74,9 +81,10 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // On Windows the composed character can come on a press of its own after the Alt release, with no // physical key and the key egui names the character by (`\` is `Key::Backslash`). It is no key the user // pressed: the press and its release are left out, and the text that follows meets the echo. A press of - // another key with no physical key (one egui does not map, such as a JIS key) is the user's. + // another key with no physical key (one egui does not map, such as a JIS key) is the user's, and so is any + // such press after a top-row code, which Windows does not compose. Event::Key { key, physical_key: None, pressed: true, repeat: false, .. } - if composes && entry.echo.as_ref().is_some_and(|echo| echo.carriers.contains(key)) => + if entry.echo.as_ref().is_some_and(|echo| echo.native && echo.carriers.contains(key)) => { entry.carrier = Some(*key); continue; @@ -85,7 +93,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt entry.carrier = None; continue; } - Event::Key { key, pressed: true, repeat, modifiers, .. } => { + Event::Key { key, physical_key, pressed: true, repeat, modifiers, .. } => { entry.swallow_text = false; entry.echo = None; // A carrier whose release never came (the platform dropped it with the held physical key's) does not @@ -99,6 +107,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt if !*repeat && entry.code.len() < MAX_DIGITS { entry.code.push(d); } + entry.top_row |= physical_key.is_some_and(|physical| digit(physical).is_some()); entry.digits_typed = true; entry.swallow_text = true; continue; @@ -106,6 +115,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // Another key (Alt itself, a letter, a digit with Ctrl or Shift) ends the entry unfinished. None => { entry.code.clear(); + entry.top_row = false; // A new Alt hold starts clean: a release that went to another window ended the last one. if matches!(key, Key::AltLeft | Key::AltRight) && !*repeat { entry.digits_typed = false; @@ -120,8 +130,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // The platform composed the same character: it is typed once. continue; } - if composes { - // On Windows the text after a code is the platform's character for it. For a code up to 255 + if echo.native { + // On Windows the text after a keypad code is the platform's character for it. For a code up to 255 // it replaces ours, which was typed just before with no key or click since; above 255 ours // stays (Windows reduces the code to a byte, Word types the Unicode character). if echo.byte_code && text.chars().count() == 1 { @@ -134,7 +144,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt } continue; } - // Linux and the BSDs compose nothing: a different text is what was typed next. + // Linux and the BSDs compose nothing, nor Windows a top-row code: a different text is what was + // typed next. } } Event::PointerButton { pressed: true, .. } => entry.echo = None, @@ -143,6 +154,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt // Focus in another window ends a code unfinished: Alt's release goes there. Event::WindowFocused(false) => { entry.code.clear(); + entry.top_row = false; entry.swallow_text = false; entry.echo = None; entry.carrier = None; @@ -151,16 +163,19 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt } let released = alt_released(&event); out.push(event); + let mut top_row = false; if released { ended |= std::mem::take(&mut entry.digits_typed); + top_row = std::mem::take(&mut entry.top_row); } if released && !entry.code.is_empty() { let code = std::mem::take(&mut entry.code); + let native = composes && !top_row; // A digit's own text comes with its press, before Alt is let go: text after this is the platform's // composed character or what is typed next. A digit that sent no text must not cost the next one. entry.swallow_text = false; if let Some(c) = craft_codepage::alt_code_char(&code, pages.ansi, pages.oem) { - entry.echo = Some(Echo::new(c, &code, pages)); + entry.echo = Some(Echo::new(c, &code, pages, native)); out.push(Event::Text(c.to_string())); } } @@ -169,8 +184,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: Alt ended } -/// The digit `key` adds to a code. egui reports keypad and top-row digits alike (`Key::Num0`…`Num9`) and carries no -/// key location, so the top-row digits compose codes too; with Alt alone held they type nothing else. +/// The digit `key` adds to a code. egui's logical key is the same for keypad and top-row digits (`Key::Num0`…`Num9`), +/// so the top-row digits compose codes too; with Alt alone held they type nothing else. fn digit(key: Key) -> Option { let n = match key { Key::Num0 => 0, diff --git a/crates/ui-contract/tests/it/runtime/alt_code.rs b/crates/ui-contract/tests/it/runtime/alt_code.rs index 2c4b4a5a52..f3e7d1d801 100644 --- a/crates/ui-contract/tests/it/runtime/alt_code.rs +++ b/crates/ui-contract/tests/it/runtime/alt_code.rs @@ -10,7 +10,7 @@ use craft_ui::runtime::focus::{FocusTarget, KeyUse, host_canvas, request}; use craft_ui::runtime::frame::take_output; use craft_ui::style::StyleCx; use craft_ui::testing::focus::{named_id, widget}; -use craft_ui::testing::input::{key_press, key_repeat, text}; +use craft_ui::testing::input::{key_press, text}; use craft_ui::testing::pointer::click; use craft_ui::testing::{Frames, trial}; use craft_ui_test_kit::contract::PlainStyle; @@ -147,12 +147,20 @@ impl Session { const ALT: Modifiers = Modifiers::ALT; -/// The keypad digit key of `digit`; egui names keypad and top-row digits alike. +/// The logical key of `digit`; egui names keypad and top-row digits alike. fn digit_key(digit: char) -> Key { const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; DIGITS[digit.to_digit(10).expect("a decimal digit") as usize] } +/// A keypad digit's press, auto-repeat or release with Alt held: its physical key is the keypad one. +fn keypad(digit: char, pressed: bool, repeat: bool) -> Event { + const KEYPAD: [Key; 10] = + [Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9]; + let physical = KEYPAD[digit.to_digit(10).expect("a decimal digit") as usize]; + Event::Key { key: digit_key(digit), physical_key: Some(physical), pressed, repeat, modifiers: ALT } +} + fn key_release(key: Key, modifiers: Modifiers) -> Event { Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers } } @@ -162,17 +170,28 @@ fn alt(down: bool) -> Event { Event::ModifiersChanged(if down { ALT } else { Modifiers::NONE }) } -/// The frame of one digit typed with Alt held: its press with the digit's own text (Linux sends it), then its release. +/// The frame of one keypad digit typed with Alt held: its press with the digit's own text (Linux sends it), then its +/// release. fn digit(d: char) -> Vec { + vec![keypad(d, true, false), text(&d.to_string()), keypad(d, false, false)] +} + +/// The frame of one top-row digit typed with Alt held. +fn top_row_digit(d: char) -> Vec { let key = digit_key(d); vec![key_press(key, ALT), text(&d.to_string()), key_release(key, ALT)] } -/// The frames of an Alt code: Alt down, each digit in a frame of its own, then Alt up. +/// The frames of an Alt code: Alt down, each keypad digit in a frame of its own, then Alt up. fn code(digits: &str) -> Vec> { std::iter::once(vec![alt(true)]).chain(digits.chars().map(digit)).chain([vec![alt(false)]]).collect() } +/// `code(digits)` typed on the top row, which Windows does not compose. +fn top_row_code(digits: &str) -> Vec> { + std::iter::once(vec![alt(true)]).chain(digits.chars().map(top_row_digit)).chain([vec![alt(false)]]).collect() +} + /// `code(digits)`, then a frame in which the platform sends `composed`, the character it made of the code itself. fn code_then(digits: &str, composed: &str) -> Vec> { let mut frames = code(digits); @@ -206,7 +225,7 @@ fn an_alt_numpad_code_types_its_character_once() { assert_eq!(session.send(code("233")), typed("Θ"), "{os:?}: no leading 0 reads the OEM page"); assert_eq!(session.send(code("8364")), typed("€"), "{os:?}: above 255 the code is the Unicode character"); // With the repeat counted the code would be 02333, U+091D. - let held = vec![key_press(Key::Num3, ALT), text("3"), key_repeat(Key::Num3, ALT), text("3"), key_release(Key::Num3, ALT)]; + let held = vec![keypad('3', true, false), text("3"), keypad('3', true, true), text("3"), keypad('3', false, false)]; let held_digit = vec![vec![alt(true)], digit('0'), digit('2'), held, digit('3'), vec![alt(false)]]; assert_eq!(session.send(held_digit), typed("é"), "{os:?}: a digit's auto-repeat adds nothing and types nothing"); // Eight digits are kept: 00000233 is é, where all nine (2334) would be U+091E. @@ -226,6 +245,10 @@ fn an_alt_numpad_code_types_its_character_once() { assert_eq!(other_echo, typed("€¬"), "{os:?}: a different text after a code is typed as normal"); } } + // Windows composes keypad codes only: after a top-row code, a different text is what was typed next. + let mut top_row_then = top_row_code("0233"); + top_row_then.push(vec![text("й")]); + assert_eq!(session.send(top_row_then), typed("éй"), "{os:?}: the text after a top-row code is typed as normal"); // Focus going to another window ends the code: its Alt release types nothing and is no lone Alt. let away = vec![vec![alt(true)], digit('0'), digit('2'), vec![Event::WindowFocused(false)], vec![Event::WindowFocused(true), alt(false)]]; @@ -356,6 +379,15 @@ fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() { refocused.push(composed_on_key(Key::Backslash, "\\")); let (_, keys) = send(&mut frames, &mut show, refocused); assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a focus loss ends the code's echo"); + // Windows composes nothing for a top-row code: a key with no physical key in egui that types the code's character + // right after it, with no focus change, is the user's. + let top_row = || { + let mut frames = top_row_code("0092"); + frames.push(composed_on_key(Key::Backslash, "\\")); + frames + }; + let (_, keys) = send(&mut frames, &mut show, top_row()); + assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a press after a top-row code reaches egui"); click(&mut frames, AT.center(), &mut show); frames.idle(1, &mut show); @@ -364,6 +396,7 @@ fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() { assert_eq!(send(&mut frames, &mut show, next_frame()).0, "\\", "a carrier press in the next frame types nothing more"); assert_eq!(send(&mut frames, &mut show, same_frame()).0, "A", "a carrier press in the release's frame types nothing more"); assert_eq!(send(&mut frames, &mut show, then_pressed()).0, "éa", "a key the user presses after a code types as normal"); + assert_eq!(send(&mut frames, &mut show, top_row()).0, "\\\\", "a key pressed after a top-row code types as normal"); } /// Alt with the digit 3, which the host canvas of the next trial claims. From b12d5bc631f10b6c150a333227956a0f3078c826 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:44:56 -0800 Subject: [PATCH 20/33] raster3d: a material with an opacity below 1 is transparent Material::transparent compared the opacity with 0.999, so a material at an opacity of 0.9995 drew in the opaque pass at full coverage and validate_passes accepted it in the opaque range. It now compares with 1, which is where the shader stops drawing the surface fully opaque. --- crates/raster3d/src/scene.rs | 5 +++-- crates/raster3d/tests/it/main.rs | 1 + crates/raster3d/tests/it/opacity.rs | 23 +++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 crates/raster3d/tests/it/opacity.rs diff --git a/crates/raster3d/src/scene.rs b/crates/raster3d/src/scene.rs index 9667561ac1..da65160a05 100644 --- a/crates/raster3d/src/scene.rs +++ b/crates/raster3d/src/scene.rs @@ -88,9 +88,10 @@ impl Default for Material { } impl Material { - /// Drawn in the transparent (sorted, blended) pass. + /// Drawn in the transparent (sorted, blended) pass: a blended material, a shadows-only one, or + /// one whose opacity is below 1. pub fn transparent(&self) -> bool { - self.alpha_mode == 2 || self.opacity < 0.999 || self.shadows_only + self.alpha_mode == 2 || self.opacity < 1.0 || self.shadows_only } } diff --git a/crates/raster3d/tests/it/main.rs b/crates/raster3d/tests/it/main.rs index 98f3485e8c..7e966a8907 100644 --- a/crates/raster3d/tests/it/main.rs +++ b/crates/raster3d/tests/it/main.rs @@ -5,6 +5,7 @@ mod bounds; mod differential; mod moved; +mod opacity; /// A verbatim copy of the app's previous code, run by `differential`. mod reference { diff --git a/crates/raster3d/tests/it/opacity.rs b/crates/raster3d/tests/it/opacity.rs new file mode 100644 index 0000000000..523efa01d2 --- /dev/null +++ b/crates/raster3d/tests/it/opacity.rs @@ -0,0 +1,23 @@ +//! Which materials draw in the transparent pass. + +use craft_raster3d::{Limits, Material, RenderError, try_render}; + +use crate::quad_scene; + +const WHITE: [f32; 4] = [1.0; 4]; + +#[test] +fn a_material_with_an_opacity_below_one_is_transparent() { + let m = |opacity: f32| Material { opacity, ..Material::default() }.transparent(); + assert!(!m(1.0)); + assert!(m(0.9995)); + assert!(m(f32::from_bits(1.0f32.to_bits() - 1))); + assert!(m(0.5)); +} + +#[test] +fn an_opaque_range_triangle_with_an_opacity_just_below_one_is_rejected() { + let mut s = quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 50.0, WHITE)]); + s.materials[0].opacity = 0.9995; + assert!(matches!(try_render(&s, &Limits::default()), Err(RenderError::BadMaterial(0)))); +} From dcb9d06b651c1d43af884c8be3b04eba3cd408e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:52:46 -0800 Subject: [PATCH 21/33] color-ui: the Color Picker's OK names the swatch its color was picked from `ColorPickerResult::swatch` gives the library and index of the Color Swatches view's swatch that the color was last picked from, so a host can tell apart swatches of one color. A later change to the color, Reset, or `set_color` leaves it `None`. - A click on a swatch takes that swatch's own color, also when the palette files no edit for it, and the clicked swatch is the marked cell. - `ColorPickerDialog::picked_swatch` and `pick_swatch`, and the dialog's `swatch` field (`[library, index]`, or null to clear it), give the same pick to automation. A refused batch of fields puts the color, the pick and the memory back. - A swatch picked before the dialog first runs keeps its color through the Only Web Colors snap. --- crates/color-ui/src/ui/mod.rs | 4 +- crates/color-ui/src/ui/picker_dialog.rs | 135 ++++++++++++++++++-- crates/color-ui/tests/it/picker.rs | 159 +++++++++++++++++++++++- 3 files changed, 283 insertions(+), 15 deletions(-) diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index d620536e75..1caccc13bc 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -78,8 +78,8 @@ pub use picker::{ PickedColor, ScreenPickGesture, TrackRamp, }; pub use picker_dialog::{ - ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary, - PickerSwatches, + ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickedSwatch, + PickerLibrary, PickerSwatches, }; pub use popover::{ColorPopover, ColorPopoverOutput}; pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords}; diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index e74230735c..5f696e3bc6 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -128,9 +128,19 @@ impl PickerSwatches { /// The Color Swatches view: the library `Select` over the chosen library's spaced palette, whose cell equal to the colour /// in `held` is marked and whose pick replaces `held`; the notice for a library without swatches. `library` is the /// remembered index, which may lie past the end; it is written only when the user chooses another. The dialog's buttons -/// stand in the cell after it, as they head the Full picker's second column. -fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: &mut Mixed, library_label: &Label) { +/// stand in the cell after it, as they head the Full picker's second column. `selected`, the swatch the colour was +/// picked from, is the marked cell when its library is shown. Returns the swatch clicked this pass, also one with the +/// colour already held, whose colour `held` then takes. +fn show_swatches( + ui: &mut Ui, + view: &PickerSwatches, + library: &mut usize, + held: &mut Mixed, + selected: Option, + library_label: &Label, +) -> Option { let mut chosen = (*library).min(view.libraries.len().saturating_sub(1)); + let mut clicked = None; Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { if !view.libraries.is_empty() { @@ -145,10 +155,20 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: Some(lib) => { // A colour that is not set marks no cell of a library without it; black stands for "none yet". let color = held.same().map_or(Srgba::BLACK, |picked| picked.color); - let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches).spacing(SwatchSpacing::Spaced).show(ui); + let marked = selected.filter(|s| s.library == chosen).map(|s| s.index); + let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches) + .spacing(SwatchSpacing::Spaced) + .selected_swatch(marked) + .show(ui); if let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()).copied() { *held = Mixed::Same(PickedColor::rgb(picked)); } + // The clicked swatch's own colour, also when the palette files no edit for it (the colour held, or + // one that rounds to it). + if let Some((index, (_, color))) = shown.picked_swatch.and_then(|index| Some((index, lib.swatches.get(index)?))) { + *held = Mixed::Same(PickedColor::rgb(*color)); + clicked = Some(PickedSwatch { library: chosen, index }); + } } None => { Notice::new(Tone::Neutral, view.empty.clone()).layout(NoticeLayout::Centred).show(ui); @@ -157,6 +177,24 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: }); let _ = FooterSlot::new().show(ui); }); + clicked +} + +/// A swatch of a [`ColorPickerDialog`]'s Color Swatches view, by its place in the [`PickerSwatches`] the app gave. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct PickedSwatch { + /// The index of its library in [`PickerSwatches::libraries`]. + pub library: usize, + /// The index of the swatch in that library's [`PickerLibrary::swatches`]. + pub index: usize, +} + +impl PickedSwatch { + /// The swatch at `index` of library `library`. + pub fn new(library: usize, index: usize) -> Self { + PickedSwatch { library, index } + } } /// The remembered scope of [`ColorPickerMemory`]. @@ -170,6 +208,9 @@ pub struct ColorPickerResult { pub key: String, /// The colour, with the model values the user typed while they still give it (CMYK inks, Lab values outside sRGB). pub picked: PickedColor, + /// The swatch of the Color Swatches view the colour was picked from, when the last change to the colour was a click + /// on that swatch; `None` when the colour was set any other way, or changed after the click. + pub swatch: Option, } /// How a [`ColorPickerDialog`] lays out its body. @@ -247,6 +288,8 @@ pub struct ColorPickerDialog { working_rgb: Option>, gamut: Option>, swatches: Option, + /// The swatch the current colour was picked from, while no other change has followed the click. + picked_swatch: Option, eyedropper: bool, canvas_samples: bool, canvas: Option, @@ -428,6 +471,7 @@ impl ColorPickerDialog { working_rgb: None, gamut: None, swatches: None, + picked_swatch: None, eyedropper: true, canvas_samples: true, canvas: None, @@ -449,10 +493,12 @@ impl ColorPickerDialog { } /// In the Full layout, a body button after Cancel switches between Color Models and Color Swatches: a library `Select` over a spaced - /// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. + /// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. A swatch + /// picked from the view it replaces is no longer named. #[must_use] pub fn swatch_view(mut self, swatches: PickerSwatches) -> ColorPickerDialog { self.swatches = Some(swatches); + self.picked_swatch = None; self } @@ -614,6 +660,23 @@ impl ColorPickerDialog { /// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour. pub fn set_color(&mut self, picked: PickedColor) { self.current = Some(picked); + self.picked_swatch = None; + } + + /// The swatch of the Color Swatches view the colour was picked from, while no other change has followed the click + /// (what OK answers as [`ColorPickerResult::swatch`]). + pub fn picked_swatch(&self) -> Option { + self.picked_swatch + } + + /// Picks `swatch` of the Color Swatches view as a click on it would, for automation and scripts: the colour becomes + /// the swatch's and its library the one shown. `None` when the view has no such swatch. + pub fn pick_swatch(&mut self, swatch: PickedSwatch) -> Option<()> { + let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?; + self.current = Some(PickedColor::rgb(*color)); + self.memory.library = swatch.library; + self.picked_swatch = Some(swatch); + Some(()) } /// The colour Add to Swatches was pressed for, once; `None` otherwise. @@ -640,7 +703,7 @@ impl ColorPickerDialog { { Remembered::::new(MEMORY_SCOPE).store(host, &self.memory); } - Some(ColorPickerResult { key: self.key.clone(), picked }) + Some(ColorPickerResult { key: self.key.clone(), picked, swatch: self.picked_swatch }) } /// Runs the dialog's start for automation that reaches it before its first pass. @@ -672,7 +735,12 @@ impl ColorPickerDialog { { let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]); self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None }); - self.current = self.opening; + if self.picked_swatch.is_none() { + self.current = self.opening; + } + } + if let Some(swatch) = self.picked_swatch { + self.memory.library = swatch.library; } } @@ -710,18 +778,33 @@ impl StackDialog for ColorPickerDialog { self.instance } - /// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` - /// and `model`. + /// `color` (`#rrggbb`, null when there is none yet), `swatch` (`[library, index]` of the swatch the colour was picked + /// from, or null), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` and `model`. fn json_fields(&self) -> Option { let mut fields = serde_fields(&self.memory)?; let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into()); - fields.as_object_mut()?.insert("color".to_owned(), color); + let swatch = self.picked_swatch.map_or(serde_json::Value::Null, |s| serde_json::json!([s.library, s.index])); + let object = fields.as_object_mut()?; + object.insert("color".to_owned(), color); + object.insert("swatch".to_owned(), swatch); Some(fields) } fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> { // The dialog's start recalls the memory and snaps the opening colour; a field set before it would be overwritten. self.start_headless(ctx); + if field == "swatch" { + if value.is_null() { + self.picked_swatch = None; + return Ok(()); + } + let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) { + (Some(2), Some(library), Some(index)) => PickedSwatch { library, index }, + _ => return Err(FieldRefusal::Rejects(&value).message(field)), + }; + return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field)); + } if field != "color" { return set_serde_field(&mut self.memory, field, value); } @@ -731,6 +814,23 @@ impl StackDialog for ColorPickerDialog { Ok(()) } + /// Sets the fields in order; when one is refused, the colour, the swatch it was picked from and the memory are put + /// back as they were after the dialog's start, which any set runs first. + fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, serde_json::Value)]) -> Result<(), String> { + if fields.is_empty() { + return Ok(()); + } + self.start_headless(ctx); + let before = (self.current, self.picked_swatch, self.memory.clone()); + for (field, value) in fields { + if let Err(refusal) = self.set_json_field(ctx, field, value.clone()) { + (self.current, self.picked_swatch, self.memory) = before; + return Err(refusal); + } + } + Ok(()) + } + /// The host closed the dialog from outside: its dropper ends with it. fn cancelled(&mut self, _: &Context) { self.requests.cancel(); @@ -774,7 +874,8 @@ impl StackDialog for ColorPickerDialog { } }; let footer = ResetFooter::new(ui, None, true); - let changed = self.current != self.opening; + // A swatch picked at the opening colour is a change Reset takes back. + let changed = self.current != self.opening || self.picked_swatch.is_some(); let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec(); let full = self.layout == ColorPickerDialogLayout::Full; // The buttons after OK and Cancel are placed by position; their indices are read back from the list. @@ -809,6 +910,7 @@ impl StackDialog for ColorPickerDialog { layout, standard, swatches: view, + picked_swatch, working_rgb, .. } = self; @@ -817,6 +919,7 @@ impl StackDialog for ColorPickerDialog { let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same))); let color = current.map(|current| current.color); let web_only = memory.web_colors; + let mut clicked = None; let shown = Dialog::new(title.clone()) .opened(Bind::bound(open)) .buttons(buttons) @@ -846,7 +949,7 @@ impl StackDialog for ColorPickerDialog { // PLAN: the swatch view should keep the value fields and replace only the area and strip, which the picker body // (picker/mod.rs, not in this set) lays out; here it replaces the whole picker body. if let Some(view) = view.as_ref().filter(|_| memory.swatches) { - show_swatches(ui, view, &mut memory.library, &mut held, &words.library); + clicked = show_swatches(ui, view, &mut memory.library, &mut held, *picked_swatch, &words.library); return; } let mut models = models_with(working_rgb, |on| on.full); @@ -883,7 +986,14 @@ impl StackDialog for ColorPickerDialog { *pending_screen = Some(gesture); } }); - self.current = held.same().copied(); + let after = held.same().copied(); + // A swatch click names the swatch; any other change to the colour leaves it picked from no swatch. + if clicked.is_some() { + self.picked_swatch = clicked; + } else if after != self.current { + self.picked_swatch = None; + } + self.current = after; let (picked, closed) = (shown.output.picked, shown.output.closed); if picked.is_some() && picked == toggle_at { @@ -893,6 +1003,7 @@ impl StackDialog for ColorPickerDialog { let ok = (picked == Some(0) || closed == Some(CloseReason::Enter)) && self.current.is_some(); if !ok && picked == Some(1) && footer.resetting() { self.current = self.opening; + self.picked_swatch = None; return None; } if picked.is_some() && picked == add_at { diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 03119e8114..a216f6f92d 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -6,7 +6,7 @@ use std::rc::Rc; use craft_behavior::Mixed; use craft_color_ui::ui::{ ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, - ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches, + ColorPopover, ColorReadout, ColorWarning, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches, }; use craft_host::{AppInfo, Host}; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId}; @@ -509,6 +509,163 @@ fn the_color_picker_dialogs_swatch_view_marks_the_current_colour_and_a_pick_is_a assert!(fixture.texts().iter().any(|run| run.text == "No swatches"), "an empty library shows the notice"); } +const SWATCH_RED: Srgba = Srgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const SWATCH_BLUE: Srgba = Srgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +/// A picker opened on red over two libraries, showing library 1: two swatches of one blue, and red. +fn swatch_picker() -> (Rc>, Fixture) { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + let libraries = vec![ + PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), + PickerLibrary::new("Inks", vec![(Label::from("Blue A"), blue), (Label::from("Blue B"), blue), (Label::from("Ink Red"), red)]), + ]; + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches"))); + fixture.idle(6); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(1)), Ok(())); + fixture.idle(4); + (dialogs, fixture) +} + +/// OK on the picker: its colour and the swatch it names. +fn swatch_answer(dialogs: &Rc>, fixture: &Fixture) -> Option<(String, Option)> { + let ctx = fixture.ctx().clone(); + assert!(dialogs.borrow_mut().confirm::(&ctx)); + dialogs.borrow_mut().take::().and_then(DialogResult::ok).map(|result| (result.picked.color.to_hex(), result.swatch)) +} + +/// OK names the swatch the colour was picked from, by its library and its place there, also among swatches of one +/// colour and for a click on the colour already held; a later change to the colour leaves it named by none. +#[trial] +fn the_color_picker_dialog_answers_the_swatch_its_colour_was_picked_from() { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let open = swatch_picker; + let answer = swatch_answer; + let click = |fixture: &mut Fixture, name: &str| { + let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}")); + fixture.click(&cell).idle(4); + }; + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Blue B"); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1))); + let selected = |fixture: &Fixture, name: &str| { + let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}")); + fixture.tree().selected_of(cell.node).unwrap_or(false) + }; + assert!(selected(&fixture, "Blue B") && !selected(&fixture, "Blue A"), "the clicked one of two blue swatches is marked"); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "the second of two blue swatches"); + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Ink Red"); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), Some(PickedSwatch::new(1, 2)))), "a click on the colour already held"); + + let (dialogs, mut fixture) = open(); + click(&mut fixture, "Blue A"); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "color", serde_json::json!("#00ff00")), Ok(())); + fixture.idle(2); + assert_eq!(answer(&dialogs, &fixture), Some(("#00ff00".to_owned(), None)), "a colour set after the click is no swatch's"); + + let (dialogs, fixture) = open(); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)), "the opening colour was picked from no swatch"); +} + +/// Automation picks a swatch by its place, as a click does, is refused a place the view does not have, and clears the +/// pick with null; a refused batch of fields leaves the colour, the pick and the library as they were. +#[trial] +fn automation_picks_a_color_picker_swatch_and_a_refused_batch_restores_the_pick() { + let (red, blue) = (SWATCH_RED, SWATCH_BLUE); + let id = dialog_id(("color-picker", "fill")); + let open = swatch_picker; + let answer = swatch_answer; + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + for bad in [serde_json::json!([1, 3]), serde_json::json!([2, 0]), serde_json::json!([1]), serde_json::json!("1,1")] { + assert!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", bad.clone()).is_err(), "{bad} is refused"); + } + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(())); + let fields = dialogs.borrow().get::().and_then(StackDialog::json_fields); + assert_eq!(fields.as_ref().map(|f| f["swatch"].clone()), Some(serde_json::json!([1, 1])), "the fields report the picked swatch"); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "a swatch picked by automation"); + + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::Value::Null), Ok(())); + assert_eq!(dialog_field(&dialogs, "swatch"), Some(serde_json::Value::Null)); + assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), None)), "clearing the pick keeps its colour"); + + for picked in [None, Some(PickedSwatch::new(1, 1))] { + let (dialogs, fixture) = open(); + let ctx = fixture.ctx().clone(); + if let Some(swatch) = picked { + assert_eq!(dialogs.borrow_mut().get_mut::().expect("the picker").pick_swatch(swatch), Some(())); + } + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(())); + let before = dialogs.borrow().get::().and_then(StackDialog::json_fields); + let current = dialogs.borrow().get::().and_then(|d| d.current()); + for order in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { + let edits = [ + ("color".to_owned(), serde_json::json!("#00ff00")), + ("swatch".to_owned(), serde_json::json!([0, 0])), + ("library".to_owned(), serde_json::json!(1)), + ]; + let mut fields: Vec<_> = order.into_iter().map(|index| edits[index].clone()).collect(); + fields.push(("swatch".to_owned(), serde_json::json!([2, 0]))); + assert!(dialogs.borrow_mut().set_json_fields(&ctx, id, &fields).is_err()); + assert_eq!(dialogs.borrow().get::().and_then(StackDialog::json_fields), before); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.current()), current); + } + let color = if picked.is_some() { blue } else { red }; + assert_eq!(answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "a refused batch restores the earlier pick"); + } +} + +/// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its +/// library. +#[trial] +fn a_color_picker_swatch_picked_before_startup_survives_it() { + let red = SWATCH_RED; + let id = dialog_id(("color-picker", "fill")); + let answer = swatch_answer; + for render in [false, true] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-start-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(())); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(())); + assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None))); + + let ink = Srgba::from_hex("#123456").expect("a colour outside the web colours"); + let libraries = + vec![PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(1, 0)), Some(())); + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + } + assert_eq!(answer(&dialogs, &fixture), Some((ink.to_hex(), Some(PickedSwatch::new(1, 0)))), "startup keeps the direct pick"); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red)); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(1)), "OK remembers the picked swatch's library"); + } +} + /// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide /// wherever the well stands and whatever the room. #[trial] From f0ca612ac5891e61fbd8f2608443408ec098b389 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:59:44 -0800 Subject: [PATCH 22/33] color-ui: a swatch pick needs the Full layout, and a refused batch also undoes the dialog's start --- crates/color-ui/src/ui/picker_dialog.rs | 13 +++-- crates/color-ui/tests/it/picker.rs | 71 +++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 5 deletions(-) diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index 5f696e3bc6..cf165657ba 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -670,8 +670,11 @@ impl ColorPickerDialog { } /// Picks `swatch` of the Color Swatches view as a click on it would, for automation and scripts: the colour becomes - /// the swatch's and its library the one shown. `None` when the view has no such swatch. + /// the swatch's and its library the one shown. `None` when the layout is not Full or the view has no such swatch. pub fn pick_swatch(&mut self, swatch: PickedSwatch) -> Option<()> { + if self.layout != ColorPickerDialogLayout::Full { + return None; + } let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?; self.current = Some(PickedColor::rgb(*color)); self.memory.library = swatch.library; @@ -814,17 +817,17 @@ impl StackDialog for ColorPickerDialog { Ok(()) } - /// Sets the fields in order; when one is refused, the colour, the swatch it was picked from and the memory are put - /// back as they were after the dialog's start, which any set runs first. + /// Sets the fields in order; when one is refused, the fields and startup state are restored to their earlier values. fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, serde_json::Value)]) -> Result<(), String> { if fields.is_empty() { return Ok(()); } + let before = + (self.started, self.host.clone(), self.opening, self.current, self.picked_swatch, self.memory.clone(), self.tab, self.on_swatches); self.start_headless(ctx); - let before = (self.current, self.picked_swatch, self.memory.clone()); for (field, value) in fields { if let Err(refusal) = self.set_json_field(ctx, field, value.clone()) { - (self.current, self.picked_swatch, self.memory) = before; + (self.started, self.host, self.opening, self.current, self.picked_swatch, self.memory, self.tab, self.on_swatches) = before; return Err(refusal); } } diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index a216f6f92d..05263f9a53 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -629,6 +629,77 @@ fn automation_picks_a_color_picker_swatch_and_a_refused_batch_restores_the_pick( } } +/// A tabbed picker shows no swatch view, so it refuses a swatch pick and keeps its colour. +#[trial] +fn a_tabbed_color_picker_refuses_swatch_picks() { + let red = SWATCH_RED; + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", red) + .layout(ColorPickerDialogLayout::Tabbed) + .swatch_view(PickerSwatches::new(libraries, "No swatches")); + let before = dialog.json_fields(); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), None); + assert_eq!(dialog.json_fields(), before); + assert!(dialog.set_json_field(&egui::Context::default(), "swatch", serde_json::json!([0, 0])).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.current(), Some(PickedColor::rgb(red))); + assert_eq!(dialog.picked_swatch(), None); +} + +/// A refused batch of fields set before the dialog first runs leaves it as it was, and its start runs later as usual. +#[trial] +fn a_refused_color_picker_batch_restores_state_before_startup() { + let opened = Srgba::from_hex("#123456").expect("a color outside the web colors"); + let snapped = Srgba::from_hex("#003366").expect("the nearest web color"); + let id = dialog_id(("color-picker", "fill")); + for render in [false, true] { + for picked in [None, Some(PickedSwatch::new(1, 0))] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-batch-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); + + let libraries = vec![ + PickerLibrary::new("Basic", vec![(Label::from("Red"), SWATCH_RED)]), + PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)]), + ]; + let request = craft_ui::runtime::requests::ColorRequest::new("fill", opened).on_swatches(); + let mut dialog = + ColorPickerDialog::from_request(request).tab(ColorPickerTab::Custom).swatch_view(PickerSwatches::new(libraries, "No swatches")); + if let Some(swatch) = picked { + assert_eq!(dialog.pick_swatch(swatch), Some(())); + } + let before = dialog.json_fields(); + let current = dialog.current(); + let fields = [("swatch".to_owned(), serde_json::json!([0, 0])), ("swatch".to_owned(), serde_json::json!([2, 0]))]; + assert!(dialog.set_json_fields(&ctx, &fields).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened))); + assert_eq!(dialog.current(), current); + assert_eq!(dialog.picked_swatch(), picked); + + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.opening()), Some(PickedColor::rgb(snapped))); + } + let color = if picked.is_some() { SWATCH_BLUE } else { snapped }; + assert_eq!(swatch_answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "startup runs after a refused batch"); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom"))); + assert_eq!(dialog_field(&dialogs, "swatches"), Some(serde_json::json!(true))); + assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(usize::from(picked.is_some())))); + } + } +} + /// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its /// library. #[trial] From fb0a7756ff06e30ed648fa8184072bd29b42d4c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:00:56 -0800 Subject: [PATCH 23/33] ui-contract: a memoized view's content keeps the flow start and gap of the Stack around it A MemoView started a layout room of its own, so its content lost the flow start and the Stack gap of the body around it. A section shown in a MemoView under SectionRhythm::Spaced then took the full section gap above its rule instead of the gap less the Stack's, and the first section under a heading title drew a rule it does not draw outside the view: 17 pt lower at the top and 4 pt lower for each later section in the new test. The view's direct children now go on with the flow the view stands in: the first starts that flow when the view does, after a rule when the view is, and each keeps the gap a Stack leaves before the view. Where the view stands in that flow is part of its place, so a view that moves from a body's start to a later cell runs again instead of replaying. --- .../ui-contract/src/contract/body/inherit.rs | 1 + .../ui-contract/src/contract/body/regions.rs | 2 +- crates/ui-contract/src/contract/lazy.rs | 10 +- crates/ui-contract/src/contract/memo_view.rs | 11 ++- crates/ui-contract/src/layout/body.rs | 25 ++++- crates/ui-contract/src/layout/mod.rs | 6 +- crates/ui-contract/src/runtime/env.rs | 58 ++++++++++-- crates/ui-panels/tests/it/sections/rhythm.rs | 93 +++++++++++++++++++ 8 files changed, 187 insertions(+), 19 deletions(-) diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 3a232d1d90..63ce185b7a 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -124,6 +124,7 @@ impl BodyHooks<'_> { scoped.after_rule = props.header.is_some_and(|header| (header.rule || (header.heads && heads)) && !header.inline) || (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule); scoped.flow_body = None; + scoped.view_flow = None; scoped.column_row = self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); // Children side by side share the layer's width, so none of them spans it: a collection in a row or a grid takes diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index d3b73ff6a0..20efb82c40 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -101,7 +101,7 @@ impl RuleBands { let above = on(start != Some(true) && props.header.is_some_and(|header| header.rule_above)); let spaced = above > 0.0 && env.get::() == SectionRhythm::Spaced; let gaps = &tokens.tokens().space.gap; - let stack_gap = env.stack_gap.filter(|(body, _)| env.flow_body == Some(*body)).map_or(0.0, |(_, gap)| gap); + let stack_gap = env.flow_gap().unwrap_or(0.0); RuleBands { lead: if spaced && start.is_none() { (gaps.section - stack_gap).max(0.0) } else { 0.0 }, above, diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index e52c88d6d2..2644823b53 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -3,7 +3,7 @@ use crate::layout::{flow_region, take_cell, take_in_flow}; use crate::runtime::egui::alloc; -use crate::runtime::env::{Env, Shrink}; +use crate::runtime::env::{Env, Flow, Shrink}; use crate::runtime::focus; use crate::runtime::layout_memory; use crate::runtime::lazy::{self, Call, Decision, Key, Place}; @@ -149,7 +149,7 @@ impl Lazy { access: crate::runtime::egui::access::builds_nodes(&ctx), opacity: ui.opacity(), env: env.key, - flow: env.flow(), + flow: flow_around(&ctx, &env, memo), }; if real && memo { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); @@ -314,6 +314,12 @@ fn open_record(ctx: &egui::Context, audited: bool) { replay::open(ctx); } +/// The flow facts of the body around a child shown under `env` (`Place::flow`). A memoized view's also hold where it +/// stands in that body's flow, which its content goes on with (`layout::open_view_flow`). +fn flow_around(ctx: &egui::Context, env: &Env, memo: bool) -> Flow { + if memo { env.flow().in_flow(crate::layout::flow_start(ctx, env), env.flow_gap()) } else { env.flow() } +} + /// Where content of `size` starts in `region`: at its start edge, the right one in a right-to-left layout. fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y) diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 886bb5c688..737a9d4620 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -50,7 +50,8 @@ use std::sync::Arc; /// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a /// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that /// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the -/// room), compared for every view and for each kind of run on its own; +/// room, whether it starts that body's flow and the gap a `Stack` body leaves before it), compared for every view and +/// for each kind of run on its own; /// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every /// app value, and the rest of `Scoped::scope_key`), in the key; /// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the @@ -67,7 +68,9 @@ use std::sync::Arc; /// no version: the containers inside measure as outside any view. /// /// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a column's sweep, a grid's -/// cursor) does not reach in, so the room it is given reaches it only through its place. To the body +/// cursor) does not reach in, so the room it is given reaches it only through its place. Its direct children go on with +/// the flow the view stands in: the first one starts that flow when the view does, and each one keeps the gap a `Stack` +/// body leaves before the view, so a section shown in the view stands where it stands shown without it. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its /// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no @@ -154,11 +157,13 @@ impl MemoVie // that body sizes from its content, whether its leaves fit their room and which axis it shares among the // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the // same content shown without the view would. + // Its direct children go on with the flow the view stands in (`layout::open_view_flow`). // Its key is its content's version: a body inside measures under it (`Scoped::view_version`). + let flow = crate::layout::open_view_flow(&ctx, &env, id); let installed = Env::install_for( ui, env.derive_local(|scoped| { - scoped.start_view_room(id); + scoped.start_view_room(id, flow); scoped.view_version = follows.then_some(key); }), ); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index a98971add0..edf92773db 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -364,12 +364,31 @@ pub(crate) struct FlowStarts(IdMap); /// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed /// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); -/// `None` once a child took room there, and outside a body. +/// `None` once a child took room there, and outside a body. The children of a memoized view's content read the flow +/// they go on with (`Scoped::flow_of`). pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { - let body = env.flow_body?; + let body = env.flow_of()?; pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) } +/// Opens the flow of the content of the memoized view `view`, which is placed in flow under `env`, and returns its id +/// (`Scoped::view_flow`); `None` when no flow places the view. The content's first child starts that flow when the +/// view starts the flow it stands in, after a rule when the view is; otherwise something precedes it there. +pub(crate) fn open_view_flow(ctx: &egui::Context, env: &Env, view: Id) -> Option { + env.flow_of()?; + let flow = sub(view, "flow"); + let start = flow_start(ctx, env); + pass_state::with::(ctx, |starts| match start { + Some(after_rule) => { + starts.0.insert(flow, after_rule); + } + None => { + starts.0.remove(&flow); + } + }); + Some(flow) +} + /// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { flow_start(ctx, env).is_some() @@ -377,7 +396,7 @@ pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { /// A child took room in the flow of the body that places the children under `env`: its flow start closes. pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { - if let Some(body) = env.flow_body { + if let Some(body) = env.flow_of() { pass_state::with::(ctx, |starts| starts.0.remove(&body)); } } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 7912e0af94..05ffc0ef11 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -27,7 +27,7 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, - members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, - report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, - view_room, + members_line, open_first_lines, open_view_fill, open_view_flow, place_in_cell, report_bracket_control, report_fill_least, report_held, + report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, + take_view_fill, view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index dea72c2f8a..1116ce6b91 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -80,10 +80,11 @@ pub(crate) struct FooterSlotOf { /// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a /// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill /// it, whether the view runs in a least measure, the -/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's -/// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its -/// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`, -/// `lazy::Measured`), not of its key. +/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell, whether its leaves fit the view's +/// room (`Scoped::view_fits`), and where the view stands in that body's flow: whether it starts the flow, after a rule +/// or not (`layout::flow_start`), and the gap a `Stack` body leaves before it (`Scoped::flow_gap`). A measuring run of a +/// container or a row lays the view out under other facts than its real run, so they are a fact of the view's place, +/// which each kind of run compares on its own (`lazy::Place`, `lazy::Measured`), not of its key. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Flow { content_column: bool, @@ -95,6 +96,17 @@ pub(crate) struct Flow { cell_fills: bool, fits: bool, egui_cell: bool, + start: Option, + /// The bits of the gap, so the facts compare exactly. + gap: Option, +} + +impl Flow { + /// These facts for a view that stands at `start` in the flow of the body around it (`layout::flow_start`), with + /// `gap` the gap a `Stack` body leaves before it (`Scoped::flow_gap`). + pub(crate) fn in_flow(self, start: Option, gap: Option) -> Flow { + Flow { start, gap: gap.map(f32::to_bits), ..self } + } } /// The values of an env. @@ -173,8 +185,13 @@ pub struct Scoped { /// and the one a child placed in flow closes. pub(crate) flow_body: Option, /// The `Stack` body that places the scope's direct children in flow and the gap it leaves between them; it holds - /// only while that body is `flow_body`. + /// only while that body is the scope's flow (`flow_of`). pub(crate) stack_gap: Option<(Id, f32)>, + /// The flow of a memoized view's content, when the view stands in a body's flow: the scope's direct children go on + /// with that body's flow from where the view stands in it. The first one starts the flow when the view does + /// (`layout::open_view_flow`), and each one follows the gap a `Stack` body left before the view (`stack_gap`), as + /// the same children shown in that body without the view would. + pub(crate) view_flow: Option, /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws /// nothing of its own and itself follows one. The body's layout opens its flow start with it. pub(crate) after_rule: bool, @@ -488,6 +505,7 @@ impl Scoped { self.row_line = None; self.first_line = None; self.flow_body = None; + self.view_flow = None; self.column_row = false; self.fill_body = None; self.fill_share = None; @@ -508,6 +526,7 @@ impl Scoped { || self.row_line.is_some() || self.first_line.is_some() || self.flow_body.is_some() + || self.view_flow.is_some() || self.column_row || self.fill_body.is_some() || self.fill_share.is_some() @@ -529,10 +548,14 @@ impl Scoped { /// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a /// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child /// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in. - pub(crate) fn start_view_room(&mut self, view: Id) { + /// + /// `flow` is the flow the content's direct children go on with (`view_flow`, from `layout::open_view_flow`): they + /// keep the gap a `Stack` body around the view leaves before it. + pub(crate) fn start_view_room(&mut self, view: Id, flow: Option) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); let shares = self.shares(); + let gap = self.flow_gap(); let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); // The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in // it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children @@ -541,6 +564,8 @@ impl Scoped { self.start_room(); (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); self.row_line = line; + self.view_flow = flow; + self.stack_gap = flow.zip(gap); self.fill_view = shares.map(|axis| (view, axis)); if fits { self.shrink = Some(Shrink::Fit); @@ -550,6 +575,21 @@ impl Scoped { } } + /// The flow that places the scope's direct children: the enclosing body's (`flow_body`), else the flow a memoized + /// view's content goes on with (`view_flow`). + pub(crate) const fn flow_of(&self) -> Option { + match self.flow_body { + Some(body) => Some(body), + None => self.view_flow, + } + } + + /// The gap a `Stack` body leaves before each of the scope's direct children it places in flow after its first + /// (`stack_gap`), while that body is the scope's flow (`flow_of`). + pub(crate) fn flow_gap(&self) -> Option { + self.stack_gap.filter(|(body, _)| self.flow_of() == Some(*body)).map(|(_, gap)| gap) + } + /// The axis the enclosing body shares among its direct children that fill it (`fill_body`). pub(crate) const fn shares(&self) -> Option { match self.fill_body { @@ -606,7 +646,8 @@ impl Scoped { }) } - /// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`). + /// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`), without where + /// the view stands in that body's flow (`Flow::in_flow`). pub(crate) const fn flow(&self) -> Flow { Flow { content_column: self.content_column, @@ -618,6 +659,8 @@ impl Scoped { cell_fills: self.cell_fills, fits: self.view_fits(), egui_cell: self.egui_cell, + start: None, + gap: None, } } @@ -758,6 +801,7 @@ impl Env { first_line: None, flow_body: None, stack_gap: None, + view_flow: None, after_rule: false, column_row: false, bracket: None, diff --git a/crates/ui-panels/tests/it/sections/rhythm.rs b/crates/ui-panels/tests/it/sections/rhythm.rs index 4fe61c1b70..5693fa493a 100644 --- a/crates/ui-panels/tests/it/sections/rhythm.rs +++ b/crates/ui-panels/tests/it/sections/rhythm.rs @@ -46,3 +46,96 @@ fn a_spaced_section_stands_its_rule_off_the_row_above_and_its_header() { assert!(spaced_above >= section_gap - 0.5, "the spaced rule stands a section gap ({section_gap}) off the row, not {spaced_above}"); assert!(spaced_below > tight_below, "the spaced header stands further below its rule ({spaced_below}) than the tight one ({tight_below})"); } + +/// A section that returns where its body's text landed, to show directly or as a memoized view's content. +fn section_at(title: &mut &'static str, ui: &mut Ui) -> Rect { + let mut body = Rect::NOTHING; + Section::fixed(*title).show(ui, |ui, _| body = Text::new("Width").show(ui).rect); + body +} + +/// Where the bodies of three sections land under `SectionRhythm::Spaced`: in a quiet-titled panel whose title heads its +/// body (`QuietHeader::Heads`) and in a plain stack after a row, each section shown directly or, with `memo`, in a +/// `MemoView` of its own. +fn section_bodies(memo: bool) -> Vec { + use craft_ui::contract::{MemoView, QuietHeader}; + use craft_ui::sections::{HeaderStrength, Panel}; + const TITLES: [&str; 3] = ["Transform", "Appearance", "Stroke"]; + let mut frames = Frames::new(); + let mut root = RootEnv::default(); + root.values.set(SectionRhythm::Spaced); + root.values.set(QuietHeader::Heads); + frames.root(root); + let sections = |ui: &mut Ui, bodies: &mut Vec| { + for (at, title) in TITLES.into_iter().enumerate() { + let body = if memo { MemoView::new(("section", at), title, section_at).show(ui) } else { Some(section_at(&mut { title }, ui)) }; + bodies.push(body.unwrap_or(Rect::NOTHING)); + } + }; + let mut bodies = Vec::new(); + let mut show = |ui: &mut Ui| { + bodies.clear(); + Panel::new("Properties").titled().strength(HeaderStrength::Quiet).show(ui, |ui, _| sections(ui, &mut bodies)); + Stack::new().show(ui, |ui, _| { + let _ = Text::new("Fill").show(ui); + sections(ui, &mut bodies); + }); + }; + frames.idle(4, &mut show); + bodies +} + +/// Regression: a section shown in a `MemoView` in a spaced stack lost the stack's gap and flow start, so under +/// `QuietHeader::Heads` the first one drew the rule above it with a section gap of room and each later one stood a +/// stack gap further down. A memoized section lands where the same section shown directly does, on its first run and +/// on its replays. +#[trial] +fn a_memoized_section_in_a_spaced_stack_lands_where_a_direct_one_does() { + let direct = section_bodies(false); + let memoized = section_bodies(true); + assert_eq!(direct.len(), 6, "every section shows its body"); + assert!(direct.iter().all(|body| body.is_positive()), "every section's body is placed: {direct:?}"); + assert_eq!(memoized, direct, "memoized sections land where direct ones do"); +} + +/// Where the bodies of two sections land in a spaced two-column grid of equal, top-aligned columns, in the last frame +/// after they swap cells, each shown directly or, with `memo`, in a `MemoView` of its own. The first cell starts the +/// grid's flow and the second does not, and both cells give a section a room of the same size. +fn bodies_after_a_swap(memo: bool) -> [Rect; 2] { + use craft_behavior::ColumnWidth; + use craft_ui::contract::MemoView; + use craft_ui::layout::CellAlign; + use craft_ui::layout_components::Grid; + static HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(0.5), ColumnWidth::fill(0.5)]; + const TITLES: [&str; 2] = ["Stroke", "Fill"]; + let mut frames = Frames::new(); + let mut root = RootEnv::default(); + root.values.set(SectionRhythm::Spaced); + frames.root(root); + let mut bodies = [Rect::NOTHING; 2]; + let mut show = |ui: &mut Ui, swapped: bool| { + Grid::new(&HALVES).fill().cells(CellAlign::Top).show(ui, |ui, _| { + for cell in 0..2 { + let at = if swapped { 1 - cell } else { cell }; + bodies[at] = if memo { + MemoView::new(("section", at), TITLES[at], section_at).show(ui).unwrap_or(Rect::NOTHING) + } else { + section_at(&mut { TITLES[at] }, ui) + }; + } + }); + }; + frames.idle(3, |ui| show(ui, false)); + frames.idle(3, |ui| show(ui, true)); + bodies +} + +/// Regression: a memoized section that ran in the cell that starts its body's flow replayed that run in a cell of the +/// same size after it, without the room a section after another stands under, and the other the other way round. A view +/// whose place in its body's flow changed runs again. +#[trial] +fn a_memoized_section_runs_again_when_its_place_in_the_flow_changes() { + let direct = bodies_after_a_swap(false); + assert!(direct.iter().all(|body| body.is_positive()), "every section's body is placed: {direct:?}"); + assert_eq!(bodies_after_a_swap(true), direct, "memoized sections land where direct ones do"); +} From 1d67a723c90b1f063c136fd72cfa723dee1f4b22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:03:46 -0800 Subject: [PATCH 24/33] color-ui: a Color Picker set to the Tabbed layout names no swatch --- crates/color-ui/src/ui/picker_dialog.rs | 4 ++++ crates/color-ui/tests/it/picker.rs | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index cf165657ba..97ee19d3ba 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -511,9 +511,13 @@ impl ColorPickerDialog { } /// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog). + /// A layout other than Full clears the picked swatch and keeps the current color. #[must_use] pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog { self.layout = l; + if l != ColorPickerDialogLayout::Full { + self.picked_swatch = None; + } self } diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 05263f9a53..31cde01130 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -644,6 +644,12 @@ fn a_tabbed_color_picker_refuses_swatch_picks() { assert_eq!(dialog.json_fields(), before); assert_eq!(dialog.current(), Some(PickedColor::rgb(red))); assert_eq!(dialog.picked_swatch(), None); + + let mut dialog = dialog.layout(ColorPickerDialogLayout::Full); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let dialog = dialog.layout(ColorPickerDialogLayout::Tabbed); + assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE))); + assert_eq!(dialog.picked_swatch(), None); } /// A refused batch of fields set before the dialog first runs leaves it as it was, and its start runs later as usual. From 842f86eb06e947af750e29df9c8048803e0f017e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:10:51 -0800 Subject: [PATCH 25/33] color-ui: Restore current color and a refused single field leave no stale swatch, and kept values stay on the opening color --- crates/color-ui/src/ui/picker/full.rs | 1 + crates/color-ui/src/ui/picker/mod.rs | 11 +++-- crates/color-ui/src/ui/picker_dialog.rs | 61 +++++++++++++++---------- crates/color-ui/tests/it/picker.rs | 35 ++++++++++++++ 4 files changed, 79 insertions(+), 29 deletions(-) diff --git a/crates/color-ui/src/ui/picker/full.rs b/crates/color-ui/src/ui/picker/full.rs index 9631147625..0a6ffb7525 100644 --- a/crates/color-ui/src/ui/picker/full.rs +++ b/crates/color-ui/src/ui/picker/full.rs @@ -99,6 +99,7 @@ impl<'a> Body<'a> { if shown.restore && let Mixed::Same(current) = pass.compare { + got.restored = true; got.clicks.push(current); } if let Some(warning) = shown.warning.and_then(|at| self.warnings.get(at)) { diff --git a/crates/color-ui/src/ui/picker/mod.rs b/crates/color-ui/src/ui/picker/mod.rs index d98387f4c6..8b462a9966 100644 --- a/crates/color-ui/src/ui/picker/mod.rs +++ b/crates/color-ui/src/ui/picker/mod.rs @@ -106,6 +106,8 @@ pub struct ColorPickerOutput { pub events: EditEvents, /// The screen-pick button's press this pass. pub screen_pick: Option, + /// The compare block's current half was activated this pass. + pub restored: bool, } impl Outcome for ColorPickerOutput { @@ -181,6 +183,7 @@ struct Collected { edits: EditEvents, /// Colours the compare swatch and the warning chips set. clicks: Vec, + restored: bool, screen_pick: Option, model_pick: Option<&'static str>, /// The mode the "Field shows" group picked. @@ -430,8 +433,8 @@ impl<'a> ColorPicker<'a> { events: EditEvents::new(), }; let shown = Stack::new().label(label).show(ui, |ui, body| run.show(ui, body)); - let (events, screen_pick) = shown.inner.unwrap_or_default(); - ColorPickerOutput { response: shown.output, events, screen_pick } + let (events, screen_pick, restored) = shown.inner.unwrap_or_default(); + ColorPickerOutput { response: shown.output, events, screen_pick, restored } } } @@ -461,7 +464,7 @@ struct Run<'s, 'a> { } impl<'a> Run<'_, 'a> { - fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents, Option) { + fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents, Option, bool) { let memo = body.memory::().clone(); let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()); let mut mode = held_mode.unwrap_or(memo.mode); @@ -546,7 +549,7 @@ impl<'a> Run<'_, 'a> { None => body.memory::().model = Some(next), } } - (std::mem::take(&mut self.events), got.screen_pick) + (std::mem::take(&mut self.events), got.screen_pick, got.restored) } /// Lands `event`, an edit of the colour: a gesture's end takes the colour it began from, the binding takes the diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index 97ee19d3ba..e7cefd1d54 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -547,7 +547,12 @@ impl ColorPickerDialog { /// what the sRGB colour converts to (storytold/photocraft#4196). #[must_use] pub fn kept(mut self, values: craft_theme::ModelValues) -> ColorPickerDialog { - for held in [&mut self.opening, &mut self.current].into_iter().flatten() { + if let Some(held) = &mut self.opening { + held.model = Some(values); + } + if self.picked_swatch.is_none() + && let Some(held) = &mut self.current + { held.model = Some(values); } self @@ -721,6 +726,29 @@ impl ColorPickerDialog { } } + /// Sets one JSON field after the dialog's start: `swatch`, `color` or a memory field. + fn set_field(&mut self, field: &str, value: serde_json::Value) -> Result<(), String> { + if field == "swatch" { + if value.is_null() { + self.picked_swatch = None; + return Ok(()); + } + let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) { + (Some(2), Some(library), Some(index)) => PickedSwatch { library, index }, + _ => return Err(FieldRefusal::Rejects(&value).message(field)), + }; + return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field)); + } + if field != "color" { + return set_serde_field(&mut self.memory, field, value); + } + let parsed = value.as_str().and_then(Srgba::from_hex); + let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?; + self.set_color(PickedColor { color, model: None }); + Ok(()) + } + /// The first pass: recalls the remembered field component and Only Web Colors, and with Only Web Colors on snaps /// the opening colour, which the compare swatch's current half follows (storytold/photocraft#4995). fn start(&mut self, host: Option<&Arc>) { @@ -798,27 +826,7 @@ impl StackDialog for ColorPickerDialog { } fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> { - // The dialog's start recalls the memory and snaps the opening colour; a field set before it would be overwritten. - self.start_headless(ctx); - if field == "swatch" { - if value.is_null() { - self.picked_swatch = None; - return Ok(()); - } - let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok()); - let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) { - (Some(2), Some(library), Some(index)) => PickedSwatch { library, index }, - _ => return Err(FieldRefusal::Rejects(&value).message(field)), - }; - return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field)); - } - if field != "color" { - return set_serde_field(&mut self.memory, field, value); - } - let parsed = value.as_str().and_then(Srgba::from_hex); - let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?; - self.set_color(PickedColor { color, model: None }); - Ok(()) + self.set_json_fields(ctx, &[(field.to_owned(), value)]) } /// Sets the fields in order; when one is refused, the fields and startup state are restored to their earlier values. @@ -830,7 +838,7 @@ impl StackDialog for ColorPickerDialog { (self.started, self.host.clone(), self.opening, self.current, self.picked_swatch, self.memory.clone(), self.tab, self.on_swatches); self.start_headless(ctx); for (field, value) in fields { - if let Err(refusal) = self.set_json_field(ctx, field, value.clone()) { + if let Err(refusal) = self.set_field(field, value.clone()) { (self.started, self.host, self.opening, self.current, self.picked_swatch, self.memory, self.tab, self.on_swatches) = before; return Err(refusal); } @@ -927,6 +935,7 @@ impl StackDialog for ColorPickerDialog { let color = current.map(|current| current.color); let web_only = memory.web_colors; let mut clicked = None; + let mut restored = false; let shown = Dialog::new(title.clone()) .opened(Bind::bound(open)) .buttons(buttons) @@ -989,7 +998,9 @@ impl StackDialog for ColorPickerDialog { picker = picker.compare(compare); } picker = picker.compare_none(*no_current); - if let Some(gesture) = picker.show(ui).screen_pick { + let output = picker.show(ui); + restored = output.restored; + if let Some(gesture) = output.screen_pick { *pending_screen = Some(gesture); } }); @@ -997,7 +1008,7 @@ impl StackDialog for ColorPickerDialog { // A swatch click names the swatch; any other change to the colour leaves it picked from no swatch. if clicked.is_some() { self.picked_swatch = clicked; - } else if after != self.current { + } else if restored || after != self.current { self.picked_swatch = None; } self.current = after; diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 31cde01130..4fcfb5d762 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -683,6 +683,11 @@ fn a_refused_color_picker_batch_restores_state_before_startup() { } let before = dialog.json_fields(); let current = dialog.current(); + assert!(dialog.set_json_field(&ctx, "swatch", serde_json::json!([2, 0])).is_err()); + assert_eq!(dialog.json_fields(), before); + assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened))); + assert_eq!(dialog.current(), current); + assert_eq!(dialog.picked_swatch(), picked); let fields = [("swatch".to_owned(), serde_json::json!([0, 0])), ("swatch".to_owned(), serde_json::json!([2, 0]))]; assert!(dialog.set_json_fields(&ctx, &fields).is_err()); assert_eq!(dialog.json_fields(), before); @@ -706,6 +711,36 @@ fn a_refused_color_picker_batch_restores_state_before_startup() { } } +/// Restoring the opening color clears an equal-color swatch selection. +#[trial] +fn restoring_the_current_color_clears_the_picked_swatch() { + let (dialogs, mut fixture) = swatch_picker(); + let red = fixture.by_label("Ink Red").expect("the opening color's swatch"); + fixture.click(&red).idle(4); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 2))); + let models = fixture.by_label("Color Models").expect("the model view button"); + fixture.click(&models).idle(4); + let restore = fixture.by_label("Restore current color").expect("the compare block's current half"); + fixture.click(&restore).idle(4); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), None); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); +} + +/// Opening model values leave a picked swatch's RGB-only result unchanged. +#[trial] +fn opening_model_values_do_not_change_a_picked_swatch() { + let values = ModelValues::new("cmyk", &[0.0, 100.0, 100.0, 0.0]); + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let mut dialog = dialog.kept(values); + assert_eq!(dialog.opening(), Some(PickedColor { color: SWATCH_RED, model: Some(values) })); + assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE))); + let result = dialog.confirm(&egui::Context::default()).expect("the selected swatch"); + assert_eq!(result.picked, PickedColor::rgb(SWATCH_BLUE)); + assert_eq!(result.swatch, Some(PickedSwatch::new(0, 0))); +} + /// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its /// library. #[trial] From 26070dd9ecbeb25e639af61bf6c1092704abb4c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:22:39 -0800 Subject: [PATCH 26/33] color-ui: an eyedropper sample clears the picked swatch, and a caller's color survives a new swatch view --- crates/color-ui/src/ui/picker_dialog.rs | 28 +++++++++++--- crates/color-ui/tests/it/picker.rs | 49 +++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index e7cefd1d54..13a7cb43b1 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -279,6 +279,9 @@ pub struct ColorPickerDialog { opening: Option, /// The colour as it stands; `None` until the first pick when the dialog opened without one. current: Option, + /// The colour was set by the caller ([`set_color`](Self::set_color), [`pick_swatch`](Self::pick_swatch)); the + /// Only Web Colors snap at the start then leaves it as it is. + color_set: bool, compare: bool, /// [`no_current`](Self::no_current). no_current: bool, @@ -463,6 +466,7 @@ impl ColorPickerDialog { title_args: Vec::new(), opening, current: opening, + color_set: false, compare: true, no_current: false, remember: true, @@ -669,6 +673,7 @@ impl ColorPickerDialog { /// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour. pub fn set_color(&mut self, picked: PickedColor) { self.current = Some(picked); + self.color_set = true; self.picked_swatch = None; } @@ -686,6 +691,7 @@ impl ColorPickerDialog { } let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?; self.current = Some(PickedColor::rgb(*color)); + self.color_set = true; self.memory.library = swatch.library; self.picked_swatch = Some(swatch); Some(()) @@ -770,7 +776,7 @@ impl ColorPickerDialog { { let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]); self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None }); - if self.picked_swatch.is_none() { + if !self.color_set { self.current = self.opening; } } @@ -834,12 +840,22 @@ impl StackDialog for ColorPickerDialog { if fields.is_empty() { return Ok(()); } - let before = - (self.started, self.host.clone(), self.opening, self.current, self.picked_swatch, self.memory.clone(), self.tab, self.on_swatches); + let before = ( + self.started, + self.host.clone(), + self.opening, + self.current, + self.color_set, + self.picked_swatch, + self.memory.clone(), + self.tab, + self.on_swatches, + ); self.start_headless(ctx); for (field, value) in fields { if let Err(refusal) = self.set_field(field, value.clone()) { - (self.started, self.host, self.opening, self.current, self.picked_swatch, self.memory, self.tab, self.on_swatches) = before; + (self.started, self.host, self.opening, self.current, self.color_set, self.picked_swatch, self.memory, self.tab, self.on_swatches) = + before; return Err(refusal); } } @@ -936,6 +952,7 @@ impl StackDialog for ColorPickerDialog { let web_only = memory.web_colors; let mut clicked = None; let mut restored = false; + let mut sample_processed = false; let shown = Dialog::new(title.clone()) .opened(Bind::bound(open)) .buttons(buttons) @@ -993,6 +1010,7 @@ impl StackDialog for ColorPickerDialog { .eyedropper_busy(busy); if let Some(sampled) = sampled { picker = picker.sampled(sampled); + sample_processed = true; } if let Some(compare) = compare_with { picker = picker.compare(compare); @@ -1008,7 +1026,7 @@ impl StackDialog for ColorPickerDialog { // A swatch click names the swatch; any other change to the colour leaves it picked from no swatch. if clicked.is_some() { self.picked_swatch = clicked; - } else if restored || after != self.current { + } else if restored || sample_processed || after != self.current { self.picked_swatch = None; } self.current = after; diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 4fcfb5d762..847a042376 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -778,6 +778,55 @@ fn a_color_picker_swatch_picked_before_startup_survives_it() { } } +/// Replacing the swatch view before startup keeps the selected color and clears its swatch identity. +#[trial] +fn replacing_the_swatch_view_before_startup_preserves_the_selected_color() { + for render in [false, true] { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-replace-test", name: "Picker test", version: "0" }).build())); + fixture.idle(1); + let ctx = fixture.ctx().clone(); + let id = dialog_id(("color-picker", "fill")); + dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED)); + assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(())); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None))); + + let ink = Srgba::from_hex("#123456").expect("a color outside the web colors"); + let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])]; + let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches")); + assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(())); + let dialog = dialog.swatch_view(PickerSwatches::new(Vec::new(), "No swatches")); + assert_eq!(dialog.picked_swatch(), None); + assert_eq!(dialog.current(), Some(PickedColor::rgb(ink))); + dialogs.borrow_mut().open(dialog); + if render { + fixture.idle(6); + } + assert_eq!(swatch_answer(&dialogs, &fixture), Some((ink.to_hex(), None))); + } +} + +/// Sampling the selected swatch's color from the canvas clears its swatch identity. +#[trial] +fn an_equal_color_canvas_sample_clears_the_picked_swatch() { + let (dialogs, mut fixture) = swatch_picker(); + let blue = fixture.by_label("Blue B").expect("the blue swatch"); + fixture.click(&blue); + fixture.settle(); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1))); + let models = fixture.by_label("Color Models").expect("the model view button"); + fixture.click(&models); + fixture.settle(); + dialogs.borrow_mut().get_mut::().expect("the picker").requests().answer_eyedropper("fill", SWATCH_BLUE); + fixture.settle(); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.current()), Some(PickedColor::rgb(SWATCH_BLUE))); + assert_eq!(dialogs.borrow().get::().and_then(|d| d.picked_swatch()), None); + assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_BLUE.to_hex(), None))); +} + /// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide /// wherever the well stands and whatever the room. #[trial] From 98c9b651108903eee715c47b9dff81aa35523bc0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:00:34 -0800 Subject: [PATCH 27/33] ui-contract: fixtures keep mirrored glyph UV rects ordered Under a negative scale the fixtures scaled each glyph's UV offset and size by the signed scale, so the point-space UV rect came out inverted with a negative size. The offset is now taken from the reordered corners and the size is nonnegative; the atlas coordinates stay as they are. The negative-parent rejection test now places both member scales so the composed box overlaps the clip and checks that nothing reported touches that overlap. --- .../ui-contract/src/runtime/egui/fixture.rs | 4 ++++ .../tests/it/paint/chunk_members.rs | 22 +++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index a5db36a176..9999ed43f1 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -718,6 +718,8 @@ fn flatten_owned( glyph.uv_rect.size *= transform.scaling; if transform.scaling < 0.0 { let rect = glyph.logical_rect(); + let uv_from = glyph.pos + glyph.uv_rect.offset; + let uv = Rect::from_two_pos(uv_from, uv_from + glyph.uv_rect.size); glyph.advance_width = glyph.advance_width.abs(); glyph.line_height = glyph.line_height.abs(); glyph.font_ascent = glyph.font_ascent.abs(); @@ -725,6 +727,8 @@ fn flatten_owned( glyph.font_face_ascent = glyph.font_face_ascent.abs(); glyph.font_face_height = glyph.font_face_height.abs(); glyph.pos = Rect::from_two_pos(rect.min, rect.max).min + egui::vec2(0.0, glyph.font_ascent); + glyph.uv_rect.offset = uv.min - glyph.pos; + glyph.uv_rect.size = uv.size(); } } if transform.scaling < 0.0 { diff --git a/crates/ui-contract/tests/it/paint/chunk_members.rs b/crates/ui-contract/tests/it/paint/chunk_members.rs index b42ef667c2..06fa1b0019 100644 --- a/crates/ui-contract/tests/it/paint/chunk_members.rs +++ b/crates/ui-contract/tests/it/paint/chunk_members.rs @@ -152,9 +152,12 @@ fn nested_chunk_members_under_negative_parent_scales_are_not_reported() { let member_clip = Rect::from_min_max(pos2(15.0, 5.0), pos2(45.0, 40.0)); let transformed_clip = Rect::from_two_pos(parent * member_clip.min, parent * member_clip.max); let expected_clip = parent_clip.intersect(transformed_clip); - for member_scale in [-0.5, 0.5] { - let member = TSTransform::new(vec2(40.0, 30.0), member_scale); - let bounds = (parent * member) * BOX; + for (member_scale, member_at) in [(-0.5, vec2(40.0, 30.0)), (0.5, vec2(15.0, 10.0))] { + let member = TSTransform::new(member_at, member_scale); + let composed = parent * member; + let bounds = Rect::from_two_pos(composed * BOX.min, composed * BOX.max); + let overlap = bounds.intersect(expected_clip); + assert!(overlap.is_positive(), "the composed box {bounds:?} overlaps the clip {expected_clip:?}"); let paint = move |ui: &mut Ui| { let galley = ui.painter().layout_no_wrap("chunk".to_owned(), FontId::proportional(14.0), Color32::WHITE); let members = [Shape::rect_filled(BOX, 0.0, FILL), Shape::galley(TEXT_AT, galley, Color32::WHITE)].map(|shape| ClippedShape { @@ -169,7 +172,7 @@ fn nested_chunk_members_under_negative_parent_scales_are_not_reported() { fixture.settle(); assert!(expected_clip.is_positive()); - assert!(!fixture.shape_bounds().contains(&bounds.intersect(expected_clip))); + assert!(!fixture.shape_bounds().iter().any(|reported| reported.intersects(overlap)), "{:?}", fixture.shape_bounds()); assert!(!fixture.texts().iter().any(|text| text.text == "chunk")); for shapes in @@ -959,6 +962,7 @@ fn mirrored_glyph_logical_rects_are_ordered_and_cover_the_transformed_source() { assert_eq!(texts.len(), 2); let (original, mirrored) = (texts[0], texts[1]); assert_eq!(mirrored.galley.rows.len(), original.galley.rows.len()); + assert!(mirrored.galley.rect.min.x <= mirrored.galley.rect.max.x && mirrored.galley.rect.min.y <= mirrored.galley.rect.max.y); for (row, source) in mirrored.galley.rows.iter().zip(&original.galley.rows) { assert!(!row.glyphs.is_empty()); assert_eq!(row.glyphs.len(), source.glyphs.len()); @@ -971,7 +975,17 @@ fn mirrored_glyph_logical_rects_are_ordered_and_cover_the_transformed_source() { let expected = transform * source_glyph.logical_rect().translate(original.pos.to_vec2() + source.pos.to_vec2()); assert!(actual.min.distance(expected.max) < 0.001, "{actual:?} versus {expected:?}"); assert!(actual.max.distance(expected.min) < 0.001, "{actual:?} versus {expected:?}"); + assert!(glyph.uv_rect.size.x >= 0.0 && glyph.uv_rect.size.y >= 0.0, "{:?}", glyph.uv_rect); + assert_eq!((glyph.uv_rect.min, glyph.uv_rect.max), (source_glyph.uv_rect.min, source_glyph.uv_rect.max)); + let uv_at = |glyph: &egui::epaint::text::Glyph, at: egui::Pos2| { + Rect::from_min_size(at + glyph.pos.to_vec2() + glyph.uv_rect.offset, glyph.uv_rect.size) + }; + let actual = uv_at(glyph, mirrored.pos + row.pos.to_vec2()); + let source_uv = uv_at(source_glyph, original.pos + source.pos.to_vec2()); + let expected = Rect::from_two_pos(transform * source_uv.min, transform * source_uv.max); + assert!(actual.min.distance(expected.min) < 0.001 && actual.max.distance(expected.max) < 0.001, "{actual:?} versus {expected:?}"); } + assert!(row.size.x >= 0.0 && row.size.y >= 0.0, "{:?}", row.size); assert!(!row.visuals.mesh.vertices.is_empty()); assert_eq!(row.visuals.mesh.vertices.len(), source.visuals.mesh.vertices.len()); for (vertex, source_vertex) in row.visuals.mesh.vertices.iter().zip(&source.visuals.mesh.vertices) { From 45cbe90df16da7f1aa473aa7965a050b996b7c1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:16:20 -0800 Subject: [PATCH 28/33] craft-raster3d: shadow casters clipped at the near plane take one f64 fraction when a position difference overflows When a caster edge crosses a perspective light's near plane and an x or y difference between its corners overflows `f32`, `light_poly` interpolated that component in `f64` but with the `f32` fraction, and the other components with the `f32` arithmetic. The crossing moved off the edge: about 1.4e31 off for corners at x = -3e38 and 3e38, and a caster that projects to a line could write shadow texels. Such a crossing now takes one `f64` fraction from the original depths for both position components and both texture coordinates. When the position differences stay finite, each component whose own difference overflows is still interpolated in `f64` with the `f32` fraction, as before. Split from #2950. --- crates/raster3d/src/shadow.rs | 99 ++++++++++++++++++++++++++++++++--- 1 file changed, 93 insertions(+), 6 deletions(-) diff --git a/crates/raster3d/src/shadow.rs b/crates/raster3d/src/shadow.rs index b18049f663..9048e236a3 100644 --- a/crates/raster3d/src/shadow.rs +++ b/crates/raster3d/src/shadow.rs @@ -103,17 +103,26 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec { if (da >= 0.0) != (db >= 0.0) { let (from_b, k) = f32_crossing(da, db); let (p, q) = if from_b { (b, a) } else { (a, b) }; - let lerp = |x: f32, y: f32| { - let d = y - x; - if d.is_finite() || !x.is_finite() || !y.is_finite() { - x + d * k + // `y - x` can overflow f32 between far-apart finite corners. An overflowing x or y + // position difference selects the f64 fraction from the original depths for both + // position and UVs. Otherwise each component whose own difference overflows is + // taken in f64 with the f32 fraction. + let overflows = |x: f32, y: f32| x.is_finite() && y.is_finite() && !(y - x).is_finite(); + let (pa, pb) = ((p.0[0], q.0[0]), (p.0[1], q.0[1])); + let (ua, ub) = ((p.1[0], q.1[0]), (p.1[1], q.1[1])); + let wide_pos = overflows(pa.0, pa.1) || overflows(pb.0, pb.1); + let (dp, dq) = (f64::from(p.0[2]) - f64::from(NEAR), f64::from(q.0[2]) - f64::from(NEAR)); + let k64 = if wide_pos { dp / (dp - dq) } else { f64::from(k) }; + let lerp = |wide: bool, x: f32, y: f32| { + if (wide || overflows(x, y)) && x.is_finite() && y.is_finite() { + (f64::from(x) + (f64::from(y) - f64::from(x)) * k64) as f32 } else { - (f64::from(x) + (f64::from(y) - f64::from(x)) * f64::from(k)) as f32 + x + (y - x) * k } }; // The crossing lies on the near plane; its depth is set to it, since the lerp of // far-apart depths can round to 0 or below. - out.push(([lerp(p.0[0], q.0[0]), lerp(p.0[1], q.0[1]), NEAR], [lerp(p.1[0], q.1[0]), lerp(p.1[1], q.1[1])])); + out.push(([lerp(wide_pos, pa.0, pa.1), lerp(wide_pos, pb.0, pb.1), NEAR], [lerp(wide_pos, ua.0, ua.1), lerp(wide_pos, ub.0, ub.1)])); } } poly = out; @@ -659,4 +668,82 @@ mod tests { assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0); } } + + #[test] + fn a_near_plane_crossing_with_one_overflowing_uv_axis_preserves_the_other_axis() { + let clipped = |u: f32, ids| { + let s = Scene { + vertices: [ + ([-1.0, 0.0, 0.0], [-u, -16_777_216.0]), + ([1.0, 0.0, 3.0 * NEAR], [u, 33_554_432.0]), + ([0.0, 1.0, 3.0 * NEAR], [0.0, 0.0]), + ] + .map(|(pos, uv)| Vertex { pos, uv, ..Vertex::default() }) + .to_vec(), + ..Scene::default() + }; + light_poly(&s, &identity_map(), ids) + }; + for ids in [[0, 1, 2], [1, 0, 2]] { + let ordinary = clipped(1.0, ids); + let overflowing = clipped(f32::MAX, ids); + assert!(overflowing.iter().any(|(p, _)| p[2] == NEAR)); + assert!(overflowing.iter().all(|(_, uv)| uv.iter().all(|v| v.is_finite()))); + let unaffected = |poly: Vec| poly.into_iter().map(|(p, uv)| (p, uv[1])).collect::>(); + assert_eq!(unaffected(overflowing), unaffected(ordinary)); + } + } + + #[test] + fn a_near_plane_crossing_whose_difference_overflows_f32_takes_its_fraction_in_f64() { + // 3e38 − (−3e38) overflows f32; the edge crosses the near plane near x = 3e35. An `f32` + // fraction puts the crossing about 1.4e31 off the edge's own crossing. + let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; + let (a, b) = ([-3e38_f32, 0.0, -1.0], [3e38_f32, 0.0, 1.0]); + let s = Scene { vertices: vec![v(a), v(b), v([0.0, 0.1, 1.0])], ..Scene::default() }; + let poly = light_poly(&s, &identity_map(), [0, 1, 2]); + assert!(!poly.is_empty()); + for (p, uv) in &poly { + assert!(p.iter().chain(uv.iter()).all(|c| c.is_finite()), "{poly:?}"); + } + let t = (f64::from(NEAR) - f64::from(a[2])) / (f64::from(b[2]) - f64::from(a[2])); + let x = f64::from(a[0]) + (f64::from(b[0]) - f64::from(a[0])) * t; + assert!(poly.iter().any(|(p, _)| (f64::from(p[0]) - x).abs() <= x.abs() * 1e-6 && p[2] == NEAR), "{poly:?}"); + } + + #[test] + fn a_wide_near_plane_crossing_stays_on_its_edge() { + // Every corner has y = x / 2; x's difference overflows f32 and y's does not. Both + // components of each crossing take the same fraction, so the crossings keep y = x / 2. + let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; + let s = Scene { vertices: vec![v([3e38, 1.5e38, -1.0]), v([-3e38, -1.5e38, 1.0]), v([0.0, 0.0, NEAR])], ..Scene::default() }; + let poly = light_poly(&s, &identity_map(), [0, 1, 2]); + assert!(!poly.is_empty()); + for (p, _) in &poly { + let (x, y) = (f64::from(p[0]), f64::from(p[1])); + assert!(x.is_finite() && (y - x / 2.0).abs() <= x.abs() * 1e-6, "{poly:?}"); + } + } + + #[test] + fn a_wide_near_plane_crossing_keeps_uvs_on_its_edge() { + let v = |pos: [f32; 3], u: f32| Vertex { pos, uv: [u, 0.0], ..Vertex::default() }; + let s = Scene { + vertices: vec![v([-3e38, 0.0, -32768.0], -32768000.0), v([3e38, 0.0, 32768.0], 32768000.0), v([0.0, 0.0, NEAR], 0.0)], + ..Scene::default() + }; + for ids in [[0, 1, 2], [1, 0, 2]] { + let poly = light_poly(&s, &identity_map(), ids); + assert!(poly.iter().any(|(p, _)| p[2] == NEAR && p[0] != 0.0), "{poly:?}"); + for (p, uv) in &poly { + let implied_u = f64::from(p[0]) / f64::from(s.vertices[0].pos[0]) * f64::from(s.vertices[0].uv[0]); + assert!((f64::from(uv[0]) - implied_u).abs() <= implied_u.abs() * 1e-6, "{poly:?}"); + } + } + } + + fn identity_map() -> ShadowMap { + let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + ShadowMap { view, focal: 1.0, ortho: false, size: 8, offset: 0, bias: 0.0, radius: 0.0 } + } } From 4b9f322363c3d4ee0d733ff67273a48113ae526b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:54:19 -0800 Subject: [PATCH 29/33] platform: the macOS screen capture uses objc2-core-graphics in place of core-graphics2 core-graphics2 0.6.1, its latest release, depends on block 0.1.6, which the compiler reports as code that a future version of Rust will reject. The `screen` feature now takes Core Graphics from objc2-core-graphics 0.3, the objc2 family craft-platform already uses, and block and core-graphics2 leave Cargo.lock. The two calls that need `unsafe` (the active display list and an image's pixel bytes) are in a new craft-appkit module, `display`, with tests. The capture makes the same Core Graphics calls and checks as before. --- Cargo.lock | 25 +++-------- crates/appkit/Cargo.toml | 9 +++- crates/appkit/src/display.rs | 83 +++++++++++++++++++++++++++++++++++ crates/appkit/src/lib.rs | 6 ++- crates/platform/Cargo.toml | 8 +++- crates/platform/src/screen.rs | 62 ++++++++++++++------------ 6 files changed, 140 insertions(+), 53 deletions(-) create mode 100644 crates/appkit/src/display.rs diff --git a/Cargo.lock b/Cargo.lock index ea03712224..6e22c5f004 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -835,12 +835,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -1685,19 +1679,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -2056,6 +2037,8 @@ dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] @@ -3805,7 +3788,7 @@ dependencies = [ "async-process", "clipboard-win", "core-graphics", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -3817,6 +3800,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "rfd", "serde", diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index 5d451b3975..12f94f2e01 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers, Save panel calls and Core Graphics display calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -9,12 +9,19 @@ repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through # `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. +# The active display list and an image's pixel bytes from Core Graphics. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" objc2 = { version = "0.6.4", default-features = false, features = ["std"] } objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGImage"] } objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } +# A test image made from known bytes. +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"] } +objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGColorSpace", "CGDataProvider", "CGImage"] } + # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one # workspace lint. diff --git a/crates/appkit/src/display.rs b/crates/appkit/src/display.rs new file mode 100644 index 0000000000..39aa0da9b4 --- /dev/null +++ b/crates/appkit/src/display.rs @@ -0,0 +1,83 @@ +//! The Core Graphics display calls that need `unsafe`: listing the active displays, and reading an image's pixels +//! without copying them a second time. + +use objc2_core_graphics::{CGDataProvider, CGDirectDisplayID, CGError, CGGetActiveDisplayList, CGImage}; + +/// The largest `max` that [`active_displays`] accepts. +pub const MAX_DISPLAYS: usize = 1024; + +/// The IDs of the active displays, at most `max` of them, or `None` when `max` is above [`MAX_DISPLAYS`] or Core +/// Graphics reports an error. +pub fn active_displays(max: usize) -> Option> { + if max > MAX_DISPLAYS { + return None; + } + let capacity = u32::try_from(max).ok()?; + let mut ids: Vec = vec![0; max]; + let mut count = 0u32; + // SAFETY: `ids` holds `capacity` writable IDs and `count` is a writable `u32`. Core Graphics writes at most + // `capacity` IDs and the number it wrote. + let result = unsafe { CGGetActiveDisplayList(capacity, ids.as_mut_ptr(), &mut count) }; + if result != CGError::Success { + return None; + } + ids.truncate(usize::try_from(count).ok()?.min(max)); + Some(ids) +} + +/// Calls `read` with the bytes of `image`'s pixels, or returns `None` when the image has no data provider or the +/// provider gives no data. +pub fn with_image_bytes(image: &CGImage, read: impl FnOnce(&[u8]) -> R) -> Option { + let data = CGDataProvider::data(CGImage::data_provider(Some(image)).as_deref())?; + // SAFETY: `CGDataProviderCopyData` returns a new immutable `CFData` that this function holds until `read` + // returns, so nothing changes its bytes while the slice is borrowed. + Some(read(unsafe { data.as_bytes_unchecked() })) +} + +#[cfg(test)] +mod tests { + use objc2_core_foundation::CFData; + use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGImageAlphaInfo, CGMainDisplayID}; + + use super::*; + + /// The list holds the main display and no more IDs than asked for; a `max` above the limit is refused. + #[test] + fn active_displays_lists_the_main_display_within_max() { + let all = active_displays(MAX_DISPLAYS).unwrap_or_default(); + assert!(all.contains(&CGMainDisplayID()), "{all:?}"); + // 0 is `kCGNullDirectDisplay`: an ID Core Graphics did not write. + assert!(!all.contains(&0), "{all:?}"); + assert_eq!(active_displays(0), Some(Vec::new())); + assert_eq!(active_displays(1).map(|ids| ids.len()), Some(1)); + assert_eq!(active_displays(MAX_DISPLAYS + 1), None); + assert_eq!(active_displays(usize::MAX), None); + } + + /// The bytes passed on are the image's own pixel rows, row padding included. + #[test] + fn image_bytes_are_the_pixels_of_the_image() { + let pixels: Vec = (0u8..24).collect(); + let provider = CGDataProvider::with_cf_data(Some(&CFData::from_bytes(&pixels))).unwrap_or_else(|| panic!("no provider")); + let space = CGColorSpace::new_device_rgb().unwrap_or_else(|| panic!("no color space")); + // SAFETY: two rows of two RGBA pixels with 4 bytes of padding (12 bytes a row), 24 bytes in the provider, and a + // null decode array. + let image = unsafe { + CGImage::new( + 2, + 2, + 8, + 32, + 12, + Some(&space), + CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0), + Some(&provider), + std::ptr::null(), + false, + CGColorRenderingIntent::RenderingIntentDefault, + ) + } + .unwrap_or_else(|| panic!("no image")); + assert_eq!(with_image_bytes(&image, <[u8]>::to_vec), Some(pixels)); + } +} diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 70ed01f92d..23f548724d 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,6 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the -//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, the +//! Save panel calls in `save_panel`, and the Core Graphics display calls in `display`. macOS only; the crate is empty +//! elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +15,7 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod display; pub mod save_panel; /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml index 1316098830..ce3fd1079f 100644 --- a/crates/platform/Cargo.toml +++ b/crates/platform/Cargo.toml @@ -24,7 +24,7 @@ pointer = ["dep:core-graphics"] # `usage`: the process's memory use. usage = ["dep:sysinfo"] # Screen capture for the screen colour picker (`craft_platform::screen`). -screen = ["dep:zbus", "zbus?/blocking-api", "dep:futures-lite", "dep:async-io", "dep:x11rb", "dep:core-graphics2", "dep:xcap"] +screen = ["dep:zbus", "zbus?/blocking-api", "dep:futures-lite", "dep:async-io", "dep:x11rb", "dep:craft-appkit", "dep:objc2-core-graphics", "dep:objc2-core-foundation", "dep:xcap"] # `clipboard`: the clipboard handle with size limits, the synthetic-input fence, the paste probe, `EventClipboard` and `MemoryClipboard`; no system crates. clipboard = [] # `clipboard-system`: `SystemClipboard` over the OS: arboard, and the formats on offer asked of Windows, macOS, Wayland and X11. @@ -67,7 +67,11 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std # Apple Events behind a safe API, pinned exactly: review the diff before bumping. fmv-macos-events = { version = "=0.1.0", optional = true } core-graphics = { version = "0.23", optional = true } -core-graphics2 = { version = "=0.6.1", default-features = false, features = ["display", "window", "link"], optional = true } +# The screen capture: the display list and pixel bytes through craft-appkit's safe wrappers, the rest of Core +# Graphics from the objc2 family the AppKit crates use, and the display profile's bytes (`CFData::to_vec`). +craft-appkit = { workspace = true, optional = true } +objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "libc", "CGColorSpace", "CGDataProvider", "CGDirectDisplay", "CGDisplayConfiguration", "CGImage", "CGWindow"], optional = true } +objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"], optional = true } # Linux reads `/proc`; elsewhere `sysinfo` gives the system's available memory (MIT). [target.'cfg(any(target_os = "macos", windows))'.dependencies] diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 8a247ab446..88f03a68d0 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -494,60 +494,66 @@ mod backend { #[cfg(target_os = "macos")] mod backend { use super::{Arc, AtomicBool, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, checked_stride, pixel_count, unpack_rgba}; - use core_graphics2::{display::get_active_display_list, image::CGImageAlphaInfo as Alpha, window}; + use craft_appkit::display::{active_displays, with_image_bytes}; + use objc2_core_graphics::{ + CGColorSpace, CGDisplayBounds, CGDisplayCopyDisplayMode, CGDisplayIsMain, CGDisplayMode, CGImage, CGImageAlphaInfo as Alpha, + CGPreflightScreenCaptureAccess, CGRequestScreenCaptureAccess, CGWindowImageOption, CGWindowListOption, kCGNullWindowID, + }; /// Captures each display's composed image at native resolution. Without the Screen Recording /// permission the system prompt is shown once; a refusal is `Denied`. pub fn capture(stop: &AtomicBool) -> Result, ScreenError> { let failed = |m: &str| ScreenError::Failed(m.into()); - if !window::preflight_screen_capture_access() && !window::request_screen_capture_access() { + if !CGPreflightScreenCaptureAccess() && !CGRequestScreenCaptureAccess() { return Err(ScreenError::Denied); } - let mut displays = get_active_display_list(MAX_MONITORS + 1).ok_or_else(|| failed("could not enumerate the displays"))?; + let mut displays = active_displays(MAX_MONITORS + 1).ok_or_else(|| failed("could not enumerate the displays"))?; if displays.is_empty() || displays.len() > MAX_MONITORS { return Err(failed("no supported screen is available")); } - displays.sort_by_key(|d| !d.is_main()); + displays.sort_by_key(|&d| !CGDisplayIsMain(d)); let mut total = 0usize; - for display in &displays { - let mode = display.copy_display_mode().ok_or_else(|| failed("the display mode is unavailable"))?; - total = add_to_budget(total, mode.pixel_width(), mode.pixel_height())?; + for &display in &displays { + let mode = CGDisplayCopyDisplayMode(display).ok_or_else(|| failed("the display mode is unavailable"))?; + total = add_to_budget(total, CGDisplayMode::pixel_width(Some(&mode)), CGDisplayMode::pixel_height(Some(&mode)))?; } let mut images = Vec::new(); for (n, display) in displays.into_iter().enumerate() { if stop.load(Ordering::Relaxed) { return Err(ScreenError::Cancelled); } - let bounds = display.bounds(); + let bounds = CGDisplayBounds(display); let (w, h) = (bounds.size.width, bounds.size.height); let (x, y) = (bounds.origin.x, bounds.origin.y); if ![w, h, x, y].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { return Err(failed("invalid display geometry")); } - let image = window::new_image( + #[allow(deprecated, reason = "deprecated in favor of ScreenCaptureKit")] + let retained = objc2_core_graphics::CGWindowListCreateImage( bounds, - window::CGWindowListOption::OnScreenOnly, - window::kCGNullWindowID, - window::CGWindowImageOption::BestResolution | window::CGWindowImageOption::ShouldBeOpaque, + CGWindowListOption::OptionOnScreenOnly, + kCGNullWindowID, + CGWindowImageOption::BestResolution | CGWindowImageOption::ShouldBeOpaque, ) .ok_or(ScreenError::Denied)?; - let (width, height) = (image.width(), image.height()); + let image = Some(&*retained); + let (width, height) = (CGImage::width(image), CGImage::height(image)); pixel_count(width, height)?; - let profile = image.color_space().and_then(|space| space.copy_icc_data()); + let profile = CGColorSpace::icc_data(CGImage::color_space(image).as_deref()); if profile.as_ref().is_some_and(|p| p.len() > 1024 * 1024) { return Err(failed("the display profile exceeds the memory budget")); } - let info = image.bitmap_info().bits(); - if image.bits_per_component() != 8 || image.bits_per_pixel() != 32 || info & (1 << 8) != 0 { + let info = CGImage::bitmap_info(image).0; + if CGImage::bits_per_component(image) != 8 || CGImage::bits_per_pixel(image) != 32 || info & (1 << 8) != 0 { return Err(failed("unsupported screen capture pixel format")); } - let (first, premultiplied, opaque) = match image.alpha_info() { - Alpha::AlphaPremultipliedFirst => (true, true, false), - Alpha::AlphaPremultipliedLast => (false, true, false), - Alpha::AlphaFirst => (true, false, false), - Alpha::AlphaLast => (false, false, false), - Alpha::AlphaNoneSkipFirst => (true, false, true), - Alpha::AlphaNoneSkipLast => (false, false, true), + let (first, premultiplied, opaque) = match CGImage::alpha_info(image) { + Alpha::PremultipliedFirst => (true, true, false), + Alpha::PremultipliedLast => (false, true, false), + Alpha::First => (true, false, false), + Alpha::Last => (false, false, false), + Alpha::NoneSkipFirst => (true, false, true), + Alpha::NoneSkipLast => (false, false, true), _ => return Err(failed("unsupported screen capture alpha layout")), }; let little = match info & 0x7000 { @@ -562,18 +568,18 @@ mod backend { (false, true) => [3, 2, 1, 0], (false, false) => [0, 1, 2, 3], }; - let stride = image.bytes_per_row(); + let stride = CGImage::bytes_per_row(image); checked_stride(width, height, stride)?; - let bytes = image.data_provider().and_then(|p| p.copy_data()).ok_or_else(|| failed("the screen image has no pixels"))?; - let rgba = unpack_rgba(bytes.bytes(), width, height, stride, order, premultiplied, opaque)?; + let rgba = with_image_bytes(&retained, |bytes| unpack_rgba(bytes, width, height, stride, order, premultiplied, opaque)) + .ok_or_else(|| failed("the screen image has no pixels"))??; let scale = width as f32 / w as f32; images.push(ScreenImage { origin: [(x as f32 * scale).round() as i32, (y as f32 * scale).round() as i32], size: [width as u32, height as u32], scale, rgba: Arc::new(rgba), - icc_profile: profile.map(|p| Arc::new(p.bytes().to_vec())), - name: if display.is_main() { "Main Display".into() } else { format!("Display {}", n + 1) }, + icc_profile: profile.map(|p| Arc::new(p.to_vec())), + name: if CGDisplayIsMain(display) { "Main Display".into() } else { format!("Display {}", n + 1) }, }); } Ok(images) From 72ac710eebc03c89d93e6c75595c2a8acf0535d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:54:29 -0800 Subject: [PATCH 30/33] craft-raster3d: perspective shadow casters edge-on to the light write no texels A caster whose plane passes through the light covers no shadow texels, but when a position difference overflows f32 its clipped corners can come apart and write depths. light_poly now drops such a caster before clipping, after the cheap check for a caster wholly behind the near plane. The test is exact: an error-bounded f64 determinant settles most casters, and the rest take an expansion sum of exact two-product parts, so a caster whose rounded determinant is zero is kept in every corner order. The clipping fixtures that were themselves edge-on now move one corner off the plane through the light and keep their original crossings. --- crates/raster3d/src/shadow.rs | 105 ++++++++++++++++++++++++++++++++-- 1 file changed, 99 insertions(+), 6 deletions(-) diff --git a/crates/raster3d/src/shadow.rs b/crates/raster3d/src/shadow.rs index 9048e236a3..c9380e9242 100644 --- a/crates/raster3d/src/shadow.rs +++ b/crates/raster3d/src/shadow.rs @@ -24,6 +24,51 @@ fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] } +/// Whether the plane through the finite `f32` corners `p` passes exactly through the origin. +/// Every product of two `f32` values is exact in `f64`, and `two_product` splits each +/// three-factor term into an exact pair, so the expansion sum gives the determinant's exact sign. +fn passes_through_origin(p: [[f32; 3]; 3]) -> bool { + let [a, b, c] = p.map(|v| v.map(f64::from)); + let fast = dot3(a, cross3(b, c)); + let permanent = [(0, 1, 2), (1, 2, 0), (2, 0, 1)].iter().map(|&(i, j, k)| a[i].abs() * ((b[j] * c[k]).abs() + (b[k] * c[j]).abs())).sum::(); + if fast.abs() > 8.0 * f64::EPSILON * permanent { + return false; + } + let two_product = |x: f64, y: f64| { + let p = x * y; + (p, x.mul_add(y, -p)) + }; + // Twelve exact parts; the expansion never holds more components than parts added. + let mut expansion = [0.0_f64; 12]; + let mut len = 0; + for (i, j, k) in [(0, 1, 2), (1, 2, 0), (2, 0, 1)] { + for (s, bc) in [(1.0, b[j] * c[k]), (-1.0, b[k] * c[j])] { + let (hi, lo) = two_product(s * a[i], bc); + for x in [lo, hi] { + let mut q = x; + let mut kept = 0; + for n in 0..len { + let h = expansion[n]; + let sum = q + h; + let bv = sum - q; + let err = (q - (sum - bv)) + (h - bv); + if err != 0.0 { + expansion[kept] = err; + kept += 1; + } + q = sum; + } + if q != 0.0 { + expansion[kept] = q; + kept += 1; + } + len = kept; + } + } + } + len == 0 +} + fn len3(a: [f64; 3]) -> f64 { dot3(a, a).sqrt() } @@ -93,6 +138,15 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec { .collect(); let mut poly = q; if !m.ortho { + // A caster edge-on to the light covers no texels. Its clipped corners can still come + // apart when a position difference overflows, so it is dropped before clipping. + let corners = [0, 1, 2].map(|i| poly[i].0); + if corners.iter().all(|c| c[2] < NEAR) { + return vec![]; + } + if corners.iter().flatten().all(|c| c.is_finite()) && passes_through_origin(corners) { + return vec![]; + } let mut out = vec![]; for i in 0..poly.len() { let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); @@ -627,6 +681,42 @@ mod tests { } } + #[test] + fn edge_on_perspective_casters_with_overflowing_differences_write_no_texels() { + let a = 2.0_f32.powi(127); + for indices in [vec![0, 1, 2], vec![0, 2, 1]] { + let s = Scene { + vertices: [[-a, -0.75 * a, -32768.0], [a, 0.75 * a, 32768.0], [0.0, 0.0, NEAR]] + .map(|pos| Vertex { pos, ..Vertex::default() }) + .to_vec(), + indices, + materials: vec![Material::default()], + ..Scene::default() + }; + let depths = shadow_raster(&s, &perspective_map(), &[0]); + assert!(depths.iter().all(|&depth| depth == f32::INFINITY)); + } + } + + #[test] + fn the_edge_on_test_keeps_the_rounding_residual_of_each_product() { + // Each three-factor term needs more than 53 bits; the rounded terms sum to -2048. + let (a, b) = ([1_000_008.0, 2_000_007.0, 3_000_002.0], [3_000_005.0, 2_000_007.0, 1_000_004.0]); + let c = [0, 1, 2].map(|i| a[i] + b[i]); + assert!(super::passes_through_origin([a, b, c])); + assert!(!super::passes_through_origin([a, b, [c[0], c[1], c[2] + 1.0]])); + } + + #[test] + fn casters_whose_rounded_determinant_is_zero_are_kept_in_every_corner_order() { + let x = 2.0_f32.powi(48); + let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; + let s = Scene { vertices: vec![v([-x, -NEAR, -x]), v([x, -NEAR, x]), v([0.0, NEAR, NEAR])], ..Scene::default() }; + for ids in [[0, 1, 2], [1, 2, 0], [2, 0, 1], [0, 2, 1]] { + assert!(!light_poly(&s, &identity_map(), ids).is_empty(), "{ids:?}"); + } + } + #[test] fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() { for z in [1e38, f32::MAX] { @@ -699,7 +789,7 @@ mod tests { // 3e38 − (−3e38) overflows f32; the edge crosses the near plane near x = 3e35. An `f32` // fraction puts the crossing about 1.4e31 off the edge's own crossing. let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; - let (a, b) = ([-3e38_f32, 0.0, -1.0], [3e38_f32, 0.0, 1.0]); + let (a, b) = ([-3e38_f32, 0.0, -1.0], [3e38_f32, 1.0, 1.0]); let s = Scene { vertices: vec![v(a), v(b), v([0.0, 0.1, 1.0])], ..Scene::default() }; let poly = light_poly(&s, &identity_map(), [0, 1, 2]); assert!(!poly.is_empty()); @@ -713,14 +803,17 @@ mod tests { #[test] fn a_wide_near_plane_crossing_stays_on_its_edge() { - // Every corner has y = x / 2; x's difference overflows f32 and y's does not. Both - // components of each crossing take the same fraction, so the crossings keep y = x / 2. + // The wide edge has y = x / 2; x's difference overflows f32 and y's does not. + // Both components of its near-plane crossing take the same fraction. let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; - let s = Scene { vertices: vec![v([3e38, 1.5e38, -1.0]), v([-3e38, -1.5e38, 1.0]), v([0.0, 0.0, NEAR])], ..Scene::default() }; + let s = Scene { vertices: vec![v([3e38, 1.5e38, -1.0]), v([-3e38, -1.5e38, 1.0 + f32::EPSILON]), v([0.0, 1.0, NEAR])], ..Scene::default() }; let poly = light_poly(&s, &identity_map(), [0, 1, 2]); - assert!(!poly.is_empty()); + assert!(poly.iter().any(|(p, _)| p[2] == NEAR && p[0] != 0.0), "{poly:?}"); for (p, _) in &poly { let (x, y) = (f64::from(p[0]), f64::from(p[1])); + if x == 0.0 { + continue; + } assert!(x.is_finite() && (y - x / 2.0).abs() <= x.abs() * 1e-6, "{poly:?}"); } } @@ -729,7 +822,7 @@ mod tests { fn a_wide_near_plane_crossing_keeps_uvs_on_its_edge() { let v = |pos: [f32; 3], u: f32| Vertex { pos, uv: [u, 0.0], ..Vertex::default() }; let s = Scene { - vertices: vec![v([-3e38, 0.0, -32768.0], -32768000.0), v([3e38, 0.0, 32768.0], 32768000.0), v([0.0, 0.0, NEAR], 0.0)], + vertices: vec![v([-3e38, 0.0, -32768.0], -32768000.0), v([3e38, 1.0, 32768.0], 32768000.0), v([0.0, 1.0, NEAR], 0.0)], ..Scene::default() }; for ids in [[0, 1, 2], [1, 0, 2]] { From 839ff945b4ff71961c37bc8dcfe4c643d450abe6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:02:47 -0800 Subject: [PATCH 31/33] ui-widgets list rows: ThumbSize::Custom, a row height in whole points from 12 to 100 ThumbSize::Custom(ThumbPoints) sets a list row's height in whole points. The row's square thumbnail is the row less the thumbnail padding, and the row is never shorter than its label's line. ThumbPoints clamps a value to 12..=100 when it is made and when a saved setting is read. A picture or tile of this size is that many points on a side. The named sizes keep their rows. ThumbSize::label names it "Custom". LayersOptions::thumbnail_size takes the custom size, and the Layers panel's rows draw at it. The options dialog still offers the named sizes only and keeps a custom size while none of them is picked. --- crates/layers/src/ui/options/mod.rs | 7 +- crates/layers/tests/it/main.rs | 1 + crates/layers/tests/it/options.rs | 62 +++++++++++++++++ crates/ui-widgets/src/list/mod.rs | 4 +- crates/ui-widgets/src/list/row.rs | 2 +- crates/ui-widgets/src/list/row/placement.rs | 16 +++-- crates/ui-widgets/src/list/row/thumb.rs | 58 +++++++++++++++- crates/ui-widgets/src/list/words.rs | 1 + crates/ui-widgets/tests/it/list.rs | 73 +++++++++++++++++++++ 9 files changed, 212 insertions(+), 12 deletions(-) create mode 100644 crates/layers/tests/it/options.rs diff --git a/crates/layers/src/ui/options/mod.rs b/crates/layers/src/ui/options/mod.rs index 6169c156a5..02c31d6b05 100644 --- a/crates/layers/src/ui/options/mod.rs +++ b/crates/layers/src/ui/options/mod.rs @@ -43,8 +43,11 @@ impl Default for LayersSettings { #[serde(default)] #[non_exhaustive] pub struct LayersOptions { - /// Thumbnail Size: [`ThumbSize::None`], `Small`, `Medium` (default) or `Large`; the row - /// height follows the size's `size.thumb.*` token. + /// Thumbnail Size: [`ThumbSize::None`], `Small`, `Medium` (default) or `Large`, whose row + /// height follows the size's `size.thumb.*` token, or [`ThumbSize::Custom`], a row height + /// the app sets in whole points (see [`ThumbPoints`](craft_ui::list::ThumbPoints) for the + /// range). The dialog's radio group offers the named sizes; it keeps a custom size while none + /// of them is picked. pub thumbnail_size: ThumbSize, /// Thumbnail Contents: Layer Bounds or Entire Document (default). The panel menu's Clip /// Thumbnails to Layer Bounds is the same setting; it is part of every diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index 36c2b8fa5b..34bec3e752 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -2,6 +2,7 @@ pub(crate) mod blend_rows; pub(crate) mod comps; +pub(crate) mod options; pub(crate) mod panel_drag_menu; pub(crate) mod panel_eye; pub(crate) mod panel_filter; diff --git a/crates/layers/tests/it/options.rs b/crates/layers/tests/it/options.rs new file mode 100644 index 0000000000..d0e2f71312 --- /dev/null +++ b/crates/layers/tests/it/options.rs @@ -0,0 +1,62 @@ +//! Layers Panel Options with a custom thumbnail size: the saved section keeps it, a saved size outside the range reads +//! back clamped, and the panel's rows take it as their height. + +use craft_layers::testing; +use craft_layers::ui::mock::FakeLayers; +use craft_layers::ui::options::LayersSettings; +use craft_layers::ui::panel::LayersPanel; +use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart}; +use craft_ui::contract::Tracked; +use craft_ui::list::{ThumbPoints, ThumbSize}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Rect, Vec2}; + +/// The panel's room: wide enough for a row's parts and inside the 800 by 600 screen of a fixture. +const PANEL: Vec2 = Vec2::new(420.0, 560.0); + +/// The settings with a custom thumbnail size of `points`. +fn custom(points: u16) -> LayersSettings { + let mut settings = LayersSettings::default(); + settings.options.thumbnail_size = ThumbSize::Custom(ThumbPoints::new(points)); + settings +} + +/// A saved section keeps a custom thumbnail size, and one saved outside the range reads back clamped into it. +#[trial] +fn a_custom_thumbnail_size_round_trips_through_the_saved_section() { + let settings = custom(48); + let saved = serde_json::to_string(&settings).expect("the section saves"); + let read: LayersSettings = serde_json::from_str(&saved).expect("the section reads back"); + assert_eq!(read, settings, "the custom size reads back as saved: {saved}"); + let mut too_large = serde_json::to_value(&settings).expect("the section saves"); + too_large["options"]["thumbnail_size"]["Custom"] = serde_json::Value::from(u16::MAX); + let clamped: LayersSettings = serde_json::from_value(too_large).expect("a size outside the range still reads"); + assert_eq!(clamped.options.thumbnail_size, ThumbSize::Custom(ThumbPoints::new(ThumbPoints::MAX)), "the size is clamped"); +} + +/// The rect of the Background row and of its thumbnail in a panel whose settings are `settings`. +fn background(settings: LayersSettings) -> (Rect, Rect) { + let info = LayerInfo::new("Background", LayerKind::Pixel); + let mut tree = FakeLayers::default(); + tree.add(None, info.clone(), false); + let tree = Tracked::new(tree); + let mut fixture = Fixture::new(move |ui| { + let _ = LayersPanel::new(&tree).settings(&settings).show(ui); + }); + fixture.room(PANEL); + fixture.settle(); + let row = fixture.by_label("Background").expect("the layer's row"); + let thumb = testing::thumb_rect(fixture.ctx(), row.node.into(), &info, LayerPart::Pixels).expect("the layer's thumbnail"); + (row.rect, thumb) +} + +/// The panel's rows take a custom thumbnail size as their height, and their thumbnails grow with it. +#[trial] +fn the_panel_rows_take_a_custom_thumbnail_size() { + let (short, tall) = (ThumbPoints::new(30), ThumbPoints::new(72)); + let (row, thumb) = background(custom(short.get())); + let (taller, larger) = background(custom(tall.get())); + assert_eq!(row.height(), f32::from(short.get()), "the row is as high as the size: {row:?}"); + assert_eq!(taller.height(), f32::from(tall.get()), "the row is as high as the size: {taller:?}"); + assert_eq!(larger.height() - thumb.height(), taller.height() - row.height(), "the thumbnail grows with the row: {thumb:?} {larger:?}"); +} diff --git a/crates/ui-widgets/src/list/mod.rs b/crates/ui-widgets/src/list/mod.rs index dc9292eae0..3f62a45a6a 100644 --- a/crates/ui-widgets/src/list/mod.rs +++ b/crates/ui-widgets/src/list/mod.rs @@ -22,8 +22,8 @@ pub use predicate::{DropTest, RowTest, RowText}; pub(crate) use row::RowThumb; pub use row::{ CellStatus, CommandHighlight, HueTarget, LabelUnderline, ListRow, ListRowStyle, RowDragSpot, RowEvent, RowInk, RowLines, RowOutput, RowRun, - RowStyleCx, ThumbAspect, ThumbPaint, ThumbRows, ThumbSize, ThumbTarget, ThumbTargets, TrailingFace, TrailingPart, TreeIndent, TreeLeaves, - label_color_label, tree_steps, + RowStyleCx, ThumbAspect, ThumbPaint, ThumbPoints, ThumbRows, ThumbSize, ThumbTarget, ThumbTargets, TrailingFace, TrailingPart, TreeIndent, + TreeLeaves, label_color_label, tree_steps, }; pub use toggle::{ToggleCell, ToggleFace, ToggleState}; pub use tree::OpenSet; diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index 6205b09228..f125520310 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -45,7 +45,7 @@ pub use style::{CommandHighlight, ListRowStyle, RowStyleCx, ThumbRows, TreeInden pub(crate) use thumb::RowThumb; pub(super) use thumb::Thumb; use thumb::ThumbPayload; -pub use thumb::{ThumbAspect, ThumbPaint, ThumbSize, ThumbTarget, ThumbTargets}; +pub use thumb::{ThumbAspect, ThumbPaint, ThumbPoints, ThumbSize, ThumbTarget, ThumbTargets}; use trailing::Hosted; pub(super) use trailing::{Trailing, TrailingItem}; pub use trailing::{TrailingFace, TrailingPart}; diff --git a/crates/ui-widgets/src/list/row/placement.rs b/crates/ui-widgets/src/list/row/placement.rs index bb3cbe3d76..7dbd25c675 100644 --- a/crates/ui-widgets/src/list/row/placement.rs +++ b/crates/ui-widgets/src/list/row/placement.rs @@ -92,16 +92,22 @@ impl Sizes { (cell - 2.0 * self.cell_inset).max(0.0) } + /// The thumbnail side of `thumb`: a token side, or for a custom size the entered height less the padding. fn side(&self, thumb: ThumbSize) -> f32 { - thumb.pick(self.thumbs) + match thumb { + ThumbSize::Custom(points) => (points.length() - self.thumb_pad).max(0.0), + _ => thumb.pick(self.thumbs), + } } /// The height of a row with a thumbnail of `thumb` and, if `detail`, a detail line: the row height, the thumbnail - /// with its padding (at least `thumb_row`), or the two lines of text, whichever is tallest. + /// with its padding (at least `thumb_row`), or the two lines of text, whichever is tallest. A custom size is the + /// row's height itself, at least the label's line. pub(super) fn height(&self, thumb: ThumbSize, detail: bool) -> f32 { - let base = match self.side(thumb) { - 0.0 => self.row, - side => (side + self.thumb_pad).max(self.thumb_row), + let base = match (thumb, self.side(thumb)) { + (ThumbSize::Custom(points), _) => points.length().max(self.label_line), + (_, 0.0) => self.row, + (_, side) => (side + self.thumb_pad).max(self.thumb_row), }; if detail { base.max(self.label_line + self.detail_line + self.gap) } else { base } } diff --git a/crates/ui-widgets/src/list/row/thumb.rs b/crates/ui-widgets/src/list/row/thumb.rs index 2000ad8dd9..745e50fbd3 100644 --- a/crates/ui-widgets/src/list/row/thumb.rs +++ b/crates/ui-widgets/src/list/row/thumb.rs @@ -47,19 +47,24 @@ pub enum ThumbSize { Medium, /// `size.thumb.lg`. Large, + /// A size the user enters: a list row is that many points high and its thumbnail is the row less the thumbnail + /// padding; a picture or a tile of this size is that many points on a side. + Custom(ThumbPoints), } impl ThumbSize { - /// Every setting a user picks from. + /// Every named setting a user picks from; [`ThumbSize::Custom`] is entered as a number instead. pub const ALL: [ThumbSize; 4] = [ThumbSize::None, ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large]; - /// The side the setting takes from the small, medium and large sides; 0 for `None`. + /// The side the setting takes from the small, medium and large sides; 0 for `None`, the entered points for + /// `Custom`. pub(crate) const fn pick(self, sides: [f32; 3]) -> f32 { match self { ThumbSize::None => 0.0, ThumbSize::Small => sides[0], ThumbSize::Medium => sides[1], ThumbSize::Large => sides[2], + ThumbSize::Custom(points) => points.length(), } } @@ -70,10 +75,59 @@ impl ThumbSize { ThumbSize::Small => words.thumb_small.clone(), ThumbSize::Medium => words.thumb_medium.clone(), ThumbSize::Large => words.thumb_large.clone(), + ThumbSize::Custom(_) => words.thumb_custom.clone(), } } } +/// The size of [`ThumbSize::Custom`]: whole points from [`ThumbPoints::MIN`] to [`ThumbPoints::MAX`]. A value outside +/// that range is clamped into it, both by [`ThumbPoints::new`] and when a saved setting is read, so a row is never +/// drawn at a size outside it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[serde(from = "u16", into = "u16")] +pub struct ThumbPoints(u16); + +impl ThumbPoints { + /// The smallest size, in points. + pub const MIN: u16 = 12; + /// The largest size, in points. + pub const MAX: u16 = 100; + + /// `points` whole points, clamped to `MIN..=MAX`. + pub const fn new(points: u16) -> Self { + Self(if points < Self::MIN { + Self::MIN + } else if points > Self::MAX { + Self::MAX + } else { + points + }) + } + + /// The size in whole points. + pub const fn get(self) -> u16 { + self.0 + } + + /// The size as a length in points. + pub(crate) const fn length(self) -> f32 { + self.0 as f32 + } +} + +impl From for ThumbPoints { + /// [`ThumbPoints::new`]: clamped to `MIN..=MAX`. + fn from(points: u16) -> Self { + Self::new(points) + } +} + +impl From for u16 { + fn from(points: ThumbPoints) -> Self { + points.get() + } +} + /// One of a row's thumbnails. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] diff --git a/crates/ui-widgets/src/list/words.rs b/crates/ui-widgets/src/list/words.rs index ec079593c3..7f5ecb6bf1 100644 --- a/crates/ui-widgets/src/list/words.rs +++ b/crates/ui-widgets/src/list/words.rs @@ -9,6 +9,7 @@ craft_ui::words! { thumb_small: "thumbSize.small" = "Small"; thumb_medium: "thumbSize.medium" = "Medium"; thumb_large: "thumbSize.large" = "Large"; + thumb_custom: "thumbSize.custom" = "Custom"; toggle_visibility: "toggleCell.visibility" = "Visibility {row}"; toggle_lock: "toggleCell.lock" = "Lock {row}"; label_none: "list.labelNone" = "None"; diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 99a82c7d7a..9cea57d438 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -248,6 +248,79 @@ fn text_rows_are_shorter_than_control_rows() { assert!(text[2].top() - text[0].top() < control[2].top() - control[0].top(), "text rows follow each other closer"); } +/// The rect of a list row with a thumbnail of `size` and the thumbnail's rect (the rect it paints into, inside its +/// frame), with the tokens' small, medium and large thumbnail sides, the thumbnail padding and a thumbnail row's least +/// height. +fn thumb_row(size: craft_ui::list::ThumbSize) -> (egui::Rect, egui::Rect, [f32; 3], f32, f32) { + use craft_ui::runtime::env::Env; + use std::cell::Cell; + let painted = Rc::new(Cell::new(egui::Rect::NOTHING)); + let read = Rc::new(Cell::new(([0.0_f32; 3], 0.0_f32, 0.0_f32, 0.0_f32))); + let (held, tokens) = (painted.clone(), read.clone()); + let mut fixture = Fixture::new(move |ui| { + let env = Env::of(ui); + let all = env.tokens.tokens(); + let thumb = &all.size.thumb; + let least = all.size.control.md + all.space.pad.regular; + tokens.set(([thumb.sm, thumb.md, thumb.lg], all.space.gap.stack, least, all.stroke.thin)); + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + let _ = List::new("Layers").show_items(ui, &source, &mut |key, _| { + let held = held.clone(); + ListRow::new(NAMES[*key]).thumb(size, move |_, rect| held.set(rect)) + }); + }); + fixture.room(Vec2::new(300.0, 400.0)); + fixture.settle(); + let row = fixture.by_label(NAMES[0]).expect("the row's node").rect; + let (sides, pad, least, frame) = read.get(); + (row, painted.get().expand(frame), sides, pad, least) +} + +/// A custom thumbnail size is the row's height, and the row's square thumbnail grows with it point for point. +#[trial] +fn a_custom_thumbnail_size_sets_the_row_height_and_its_thumbnail() { + use craft_ui::list::{ThumbPoints, ThumbSize}; + let (small, large) = (ThumbPoints::new(40), ThumbPoints::new(64)); + let (row, thumb, ..) = thumb_row(ThumbSize::Custom(small)); + let (taller, larger, ..) = thumb_row(ThumbSize::Custom(large)); + assert_eq!(row.height(), f32::from(small.get()), "the row is as high as its size: {row:?}"); + assert_eq!(taller.height(), f32::from(large.get()), "the row is as high as its size: {taller:?}"); + assert!(row.contains_rect(thumb) && thumb.height() < row.height(), "the thumbnail lies inside its row: {row:?} {thumb:?}"); + assert_eq!(thumb.width(), thumb.height(), "the thumbnail is square: {thumb:?}"); + assert_eq!(larger.height() - thumb.height(), taller.height() - row.height(), "the thumbnail grows as the row does: {thumb:?} {larger:?}"); +} + +/// A custom thumbnail size outside its range is clamped into it, so a row is drawn at the nearest size it takes. +#[trial] +fn a_custom_thumbnail_size_is_clamped_to_its_range() { + use craft_ui::list::{ThumbPoints, ThumbSize}; + assert_eq!(ThumbPoints::new(0).get(), ThumbPoints::MIN, "below the range is the least size"); + assert_eq!(ThumbPoints::from(u16::MAX).get(), ThumbPoints::MAX, "above the range is the largest size"); + let (least, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(1))); + let (most, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(u16::MAX))); + assert_eq!(most.height(), f32::from(ThumbPoints::MAX), "the tallest row is the largest size: {most:?}"); + let (at_least, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(ThumbPoints::MIN))); + assert_eq!(least.height(), at_least.height(), "a size below the range draws as the least size: {least:?}"); + let (small, ..) = thumb_row(ThumbSize::Small); + assert!(least.height() < small.height(), "the least size is shorter than a small thumbnail's row: {least:?} {small:?}"); +} + +/// The named thumbnail sizes keep their rows: without a thumbnail a row is a plain row's height, and with one it is the +/// token side with the thumbnail padding, at least a thumbnail row's least height. +#[trial] +fn the_named_thumbnail_sizes_keep_their_row_heights() { + use craft_ui::list::ThumbSize; + let plain = row_rects(RowHeight::Control)[0]; + let (none, ..) = thumb_row(ThumbSize::None); + assert_eq!(none.height(), plain.height(), "no thumbnail keeps a plain row: {none:?} {plain:?}"); + for (at, size) in [ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large].into_iter().enumerate() { + let (row, thumb, sides, pad, least) = thumb_row(size); + assert_eq!(row.height(), (sides[at] + pad).max(least), "{size:?} keeps its row height: {row:?}"); + assert_eq!(thumb.height(), sides[at], "{size:?} keeps its token side: {thumb:?}"); + } +} + /// The text the rename field of `row` opens with. fn opened_with(draft: fn(&usize) -> Option, row: usize) -> Option { let (mut fixture, seen) = rig(draft); From 3c7dbc8a57f5d77eefe945224476cb0943c15772 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:19:35 -0800 Subject: [PATCH 32/33] platform: the crash hook tests run in their own process `cargo test -p craft-platform --lib` failed one of the two `logs::crash` tests on most runs. The panic hook and the last-panic slot are process-wide, and `cargo test` runs the binary's tests on parallel threads, so the panic in `logs_tests::a_poisoned_sink_still_logs` (`poison the sink`) replaced the trial's own panic in `take_last`. Each crash test now runs its body in a child process of the test binary that runs only that test (`--exact`), and fails when the child fails or did not run it. The serial lock between the two tests is removed. --- crates/platform/src/logs/crash_tests.rs | 132 ++++++++++++++---------- 1 file changed, 78 insertions(+), 54 deletions(-) diff --git a/crates/platform/src/logs/crash_tests.rs b/crates/platform/src/logs/crash_tests.rs index 6467b067c5..e6128370d2 100644 --- a/crates/platform/src/logs/crash_tests.rs +++ b/crates/platform/src/logs/crash_tests.rs @@ -1,34 +1,57 @@ //! Behaviour tests of `logs::crash`. +#![allow(clippy::expect_used, reason = "tests fail by panicking")] use super::*; -/// The hook, its crash log directory and the last-panic slot are process-wide; trials that -/// install and panic take turns. +/// Runs `body` in a child process of this test binary that runs only the trial `trial`, and +/// fails when the child fails or did not run it. +/// +/// The hook, its crash log directory and the last-panic slot are process-wide, and `cargo test` +/// runs a binary's tests on parallel threads, so a panic in any other test of the binary would +/// land in the trial's report. #[cfg(not(target_arch = "wasm32"))] -fn serial() -> MutexGuard<'static, ()> { - static SERIAL: Mutex<()> = Mutex::new(()); - lock(&SERIAL) +fn alone(trial: &str, body: fn()) { + const DONE: &str = "CRAFT_CRASH_TRIAL_DONE"; + if let Some(done) = std::env::var_os(DONE) { + body(); + std::fs::write(done, trial).expect("mark the trial done"); + return; + } + let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path); + let name = format!("{module}::{trial}"); + let done = std::env::temp_dir().join(format!("craft-crash-done-{trial}-{}", std::process::id())); + let _ = std::fs::remove_file(&done); + let out = std::process::Command::new(std::env::current_exe().expect("the test binary")) + .args(["--exact", &name, "--test-threads=1", "--nocapture"]) + .env(DONE, &done) + .output() + .expect("run the trial"); + let report = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "{name} failed in its own process:\n{report}"); + assert_eq!(std::fs::read_to_string(&done).ok().as_deref(), Some(trial), "the child ran {name}:\n{report}"); + let _ = std::fs::remove_file(&done); } // A panic on a named worker thread is kept for take_last with its message and thread, and appended to the crash log. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_worker_panic_is_kept_and_written_to_the_crash_log() { - let _serial = serial(); - let dir = std::env::temp_dir().join(format!("craft-crash-{}", std::process::id())); - install("CrashTest", "1.2.3", Some(dir.clone())); - let _ = take_last(); - let joined = std::thread::Builder::new().name("crash-test-worker".into()).spawn(|| panic!("boom in a worker")).expect("spawn").join(); - assert!(joined.is_err()); - let last = take_last().expect("the hook kept the panic"); - assert!(last.contains("boom in a worker") && last.contains("thread crash-test-worker"), "{last}"); - assert!(take_last().is_none(), "take_last empties the slot"); - let path = log_path().expect("crash log path"); - assert_eq!(path.parent(), Some(dir.as_path())); - let log = std::fs::read_to_string(&path).expect("crash log"); - assert!(log.contains("=== CrashTest 1.2.3 (unix ") && log.contains("boom in a worker"), "{log}"); - record("window could not be created"); - assert!(std::fs::read_to_string(&path).expect("crash log").contains("window could not be created")); - let _ = std::fs::remove_dir_all(dir); + alone("a_worker_panic_is_kept_and_written_to_the_crash_log", || { + let dir = std::env::temp_dir().join(format!("craft-crash-{}", std::process::id())); + install("CrashTest", "1.2.3", Some(dir.clone())); + let _ = take_last(); + let joined = std::thread::Builder::new().name("crash-test-worker".into()).spawn(|| panic!("boom in a worker")).expect("spawn").join(); + assert!(joined.is_err()); + let last = take_last().expect("the hook kept the panic"); + assert!(last.contains("boom in a worker") && last.contains("thread crash-test-worker"), "{last}"); + assert!(take_last().is_none(), "take_last empties the slot"); + let path = log_path().expect("crash log path"); + assert_eq!(path.parent(), Some(dir.as_path())); + let log = std::fs::read_to_string(&path).expect("crash log"); + assert!(log.contains("=== CrashTest 1.2.3 (unix ") && log.contains("boom in a worker"), "{log}"); + record("window could not be created"); + assert!(std::fs::read_to_string(&path).expect("crash log").contains("window could not be created")); + let _ = std::fs::remove_dir_all(dir); + }); } // Text a panic quotes between backticks (std quotes the string it was slicing, which can be the @@ -38,38 +61,39 @@ fn a_worker_panic_is_kept_and_written_to_the_crash_log() { #[cfg(not(target_arch = "wasm32"))] #[test] fn a_panic_report_leaves_out_quoted_text() { - let _serial = serial(); - let dir = std::env::temp_dir().join(format!("craft-crash-quoted-{}", std::process::id())); - install("CrashTest", "1.2.3", Some(dir.clone())); - let _ = take_last(); - let secret = "Dear Ms Smith"; - let joined = std::thread::Builder::new() - .name("crash-quoted-worker".into()) - .spawn(move || panic!("byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `{secret}`")) - .expect("spawn") - .join(); - assert!(joined.is_err()); - let last = take_last().expect("the hook kept the panic"); - assert!(last.starts_with("byte index 5 is not a char boundary") && last.contains("of `…` (at "), "{last}"); - assert!(!last.contains(secret), "{last}"); - let log = std::fs::read_to_string(log_path().expect("crash log path")).expect("crash log"); - assert!(log.contains("of `…` (at ") && !log.contains(secret), "{log}"); + alone("a_panic_report_leaves_out_quoted_text", || { + let dir = std::env::temp_dir().join(format!("craft-crash-quoted-{}", std::process::id())); + install("CrashTest", "1.2.3", Some(dir.clone())); + let _ = take_last(); + let secret = "Dear Ms Smith"; + let joined = std::thread::Builder::new() + .name("crash-quoted-worker".into()) + .spawn(move || panic!("byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `{secret}`")) + .expect("spawn") + .join(); + assert!(joined.is_err()); + let last = take_last().expect("the hook kept the panic"); + assert!(last.starts_with("byte index 5 is not a char boundary") && last.contains("of `…` (at "), "{last}"); + assert!(!last.contains(secret), "{last}"); + let log = std::fs::read_to_string(log_path().expect("crash log path")).expect("crash log"); + assert!(log.contains("of `…` (at ") && !log.contains(secret), "{log}"); - let caught = catch(|| -> u8 { panic!("of `{secret}` and `more`") }); - let message = caught.expect_err("the closure panicked").message; - assert!(message.starts_with("of `…`") && message.contains(" and "), "the text outside the backticks stays: {message}"); - assert!(!message.contains(secret) && !message.contains("more"), "{message}"); - assert!(take_last().is_none(), "a caught quoted panic is reported once, by the caller"); - let caught = catch(|| -> u8 { panic!("of `half a sentence that {secret} wrote") }); - let message = caught.expect_err("the closure panicked").message; - assert!( - message.starts_with("of `") && !message.contains("half a sentence") && !message.contains(secret), - "an unpaired backtick hides the rest: {message}" - ); - assert!(take_last().is_none()); - let plain = "index out of bounds: the len is 3 but the index is 5"; - let caught = catch(|| -> u8 { panic!("{plain}") }); - assert_eq!(caught.map_err(|p| p.message), Err(plain.to_owned()), "a message without backticks is unchanged"); - assert!(take_last().is_none()); - let _ = std::fs::remove_dir_all(dir); + let caught = catch(|| -> u8 { panic!("of `{secret}` and `more`") }); + let message = caught.expect_err("the closure panicked").message; + assert!(message.starts_with("of `…`") && message.contains(" and "), "the text outside the backticks stays: {message}"); + assert!(!message.contains(secret) && !message.contains("more"), "{message}"); + assert!(take_last().is_none(), "a caught quoted panic is reported once, by the caller"); + let caught = catch(|| -> u8 { panic!("of `half a sentence that {secret} wrote") }); + let message = caught.expect_err("the closure panicked").message; + assert!( + message.starts_with("of `") && !message.contains("half a sentence") && !message.contains(secret), + "an unpaired backtick hides the rest: {message}" + ); + assert!(take_last().is_none()); + let plain = "index out of bounds: the len is 3 but the index is 5"; + let caught = catch(|| -> u8 { panic!("{plain}") }); + assert_eq!(caught.map_err(|p| p.message), Err(plain.to_owned()), "a message without backticks is unchanged"); + assert!(take_last().is_none()); + let _ = std::fs::remove_dir_all(dir); + }); } From 3215285d7b7fee69a2737c5ffa8d0d7c5bd95198 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:45:38 -0800 Subject: [PATCH 33/33] platform: craft-theme is an optional dependency of the appearance feature Cargo warned that craft-theme is an unused dependency of craft-platform (crates/platform/Cargo.toml:36) when the `appearance` feature is off. The crate uses it in two places: the `From` impl for `craft_theme::SystemAppearance`, compiled only with `appearance`, and the browser eyedropper in `screen`, which used `Srgba::from_hex` on the EyeDropper's `sRGBHex` answer. - craft-theme is optional, and `appearance` enables it. - The eyedropper reads the `#rrggbb` answer with `eyedropper_color` in screen.rs, so `screen` does not need craft-theme. Any other text is still reported as an invalid color. - README: the `SystemAppearance` conversion is listed under `appearance` instead of "always". Cargo.lock does not change. --- crates/platform/Cargo.toml | 4 ++-- crates/platform/README.md | 2 +- crates/platform/src/screen.rs | 29 +++++++++++++++++++++++++---- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml index 1316098830..30563aa223 100644 --- a/crates/platform/Cargo.toml +++ b/crates/platform/Cargo.toml @@ -14,7 +14,7 @@ workspace = true [features] default = [] # `appearance`: also Windows' UI settings and macOS' accessibility display setting (reduced motion). -appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"] +appearance = ["dep:craft-theme", "dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"] # `browser`: downloads, and the file picker and save through `rfd`. browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys", "dep:rfd", "dep:wasm-bindgen-futures"] # `SystemReader::report_contrast` and `report_reduced_motion`: preferences a test sets in place of an OS source. @@ -33,7 +33,7 @@ clipboard-system = ["clipboard", "dep:arboard", "dep:clipboard-win", "dep:objc2- apple-events = ["dep:fmv-macos-events"] [dependencies] -craft-theme = { workspace = true } +craft-theme = { workspace = true, optional = true } log = "0.4" web-time = "1.1" craft-atomic = { workspace = true } diff --git a/crates/platform/README.md b/crates/platform/README.md index e7d1e8afae..9d6541dc42 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -8,7 +8,7 @@ pull in heavier dependencies. | --- | --- | | default | Typed dialog outcomes; `PlatformText`; `open` (see below); no backend or toolkit. | | always (not wasm) | `dialogs`: reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. | -| always | `From for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. | +| `appearance` | `From for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. | | `pointer` | Move the system pointer (`pointer::warp`), installed by the app as craft-ui's `Scrub::install_warp` service for a scrub's screen-edge wrap; macOS only, `false` elsewhere. | | `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, GNOME's text scale, button layout); reduced motion on Windows and macOS; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. | | `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking; the file picker and save. | diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 8a247ab446..a65065de27 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -155,6 +155,18 @@ fn picked_color(rgb: [f64; 3]) -> Result { Ok(Capture::Color(rgb.map(|v| v as f32))) } +/// The browser EyeDropper's `sRGBHex` answer, `#rrggbb`, as sRGB, 0 to 1 each. `None` for any other text. +#[cfg(any(test, all(target_arch = "wasm32", feature = "browser")))] +fn eyedropper_color(hex: &str) -> Option<[f32; 3]> { + let digits = hex.strip_prefix('#')?; + // `from_str_radix` accepts a leading '+', so require plain hex digits first. + if digits.len() != 6 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let channel = |i: usize| digits.get(i..i + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()).map(|v| f32::from(v) / 255.0); + Some([channel(0)?, channel(2)?, channel(4)?]) +} + /// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape. #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> { @@ -586,8 +598,7 @@ mod backend { /// future executor is needed. #[cfg(all(target_arch = "wasm32", feature = "browser"))] mod web { - use super::{Arc, AtomicBool, Capture, CaptureHandle, Ordering, ScreenError, Wake}; - use craft_theme::Srgba; + use super::{Arc, AtomicBool, Capture, CaptureHandle, Ordering, ScreenError, Wake, eyedropper_color}; use js_sys::{Array, Function, Object, Promise, Reflect}; use std::sync::mpsc::Sender; use wasm_bindgen::{JsCast, JsValue, closure::Closure}; @@ -681,8 +692,8 @@ mod web { if field(entry, "status").as_string().as_deref() == Some("fulfilled") { return field(&field(entry, "value"), "sRGBHex") .as_string() - .and_then(|hex| Srgba::from_hex(&hex)) - .map(|c| Capture::Color([c.r, c.g, c.b])) + .and_then(|hex| eyedropper_color(&hex)) + .map(Capture::Color) .ok_or_else(|| ScreenError::Failed("the browser eyedropper returned an invalid color".into())); } let reason = field(entry, "reason"); @@ -740,6 +751,16 @@ mod tests { assert!(checked_stride(1, 1, usize::MAX).is_err()); } + /// The EyeDropper's `#rrggbb` reads as its three channels, either case; any other text gives no colour. + #[test] + fn eyedropper_hex_reads_as_its_channels() { + assert_eq!(eyedropper_color("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0])); + assert_eq!(eyedropper_color("#00FFaa"), Some([0.0, 1.0, 170.0 / 255.0])); + for text in ["ff8000", "#f80", "#ff8000ff", "#ff80", "#ff800g", "#+f8000", "# ff8000", "", "#", "#ff8000 "] { + assert_eq!(eyedropper_color(text), None, "{text:?}"); + } + } + /// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array) /// gives no colour; a `(ddd)` value gives its channels. #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]