Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.2 KB
Raw Blame
//! Rounded quads against Chromium: port/fixtures/corners/lab.json drawn by GPUI must give the pixels the
//! reference's Chromium gives the same boxes as CSS (port/fixtures/corners/chromium.png, from port/tools/corner-lab).

use gpui::{AppContext, BoxShadow, Div, HeadlessAppContext, IntoElement, ParentElement, Render, Styled, div, point, px, rgba, size};
use serde_json::Value;
use std::sync::Arc;

/// port/tools/corner-lab's grid: 8 columns of 48px cells, each box 8px into its cell.
const CELL: f32 = 48.;
const COLUMNS: usize = 8;
const INSET: f32 = 8.;
const SCALE: usize = 2;

struct Lab(Value);

impl Render for Lab {
    fn render(&mut self, _: &mut gpui::Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
        let cases = self.0["cases"].as_array().unwrap();
        div().size_full().bg(color(&self.0["page"])).children(cases.iter().enumerate().flat_map(|(index, case)| {
            let (left, top) = lab_case_origin(index);
            // A square of `under` color behind the box, for probes on a contrasting background.
            let under_width = case.get("underWidth").map_or(44., |width| width.as_f64().unwrap() as f32);
            let under = case.get("under").map(|under| div().absolute().left(px(left - 6.)).top(px(top - 6.)).w(px(under_width)).h(px(44.)).bg(color(under)));
            under.into_iter().chain([lab_box(index, case)])
        }))
    }
}

fn lab_box(index: usize, case: &Value) -> Div {
    let number = |value: &Value| value.as_f64().unwrap() as f32;
    let (left, top) = lab_case_origin(index);
    let radii: Vec<f32> = case["r"].as_array().unwrap().iter().map(number).collect();
    let borders: Vec<f32> = case["b"].as_array().unwrap().iter().map(number).collect();
    let mut element = div()
        .absolute()
        .left(px(left + case.get("dx").map_or(0., number)))
        .top(px(top + case.get("dy").map_or(0., number)))
        .w(px(case.get("w").map_or(32., number)))
        .h(px(case.get("h").map_or(32., number)));
    let backdrop = case.get("backdrop").map(number);
    if backdrop.is_none() {
        element = element.bg(color(&case["bg"]));
    }
    let style = element.style();
    style.corner_radii.top_left = Some(px(radii[0]).into());
    style.corner_radii.top_right = Some(px(radii[1]).into());
    style.corner_radii.bottom_right = Some(px(radii[2]).into());
    style.corner_radii.bottom_left = Some(px(radii[3]).into());
    style.border_widths.top = Some(px(borders[0]).into());
    style.border_widths.right = Some(px(borders[1]).into());
    style.border_widths.bottom = Some(px(borders[2]).into());
    style.border_widths.left = Some(px(borders[3]).into());
    if let Some(border) = case.get("bc") {
        element = element.border_color(color(border));
    }
    if let Some(shadow) = case.get("shadow") {
        element = element.shadow(vec![BoxShadow {
            color: color(&shadow["color"]).into(),
            offset: point(px(0.), px(number(&shadow["y"]))),
            // GPUI's blur_radius is the sigma, half the CSS blur.
            blur_radius: px(number(&shadow["blur"]) / 2.),
            spread_radius: px(number(&shadow["spread"])),
            inset: false,
        }]);
    }
    // frostedGlass.css's `::before`, as Workbench::frosted_glass paints it.
    if let Some(blur) = backdrop {
        let fill = color(&case["bg"]);
        let radii = gpui::Corners::all(px(radii[0] - borders[0]));
        element = element.child(
            gpui::canvas(|_, _, _| (), move |bounds, _, window, _| {
                window.paint_backdrop_blur(bounds, radii, px(blur), fill);
            })
            .absolute()
            .inset_0(),
        );
    }
    // GPUI clips children to rectangles only: a child in a rounded corner takes the parent's inner radius instead.
    if let Some(child) = case.get("child") {
        element = element.child(
            div()
                .absolute()
                .top_0()
                .left_0()
                .right_0()
                .h(px(number(&child["h"])))
                .bg(color(&child["bg"]))
                .rounded_tl(px(radii[0] - borders[3].max(borders[0])))
                .rounded_tr(px(radii[1] - borders[1].max(borders[0]))),
        );
    }
    element
}

