Mosaic: motore di rendering proprio, gusci desktop e Sailfish

Primo commit del progetto: motore Rust con parser HTML, cascata CSS, layout,
raster CPU, formulari, bidi, flex, tabelle, JavaScript (Boa) con eventi e
costruzione di nodi, rete HTTP/HTTPS con TLS, sotto-risorse, invio dei
formulari; guscio grafico per Sailfish (QML/Silica) e per desktop (minifb,
distribuito come AppImage), con 11 documenti di specifica e 91 casi di
reftest.
This commit is contained in:
Carlo Baratto committed 2026-11-12 19:10:26 +01:00
commit 577682ae22
173 files changed
+23685

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
//! Harness di reftest: esegue i casi JSON di una cartella e confronta
//! pixel sondati, geometria dei box e numero di righe di testo.
//!
//! Uso:
//! reftest --cases cases [--only nome] [--bless] [--png-dir /tmp/shots]
//!
//! Ogni caso ha la forma:
//! {
//! "name": "div-sfondo",
//! "html": "<div style=\"width:100px;height:50px;background:#ff0000\"></div>",
//! "css": "",
//! "viewport": [200, 150],
//! "probes": [{ "x": 10, "y": 10, "rgb": [255,0,0], "tol": 2 }],
//! "boxes": [{ "path": "html>body>div:0", "rect": [8,8,100,50], "tol": 0.6 }],
//! "lines": [{ "path": "html>body>p:0", "count": 2 }],
//! "golden": "div-sfondo.png"
//! }
use std::path::{Path, PathBuf};
use engine::{pngio, render_with_form, FormState, RenderOptions};
use serde_json::Value;
fn main() {
let mut dir = PathBuf::from("cases");
let mut only: Option<String> = None;
let mut bless = false;
let mut png_dir: Option<PathBuf> = None;
let args: Vec<String> = std::env::args().skip(1).collect();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--cases" => {
dir = PathBuf::from(&args[i + 1]);
i += 2;
}
"--only" => {
only = Some(args[i + 1].clone());
i += 2;
}
"--bless" => {
bless = true;
i += 1;
}
"--png-dir" => {
png_dir = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
other => {
eprintln!("argomento non riconosciuto: {}", other);
std::process::exit(2);
}
}
}
let font = std::env::var("ENGINE_FONT")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"));
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
.expect("cartella dei casi")
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false))
.collect();
files.sort();
let mut pass = 0usize;
let mut fail = 0usize;
let mut failures: Vec<String> = Vec::new();
for file in files {
let raw = std::fs::read_to_string(&file).expect("lettura caso");
let case: Value = serde_json::from_str(&raw).expect("JSON del caso");
let name = case["name"]
.as_str()
.unwrap_or_else(|| file.to_str().unwrap())
.to_string();
if let Some(filter) = &only {
if !name.contains(filter.as_str()) {
continue;
}
}
// casi che richiedono l'interprete JavaScript: senza la feature si saltano
if case["requires"].as_str() == Some("js") && !cfg!(feature = "js") {
println!("skip {} (richiede JavaScript)", name);
continue;
}
let html = case["html"].as_str().unwrap_or("").to_string();
let css = case["css"].as_str().unwrap_or("").to_string();
let vw = case["viewport"][0].as_u64().unwrap_or(200) as u32;
let vh = case["viewport"][1].as_u64().unwrap_or(200) as u32;
let scale = case["scale"].as_f64().unwrap_or(1.0) as f32;
let auto_height = case["auto_height"].as_bool().unwrap_or(false);
let opts = RenderOptions {
viewport: (vw, vh),
dpi_scale: scale,
font_path: font.clone(),
auto_height,
base_dir: dir.clone(),
// i casi non escono in rete: nessun indirizzo di base
base_url: None,
};
// stato dei moduli: valori digitati e fuoco arrivano dal caso
let mut form = FormState::default();
if let Some(f) = case["form"].as_object() {
if let Some(values) = f.get("values").and_then(|v| v.as_object()) {
for (k, v) in values {
form.values
.insert(k.clone(), v.as_str().unwrap_or("").to_string());
}
}
form.focus = f
.get("focus")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
form.caret = f.get("caret").and_then(|v| v.as_u64()).map(|v| v as usize);
form.open_select = f
.get("open_select")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
form.select_highlight = f
.get("select_highlight")
.and_then(|v| v.as_u64())
.map(|v| v as usize);
if let Some(sel) = f.get("selection").and_then(|v| v.as_array()) {
if sel.len() == 2 {
let a = sel[0].as_u64().unwrap_or(0) as usize;
let b = sel[1].as_u64().unwrap_or(0) as usize;
form.selection = Some((a, b));
}
}
}
let res = match render_with_form(&html, &css, &opts, &form) {
Ok(r) => r,
Err(e) => {
fail += 1;
println!("FAIL {}\n - motore: {}", name, e);
failures.push(name);
continue;
}
};
let mut problems: Vec<String> = Vec::new();
if let Some(probes) = case["probes"].as_array() {
for p in probes {
let x = p["x"].as_u64().unwrap_or(0) as u32;
let y = p["y"].as_u64().unwrap_or(0) as u32;
let tol = p["tol"].as_u64().unwrap_or(2) as i32;
let expected: Vec<i32> = p["rgb"]
.as_array()
.map(|a| a.iter().map(|v| v.as_i64().unwrap_or(0) as i32).collect())
.unwrap_or_default();
if expected.len() < 3 {
problems.push(format!("sonda ({},{}): rgb mancante", x, y));
continue;
}
if x >= res.width || y >= res.height {
problems.push(format!("sonda ({},{}) fuori dall'immagine", x, y));
continue;
}
let idx = ((y * res.width + x) * 4) as usize;
let got = [
res.rgba[idx] as i32,
res.rgba[idx + 1] as i32,
res.rgba[idx + 2] as i32,
];
let d = (0..3)
.map(|c| (got[c] - expected[c]).abs())
.max()
.unwrap_or(0);
if d > tol {
problems.push(format!(
"sonda ({},{}): atteso {:?}, trovato {:?} (delta {})",
x, y, expected, got, d
));
}
}
}
if let Some(boxes) = case["boxes"].as_array() {
for b in boxes {
let path = b["path"].as_str().unwrap_or("html");
let tol = b["tol"].as_f64().unwrap_or(0.6) as f32;
let expected: Vec<f32> = b["rect"]
.as_array()
.map(|a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())
.unwrap_or_default();
match res.layout.find_path(path) {
None => problems.push(format!("box '{}' assente", path)),
Some(found) => {
let got = [found.rect.x, found.rect.y, found.rect.w, found.rect.h];
if expected.len() == 4 {
let bad = (0..4).any(|c| (got[c] - expected[c]).abs() > tol);
if bad {
problems.push(format!(
"box '{}': atteso {:?}, trovato {:?}",
path, expected, got
));
}
}
if let Some(min_h) = b["min_h"].as_f64() {
if (found.rect.h as f64) < min_h {
problems.push(format!(
"box '{}': altezza {} < min_h {}",
path, found.rect.h, min_h
));
}
}
if let Some(max_h) = b["max_h"].as_f64() {
if (found.rect.h as f64) > max_h {
problems.push(format!(
"box '{}': altezza {} > max_h {}",
path, found.rect.h, max_h
));
}
}
}
}
}
}
if let Some(min_h) = case["png_min_height"].as_u64() {
if (res.height as u64) < min_h {
problems.push(format!(
"altezza immagine {} < png_min_height {}",
res.height, min_h
));
}
}
// larghezza del testo in un box: serve a verificare i cambi di font
if let Some(tw) = case["text_width"].as_array() {
for t in tw {
let path = t["path"].as_str().unwrap_or("html");
let min = t["min"].as_f64();
let max = t["max"].as_f64();
match res.layout.find_path(path) {
None => problems.push(format!("box '{}' assente (testo)", path)),
Some(found) => {
let mut lo = f32::MAX;
let mut hi = f32::MIN;
for line in &found.lines {
for run in &line.runs {
lo = lo.min(run.x);
hi = hi.max(run.x + run.width);
}
}
if hi <= lo {
problems.push(format!("box '{}': nessun testo", path));
} else {
let w = (hi - lo) as f64;
if let Some(m) = min {
if w < m {
problems.push(format!("testo largo {:.1} < min {:.1}", w, m));
}
}
if let Some(m) = max {
if w > m {
problems.push(format!("testo largo {:.1} > max {:.1}", w, m));
}
}
}
}
}
}
}
// estensione dell'inchiostro in un rettangolo: intercetta i glifi
// ammassati (avanzamenti non riscalati col fattore di zoom)
if let Some(ext) = case["ink_extent"].as_array() {
for e in ext {
let rect: Vec<f32> = e["rect"]
.as_array()
.map(|a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())
.unwrap_or_default();
if rect.len() != 4 {
problems.push("ink_extent: rect mancante".to_string());
continue;
}
let x0 = rect[0].floor().max(0.0) as u32;
let y0 = rect[1].floor().max(0.0) as u32;
let x1 = (rect[0] + rect[2]).ceil().min(res.width as f32) as u32;
let y1 = (rect[1] + rect[3]).ceil().min(res.height as f32) as u32;
let (mut lo_x, mut hi_x) = (u32::MAX, 0u32);
let (mut lo_y, mut hi_y) = (u32::MAX, 0u32);
for y in y0..y1 {
for x in x0..x1 {
let i = ((y * res.width + x) * 4) as usize;
let lum =
(res.rgba[i] as u32 + res.rgba[i + 1] as u32 + res.rgba[i + 2] as u32)
/ 3;
if lum < 120 {
lo_x = lo_x.min(x);
hi_x = hi_x.max(x);
lo_y = lo_y.min(y);
hi_y = hi_y.max(y);
}
}
}
if hi_x <= lo_x {
problems.push("ink_extent: nessun pixel scuro".to_string());
continue;
}
let (w, h) = ((hi_x - lo_x) as f64, (hi_y - lo_y) as f64);
if let Some(m) = e["min_w"].as_f64() {
if w < m {
problems.push(format!("inchiostro largo {:.1} < min_w {:.1}", w, m));
}
}
if let Some(m) = e["max_w"].as_f64() {
if w > m {
problems.push(format!("inchiostro largo {:.1} > max_w {:.1}", w, m));
}
}
if let Some(m) = e["min_h"].as_f64() {
if h < m {
problems.push(format!("inchiostro alto {:.1} < min_h {:.1}", h, m));
}
}
// limiti assoluti: servono a verificare l'allineamento (bidi, text-align)
if let Some(m) = e["min_x"].as_f64() {
if (lo_x as f64) < m {
problems.push(format!("inchiostro inizia a {:.1} < min_x {:.1}", lo_x, m));
}
}
if let Some(m) = e["max_x"].as_f64() {
if (hi_x as f64) > m {
problems.push(format!("inchiostro finisce a {:.1} > max_x {:.1}", hi_x, m));
}
}
}
}
// colore di singoli pixel: verifica cornici, spunte e anelli di fuoco
if let Some(pixels) = case["pixels"].as_array() {
for p in pixels {
let x = p["x"].as_u64().unwrap_or(0) as u32;
let y = p["y"].as_u64().unwrap_or(0) as u32;
let tol = p["tol"].as_f64().unwrap_or(24.0) as i32;
let atteso: Vec<i32> = p["rgb"]
.as_array()
.map(|a| a.iter().map(|v| v.as_i64().unwrap_or(0) as i32).collect())
.unwrap_or_default();
if atteso.len() != 3 {
problems.push("pixels: rgb mancante".to_string());
continue;
}
if x >= res.width || y >= res.height {
problems.push(format!("pixels: ({},{}) fuori immagine", x, y));
continue;
}
let i = ((y * res.width + x) * 4) as usize;
let trovato = [
res.rgba[i] as i32,
res.rgba[i + 1] as i32,
res.rgba[i + 2] as i32,
];
let diverso = (0..3)
.map(|k| (trovato[k] - atteso[k]).abs())
.max()
.unwrap_or(0);
if diverso > tol {
problems.push(format!(
"pixel ({},{}): trovato {:?}, atteso {:?} (tolleranza {})",
x, y, trovato, atteso, tol
));
}
}
}
if let Some(absent) = case["absent"].as_array() {
for a in absent {
if let Some(path) = a.as_str() {
if res.layout.find_path(path).is_some() {
problems.push(format!("box '{}' non dovrebbe esistere", path));
}
}
}
}
if let Some(inks) = case["ink"].as_array() {
for ink in inks {
let rect: Vec<f32> = ink["rect"]
.as_array()
.map(|a| a.iter().map(|v| v.as_f64().unwrap_or(0.0) as f32).collect())
.unwrap_or_default();
if rect.len() != 4 {
problems.push("ink: rect mancante".to_string());
continue;
}
let rgb: Vec<i32> = ink["rgb"]
.as_array()
.map(|a| a.iter().map(|v| v.as_i64().unwrap_or(0) as i32).collect())
.unwrap_or_default();
if rgb.len() < 3 {
problems.push("ink: rgb mancante".to_string());
continue;
}
let tol = ink["tol"].as_i64().unwrap_or(60) as i32;
let min = ink["min"].as_u64().unwrap_or(1) as usize;
let x0 = rect[0].floor().max(0.0) as u32;
let y0 = rect[1].floor().max(0.0) as u32;
let x1 = (rect[0] + rect[2]).ceil().min(res.width as f32) as u32;
let y1 = (rect[1] + rect[3]).ceil().min(res.height as f32) as u32;
let mut count = 0usize;
for y in y0..y1 {
for x in x0..x1 {
let idx = ((y * res.width + x) * 4) as usize;
let got = [
res.rgba[idx] as i32,
res.rgba[idx + 1] as i32,
res.rgba[idx + 2] as i32,
];
let d = (0..3).map(|c| (got[c] - rgb[c]).abs()).max().unwrap_or(255);
if d <= tol {
count += 1;
}
}
}
if count < min {
problems.push(format!(
"ink {:?} in {:?}: {} pixel, attesi almeno {}",
rgb, rect, count, min
));
}
}
}
if let Some(lines) = case["lines"].as_array() {
for l in lines {
let path = l["path"].as_str().unwrap_or("html");
let expected = l["count"].as_u64().unwrap_or(0) as usize;
match res.layout.find_path(path) {
None => problems.push(format!("box '{}' assente (righe)", path)),
Some(found) => {
if found.lines.len() != expected {
problems.push(format!(
"box '{}': righe attese {}, trovate {}",
path,
expected,
found.lines.len()
));
}
}
}
}
}
// golden PNG: creato al primo passaggio, confrontato dopo
if let Some(golden_name) = case["golden"].as_str() {
let golden_path = dir.join(golden_name);
if !golden_path.exists() {
pngio::write_rgba(&golden_path, res.width, res.height, &res.rgba)
.expect("scrittura golden");
println!("[bless] {} → {}", name, golden_path.display());
} else if bless {
pngio::write_rgba(&golden_path, res.width, res.height, &res.rgba)
.expect("scrittura golden");
} else {
match pngio::read_rgba(&golden_path) {
Err(e) => problems.push(format!("golden illeggibile: {}", e)),
Ok((gw, gh, grgba)) => {
if gw != res.width || gh != res.height {
problems.push(format!(
"golden {}x{}, atteso {}x{}",
gw, gh, res.width, res.height
));
} else {
let diff = pngio::mean_diff(&grgba, &res.rgba);
if diff > 2.0 {
problems.push(format!("golden: differenza media {:.2}/255", diff));
}
}
}
}
}
}
if let Some(dirpng) = &png_dir {
std::fs::create_dir_all(dirpng).ok();
pngio::write_rgba(
&dirpng.join(format!("{}.png", name)),
res.width,
res.height,
&res.rgba,
)
.ok();
}
if problems.is_empty() {
pass += 1;
println!(
"ok {:<32} parse {:.1}ms layout {:.1}ms | nodi {} box {} righe {}",
name,
res.timings.parse_ms,
res.timings.layout_ms,
res.page.doc.node_count(),
res.layout.box_count(),
res.layout.total_lines()
);
} else {
fail += 1;
println!("FAIL {}", name);
for p in &problems {
println!(" - {}", p);
}
failures.push(name);
}
}
println!("\n{} passati, {} falliti", pass, fail);
if !failures.is_empty() {
println!("falliti: {}", failures.join(", "));
let _ = Path::new(".");
std::process::exit(1);
}
}
+236
View File
@@ -0,0 +1,236 @@
//! CLI: HTML (+ CSS opzionale) → PNG e dump dell'albero dei box.
//!
//! Uso:
//! render --html pagina.html [--css extra.css] --out out.png [--size 800x600]
//! [--font /percorso/font.ttf] [--scale 1.0] [--tree tree.json]
use std::path::PathBuf;
use std::time::Instant;
use engine::layout::LayoutBox;
use engine::{pngio, render_with_form, RenderOptions};
fn main() {
let mut html_path: Option<PathBuf> = None;
let mut url: Option<String> = None;
let mut css_path: Option<PathBuf> = None;
let mut out_path: Option<PathBuf> = None;
let mut tree_path: Option<PathBuf> = None;
let mut size = (800u32, 600u32);
let mut scale = 1.0f32;
let mut auto_height = false;
let mut base_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut repeat = 1u32;
let mut font_path = default_font();
let mut form = engine::FormState::default();
let args: Vec<String> = std::env::args().skip(1).collect();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--html" => {
html_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--url" => {
url = Some(args[i + 1].clone());
i += 2;
}
"--css" => {
css_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--out" => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--tree" => {
tree_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--font" => {
font_path = PathBuf::from(&args[i + 1]);
i += 2;
}
"--scale" => {
scale = args[i + 1].parse().expect("--scale numerico");
i += 2;
}
"--base-dir" => {
base_dir = PathBuf::from(&args[i + 1]);
i += 2;
}
"--form-value" => {
if let Some((k, v)) = args[i + 1].split_once('=') {
form.values.insert(k.to_string(), v.to_string());
}
i += 2;
}
"--form-focus" => {
form.focus = Some(args[i + 1].clone());
i += 2;
}
"--form-caret" => {
form.caret = args[i + 1].parse::<usize>().ok();
i += 2;
}
"--form-select" => {
if let Some((a, b)) = args[i + 1].split_once(',') {
if let (Ok(a), Ok(b)) = (a.parse::<usize>(), b.parse::<usize>()) {
form.selection = Some((a, b));
}
}
i += 2;
}
"--form-open-select" => {
form.open_select = Some(args[i + 1].clone());
i += 2;
}
"--form-select-highlight" => {
form.select_highlight = args[i + 1].parse::<usize>().ok();
i += 2;
}
"--auto-height" => {
auto_height = true;
i += 1;
}
"--repeat" => {
repeat = args[i + 1].parse().expect("--repeat numerico");
i += 2;
}
"--size" => {
let v = &args[i + 1];
let (w, h) = v.split_once('x').expect("--size WxH");
size = (w.parse().expect("larghezza"), h.parse().expect("altezza"));
i += 2;
}
other => {
eprintln!("argomento non riconosciuto: {}", other);
std::process::exit(2);
}
}
}
let html_path = match &url {
Some(_) => PathBuf::new(),
None => html_path.expect("serve --html oppure --url"),
};
let out_path = out_path.unwrap_or_else(|| PathBuf::from("out.png"));
// con --url il documento arriva dalla rete; l'HTML locale resta il caso base
let html = match &url {
Some(u) => {
let risposta = match engine::net::get(u, &engine::net::Limiti::default()) {
Ok(r) => r,
Err(e) => {
// errore di rete: messaggio leggibile, nessuno stack trace
eprintln!("errore: richiesta a {} fallita: {}", u, e);
std::process::exit(1);
}
};
eprintln!("{} → HTTP {}", u, risposta.status);
match risposta.text() {
Ok(t) => t,
Err(e) => {
eprintln!("errore: corpo di {} inutilizzabile: {}", u, e);
std::process::exit(1);
}
}
}
None => std::fs::read_to_string(&html_path).expect("lettura HTML"),
};
let css = match css_path {
Some(p) => std::fs::read_to_string(p).expect("lettura CSS"),
None => String::new(),
};
let opts = RenderOptions {
viewport: size,
dpi_scale: scale,
font_path,
auto_height,
base_dir,
// con --url il documento viene dalla rete: i riferimenti relativi si
// risolvono su quell'indirizzo
base_url: url.clone(),
};
let started = Instant::now();
let res = match render_with_form(&html, &css, &opts, &form) {
Ok(r) => r,
Err(e) => {
eprintln!("errore: {}", e);
std::process::exit(1);
}
};
let total_ms = started.elapsed().as_secs_f64() * 1000.0;
// ripetizioni: servono a misurare il render a cache calda (zoom, scroll)
let mut warm_ms = Vec::new();
for _ in 1..repeat {
let t = Instant::now();
let _ = render_with_form(&html, &css, &opts, &form).expect("render ripetuto");
warm_ms.push(round3(t.elapsed().as_secs_f64() * 1000.0));
}
pngio::write_rgba(&out_path, res.width, res.height, &res.rgba).expect("scrittura PNG");
if let Some(tp) = tree_path {
let tree = dump_tree(&res.layout);
std::fs::write(&tp, serde_json::to_string_pretty(&tree).unwrap())
.expect("scrittura albero");
}
println!(
"{}",
serde_json::json!({
"png": out_path.display().to_string(),
"size": [res.width, res.height],
"nodes": res.page.doc.node_count(),
"boxes": res.layout.box_count(),
"lines": res.layout.total_lines(),
"cmds": res.cmds.len(),
"ms": {
"parse": round3(res.timings.parse_ms),
"style": round3(res.timings.style_ms),
"layout": round3(res.timings.layout_ms),
"display": round3(res.timings.display_ms),
"raster": round3(res.timings.raster_ms),
"paint": round3(res.timings.paint_ms),
"total": round3(total_ms),
},
"parse_errors": res.parse_errors,
"resource_errors": res.resource_errors,
"focusables": res.focusables.iter().map(|f| f.key.clone()).collect::<Vec<_>>(),
"warm_ms": warm_ms,
})
);
}
fn default_font() -> PathBuf {
if let Ok(p) = std::env::var("ENGINE_FONT") {
return PathBuf::from(p);
}
PathBuf::from("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")
}
fn round3(v: f64) -> f64 {
(v * 1000.0).round() / 1000.0
}
fn dump_tree(root: &LayoutBox) -> serde_json::Value {
fn walk(b: &LayoutBox, sibling_index: usize) -> serde_json::Value {
let children: Vec<serde_json::Value> = b
.children
.iter()
.enumerate()
.map(|(i, c)| walk(c, i))
.collect();
serde_json::json!({
"tag": b.tag,
"index": sibling_index,
"rect": [b.rect.x, b.rect.y, b.rect.w, b.rect.h],
"content": [b.content.x, b.content.y, b.content.w, b.content.h],
"lines": b.lines.len(),
"children": children,
})
}
walk(root, 0)
}