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

+213
View File
@@ -0,0 +1,213 @@
//! Eventi e stile dal codice (M2.5b), provati come li usa il guscio: documento
//! vivo, macchina JavaScript che resta in piedi, clic consegnato al nodo sotto il
//! puntatore, pagina ridisegnata dal DOM modificato.
use std::path::PathBuf;
use engine::{render_contenuto, script::Macchina, ContenutoPagina, FormState, RenderOptions};
fn opzioni() -> RenderOptions {
let mut font = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
font.push("cases/mono.ttf");
RenderOptions {
viewport: (200, 160),
dpi_scale: 1.0,
font_path: font,
auto_height: true,
base_dir: PathBuf::from("."),
base_url: None,
}
}
fn nodo_con_id(doc: &engine::dom::Document, id: &str) -> usize {
for (i, n) in doc.nodes.iter().enumerate() {
if let engine::dom::NodeKind::Element(e) = &n.kind {
if e.attr("id") == Some(id) {
return i;
}
}
}
panic!("nodo {} assente", id);
}
fn catena(doc: &engine::dom::Document, nodo: usize) -> Vec<usize> {
let mut out = Vec::new();
let mut corrente = Some(nodo);
while let Some(n) = corrente {
out.push(n);
corrente = doc.nodes.get(n).and_then(|x| x.parent);
}
out
}
fn conta(res: &engine::RenderResult, rgb: [u8; 3]) -> usize {
res.rgba
.chunks_exact(4)
.filter(|p| p[0] == rgb[0] && p[1] == rgb[1] && p[2] == rgb[2])
.count()
}
const PAGINA: &str = concat!(
"<html><body style=\"margin:0\">",
"<div id=\"riquadro\" style=\"width:60px;height:40px;background:#0000ff\">x</div>",
"<script>",
"document.getElementById('riquadro').addEventListener('click', function (ev) {",
" this.style.backgroundColor = '#ff0000';",
" this.textContent = 'premuto a ' + ev.clientX;",
"});",
"</script>",
"</body></html>"
);
#[test]
fn clic_cambia_colore_e_testo_e_la_pagina_si_ridisegna() {
let mut contenuto = ContenutoPagina::da_html(PAGINA);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = contenuto.esegui_script(&mut macchina);
assert!(errori.is_empty(), "errori script: {:?}", errori);
// prima del clic: riquadro blu, nessun rosso
let prima =
render_contenuto(&contenuto, "", &opzioni(), &FormState::default()).expect("render");
assert!(conta(&prima, [0, 0, 255]) > 500, "il riquadro non è blu");
assert_eq!(conta(&prima, [255, 0, 0]), 0);
// il clic arriva al nodo e ai suoi antenati
let nodo = nodo_con_id(&contenuto.doc, "riquadro");
let rami = catena(&contenuto.doc, nodo);
let eseguiti = macchina.clic(&mut contenuto.doc, &rami, 17.0, 9.0);
assert_eq!(eseguiti, 1, "il gestore non è stato eseguito");
// dopo il clic: rosso al posto del blu
let dopo = render_contenuto(&contenuto, "", &opzioni(), &FormState::default()).expect("render");
assert!(conta(&dopo, [255, 0, 0]) > 500, "il colore non è cambiato");
assert_eq!(conta(&dopo, [0, 0, 255]), 0);
}
#[test]
fn il_clic_risale_agli_antenati() {
// l'ascoltatore sta sul contenitore, il clic cade sul figlio
let html = concat!(
"<html><body style=\"margin:0\">",
"<div id=\"scatola\" style=\"width:80px;height:60px;background:#00aa00\">",
"<span id=\"dentro\">testo</span>",
"</div>",
"<script>",
"document.getElementById('scatola').addEventListener('click', function () {",
" this.style.backgroundColor = '#000000';",
"});",
"</script></body></html>"
);
let mut contenuto = ContenutoPagina::da_html(html);
let mut macchina = Macchina::nuova().expect("interprete");
contenuto.esegui_script(&mut macchina);
let nodo = nodo_con_id(&contenuto.doc, "dentro");
let rami = catena(&contenuto.doc, nodo);
let eseguiti = macchina.clic(&mut contenuto.doc, &rami, 5.0, 5.0);
assert_eq!(eseguiti, 1, "l'antenato non ha ricevuto l'evento");
let res = render_contenuto(&contenuto, "", &opzioni(), &FormState::default()).expect("render");
assert!(conta(&res, [0, 0, 0]) > 100, "lo sfondo non è cambiato");
}
#[test]
fn il_clic_aggiunge_un_elemento_alla_pagina() {
let html = concat!(
"<html><body style=\"margin:0\">",
"<div id=\"zona\" style=\"width:120px;height:40px;background:#0000ff\">x</div>",
"<script>",
"document.getElementById('zona').addEventListener('click', function () {",
" var p = document.createElement('p');",
" p.textContent = 'nuovo';",
" p.style.backgroundColor = '#ff0000';",
" p.style.height = '30px';",
" document.body.appendChild(p);",
"});",
"</script></body></html>"
);
let mut contenuto = ContenutoPagina::da_html(html);
let mut macchina = Macchina::nuova().expect("interprete");
contenuto.esegui_script(&mut macchina);
let prima =
render_contenuto(&contenuto, "", &opzioni(), &FormState::default()).expect("render");
assert_eq!(
conta(&prima, [255, 0, 0]),
0,
"il rosso non deve esserci prima"
);
let nodo = nodo_con_id(&contenuto.doc, "zona");
let rami = catena(&contenuto.doc, nodo);
assert_eq!(macchina.clic(&mut contenuto.doc, &rami, 10.0, 10.0), 1);
let dopo = render_contenuto(&contenuto, "", &opzioni(), &FormState::default()).expect("render");
assert!(
conta(&dopo, [255, 0, 0]) > 1000,
"il paragrafo nuovo non è stato disegnato"
);
// il paragrafo nuovo sta **sotto** il riquadro blu, non al suo posto:
// i primi pixel rossi devono cadere oltre i 40 px del riquadro
let mut prima_riga_rossa = u32::MAX;
for y in 0..dopo.height {
for x in 0..dopo.width {
let i = ((y * dopo.width + x) * 4) as usize;
if dopo.rgba[i] == 255 && dopo.rgba[i + 1] == 0 && dopo.rgba[i + 2] == 0 {
prima_riga_rossa = prima_riga_rossa.min(y);
}
}
}
assert!(
prima_riga_rossa >= 40,
"il paragrafo nuovo è finito sopra il riquadro (y={})",
prima_riga_rossa
);
}
#[test]
fn senza_ascoltatori_il_clic_non_ridisegna() {
let html = "<html><body><div id=\"t\">fermo</div></body></html>";
let mut contenuto = ContenutoPagina::da_html(html);
let mut macchina = Macchina::nuova().expect("interprete");
contenuto.esegui_script(&mut macchina);
let nodo = nodo_con_id(&contenuto.doc, "t");
let rami = catena(&contenuto.doc, nodo);
assert_eq!(macchina.clic(&mut contenuto.doc, &rami, 1.0, 1.0), 0);
}
#[test]
fn due_clic_si_sommano() {
// il gestore incrementa un contatore: prova che lo stato JS sopravvive
let html = concat!(
"<html><body style=\"margin:0\">",
"<div id=\"t\" style=\"width:60px;height:30px;background:#0000ff\">x</div>",
"<script>",
"var n = 0;",
"document.getElementById('t').addEventListener('click', function () {",
" n = n + 1;",
" this.textContent = 'clic ' + n;",
"});",
"</script></body></html>"
);
let mut contenuto = ContenutoPagina::da_html(html);
let mut macchina = Macchina::nuova().expect("interprete");
contenuto.esegui_script(&mut macchina);
let nodo = nodo_con_id(&contenuto.doc, "t");
let rami = catena(&contenuto.doc, nodo);
macchina.clic(&mut contenuto.doc, &rami, 1.0, 1.0);
macchina.clic(&mut contenuto.doc, &rami, 1.0, 1.0);
// il testo del nodo contiene "clic 2"
let testo = contenuto
.doc
.node(nodo)
.children
.iter()
.filter_map(|c| match &contenuto.doc.node(*c).kind {
engine::dom::NodeKind::Text(t) => Some(t.clone()),
_ => None,
})
.collect::<String>();
assert_eq!(testo.trim(), "clic 2");
}
+152
View File
@@ -0,0 +1,152 @@
/* Verifica del confine C: compila contro engine.h e linka libengine.a.
* Se questo programma passa, il contratto dell'API è rispettato. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "engine.h"
static int fails = 0;
static void check(int cond, const char *what) {
printf("%s %s\n", cond ? "ok " : "FAIL", what);
if (!cond) fails++;
}
int main(int argc, char **argv) {
const char *font = argc > 1 ? argv[1] : "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf";
printf("versione: %s\n", engine_version());
/* 1. rettangolo: il pixel interno deve essere del colore dichiarato */
const char *html =
"<div style=\"width:40px;height:20px;background:#ff0000\"></div>";
EngineImage *img = engine_render(html, "", 100, 60, 1.0f, 0, font, "");
check(img != NULL, "engine_render restituisce un'immagine");
if (img) {
check(img->error == NULL, "nessun errore");
check(img->width == 100 && img->height == 60, "dimensioni del buffer");
if (img->pixels) {
/* body margin 8: il div parte a (8,8) */
size_t idx = (size_t)((10 * img->width) + 10) * 4;
check(img->pixels[idx] == 255 && img->pixels[idx + 1] == 0 &&
img->pixels[idx + 2] == 0,
"pixel (10,10) rosso");
size_t idx2 = (size_t)((10 * img->width) + 80) * 4;
check(img->pixels[idx2] == 255 && img->pixels[idx2 + 1] == 255,
"pixel (80,10) bianco");
}
engine_image_free(img);
}
/* 2. testo: glyph rasterizzati presenti nel buffer */
const char *html2 = "<p style=\"font-size:24px\">Prova</p>";
EngineImage *img2 = engine_render(html2, "", 200, 100, 1.0f, 0, font, "");
if (img2 && img2->pixels) {
int dark = 0;
for (size_t i = 0; i < img2->len; i += 4) {
if (img2->pixels[i] < 100 && img2->pixels[i + 1] < 100) dark++;
}
check(dark > 50, "testo rasterizzato (pixel scuri)");
engine_image_free(img2);
} else {
check(0, "immagine di testo prodotta");
}
/* 3. errore: font inesistente non deve crashare, deve riportare un errore */
EngineImage *img3 = engine_render("<p>x</p>", "", 50, 50, 1.0f, 0, "/non/esiste.ttf", "");
check(img3 != NULL, "errore restituito come immagine");
if (img3) {
check(img3->error != NULL, "messaggio di errore presente");
check(img3->pixels == NULL, "nessun pixel in caso di errore");
printf(" messaggio: %s\n", img3->error ? img3->error : "(null)");
engine_image_free(img3);
}
/* 3b. stato dei moduli: l'elenco aperto deve arrivare al motore */
{
const char *form_html =
"<p style=\"margin:0\"><select><option>uno</option>"
"<option selected>due</option></select></p>";
const char *stato = "{\"open_select\":\"html>body:0>p:0>select:0\","
"\"select_highlight\":1}";
EngineImage *imgf = engine_render_form(form_html, "", 200, 120, 1.0f, 0,
font, "", stato);
check(imgf != NULL, "engine_render_form risponde");
if (imgf) {
check(imgf->error == NULL, "nessun errore con lo stato dei moduli");
check(imgf->controls != NULL, "elenco dei controlli presente");
if (imgf->controls) {
/* con il select aperto il guscio deve ricevere il rettangolo
* dell'elenco: senza, il menù non si può disegnare né toccare */
check(strstr(imgf->controls, "\"popup\"") != NULL &&
strstr(imgf->controls, "\"uno\"") != NULL,
"lo stato open_select arriva al motore (popup + opzioni)");
printf(" controlli: %.120s...\n", imgf->controls);
}
engine_image_free(imgf);
}
}
/* 3c. rete: un indirizzo impossibile deve dare errore, non un crash */
{
int stato = 0;
char *errore = NULL;
char *testo = engine_fetch("ftp://esempio.test/", &stato, &errore);
check(testo == NULL, "schema non supportato: nessun testo");
check(errore != NULL, "schema non supportato: messaggio presente");
if (errore) {
check(strstr(errore, "schema") != NULL, "messaggio sulla schema");
engine_string_free(errore);
}
check(stato == 0, "nessun codice HTTP senza risposta");
}
/* 4. viewport nullo */
EngineImage *img4 = engine_render("<p>x</p>", "", 0, 50, 1.0f, 0, font, "");
check(img4 && img4->error != NULL, "viewport nullo segnalato");
engine_image_free(img4);
engine_image_free(NULL); /* idempotente */
/* 5. scala 2: la geometria raddoppia (viewport CSS 100, div 40x20 a (8,8)) */
EngineImage *img5 = engine_render(html, "", 200, 120, 2.0f, 0, font, "");
if (img5 && img5->pixels && img5->width == 200) {
size_t a = (size_t)((20 * img5->width) + 20) * 4;
size_t b = (size_t)((20 * img5->width) + 110) * 4;
check(img5->pixels[a] == 255 && img5->pixels[a + 1] == 0, "scala 2: pixel interno rosso");
check(img5->pixels[b] == 255 && img5->pixels[b + 1] == 255, "scala 2: fuori dal box bianco");
engine_image_free(img5);
} else {
check(0, "immagine a scala 2 prodotta");
}
/* 6. auto_height: l'immagine è alta quanto il documento */
const char *tall =
"<div style=\"height:300px;background:#00ff00\"></div>";
EngineImage *img6 = engine_render(tall, "", 100, 40, 1.0f, 1, font, "");
if (img6 && img6->pixels) {
check(img6->height > 300, "auto_height: immagine più alta del viewport richiesto");
engine_image_free(img6);
} else {
check(0, "immagine con auto_height prodotta");
}
/* 7. immagine da data URI: un PNG 1x1 rosso scalato a 20x20 */
const char *html_img =
"<img src=\"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
"\" width=\"20\" height=\"20\">";
EngineImage *img7 = engine_render(html_img, "", 100, 100, 1.0f, 0, font, "");
if (img7 && img7->pixels) {
/* body margin 8: l'immagine parte a (8,8) */
size_t i7 = (size_t)((12 * img7->width) + 12) * 4;
check(img7->pixels[i7] > 200 && img7->pixels[i7 + 1] < 60 && img7->pixels[i7 + 2] < 60,
"immagine disegnata (rosso)");
engine_image_free(img7);
} else {
check(0, "immagine con data URI prodotta");
}
printf("\n%s\n", fails == 0 ? "confine C: tutto ok" : "confine C: FALLITO");
return fails == 0 ? 0 : 1;
}
+179
View File
@@ -0,0 +1,179 @@
//! Sotto-risorse dalla rete (M2.6), provate sul serio: un server locale serve la
//! pagina, il foglio di stile e l'immagine separatamente, e il test guarda i
//! pixel che ne risultano. Niente internet: la CI resta deterministica.
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::thread;
use engine::{render_with_form, FormState, RenderOptions};
const PAGINA: &str = concat!(
"<!doctype html><html><head><meta charset=\"utf-8\">",
"<link rel=\"stylesheet\" href=\"stile.css\">",
"</head><body><h1>Titolo</h1><p>testo</p>",
"<img src=\"img/quadrato.png\" width=\"40\" height=\"40\">",
"</body></html>"
);
const STILE: &str = "body{margin:0;padding:4px}h1{color:#cc0000;font-size:24px;margin:0}\
p{margin:0;font-size:12px}";
fn font() -> PathBuf {
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.push("cases/mono.ttf");
p
}
fn immagine() -> Vec<u8> {
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.push("cases/quadrato-blu.png");
std::fs::read(p).expect("quadrato di prova")
}
/// Server usa-e-getta: risponde con l'elenco dato e chiude. `404` per il resto.
fn server(risposte: Vec<(String, String, Vec<u8>)>) -> u16 {
let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera");
let porta = ascolto.local_addr().unwrap().port();
thread::spawn(move || {
for flusso in ascolto.incoming().flatten() {
let mut flusso = flusso;
let mut buf = [0u8; 4096];
let n = flusso.read(&mut buf).unwrap_or(0);
let richiesta = String::from_utf8_lossy(&buf[..n]).to_string();
let percorso = richiesta
.split_whitespace()
.nth(1)
.unwrap_or("/")
.to_string();
let trovato = risposte.iter().find(|(p, _, _)| *p == percorso);
let (codice, tipo, corpo) = match trovato {
Some((_, tipo, corpo)) => ("200 OK", tipo.clone(), corpo.clone()),
None => (
"404 Not Found",
"text/plain".to_string(),
b"non c'e'".to_vec(),
),
};
let testa = format!(
"HTTP/1.1 {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
codice,
tipo,
corpo.len()
);
let _ = flusso.write_all(testa.as_bytes());
let _ = flusso.write_all(&corpo);
}
});
porta
}
fn opzioni(porta: u16) -> RenderOptions {
RenderOptions {
viewport: (300, 200),
dpi_scale: 1.0,
font_path: font(),
auto_height: true,
base_dir: PathBuf::from("."),
base_url: Some(format!("http://127.0.0.1:{}/pagina.html", porta)),
}
}
fn conta(res: &engine::RenderResult, rgb: [u8; 3]) -> usize {
res.rgba
.chunks_exact(4)
.filter(|p| p[0] == rgb[0] && p[1] == rgb[1] && p[2] == rgb[2])
.count()
}
#[test]
fn stile_esterno_e_immagine_arrivano_dalla_rete() {
let porta = server(vec![
(
"/pagina.html".to_string(),
"text/html".to_string(),
PAGINA.as_bytes().to_vec(),
),
(
"/stile.css".to_string(),
"text/css".to_string(),
STILE.as_bytes().to_vec(),
),
(
"/img/quadrato.png".to_string(),
"image/png".to_string(),
immagine(),
),
]);
let res = render_with_form(PAGINA, "", &opzioni(porta), &FormState::default()).expect("render");
assert!(
res.resource_errors.is_empty(),
"sotto-risorse fallite: {:?}",
res.resource_errors
);
// il colore del titolo viene dal foglio esterno
assert!(
conta(&res, [0xcc, 0x00, 0x00]) > 50,
"il foglio esterno non è stato applicato"
);
// l'immagine: 40x40 px tutti blu
assert!(
conta(&res, [0x00, 0x00, 0xff]) >= 40 * 40,
"l'immagine non è stata scaricata e disegnata"
);
}
#[test]
fn risorsa_mancante_e_un_errore_riportato_non_un_render_rotto() {
let html = "<html><head><link rel=\"stylesheet\" href=\"manca.css\"></head>\
<body><p>testo comunque impaginato</p></body></html>";
let porta = server(vec![(
"/pagina.html".to_string(),
"text/html".to_string(),
html.as_bytes().to_vec(),
)]);
let res = render_with_form(html, "", &opzioni(porta), &FormState::default())
.expect("il render non deve fallire per una sotto-risorsa mancante");
assert_eq!(res.resource_errors.len(), 1, "{:?}", res.resource_errors);
assert!(
res.resource_errors[0].contains("404"),
"{:?}",
res.resource_errors
);
assert!(res.layout.rect.h > 0.0, "la pagina è comunque impaginata");
}
#[test]
fn documenti_locali_non_escono_in_rete() {
// senza base_url nessuna richiesta: la pagina resta quella di sempre
let opts = RenderOptions {
viewport: (200, 120),
dpi_scale: 1.0,
font_path: font(),
auto_height: true,
base_dir: PathBuf::from("."),
base_url: None,
};
let html = "<html><head><link rel=\"stylesheet\" href=\"http://127.0.0.1:1/x.css\">\
</head><body><p>solo locale</p></body></html>";
let res = render_with_form(html, "", &opts, &FormState::default()).expect("render");
assert!(res.resource_errors.is_empty(), "{:?}", res.resource_errors);
}
#[test]
fn risoluzione_dei_riferimenti() {
use engine::resource::risolvi_url;
assert_eq!(
risolvi_url(Some("https://a.test/d/p.html"), "../i/a.png").as_deref(),
Some("https://a.test/i/a.png")
);
assert_eq!(
risolvi_url(Some("https://a.test/d/p.html"), "s.css").as_deref(),
Some("https://a.test/d/s.css")
);
assert_eq!(risolvi_url(None, "s.css"), None);
// il client HTTP accetta solo http/https: gli altri schemi non si risolvono
assert_eq!(risolvi_url(Some("ftp://a.test/"), "s.css"), None);
}