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

+706
View File
@@ -0,0 +1,706 @@
//! Display list e raster software.
//!
//! La display list è immutabile e non contiene riferimenti al DOM: su Sailfish è
//! esattamente questo codice a produrre i pixel (doc 11 §3).
use std::sync::Arc;
use crate::font::{FontHolder, ShapedText};
use crate::img::ImageData;
use crate::layout::{LayoutBox, Rect};
use crate::style::Color;
#[derive(Clone, Debug)]
pub enum Cmd {
Rect {
rect: Rect,
color: Color,
},
/// Immagine sostituita, già scalata al rettangolo.
Image {
rect: Rect,
data: Arc<ImageData>,
},
/// Controllo di modulo: il motore disegna la cornice e il valore.
Control {
rect: Rect,
kind: crate::layout::ControlKind,
text: String,
checked: bool,
focused: bool,
font: std::rc::Rc<FontHolder>,
size: f32,
color: Color,
/// ascissa del cursore rispetto al testo (px CSS)
caret_x: Option<f32>,
/// intervallo selezionato in ascissa (px CSS)
selection: Option<(f32, f32)>,
/// scorrimento orizzontale del testo (px CSS)
text_offset: f32,
/// righe (textarea) e riga del cursore
lines: Vec<String>,
caret_line: usize,
/// selezione per riga (textarea)
line_sel: Vec<Option<(f32, f32)>>,
},
/// Elenco aperto di un `select`: disegnato sopra tutto il resto.
SelectPopup {
rect: Rect,
row_h: f32,
labels: Vec<String>,
highlight: Option<usize>,
font: std::rc::Rc<FontHolder>,
size: f32,
},
/// Glifi già posizionati: nessuna stringa nel percorso caldo del raster.
Glyphs {
font: std::rc::Rc<FontHolder>,
shaped: ShapedText,
text: String,
x: f32,
baseline: f32,
size: f32,
weight: u16,
color: Color,
},
}
pub fn build_display_list(root: &LayoutBox, altezza_viewport: f32, out: &mut Vec<Cmd>) {
// gli elenchi aperti stanno sopra ogni altro comando
let mut popups: Vec<Cmd> = Vec::new();
let altezza_documento = if altezza_viewport > 0.0 {
altezza_viewport
} else {
root.rect.h
};
walk(root, out, &mut popups, altezza_documento);
out.extend(popups);
}
fn walk(b: &LayoutBox, out: &mut Vec<Cmd>, popups: &mut Vec<Cmd>, altezza_documento: f32) {
let bw = b.style.border_width;
// Elemento sostituito (immagine come blocco o float): prima dello sfondo.
if let Some((data, _, _)) = &b.replaced {
out.push(Cmd::Image {
rect: b.rect,
data: Arc::clone(data),
});
}
// Sfondo: padding box (il bordo lo copre).
if b.style.background.a > 0 {
let inner = b.rect.inset(bw[0], bw[1], bw[2], bw[3]);
if inner.w > 0.0 && inner.h > 0.0 {
out.push(Cmd::Rect {
rect: inner,
color: b.style.background,
});
}
}
// Bordi: quattro rettangoli, nessun raggio in M0.
let r = b.rect;
let sides = [
Rect::new(r.x, r.y, r.w, bw[0]),
Rect::new(r.right() - bw[1], r.y, bw[1], r.h),
Rect::new(r.x, r.bottom() - bw[2], r.w, bw[2]),
Rect::new(r.x, r.y, bw[3], r.h),
];
for (i, side) in sides.iter().enumerate() {
if bw[i] > 0.0 && b.style.border_color[i].a > 0 && side.w > 0.0 && side.h > 0.0 {
out.push(Cmd::Rect {
rect: *side,
color: b.style.border_color[i],
});
}
}
for line in &b.lines {
for run in &line.runs {
if let Some((data, w, h)) = &run.image {
out.push(Cmd::Image {
rect: Rect::new(run.x, run.baseline - *h, *w, *h),
data: Arc::clone(data),
});
continue;
}
if let Some(c) = &run.control {
if c.open && !c.options.is_empty() {
let riga = crate::layout::select_row_height(c.font_size);
let altezza_popup = riga * c.options.len() as f32;
let sotto = run.baseline - c.above + c.height;
let y = if sotto + altezza_popup > altezza_documento {
// non c'è spazio sotto: l'elenco si apre verso l'alto
(run.baseline - c.above - altezza_popup).max(0.0)
} else {
sotto
};
let rect = Rect::new(run.x, y, c.popup_width, altezza_popup);
popups.push(Cmd::SelectPopup {
rect,
row_h: riga,
labels: c.options.iter().map(|(e, _)| e.clone()).collect(),
highlight: c.highlight,
font: std::rc::Rc::clone(&run.font),
size: c.font_size,
});
}
out.push(Cmd::Control {
rect: Rect::new(run.x, run.baseline - c.above, c.width, c.height),
kind: c.kind,
text: c.text.clone(),
checked: c.checked,
focused: c.focused,
font: std::rc::Rc::clone(&run.font),
size: c.font_size,
color: c.color,
caret_x: c.caret_x,
selection: c.selection,
text_offset: c.text_offset,
lines: c.lines.clone(),
caret_line: c.caret_line,
line_sel: c.line_sel.clone(),
});
continue;
}
out.push(Cmd::Glyphs {
font: std::rc::Rc::clone(&run.font),
shaped: run.shaped.clone(),
text: run.text.clone(),
x: run.x,
baseline: run.baseline,
size: run.font_size,
weight: run.font_weight,
color: run.color,
});
}
}
for c in &b.children {
walk(c, out, popups, altezza_documento);
}
}
/// Sfondo bianco (canvas Mosaic), poi i comandi in ordine.
/// `scale` converte i pixel CSS in pixel del dispositivo: si scala la geometria
/// prima del raster, non l'immagine dopo (altrimenti il testo sfoca).
pub fn rasterize(cmds: &[Cmd], w: u32, h: u32, scale: f32) -> Vec<u8> {
let stats = std::env::var("ENGINE_PAINT_STATS").is_ok();
let mut rect_px: u64 = 0;
let mut text_cmds: u64 = 0;
let mut text_chars: u64 = 0;
let mut buf = vec![255u8; (w as usize) * (h as usize) * 4];
for cmd in cmds {
match cmd {
Cmd::Rect { rect, color } => {
if stats {
rect_px += (rect.w * scale).max(0.0) as u64 * (rect.h * scale).max(0.0) as u64;
}
fill_rect(
&mut buf,
w,
h,
Rect::new(
rect.x * scale,
rect.y * scale,
rect.w * scale,
rect.h * scale,
),
*color,
);
}
Cmd::Image { rect, data } => {
crate::img::draw_image(
&mut buf,
w,
h,
(
rect.x * scale,
rect.y * scale,
rect.w * scale,
rect.h * scale,
),
data,
);
}
Cmd::SelectPopup {
rect,
row_h,
labels,
highlight,
font,
size,
} => {
let r = Rect::new(
rect.x * scale,
rect.y * scale,
rect.w * scale,
rect.h * scale,
);
let riga = *row_h * scale;
// ombra leggera, fondo bianco e cornice
fill_rect(
&mut buf,
w,
h,
Rect::new(r.x + 2.0, r.y + 2.0, r.w, r.h),
Color {
r: 0,
g: 0,
b: 0,
a: 40,
},
);
fill_rect(
&mut buf,
w,
h,
r,
Color {
r: 255,
g: 255,
b: 255,
a: 255,
},
);
for (i, etichetta) in labels.iter().enumerate() {
let riga_rect = Rect::new(r.x, r.y + i as f32 * riga, r.w, riga);
if *highlight == Some(i) {
fill_rect(
&mut buf,
w,
h,
riga_rect,
Color {
r: 26,
g: 95,
b: 180,
a: 255,
},
);
}
let px = size * scale;
let shaped = font.shape_dir(etichetta, px, false);
let colore = if *highlight == Some(i) {
Color {
r: 255,
g: 255,
b: 255,
a: 255,
}
} else {
Color {
r: 0,
g: 0,
b: 0,
a: 255,
}
};
font.draw_shaped(
&mut buf,
w,
h,
r.x + 8.0 * scale,
riga_rect.y + riga * 0.72,
&shaped,
px,
px,
colore,
400,
);
}
frame_rect(
&mut buf,
w,
h,
r,
Color {
r: 118,
g: 118,
b: 118,
a: 255,
},
(1.0 * scale).max(1.0),
);
}
Cmd::Control {
rect,
kind,
text,
checked,
focused,
font,
size,
color,
caret_x,
selection,
text_offset,
lines,
caret_line,
line_sel,
} => {
draw_control(
&mut buf,
w,
h,
Rect::new(
rect.x * scale,
rect.y * scale,
rect.w * scale,
rect.h * scale,
),
*kind,
text,
*checked,
*focused,
font,
*size,
scale,
*color,
*caret_x,
*selection,
*text_offset,
lines,
*caret_line,
line_sel,
);
}
Cmd::Glyphs {
font,
shaped,
text,
x,
baseline,
size,
weight,
color,
} => {
if stats {
text_cmds += 1;
text_chars += text.chars().count() as u64;
}
font.draw_shaped(
&mut buf,
w,
h,
x * scale,
baseline * scale,
shaped,
*size,
size * scale,
*color,
*weight,
);
}
}
}
if stats {
eprintln!(
"paint-stats: rect_px={} text_cmds={} text_chars={} area={}",
rect_px,
text_cmds,
text_chars,
w as u64 * h as u64
);
}
buf
}
/// Disegna un controllo di modulo: cornice, sfondo, valore, eventuale spunta e
/// anello di fuoco. Il rettangolo è già in pixel del dispositivo.
#[allow(clippy::too_many_arguments)]
fn draw_control(
buf: &mut [u8],
w: u32,
h: u32,
r: Rect,
kind: crate::layout::ControlKind,
text: &str,
checked: bool,
focused: bool,
font: &std::rc::Rc<FontHolder>,
size_css: f32,
scale: f32,
color: Color,
caret_x: Option<f32>,
selection: Option<(f32, f32)>,
text_offset: f32,
lines: &[String],
caret_line: usize,
line_sel: &[Option<(f32, f32)>],
) {
use crate::layout::ControlKind;
const BORDO: Color = Color {
r: 118,
g: 118,
b: 118,
a: 255,
};
const FUOCO: Color = Color {
r: 26,
g: 95,
b: 180,
a: 255,
};
const BIANCO: Color = Color {
r: 255,
g: 255,
b: 255,
a: 255,
};
const GRIGIO: Color = Color {
r: 232,
g: 232,
b: 232,
a: 255,
};
let bordo = if focused { FUOCO } else { BORDO };
match kind {
ControlKind::Checkbox | ControlKind::Radio => {
fill_rect(buf, w, h, r, BIANCO);
frame_rect(buf, w, h, r, bordo, (scale).max(1.0));
if checked {
let inset = (r.w * 0.28).max(1.0);
if kind == ControlKind::Radio {
// cerchio: una fascia per riga di pixel, ampiezza dal teorema
// di Pitagora — a 13 px una approssimazione grossolana si
// legge come un quadrato
let passo = 1.0f32;
let mut y = r.y + inset;
while y < r.bottom() - inset {
let dy = (y + passo / 2.0) - (r.y + r.h / 2.0);
let mezza = (r.w / 2.0 - inset.max(1.0)).max(0.0);
let ampiezza = (mezza * mezza - dy * dy).max(0.0).sqrt();
if ampiezza > 0.5 {
fill_rect(
buf,
w,
h,
Rect::new(r.x + r.w / 2.0 - ampiezza, y, ampiezza * 2.0, passo),
FUOCO,
);
}
y += passo;
}
} else {
fill_rect(buf, w, h, r.inset(inset, inset, inset, inset), FUOCO);
}
}
}
_ => {
let sfondo = if kind == ControlKind::Button {
GRIGIO
} else {
BIANCO
};
fill_rect(buf, w, h, r, sfondo);
let spessore = (1.0 * scale).max(1.0);
frame_rect(buf, w, h, r, bordo, spessore);
if focused {
frame_rect(
buf,
w,
h,
r.inset(
spessore * 2.0,
spessore * 2.0,
spessore * 2.0,
spessore * 2.0,
),
FUOCO,
spessore,
);
}
// rientro del testo dentro il controllo (lo stesso usato per i glifi)
let rientro = 4.0 * scale;
let px = size_css * scale;
let interlinea = px * 1.35;
let textarea = kind == ControlKind::Textarea;
let scorrimento = text_offset * scale;
// ritaglio orizzontale: il testo non esce dal riquadro
let clip = Some((r.x + rientro - 1.0, r.right() - rientro + 1.0));
let baseline = if textarea {
r.y + interlinea * 0.85
} else {
r.y + (r.h + px * 0.72) / 2.0
};
let altezza_testo = px * 1.2;
let top_testo = baseline - px * 0.78;
// selezione sulle righe della textarea
if textarea {
for (i, sel) in line_sel.iter().enumerate() {
if let Some((x0, x1)) = sel {
let base = baseline + i as f32 * interlinea;
let (x0, x1) = (*x0, *x1);
let da = r.x + rientro + x0.min(x1) * scale;
let a = r.x + rientro + x0.max(x1) * scale;
if a > da {
fill_rect(
buf,
w,
h,
Rect::new(da, base - px * 0.78, a - da, px * 1.2),
Color {
r: 180,
g: 205,
b: 240,
a: 255,
},
);
}
}
}
}
// selezione: fascia dietro il testo, prima dei glifi (solo riga singola)
if !textarea {
if let Some((x0, x1)) = selection {
let da = r.x + rientro + x0.min(x1) * scale - scorrimento;
let a = r.x + rientro + x0.max(x1) * scale - scorrimento;
if a > da {
fill_rect(
buf,
w,
h,
Rect::new(da, top_testo, a - da, altezza_testo),
Color {
r: 180,
g: 205,
b: 240,
a: 255,
},
);
}
}
}
let x_testo = r.x + rientro - scorrimento;
if textarea {
// una riga per ogni \n, fermandosi quando si esce dal riquadro
for (i, riga) in lines.iter().enumerate() {
let base_riga = baseline + i as f32 * interlinea;
if base_riga - px > r.bottom() {
break;
}
if riga.is_empty() {
continue;
}
let shaped = font.shape_dir(riga, px, false);
font.draw_shaped_in(
buf, w, h, x_testo, base_riga, &shaped, px, px, color, 400, clip,
);
}
} else if !text.is_empty() {
let shaped = font.shape_dir(text, px, false);
font.draw_shaped_in(
buf, w, h, x_testo, baseline, &shaped, px, px, color, 400, clip,
);
}
// cursore: barra verticale dove finisce il testo precedente
if let Some(cx) = caret_x {
let (car_y, car_h) = if textarea {
let base = baseline + caret_line as f32 * interlinea;
(base - px * 0.78, altezza_testo)
} else {
(top_testo, altezza_testo)
};
fill_rect(
buf,
w,
h,
Rect::new(
r.x + rientro + cx * scale - scorrimento,
car_y,
(1.5 * scale).max(1.0),
car_h,
),
Color {
r: 0,
g: 0,
b: 0,
a: 255,
},
);
}
if kind == ControlKind::Select {
// freccia del menu a tendina: triangolo verso il basso
let cx = r.right() - 10.0 * scale;
let cy = r.y + r.h / 2.0 - 2.0 * scale;
for i in 0..6 {
let larghezza = (6 - i) as f32 * scale;
fill_rect(
buf,
w,
h,
Rect::new(
cx - larghezza,
cy + i as f32 * scale,
larghezza * 2.0,
scale,
),
BORDO,
);
}
}
}
}
}
/// Cornice di spessore dato attorno al rettangolo (quattro fasce).
fn frame_rect(buf: &mut [u8], w: u32, h: u32, r: Rect, color: Color, t: f32) {
fill_rect(buf, w, h, Rect::new(r.x, r.y, r.w, t), color);
fill_rect(buf, w, h, Rect::new(r.x, r.bottom() - t, r.w, t), color);
fill_rect(buf, w, h, Rect::new(r.x, r.y, t, r.h), color);
fill_rect(buf, w, h, Rect::new(r.right() - t, r.y, t, r.h), color);
}
fn fill_rect(buf: &mut [u8], w: u32, h: u32, rect: Rect, color: Color) {
let x0 = rect.x.floor().max(0.0) as i64;
let y0 = rect.y.floor().max(0.0) as i64;
let x1 = rect.right().ceil().min(w as f32) as i64;
let y1 = rect.bottom().ceil().min(h as f32) as i64;
if x1 <= x0 || y1 <= y0 {
return;
}
// Percorso rapido: colore opaco. È il caso dello sfondo di pagina, che copre
// quasi tutta l'immagine: si prepara una riga e la si copia con memcpy.
// Il ciclo pixel-per-pixel costava 60 ns/px, cioè ~100 ms su una pagina piena.
if color.a == 255 {
let px = [color.r, color.g, color.b, 255u8];
let row_px = (x1 - x0) as usize;
let row_bytes = row_px * 4;
let mut row: Vec<u8> = Vec::with_capacity(row_bytes);
for _ in 0..row_px {
row.extend_from_slice(&px);
}
for y in y0..y1 {
let start = ((y as u32 * w + x0 as u32) * 4) as usize;
buf[start..start + row_bytes].copy_from_slice(&row);
}
return;
}
let a = color.a as f32 / 255.0;
for y in y0..y1 {
for x in x0..x1 {
let idx = ((y as u32 * w + x as u32) * 4) as usize;
for c in 0..3 {
let src = match c {
0 => color.r,
1 => color.g,
_ => color.b,
} as f32;
buf[idx + c] = (src * a + buf[idx + c] as f32 * (1.0 - a))
.round()
.clamp(0.0, 255.0) as u8;
}
buf[idx + 3] = 255;
}
}
}