M1: strengthen page transparency and sidebar review tests

This commit is contained in:
Carbocode
2026-11-10 12:50:16 +01:00
parent d9f52aab1a
commit 67c232eab2
3 changed files with 181 additions and 57 deletions
+130 -40
View File
@@ -2,6 +2,7 @@
use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, pos2};
/// Reuse the checkerboard texture, updating its pixels when the active theme changes.
fn grid_texture(ctx: &egui::Context) -> TextureHandle {
let id = Id::unique("canvas_transparency_grid");
let tokens = crate::theme::Tokens::get(ctx);
@@ -24,6 +25,7 @@ fn grid_texture(ctx: &egui::Context) -> TextureHandle {
texture
}
/// Draw the transparency grid and apply page colour only outside the rendered image.
pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option<Rect>) {
if background.a() < 255 {
// Repeat four pixels instead of allocating one shape per square on a large canvas.
@@ -51,41 +53,127 @@ pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered
#[cfg(test)]
mod tests {
use super::*;
use egui::vec2;
use egui::{Mesh, TextureId, vec2};
/// Paint a small canvas and consume its texture uploads as the UI harness does.
fn shapes(alpha: u8, rendered: Option<Rect>) -> egui::FullOutput {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(Default::default(), |ui| {
paint(
ui.painter(),
Rect::from_min_size(egui::Pos2::ZERO, vec2(100.0, 100.0)),
Color32::from_rgba_unmultiplied(255, 0, 0, alpha),
rendered,
);
paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered);
});
out.textures_delta.clear();
out
}
/// Fixed canvas bounds make clipping and uncovered-area checks independent of UI layout.
fn canvas() -> Rect {
Rect::from_min_size(egui::Pos2::ZERO, vec2(100.0, 100.0))
}
/// Check the actual checkerboard quad, including clipping and its screen-sized UV mapping.
fn assert_grid(out: &egui::FullOutput, tile: TextureId, rect: Rect) -> usize {
let meshes: Vec<_> = out
.shapes
.iter()
.enumerate()
.filter_map(|(index, shape)| match &shape.shape {
egui::Shape::Mesh(mesh) if mesh.texture_id == tile => Some((index, shape.clip_rect, mesh)),
_ => None,
})
.collect();
assert_eq!(meshes.len(), 1, "one checkerboard covers the canvas");
let (index, clip, mesh) = meshes[0];
assert_eq!(mesh.calc_bounds(), rect);
assert!(clip.contains_rect(rect), "the whole checkerboard is visible");
assert_eq!(mesh.vertices.len(), 4);
for vertex in &mesh.vertices {
let expected = (vertex.pos - rect.min) / 16.0;
assert!((vertex.uv.to_vec2() - expected).length() < 0.001, "UVs keep the squares at a fixed screen size");
}
index
}
/// Assert strips have the correct colour and partition exactly the area outside the render.
fn assert_partition(alpha: u8, rendered: Option<Rect>) {
let out = shapes(alpha, rendered);
let fills: Vec<_> = out
.shapes
.iter()
.enumerate()
.filter_map(|(index, s)| match &s.shape {
egui::Shape::Rect(r) => Some((index, r)),
_ => None,
})
.collect();
let covered = rendered.map(|r| r.intersect(canvas())).filter(|r| r.is_positive());
let background = Color32::from_rgba_unmultiplied(255, 0, 0, alpha);
for (i, (_, strip)) in fills.iter().enumerate() {
assert_eq!(strip.fill.a(), alpha, "each fallback strip applies alpha exactly once");
assert_eq!(strip.fill, background, "the fallback keeps the page colour too");
assert!(strip.rect.is_positive() && canvas().contains_rect(strip.rect));
if let Some(covered) = covered {
assert!(!strip.rect.intersect(covered).is_positive(), "no fallback beneath rendered pixels");
}
for (_, other) in fills.iter().skip(i + 1) {
assert!(!strip.rect.intersect(other.rect).is_positive(), "fallback strips do not overlap");
}
}
let area: f32 = fills.iter().map(|(_, strip)| strip.rect.area()).sum();
assert_eq!(area, canvas().area() - covered.map_or(0.0, |r| r.area()), "no uncovered gaps");
if covered == Some(canvas()) {
assert!(fills.is_empty(), "full coverage needs no fallback fills");
}
let meshes: Vec<&Mesh> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Mesh(mesh) => Some(mesh.as_ref()),
_ => None,
})
.collect();
if alpha < 255 {
assert_eq!(meshes.len(), 1);
let index = assert_grid(&out, meshes[0].texture_id, canvas());
assert!(fills.iter().all(|(fill_index, _)| *fill_index > index), "the grid is behind every fallback strip");
} else {
assert!(meshes.is_empty(), "opaque pages need no checkerboard");
}
}
/// Exercise the real canvas with a render present, checking the grid covers it and draws first.
#[test]
fn the_canvas_draws_the_transparency_grid_for_a_transparent_page() {
let mut ui = crate::layers_drag_tests::Ui::new(figcraft_engine::Session::new());
ui.app.run("page.setBackground", serde_json::json!({"color": "#FF000000"}));
let ds = ui.app.session.ds().unwrap();
let shown = (ds.uid, ds.page);
// Seed an image so this test does not depend on when the asynchronous worker finishes.
ui.app.canvas.texture =
Some(ui.ctx.load_texture("test-page-render", egui::ColorImage::filled([16, 16], Color32::TRANSPARENT), egui::TextureOptions::NEAREST));
ui.app.canvas.tex_view = Some(figcraft_render::View { origin: (0.0, 0.0), scale: 1.0, width: 16, height: 16 });
ui.app.canvas.tex_of = Some(shown);
let out = ui.frame_output(vec![]);
let (tile, _) =
ui.ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("the canvas checkerboard");
assert!(out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == tile.id())));
let grid_index = assert_grid(&out, tile.id(), ui.app.canvas.rect);
let rendered = ui.app.canvas.texture.as_ref().unwrap().id();
let render_index =
out.shapes.iter().position(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == rendered)).expect("the rendered page");
assert!(grid_index < render_index, "the checkerboard is behind the rendered page");
}
/// Theme changes must reach drawing, update the pixels used by its mesh and reuse the texture.
#[test]
fn the_grid_updates_its_colours_when_the_theme_changes() {
let ctx = egui::Context::default();
let mut previous_id = None;
for tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark(), crate::theme::Tokens::light()] {
crate::theme::apply(&ctx, tokens);
let mut tile = None;
let mut out = ctx.run_ui(Default::default(), |_ui| tile = Some(grid_texture(&ctx)));
let tile = tile.unwrap();
let mut out = ctx.run_ui(Default::default(), |ui| paint(ui.painter(), canvas(), Color32::TRANSPARENT, None));
let (tile, _) =
ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("drawn checkerboard");
let grid_index = assert_grid(&out, tile.id(), canvas());
assert!(out.shapes.iter().enumerate().all(|(index, s)| !matches!(&s.shape, egui::Shape::Rect(_)) || index > grid_index));
if let Some(previous_id) = previous_id {
assert_eq!(tile.id(), previous_id, "changing theme updates the same texture");
}
@@ -97,44 +185,46 @@ mod tests {
}
}
/// Interior, edge-straddling and fully covering renders must all apply the page alpha once.
#[test]
fn translucent_pages_show_the_grid_without_applying_page_alpha_twice() {
let rendered = Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 80.0));
let renders = [
Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 80.0)),
Rect::from_min_max(pos2(-20.0, 20.0), pos2(80.0, 80.0)),
Rect::from_min_max(pos2(20.0, -20.0), pos2(80.0, 80.0)),
Rect::from_min_max(pos2(20.0, 20.0), pos2(120.0, 80.0)),
Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 120.0)),
Rect::from_min_max(pos2(-20.0, -20.0), pos2(80.0, 80.0)),
canvas(),
Rect::from_min_max(pos2(-20.0, -20.0), pos2(120.0, 120.0)),
];
for alpha in [0, 128, 255] {
let out = shapes(alpha, Some(rendered));
let fills: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Rect(r) => Some(r.rect),
_ => None,
})
.collect();
assert_eq!(fills.len(), 4);
assert!(fills.iter().all(|r| !r.intersect(rendered).is_positive()), "the render's alpha has no page colour beneath it");
for point in [pos2(10.0, 10.0), pos2(90.0, 90.0), pos2(10.0, 50.0), pos2(90.0, 50.0)] {
assert_eq!(fills.iter().filter(|r| r.contains(point)).count(), 1, "uncovered pixels get the page colour once");
for rendered in renders {
assert_partition(alpha, Some(rendered));
}
let images = out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Mesh(_))).count();
assert_eq!(images, usize::from(alpha < 255), "only transparent pages need the checkerboard");
}
}
/// Missing, offscreen and merely edge-touching images leave exactly one fallback page fill.
#[test]
fn absent_or_offscreen_renders_fill_the_page_once() {
for rendered in [None, Some(Rect::from_min_size(pos2(200.0, 200.0), vec2(10.0, 10.0)))] {
let out = shapes(128, rendered);
let fills: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Rect(r) => Some(r),
_ => None,
})
.collect();
assert_eq!(fills.len(), 1);
assert_eq!(fills[0].rect, Rect::from_min_size(egui::Pos2::ZERO, vec2(100.0, 100.0)));
assert_eq!(fills[0].fill.a(), 128);
for rendered in
[None, Some(Rect::from_min_size(pos2(200.0, 200.0), vec2(10.0, 10.0))), Some(Rect::from_min_max(pos2(-20.0, 20.0), pos2(0.0, 80.0)))]
{
for alpha in [0, 128, 255] {
assert_partition(alpha, rendered);
let out = shapes(alpha, rendered);
let fills: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Rect(r) => Some(r),
_ => None,
})
.collect();
assert_eq!(fills.len(), 1);
assert_eq!(fills[0].rect, canvas());
}
}
}
}
+48 -15
View File
@@ -1300,37 +1300,70 @@ fn page_background_shows_fractional_opacity_like_fill_and_keeps_it_when_opening_
u.app.run("page.setBackground", json!({"color": "#FF000080"}));
u.frame(vec![]);
assert_eq!(field(&mut u, "Opacity").1, "50.2%");
let page = u.app.session.page().unwrap();
let background = |u: &Ui| match u.app.session.doc().unwrap().node(page).unwrap().kind {
figcraft_doc::NodeKind::Page { background, .. } => background,
_ => panic!("the page"),
};
let original = background(&u);
let steps = undo_steps(&u);
let swatch = u.ctx.read_response(Id::unique("pagebg_swatch")).expect("shared page swatch").rect.center();
click(&mut u, swatch);
assert!(matches!(u.app.ui.picker, Some(crate::colorpicker::PickerTarget::PageBackground)));
assert_eq!(undo_steps(&u), steps, "opening the picker does not edit the colour");
assert_eq!(background(&u), original, "opening preserves the stored alpha");
assert_eq!(field(&mut u, "Opacity").1, "50.2%");
click(&mut u, swatch);
assert!(u.app.ui.picker.is_none(), "the swatch toggles the picker closed");
assert_eq!(background(&u), original, "closing preserves the stored alpha");
assert_eq!(field(&mut u, "Opacity").1, "50.2%");
assert_eq!(undo_steps(&u), steps, "neither toggle creates an edit");
}
/// The shared page colour row uses the sidebar's width without hiding either field.
#[test]
fn page_background_colour_and_opacity_fit_a_resized_sidebar() {
let mut u = Ui::new(Session::new());
let mut previous_widths: Option<(f32, f32)> = None;
for width in [240.0, 500.0] {
u.app.ui.right_width = width;
for _ in 0..3 {
u.frame(vec![]);
// Find the whole galley, rather than its already-clipped bounding box.
fn hex_text(shape: &egui::Shape) -> Option<&egui::epaint::TextShape> {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().find_map(hex_text),
egui::Shape::Text(text) if text.galley.text() == "123ABC" => Some(text),
_ => None,
}
let hex = u.ctx.read_response(Id::unique("pagebg").with("click")).unwrap().rect;
let alpha = u.ctx.read_response(Id::unique("pagebg_a").with("field")).unwrap().rect;
let panel = u.app.ui.right_panel_rect.unwrap();
}
let mut widths = Vec::new();
for width in [240.0, 500.0] {
let mut session = Session::new();
session.prefs.panel_widths.1 = width;
session.execute("page.setBackground", &json!({"color": "#123ABC80"})).unwrap();
let mut u = Ui::new(session);
let mut previous = None;
let mut settled = None;
// Stop at stable geometry, with a bound so a layout regression cannot hang the test.
for _ in 0..16 {
let out = u.frame_output(vec![]);
let hex = u.ctx.read_response(Id::unique("pagebg").with("click")).unwrap().rect;
let alpha = u.ctx.read_response(Id::unique("pagebg_a").with("field")).unwrap().rect;
let panel = u.app.ui.right_panel_rect.unwrap();
if previous == Some((hex, alpha, panel)) {
settled = Some((out, hex, alpha, panel));
break;
}
previous = Some((hex, alpha, panel));
}
let (out, hex, alpha, panel) = settled.expect("the page row settles");
assert!(hex.left() >= u.app.canvas.rect.right(), "the colour stays in the sidebar");
assert!(hex.right() < alpha.left(), "the colour and opacity never overlap");
assert!(alpha.right() <= u.screen.x, "the opacity stays visible");
// The colour uses the extra room while opacity keeps its place at the right edge.
if let Some((previous_hex, previous_panel)) = previous_widths {
assert!((hex.width() - previous_hex - (panel.width() - previous_panel)).abs() < 1.0, "the shared control grows with the panel");
}
previous_widths = Some((hex.width(), panel.width()));
// Half a point permits device-pixel rounding, not an arbitrary gap from the panel edge.
assert!((alpha.right() - (panel.right() - crate::widgets::PAD_RIGHT)).abs() <= 0.5, "opacity stays at the right edge");
assert!((hex.center().y - alpha.center().y).abs() <= 0.5, "both fields stay on the same row");
let (text, clip) = out.shapes.iter().find_map(|s| hex_text(&s.shape).map(|text| (text, s.clip_rect))).expect("the HEX text");
assert!(!text.galley.elided, "the whole HEX value fits at {width} pt");
assert!(hex.expand(0.5).contains_rect(text.visual_bounding_rect()), "the HEX text fits its field");
assert!(clip.expand(0.5).contains_rect(text.visual_bounding_rect()), "the HEX text is not clipped");
widths.push(hex.width());
}
assert!(widths[1] > widths[0], "a wider sidebar gives the colour field more room");
}
/// The Page section's opacity field edits the page background's alpha (#1748; it was a label),
+3 -2
View File
File diff suppressed because one or more lines are too long