//! 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 = None;
let mut url: Option = None;
let mut css_path: Option = None;
let mut out_path: Option = None;
let mut tree_path: Option = 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 = 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::().ok();
i += 2;
}
"--form-select" => {
if let Some((a, b)) = args[i + 1].split_once(',') {
if let (Ok(a), Ok(b)) = (a.parse::(), b.parse::()) {
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::().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::>(),
"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 = 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)
}