fn lab_case_origin(index: usize) -> (f32, f32) {
    ((index % COLUMNS) as f32 * CELL + INSET, (index / COLUMNS) as f32 * CELL + INSET)
}

fn color(value: &Value) -> gpui::Rgba {
    let hex = value.as_str().unwrap().trim_start_matches('#');
    let hex = if hex.len() == 6 { format!("{hex}ff") } else { hex.to_string() };
    rgba(u32::from_str_radix(&hex, 16).unwrap())
}

// `input r4 b1 focus`: the inner corner's last pixels by 4. `backdrop blur`: Skia clips the blurred backdrop on the
// corner arc differently from AnalyticRRect (up to 9 there); inside the corners by 1 (Skia keeps each downscale level
// in 8 bits).
const MAX_DIFFERENCE: u8 = 4;
const MAX_BACKDROP_DIFFERENCE: u8 = 9;
const MAX_BACKDROP_INSIDE_DIFFERENCE: u8 = 1;

#[test]
fn rounded_quads_match_chromium() {
    let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/corners");
    let lab: Value = serde_json::from_str(&std::fs::read_to_string(fixtures.join("lab.json")).unwrap()).unwrap();
    let chromium = image::open(fixtures.join("chromium.png")).unwrap().to_rgba8();
    let cases = lab["cases"].as_array().unwrap().clone();
    let rows = cases.len().div_ceil(COLUMNS);
    let mut cx = HeadlessAppContext::with_platform(Arc::new(gpui::NoopTextSystem), Arc::new(()), gpui_platform::current_headless_renderer);
    let window = cx.open_window(size(px(CELL * COLUMNS as f32), px(CELL * rows as f32)), |_, cx| cx.new(|_| Lab(lab))).unwrap();
    cx.run_until_parked();
    let port = cx.capture_screenshot(window.into()).unwrap();
    port.save(std::env::temp_dir().join("corner-lab-port.png")).unwrap();
    assert_eq!(port.dimensions(), chromium.dimensions());

    let cell = CELL as usize * SCALE;
    let mut report = String::new();
    let mut failed = false;
    for (index, case) in cases.iter().enumerate() {
        let (x0, y0) = ((index % COLUMNS) * cell, (index / COLUMNS) * cell);
        // The box's 32px square less its 8px corners, in device pixels.
        let inside = (INSET as usize + 8) * SCALE..(INSET as usize + 24) * SCALE;
        let (mut differing, mut max, mut max_inside) = (0, 0, 0);
        for y in y0..y0 + cell {
            for x in x0..x0 + cell {
                let (a, b) = (chromium.get_pixel(x as u32, y as u32), port.get_pixel(x as u32, y as u32));
                let difference = (0..3).map(|channel| a[channel].abs_diff(b[channel])).max().unwrap();
                differing += usize::from(difference > 0);
                max = max.max(difference);
                if inside.contains(&(x - x0)) && inside.contains(&(y - y0)) {
                    max_inside = max_inside.max(difference);
                }
            }
        }
        failed |= match case.get("backdrop") {
            Some(_) => max > MAX_BACKDROP_DIFFERENCE || max_inside > MAX_BACKDROP_INSIDE_DIFFERENCE,
            None => max > MAX_DIFFERENCE,
        };
        report += &format!("{:<28} AE {differing:>4} max {max:>3} inside {max_inside:>3}\n", case["name"].as_str().unwrap());
    }
    println!("{report}");
    assert!(!failed, "GPUI's rounded quads differ from Chromium's:\n{report}");
}