Something went wrong. Try again.
Exploring the idea of generated web rendering engine.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344//! [`crate::runner`]'s counterpart for the floats/block-formatting-context seam//! (`crates/layout/src/float.rs`, `specs/floats-bfc.md`). Structurally identical to//! `crate::absolute_runner`: same scoring, same regression-set admission gate, no extra//! intermediate-fact check the way `crate::margin_runner` adds one against `crates/logic`'s//! rules -- there is no analogous rules engine for float placement to cross-check against//! either, so geometry-regression-free is this seam's whole admission gate too.
use std::collections::BTreeMap;use std::fs;use std::path::PathBuf;
use anyhow::{bail, Context, Result};use dom::Document;use harness::compare::{compare, relative_offset, CaseComparison, Consensus, Metric, VoteMeasurement};use harness::dump::{Dump, Node as DumpNode, Rect, Viewport, TOLERANCE_PX};use layout::boxtree::BoxTree;use layout::float::FloatResolver;use layout::fragment;
use crate::groundtruth::CachedCase;use crate::runner::{CandidateReport, CategoryTally, Report};
/// The harness's fixed viewport, matching `crate::runner::VIEWPORT_WIDTH`.const VIEWPORT_WIDTH: f64 = 800.0;const VIEWPORT_HEIGHT: f64 = 600.0;
/// Renders `html` through the real layout path with the width equation, margin/// collapsing, percentage resolution and absolute positioning held at their own baselines/// (none of the float recipes need auto-margin balancing, collapsing, a percentage value/// or absolute positioning on anything those seams themselves resolve --/// `crates/harness/src/float_cases.rs`'s own module doc) and `resolver` standing in for/// the float-placement seam. Mirrors `crate::absolute_runner::candidate_dump`,/// generalized over which resolver runs.pub fn candidate_dump(html: &str, resolver: FloatResolver) -> Dump { let document = Document::parse(html); let elements = document.elements_in_document_order(); let tree = BoxTree::build(&document); let root_fragment = fragment::layout_with_resolvers( &document, &tree, (VIEWPORT_WIDTH, VIEWPORT_HEIGHT), &fragment::Resolvers { float_resolver: resolver, containing_block_resolver: layout::generated_containing_block_resolve, ..fragment::Resolvers::baselines() }, );
let mut rects: BTreeMap<dom::node::NodeId, Rect> = BTreeMap::new(); root_fragment.walk_absolute(0.0, 0.0, &mut |node, x, y, w, h| { rects.insert(node, Rect { x, y, w, h }); });
let mut index_of: BTreeMap<dom::node::NodeId, usize> = BTreeMap::new(); for (i, &el) in elements.iter().enumerate() { index_of.insert(el, i); }
let nodes = elements .iter() .enumerate() .map(|(index, el)| { let parent = el.dom_parent().map(|p| index_of[&p] as i64).unwrap_or(-1); let mut depth = 0u32; let mut cur = *el; while let Some(p) = cur.dom_parent() { depth += 1; cur = p; } let rect = rects.get(el).copied(); DumpNode { index, parent, tag: el.tag(), depth, bounding: rect.unwrap_or(Rect { x: 0.0, y: 0.0, w: 0.0, h: 0.0 }), rects: rect.map(|r| vec![r]).unwrap_or_default(), scroll: None, style: Default::default(), } }) .collect();
Dump { engine: "candidate".to_string(), engine_version: "0".to_string(), viewport: Viewport { width: 800, height: 600 }, overflowed: false, nodes, }}
fn majority_value(m: &VoteMeasurement) -> Option<f64> { match &m.consensus { Consensus::Split => None, Consensus::Unanimous => m.values.values().next().copied(), Consensus::Majority { outlier } => { m.values.iter().find(|(engine, _)| *engine != outlier).map(|(_, v)| *v) } }}
fn candidate_value(candidate: &Dump, m: &VoteMeasurement) -> Option<f64> { let node = candidate.nodes.get(m.node_index)?; Some(match m.metric { Metric::Width => node.bounding.w, Metric::Height => node.bounding.h, Metric::OffsetX => relative_offset(candidate, node).0, Metric::OffsetY => relative_offset(candidate, node).1, Metric::FragmentCount => node.rects.len() as f64, Metric::FragmentWidth(i) => node.rects.get(i)?.w, Metric::FragmentHeight(i) => node.rects.get(i)?.h, })}
fn agrees_with_vote(candidate: &Dump, vote_report: &harness::compare::VoteReport) -> bool { vote_report.measurements.iter().filter(|m| m.is_trustworthy()).all(|m| { let Some(reference) = majority_value(m) else { return true }; match candidate_value(candidate, m) { Some(v) => (v - reference).abs() <= TOLERANCE_PX, None => false, } })}
#[derive(Debug, Clone, Copy, PartialEq)]enum Outcome { Passed, Failed, Untrustworthy,}
fn score_case(case: &CachedCase, resolver: FloatResolver) -> Outcome { let Some(reference) = case.dumps.get("chromium").or_else(|| case.dumps.values().next()) else { return Outcome::Untrustworthy; }; let candidate = candidate_dump(&case.html, resolver);
match compare(&candidate, reference) { CaseComparison::Discarded(_) => Outcome::Untrustworthy, CaseComparison::ShapeMismatch(_) => Outcome::Failed, CaseComparison::Compared(pairwise) => match case.vote() { Ok(vote_report) => { if agrees_with_vote(&candidate, &vote_report) { Outcome::Passed } else { Outcome::Failed } } Err(_) => { if pairwise.passed { Outcome::Passed } else { Outcome::Failed } } }, }}
pub fn passing_case_ids(resolver: FloatResolver, cases: &[CachedCase]) -> Vec<String> { cases .iter() .filter(|case| score_case(case, resolver) == Outcome::Passed) .map(|case| case.case_id.clone()) .collect()}
pub fn evaluate( registry: &[(&str, FloatResolver)], cases: &[CachedCase], regression_set: Option<&[String]>,) -> Report { let candidates = registry .iter() .map(|(name, resolver)| { let mut cases_run = 0u64; let mut cases_passed = 0u64; let mut passed_ids: Vec<String> = Vec::new(); let mut per_category: BTreeMap<String, CategoryTally> = BTreeMap::new();
for case in cases { let outcome = score_case(case, *resolver); if outcome == Outcome::Untrustworthy { continue; } cases_run += 1; let passed = outcome == Outcome::Passed; if passed { cases_passed += 1; passed_ids.push(case.case_id.clone()); } for category in &case.categories { let tally = per_category.entry(category.clone()).or_default(); tally.total += 1; if passed { tally.passed += 1; } } }
let regressed_cases: Vec<String> = regression_set .unwrap_or(&[]) .iter() .filter(|id| !passed_ids.contains(id)) .cloned() .collect();
CandidateReport { name: name.to_string(), cases_run, cases_passed, admitted: regressed_cases.is_empty(), regressed_cases, per_category, passed_case_ids: passed_ids, // See `margin_runner.rs`: only the absolute-positioning seam builds a // geometry-diff prompt from this field. failing_case_diffs: Vec::new(), } }) .collect();
Report { candidates }}
/// Entry point a generated float candidate crate's `main.rs` calls/// (`crate::candidate_crate::write_for` with `Seam::Floats`), the same/// environment-variable contract `crate::runner::main`/`crate::absolute_runner::main`/// use.pub fn main(registry: &[(&str, FloatResolver)]) -> Result<()> { let cache_dir = PathBuf::from( std::env::var("GENERATION_CACHE_DIR") .context("GENERATION_CACHE_DIR must name the ground-truth cache directory")?, ); let cases = crate::groundtruth::load_all(&cache_dir)?; if cases.is_empty() { bail!("no cached cases under {}; run the ground_truth_cache binary first", cache_dir.display()); }
let regression_set: Option<Vec<String>> = match std::env::var("GENERATION_REGRESSION_SET") { Ok(path) => { let json = fs::read_to_string(&path).with_context(|| format!("reading {path}"))?; Some(serde_json::from_str(&json).with_context(|| format!("parsing {path}"))?) } Err(_) => None, };
let report = evaluate(registry, &cases, regression_set.as_deref()); let json = serde_json::to_string_pretty(&report)?; if let Ok(out) = std::env::var("GENERATION_REPORT_OUT") { fs::write(&out, &json).with_context(|| format!("writing {out}"))?; } println!("{json}"); Ok(())}
#[cfg(test)]mod tests { use super::*; use layout::float::{FloatInputs, FloatOutputs, FloatSide, Subject};
/// A resolver that places a left/right float beside earlier same-side floats /// correctly (summing their widths, like the real placement rules would for two /// floats that both fit on one line) but never applies `clear` -- wrong in one way, /// the same spirit as `absolute_runner`'s own `resolve_left_top_only`, used only to /// check this runner's own scoring plumbing (candidate crates plug in a real /// candidate instead). Not registered anywhere the generation loop reads. fn resolve_placement_only(inputs: &FloatInputs) -> FloatOutputs { match inputs.subject { Subject::Float(FloatSide::Left) => { let left = inputs .placed .iter() .filter(|p| p.side == FloatSide::Left) .map(|p| p.right) .fold(inputs.containing_block_left, f64::max); FloatOutputs { left, right: left + inputs.margin_box_width, top: inputs.flow_top, clearance: 0.0 } } Subject::Float(FloatSide::Right) => { let right = inputs .placed .iter() .filter(|p| p.side == FloatSide::Right) .map(|p| p.left) .fold(inputs.containing_block_right, f64::min); FloatOutputs { left: right - inputs.margin_box_width, right, top: inputs.flow_top, clearance: 0.0 } } Subject::Block | Subject::BfcRoot => FloatOutputs { left: inputs.containing_block_left, right: inputs.containing_block_right, top: inputs.flow_top, clearance: 0.0, }, } }
const RESET: &str = "* { margin: 0; padding: 0; border: 0; box-sizing: content-box; }\nhtml, body { display: block; }\n";
fn find_index(html: &str, class: &str) -> usize { let document = Document::parse(html); document .elements_in_document_order() .into_iter() .enumerate() .find(|(_, e)| document.nodes()[e.index()].as_element().unwrap().attr("class") == Some(class)) .map(|(i, _)| i) .unwrap_or_else(|| panic!("no element with class={class:?}")) }
fn two_left_floats_html() -> String { format!( "<!doctype html><style>{RESET}.c{{width:300px}}\ .a{{float:left;width:120px;height:80px}}\ .b{{float:left;width:120px;height:60px}}\ </style><div class=c><div class=a></div><div class=b></div></div>" ) }
#[test] fn baseline_pins_both_left_floats_to_the_left_edge_ignoring_the_earlier_one() { let html = two_left_floats_html(); let dump = candidate_dump(&html, layout::float::resolve_baseline); let a = &dump.nodes[find_index(&html, "a")]; let b = &dump.nodes[find_index(&html, "b")]; assert_eq!(relative_offset(&dump, a).0, 0.0); assert_eq!( relative_offset(&dump, b).0, 0.0, "baseline pins every left float to the left edge, ignoring earlier ones" ); }
#[test] fn a_candidate_that_reads_earlier_floats_places_the_second_beside_the_first() { let html = two_left_floats_html(); let dump = candidate_dump(&html, resolve_placement_only); let a = &dump.nodes[find_index(&html, "a")]; let b = &dump.nodes[find_index(&html, "b")]; assert_eq!(relative_offset(&dump, a).0, 0.0); assert_eq!(relative_offset(&dump, b).0, 120.0); }}