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.
2330 lines
88 KiB
Rust
2330 lines
88 KiB
Rust
//! Layout block flow + inline (M1). Fuori ambito: float, posizionamento, tabelle,
|
|
//! flex/grid — vedi doc 05 per la progressione.
|
|
|
|
use std::cell::RefCell;
|
|
use std::sync::Arc;
|
|
|
|
use crate::bidi;
|
|
use crate::dom::{Document, NodeId, NodeKind};
|
|
use crate::font::{FontHolder, Fonts, ShapedText};
|
|
use crate::img::{ImageCache, ImageData};
|
|
use crate::style::{
|
|
AlignItems, Color, ComputedStyle, Display, FlexDirection, FlexWrap, FloatSide, JustifyContent,
|
|
Position, TextAlign, WhiteSpace,
|
|
};
|
|
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
|
pub struct Rect {
|
|
pub x: f32,
|
|
pub y: f32,
|
|
pub w: f32,
|
|
pub h: f32,
|
|
}
|
|
|
|
impl Rect {
|
|
pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
|
|
Rect { x, y, w, h }
|
|
}
|
|
pub fn right(&self) -> f32 {
|
|
self.x + self.w
|
|
}
|
|
pub fn bottom(&self) -> f32 {
|
|
self.y + self.h
|
|
}
|
|
pub fn inset(&self, t: f32, r: f32, b: f32, l: f32) -> Rect {
|
|
Rect {
|
|
x: self.x + l,
|
|
y: self.y + t,
|
|
w: (self.w - l - r).max(0.0),
|
|
h: (self.h - t - b).max(0.0),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct TextRun {
|
|
/// font con cui sono stati prodotti i glifi (uno per run, non per pagina)
|
|
pub font: std::rc::Rc<FontHolder>,
|
|
pub shaped: ShapedText,
|
|
/// immagine sostituita: (dati, larghezza, altezza) al posto dei glifi
|
|
pub image: Option<(Arc<ImageData>, f32, f32)>,
|
|
/// testo di origine, per diagnostica e dump
|
|
pub text: String,
|
|
pub x: f32,
|
|
pub baseline: f32,
|
|
pub width: f32,
|
|
pub color: Color,
|
|
pub font_size: f32,
|
|
pub font_weight: u16,
|
|
/// se presente, il run è un controllo di modulo disegnato dal motore
|
|
pub control: Option<ControlSpec>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct Line {
|
|
pub y: f32,
|
|
pub height: f32,
|
|
pub runs: Vec<TextRun>,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct LayoutBox {
|
|
pub node: NodeId,
|
|
pub tag: String,
|
|
pub rect: Rect,
|
|
pub content: Rect,
|
|
pub style: Arc<ComputedStyle>,
|
|
pub lines: Vec<Line>,
|
|
pub children: Vec<LayoutBox>,
|
|
pub marker: bool,
|
|
/// contenuto sostituito (immagine) disegnato nel rect del box
|
|
pub replaced: Option<(Arc<ImageData>, f32, f32)>,
|
|
}
|
|
|
|
impl LayoutBox {
|
|
/// Percorso tipo `html>body>div:0>p:1`: indice fra i box fratelli con lo stesso tag.
|
|
pub fn find_path(&self, path: &str) -> Option<&LayoutBox> {
|
|
let mut cur = self;
|
|
for (i, segment) in path.split('>').enumerate() {
|
|
let segment = segment.trim();
|
|
let (tag, idx) = match segment.split_once(':') {
|
|
Some((t, n)) => (t, n.parse::<usize>().unwrap_or(0)),
|
|
None => (segment, 0),
|
|
};
|
|
if i == 0 {
|
|
if !cur.tag.eq_ignore_ascii_case(tag) {
|
|
return None;
|
|
}
|
|
continue;
|
|
}
|
|
let mut seen = 0usize;
|
|
let mut next: Option<&LayoutBox> = None;
|
|
for c in &cur.children {
|
|
if c.tag.eq_ignore_ascii_case(tag) {
|
|
if seen == idx {
|
|
next = Some(c);
|
|
break;
|
|
}
|
|
seen += 1;
|
|
}
|
|
}
|
|
cur = next?;
|
|
}
|
|
Some(cur)
|
|
}
|
|
|
|
pub fn total_lines(&self) -> usize {
|
|
self.lines.len() + self.children.iter().map(|c| c.total_lines()).sum::<usize>()
|
|
}
|
|
|
|
pub fn box_count(&self) -> usize {
|
|
1 + self.children.iter().map(|c| c.box_count()).sum::<usize>()
|
|
}
|
|
}
|
|
|
|
enum InlineItem {
|
|
Text(String, Arc<ComputedStyle>),
|
|
Image(Arc<ImageData>, f32, f32),
|
|
/// controllo di modulo (input, select, textarea, button)
|
|
Control(ControlSpec),
|
|
Break,
|
|
}
|
|
|
|
/// Tipo di controllo di modulo disegnato dal motore.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ControlKind {
|
|
Text,
|
|
Password,
|
|
Checkbox,
|
|
Radio,
|
|
Button,
|
|
Select,
|
|
Textarea,
|
|
}
|
|
|
|
/// Un controllo già misurato: il motore lo disegna, il guscio gli manda il testo.
|
|
#[derive(Clone, Debug)]
|
|
pub struct ControlSpec {
|
|
/// chiave stabile (`html>body>form:0>input:1`) usata per fuoco e valori
|
|
pub key: String,
|
|
/// nodo del DOM a cui il controllo corrisponde: serve a consegnare gli
|
|
/// eventi JavaScript al punto giusto (un `<button>` non ha un box proprio)
|
|
pub node: NodeId,
|
|
pub kind: ControlKind,
|
|
pub width: f32,
|
|
pub height: f32,
|
|
/// testo mostrato: valore digitato, etichetta del pulsante, opzione scelta
|
|
pub text: String,
|
|
pub checked: bool,
|
|
pub focused: bool,
|
|
pub font_size: f32,
|
|
pub color: Color,
|
|
/// distanza dalla baseline al bordo superiore del controllo: i controlli si
|
|
/// centrano sul testo (`vertical-align: middle`), non appoggiano sulla baseline
|
|
pub above: f32,
|
|
/// ascissa del cursore rispetto al bordo sinistro del controllo (px CSS)
|
|
pub caret_x: Option<f32>,
|
|
/// intervallo selezionato in ascissa (px CSS), relativo al bordo sinistro
|
|
pub selection: Option<(f32, f32)>,
|
|
/// opzioni di un `select`: (etichetta, valore)
|
|
pub options: Vec<(String, String)>,
|
|
/// indice dell'opzione scelta
|
|
pub selected: usize,
|
|
/// vero se l'elenco è aperto
|
|
pub open: bool,
|
|
/// voce evidenziata nell'elenco aperto
|
|
pub highlight: Option<usize>,
|
|
/// larghezza dell'elenco aperto (px CSS)
|
|
pub popup_width: f32,
|
|
/// vero se l'elenco va aperto sopra il controllo (non c'è spazio sotto)
|
|
pub popup_above: bool,
|
|
/// scorrimento orizzontale del testo nei campi a riga singola (px CSS)
|
|
pub text_offset: f32,
|
|
/// riga del cursore in una textarea
|
|
pub caret_line: usize,
|
|
/// righe di una textarea
|
|
pub lines: Vec<String>,
|
|
/// per ogni riga di una textarea, la selezione (ascisse px CSS)
|
|
pub line_sel: Vec<Option<(f32, f32)>>,
|
|
}
|
|
|
|
/// Controllo raggiungibile con Tab: chiave stabile e tipo.
|
|
#[derive(Clone, Debug)]
|
|
pub struct Focusable {
|
|
pub key: String,
|
|
/// nodo del DOM: serve a consegnare gli eventi JavaScript
|
|
pub node: NodeId,
|
|
pub kind: ControlKind,
|
|
/// rettangolo in pixel CSS, per il tocco e il clic
|
|
pub rect: Rect,
|
|
/// opzioni (etichetta, valore) dei `select`
|
|
pub options: Vec<(String, String)>,
|
|
/// indice dell'opzione scelta
|
|
pub selected: usize,
|
|
/// rettangolo dell'elenco aperto, se visibile
|
|
pub popup: Option<Rect>,
|
|
/// altezza di una voce dell'elenco (px CSS)
|
|
pub row_height: f32,
|
|
/// corpo del testo del controllo (px CSS): serve al guscio per posizionare il cursore
|
|
pub font_size: f32,
|
|
/// testo mostrato dal controllo (valore digitato o valore dell'HTML)
|
|
pub text: String,
|
|
}
|
|
|
|
/// Stato dei moduli: valori digitati e controllo che ha il fuoco.
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct FormState {
|
|
pub values: std::collections::HashMap<String, String>,
|
|
pub focus: Option<String>,
|
|
/// posizione del cursore nel controllo con il fuoco, in caratteri
|
|
pub caret: Option<usize>,
|
|
/// intervallo selezionato (inizio, fine) in caratteri, ordinato
|
|
pub selection: Option<(usize, usize)>,
|
|
/// chiave del menu a tendina aperto (elenco delle opzioni visibile)
|
|
pub open_select: Option<String>,
|
|
/// voce evidenziata nell'elenco aperto
|
|
pub select_highlight: Option<usize>,
|
|
}
|
|
|
|
struct Ctx<'a> {
|
|
doc: &'a Document,
|
|
styles: &'a [Arc<ComputedStyle>],
|
|
fonts: &'a Fonts,
|
|
images: &'a RefCell<ImageCache>,
|
|
/// elementi assoluti/fissi che non hanno un antenato posizionato noto:
|
|
/// vengono risolti sull'initial containing block (il viewport).
|
|
viewport_absolutes: RefCell<Vec<(NodeId, NodeId, f32)>>,
|
|
/// stato dei moduli (valori e fuoco) fornito dal guscio
|
|
form: &'a FormState,
|
|
/// percorsi stabili dei nodi (`html>body>form:0>input:1`)
|
|
paths: &'a [Option<String>],
|
|
/// controlli in ordine di tabulazione, riempito durante il layout
|
|
focusables: RefCell<Vec<Focusable>>,
|
|
}
|
|
|
|
pub fn layout_document(
|
|
doc: &Document,
|
|
styles: &[Arc<ComputedStyle>],
|
|
viewport: (f32, f32),
|
|
fonts: &Fonts,
|
|
images: &mut ImageCache,
|
|
form: &FormState,
|
|
) -> (LayoutBox, Vec<Focusable>) {
|
|
let images = RefCell::new(std::mem::replace(
|
|
images,
|
|
ImageCache::new(std::path::Path::new("."), None),
|
|
));
|
|
let paths = node_paths(doc);
|
|
let ctx = Ctx {
|
|
doc,
|
|
styles,
|
|
fonts,
|
|
images: &images,
|
|
viewport_absolutes: RefCell::new(Vec::new()),
|
|
form,
|
|
paths: &paths,
|
|
focusables: RefCell::new(Vec::new()),
|
|
};
|
|
let mut focusables: Vec<Focusable> = Vec::new();
|
|
match doc.find_element(doc.root(), "html") {
|
|
Some(html) => {
|
|
let mut root = ctx.layout_block(html, 0.0, 0.0, viewport.0, true);
|
|
focusables = raccogli_controlli(&root, viewport.1);
|
|
// Assoluti senza antenato posizionato: coordinate del viewport, ma
|
|
// restano appesi al loro genitore nel DOM (per percorso e paint order).
|
|
let pending: Vec<(NodeId, NodeId, f32)> =
|
|
ctx.viewport_absolutes.borrow_mut().drain(..).collect();
|
|
for (child, parent, sy) in pending {
|
|
let cs = ctx.style_of(child);
|
|
let x = cs.left.map(|l| l.resolve(viewport.0)).unwrap_or(0.0);
|
|
let y = cs.top.map(|l| l.resolve(viewport.1)).unwrap_or(sy);
|
|
let b = ctx.layout_block(child, x, y, viewport.0, false);
|
|
if let Some(parent_box) = find_box_mut(&mut root, parent) {
|
|
parent_box.children.push(b);
|
|
} else {
|
|
root.children.push(b);
|
|
}
|
|
}
|
|
(root, focusables)
|
|
}
|
|
None => (
|
|
LayoutBox {
|
|
node: doc.root(),
|
|
tag: "document".to_string(),
|
|
rect: Rect::new(0.0, 0.0, viewport.0, 0.0),
|
|
content: Rect::new(0.0, 0.0, viewport.0, 0.0),
|
|
style: Arc::new(ComputedStyle::default()),
|
|
lines: Vec::new(),
|
|
children: Vec::new(),
|
|
marker: false,
|
|
replaced: None,
|
|
},
|
|
focusables,
|
|
),
|
|
}
|
|
}
|
|
|
|
/// Percorsi stabili per ogni nodo: `html>body>form:0>input:1`, dove l'indice conta
|
|
/// i fratelli con lo stesso tag. Servono come chiavi di fuoco e di valore dei moduli.
|
|
pub fn node_paths(doc: &Document) -> Vec<Option<String>> {
|
|
let mut out: Vec<Option<String>> = vec![None; doc.node_count()];
|
|
fn scendi(
|
|
doc: &Document,
|
|
node: NodeId,
|
|
prefisso: &str,
|
|
indice: usize,
|
|
out: &mut Vec<Option<String>>,
|
|
) {
|
|
let tag = doc.element_name(node).unwrap_or("?");
|
|
let percorso = if prefisso.is_empty() {
|
|
tag.to_string()
|
|
} else {
|
|
format!("{}>{}:{}", prefisso, tag, indice)
|
|
};
|
|
if let Some(slot) = out.get_mut(node) {
|
|
*slot = Some(percorso.clone());
|
|
}
|
|
let mut contatori: std::collections::HashMap<&str, usize> =
|
|
std::collections::HashMap::new();
|
|
for &c in &doc.node(node).children {
|
|
let Some(t) = doc.element_name(c) else {
|
|
continue;
|
|
};
|
|
let n = contatori.entry(t).or_insert(0);
|
|
let idx = *n;
|
|
*n += 1;
|
|
scendi(doc, c, &percorso, idx, out);
|
|
}
|
|
}
|
|
// il percorso parte da `<html>`: la radice del documento non è un elemento
|
|
let partenza = doc.find_element(doc.root(), "html").unwrap_or(doc.root());
|
|
scendi(doc, partenza, "", 0, &mut out);
|
|
out
|
|
}
|
|
|
|
impl<'a> Ctx<'a> {
|
|
fn style_of(&self, node: NodeId) -> Arc<ComputedStyle> {
|
|
self.styles
|
|
.get(node)
|
|
.cloned()
|
|
.unwrap_or_else(|| Arc::new(ComputedStyle::default()))
|
|
}
|
|
|
|
fn layout_block(
|
|
&self,
|
|
node: NodeId,
|
|
border_x: f32,
|
|
border_y: f32,
|
|
available_w: f32,
|
|
is_root: bool,
|
|
) -> LayoutBox {
|
|
let st = self.style_of(node);
|
|
let tag = self.doc.element_name(node).unwrap_or("?").to_string();
|
|
let bw = st.border_width;
|
|
let pl = st.padding[3].resolve(available_w);
|
|
let pr = st.padding[1].resolve(available_w);
|
|
let pt = st.padding[0].resolve(available_w);
|
|
let pb = st.padding[2].resolve(available_w);
|
|
|
|
let mut content_w = match st.width {
|
|
Some(l) => l.resolve(available_w),
|
|
None => (available_w - bw[1] - bw[3] - pl - pr).max(0.0),
|
|
};
|
|
// max-width: il contenuto non si stende oltre il limite dichiarato
|
|
if let Some(massimo) = st.max_width {
|
|
let m = massimo.resolve(available_w);
|
|
if m > 0.0 && content_w > m {
|
|
content_w = m;
|
|
}
|
|
}
|
|
let mut content_x = border_x + bw[3] + pl;
|
|
// margini automatici: lo spazio che avanza si divide a metà ai due lati
|
|
if st.margin_auto_x {
|
|
let spazio = available_w - (content_w + pl + pr + bw[1] + bw[3]);
|
|
if spazio > 0.0 {
|
|
content_x += spazio / 2.0;
|
|
}
|
|
}
|
|
let content_y = border_y + bw[0] + pt;
|
|
|
|
let mut lines: Vec<Line> = Vec::new();
|
|
let mut children: Vec<LayoutBox> = Vec::new();
|
|
let mut items: Vec<InlineItem> = Vec::new();
|
|
let mut cursor_y = content_y;
|
|
let block_children = self.has_block_child(node);
|
|
let marker = st.display == Display::ListItem;
|
|
|
|
// Tabella: griglia di righe e celle impaginata a parte.
|
|
if st.display == Display::Table {
|
|
return self.layout_table(node, border_x, border_y, available_w, &st);
|
|
}
|
|
|
|
// Contenitore flex: i figli si dispongono lungo l'asse principale e il box
|
|
// si chiude qui, senza passare per float e inline.
|
|
if st.display == Display::Flex {
|
|
let (figli, altezza) =
|
|
self.layout_flex_children(node, content_x, content_y, content_w, &st);
|
|
let content_h = match st.height {
|
|
Some(h) => h.resolve(available_w),
|
|
None => altezza,
|
|
};
|
|
return LayoutBox {
|
|
node,
|
|
tag,
|
|
rect: Rect::new(
|
|
border_x,
|
|
border_y,
|
|
content_w + pl + pr + bw[1] + bw[3],
|
|
content_h + pt + pb + bw[0] + bw[2],
|
|
),
|
|
content: Rect::new(content_x, content_y, content_w, content_h),
|
|
style: st,
|
|
lines: Vec::new(),
|
|
children: figli,
|
|
marker,
|
|
replaced: None,
|
|
};
|
|
}
|
|
|
|
// Margini collassanti: il margine del primo/ultimo figlio esce dal box se
|
|
// non c'è bordo o padding a separarlo (approssimazione della specifica:
|
|
// il margine non viene trasferito al genitore, viene solo annullato qui).
|
|
// Alla radice i margini non escono dal documento: non hanno un genitore
|
|
// con cui collassare, quindi restano dentro.
|
|
let collapse_top = !is_root && bw[0] == 0.0 && pt == 0.0;
|
|
let collapse_bottom = !is_root && bw[2] == 0.0 && pb == 0.0 && st.height.is_none();
|
|
let mut prev_mb: Option<f32> = None;
|
|
let mut had_block = false;
|
|
// float: fascia occupata a sinistra e a destra del content box; il testo
|
|
// che segue si impagina nella larghezza che resta.
|
|
let mut float_left_w = 0.0f32;
|
|
let mut float_right_w = 0.0f32;
|
|
let mut float_bottom = content_y;
|
|
let replaced: Option<(Arc<ImageData>, f32, f32)> = None;
|
|
// assoluti che appartengono a questo box (solo se il box è posizionato)
|
|
let mut deferred: Vec<(NodeId, f32)> = Vec::new();
|
|
let block_positioned = st.position != Position::Static;
|
|
|
|
if marker {
|
|
let bullet = format!("\u{2022}{}", "\u{00a0}");
|
|
items.push(InlineItem::Text(bullet, st.clone()));
|
|
}
|
|
|
|
for &child in &self.doc.node(node).children {
|
|
match &self.doc.node(child).kind {
|
|
NodeKind::Text(t) => {
|
|
if t.trim().is_empty() && block_children {
|
|
continue;
|
|
}
|
|
items.push(InlineItem::Text(t.clone(), self.style_of(child)));
|
|
}
|
|
NodeKind::Element(_) => {
|
|
let cs = self.style_of(child);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
if is_control_tag(self.doc.element_name(child).unwrap_or("")) {
|
|
// i controlli sono elementi sostituiti in linea: si
|
|
// accodano agli item e il testo intorno scorre accanto
|
|
if let Some(spec) = self.control_spec(child, &cs) {
|
|
items.push(InlineItem::Control(spec));
|
|
continue;
|
|
}
|
|
}
|
|
if cs.float != FloatSide::None {
|
|
// fuori dal flusso: si impagina a sinistra o a destra del
|
|
// content box e il testo seguente gli passa accanto
|
|
if !items.is_empty() {
|
|
let avail = (content_w - float_left_w - float_right_w).max(0.0);
|
|
let (mut ls, height) = layout_lines(
|
|
&items,
|
|
avail,
|
|
self.fonts,
|
|
st.text_align,
|
|
st.line_height,
|
|
st.white_space,
|
|
st.direction.base_level(),
|
|
);
|
|
offset_lines(&mut ls, content_x + float_left_w, cursor_y);
|
|
cursor_y += height;
|
|
lines.extend(ls);
|
|
items.clear();
|
|
}
|
|
let avail = (content_w - float_left_w - float_right_w).max(0.0);
|
|
// il float si colloca dove siamo nel flusso, non in cima al
|
|
// contenitore: altrimenti scavalca i titoli e i paragrafi
|
|
// che lo precedono e il loro testo gli finisce sopra
|
|
let mut fb = self.layout_float(child, content_x, cursor_y, avail);
|
|
if cs.float == FloatSide::Right {
|
|
let dx = (content_w - float_right_w - fb.rect.w).max(0.0);
|
|
translate_box(&mut fb, dx, 0.0);
|
|
float_right_w += fb.rect.w;
|
|
} else {
|
|
translate_box(&mut fb, float_left_w, 0.0);
|
|
float_left_w += fb.rect.w;
|
|
}
|
|
float_bottom = float_bottom.max(fb.rect.bottom());
|
|
children.push(fb);
|
|
continue;
|
|
}
|
|
if matches!(cs.position, Position::Absolute | Position::Fixed) {
|
|
// fuori dal flusso: lo si aggancia all'antenato posizionato
|
|
// più vicino, o al viewport
|
|
if cs.position == Position::Fixed || !block_positioned {
|
|
self.viewport_absolutes
|
|
.borrow_mut()
|
|
.push((child, node, cursor_y));
|
|
} else {
|
|
deferred.push((child, cursor_y));
|
|
}
|
|
continue;
|
|
}
|
|
match cs.display {
|
|
Display::None => {}
|
|
Display::Inline => self.collect_inline(child, &mut items),
|
|
_ => {
|
|
if !items.is_empty() {
|
|
let avail = (content_w - float_left_w - float_right_w).max(0.0);
|
|
let (mut ls, height) = layout_lines(
|
|
&items,
|
|
avail,
|
|
self.fonts,
|
|
st.text_align,
|
|
st.line_height,
|
|
st.white_space,
|
|
st.direction.base_level(),
|
|
);
|
|
offset_lines(&mut ls, content_x + float_left_w, cursor_y);
|
|
cursor_y += height;
|
|
lines.extend(ls);
|
|
items.clear();
|
|
}
|
|
let ml = cs.margin[3].resolve(content_w);
|
|
let mr = cs.margin[1].resolve(content_w);
|
|
// I margini collassanti si propagano: il margine che
|
|
// "esce" dal figlio è il massimo fra il suo e quello
|
|
// dei suoi discendenti, se non c'è bordo/padding a
|
|
// trattenerlo.
|
|
let mt = self.collapsed_top(child, child_avail_hint(content_w, ml, mr));
|
|
let mb =
|
|
self.collapsed_bottom(child, child_avail_hint(content_w, ml, mr));
|
|
let gap = match prev_mb {
|
|
None => {
|
|
if collapse_top && lines.is_empty() && !had_block {
|
|
0.0
|
|
} else {
|
|
mt
|
|
}
|
|
}
|
|
Some(pb_prev) => mt.max(pb_prev),
|
|
};
|
|
cursor_y += gap;
|
|
// I blocchi successivi a un float non gli passano sotto:
|
|
// si restringe la loro larghezza e si spostano a fianco
|
|
// (approssimazione: vale per tutto il blocco, non solo
|
|
// per le righe che affiancano il float).
|
|
let child_avail =
|
|
(content_w - ml - mr - float_left_w - float_right_w).max(0.0);
|
|
let mut cb = self.layout_block(
|
|
child,
|
|
content_x + ml + float_left_w,
|
|
cursor_y,
|
|
child_avail,
|
|
false,
|
|
);
|
|
cursor_y = cb.rect.bottom();
|
|
prev_mb = Some(mb);
|
|
had_block = true;
|
|
if cs.position == Position::Relative {
|
|
let dx = cs.left.map(|l| l.resolve(content_w)).unwrap_or(0.0)
|
|
- cs.right.map(|l| l.resolve(content_w)).unwrap_or(0.0);
|
|
let dy = cs.top.map(|l| l.resolve(content_w)).unwrap_or(0.0)
|
|
- cs.bottom.map(|l| l.resolve(content_w)).unwrap_or(0.0);
|
|
translate_box(&mut cb, dx, dy);
|
|
}
|
|
children.push(cb);
|
|
}
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
if !items.is_empty() {
|
|
let avail = (content_w - float_left_w - float_right_w).max(0.0);
|
|
let (mut ls, height) = layout_lines(
|
|
&items,
|
|
avail,
|
|
self.fonts,
|
|
st.text_align,
|
|
st.line_height,
|
|
st.white_space,
|
|
st.direction.base_level(),
|
|
);
|
|
offset_lines(&mut ls, content_x + float_left_w, cursor_y);
|
|
cursor_y += height;
|
|
lines.extend(ls);
|
|
}
|
|
|
|
// Il margine inferiore dell'ultimo figlio resta dentro il box solo se c'è
|
|
// bordo o padding a trattenerlo.
|
|
if let (Some(mb), false) = (prev_mb, collapse_bottom) {
|
|
cursor_y += mb;
|
|
}
|
|
|
|
let mut content_h = (cursor_y - content_y)
|
|
.max(float_bottom - content_y)
|
|
.max(0.0);
|
|
if let Some(h) = st.height {
|
|
content_h = h.resolve(available_w);
|
|
}
|
|
|
|
// Assoluti agganciati a questo box: ora che l'altezza è nota si possono
|
|
// posizionare. `bottom`/`right` senza `top`/`left` non sono supportati.
|
|
for (child, static_y) in deferred.drain(..) {
|
|
let cs = self.style_of(child);
|
|
let x = content_x + cs.left.map(|l| l.resolve(content_w)).unwrap_or(0.0);
|
|
let y = content_y
|
|
+ cs.top
|
|
.map(|l| l.resolve(content_h))
|
|
.unwrap_or(static_y - content_y);
|
|
let b = self.layout_block(child, x, y, content_w, false);
|
|
children.push(b);
|
|
}
|
|
|
|
let rect_w = content_w + pl + pr + bw[1] + bw[3];
|
|
let rect_h = content_h + pt + pb + bw[0] + bw[2];
|
|
|
|
LayoutBox {
|
|
node,
|
|
tag,
|
|
rect: Rect::new(border_x, border_y, rect_w, rect_h),
|
|
content: Rect::new(content_x, content_y, content_w, content_h),
|
|
style: st,
|
|
lines,
|
|
children,
|
|
marker,
|
|
replaced,
|
|
}
|
|
}
|
|
|
|
/// Impagina i figli di un contenitore flex.
|
|
///
|
|
/// Sottoinsieme dichiarato: `row`/`column` (anche invertite), `justify-content`
|
|
/// (5 valori), `align-items` (4), `gap`, `flex-grow`/`flex-shrink`/`flex-basis`,
|
|
/// `flex-wrap` (solo per le righe). Fuori: `order`, `align-self`, allineamento
|
|
/// sulla baseline, testo direttamente nel contenitore (viene ignorato).
|
|
fn layout_flex_children(
|
|
&self,
|
|
node: NodeId,
|
|
content_x: f32,
|
|
content_y: f32,
|
|
content_w: f32,
|
|
st: &Arc<ComputedStyle>,
|
|
) -> (Vec<LayoutBox>, f32) {
|
|
let riga = matches!(
|
|
st.flex_direction,
|
|
FlexDirection::Row | FlexDirection::RowReverse
|
|
);
|
|
let inverso = matches!(
|
|
st.flex_direction,
|
|
FlexDirection::RowReverse | FlexDirection::ColumnReverse
|
|
);
|
|
let gap_main = if riga { st.column_gap } else { st.row_gap };
|
|
let gap_cross = if riga { st.row_gap } else { st.column_gap };
|
|
|
|
struct Voce {
|
|
node: NodeId,
|
|
/// dimensione sull'asse principale
|
|
main: f32,
|
|
grow: f32,
|
|
shrink: f32,
|
|
/// margini top, right, bottom, left
|
|
m: [f32; 4],
|
|
}
|
|
|
|
let mut voci: Vec<Voce> = Vec::new();
|
|
for &child in &self.doc.node(node).children {
|
|
if !matches!(self.doc.node(child).kind, NodeKind::Element(_)) {
|
|
continue;
|
|
}
|
|
let cs = self.style_of(child);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
let m = [
|
|
cs.margin[0].resolve(content_w),
|
|
cs.margin[1].resolve(content_w),
|
|
cs.margin[2].resolve(content_w),
|
|
cs.margin[3].resolve(content_w),
|
|
];
|
|
let main = if let Some(b) = cs.flex_basis {
|
|
b.resolve(content_w)
|
|
} else if let Some(d) = if riga { cs.width } else { cs.height } {
|
|
d.resolve(content_w)
|
|
} else {
|
|
// riga: larghezza massima del contenuto (misurata con spazio
|
|
// abbondante); colonna: altezza naturale alla larghezza data
|
|
let prova = self.layout_block(
|
|
child,
|
|
0.0,
|
|
0.0,
|
|
if riga { 100000.0 } else { content_w },
|
|
false,
|
|
);
|
|
if riga {
|
|
// un blocco con larghezza auto riempie lo spazio disponibile:
|
|
// la larghezza "naturale" è il bordo destro del suo contenuto
|
|
intrinsic_width(&prova)
|
|
} else {
|
|
prova.rect.h
|
|
}
|
|
};
|
|
voci.push(Voce {
|
|
node: child,
|
|
main,
|
|
grow: cs.flex_grow,
|
|
shrink: cs.flex_shrink,
|
|
m,
|
|
});
|
|
}
|
|
|
|
if voci.is_empty() {
|
|
return (Vec::new(), 0.0);
|
|
}
|
|
|
|
// righe (per il wrap) o singola linea
|
|
let mut linee: Vec<Vec<Voce>> = Vec::new();
|
|
if riga && st.flex_wrap == FlexWrap::Wrap {
|
|
let mut corrente: Vec<Voce> = Vec::new();
|
|
let mut usato = 0.0f32;
|
|
for v in voci {
|
|
let esterno = v.main + v.m[3] + v.m[1];
|
|
let serve = if corrente.is_empty() {
|
|
esterno
|
|
} else {
|
|
gap_main + esterno
|
|
};
|
|
if !corrente.is_empty() && usato + serve > content_w {
|
|
linee.push(std::mem::take(&mut corrente));
|
|
usato = esterno;
|
|
} else {
|
|
usato += serve;
|
|
}
|
|
corrente.push(v);
|
|
}
|
|
if !corrente.is_empty() {
|
|
linee.push(corrente);
|
|
}
|
|
} else {
|
|
linee.push(voci);
|
|
}
|
|
|
|
let mut figli: Vec<LayoutBox> = Vec::new();
|
|
let mut y_linea = content_y;
|
|
|
|
for linea in linee {
|
|
let n = linea.len();
|
|
let n_gap = gap_main * (n.saturating_sub(1)) as f32;
|
|
let somma: f32 = linea.iter().map(|v| v.main + v.m[3] + v.m[1]).sum::<f32>();
|
|
|
|
// crescita e riduzione: prima si distribuisce lo spazio libero secondo
|
|
// flex-grow, poi si taglia in proporzione a flex-shrink * base.
|
|
let mut main: Vec<f32> = linea.iter().map(|v| v.main).collect();
|
|
let mut spazio = content_w - somma - n_gap;
|
|
if spazio > 0.0 {
|
|
let peso: f32 = linea.iter().map(|v| v.grow).sum();
|
|
if peso > 0.0 {
|
|
for (i, v) in linea.iter().enumerate() {
|
|
main[i] += spazio * v.grow / peso;
|
|
}
|
|
spazio = 0.0;
|
|
}
|
|
} else if spazio < 0.0 {
|
|
let peso: f32 = linea
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, v)| v.shrink * main[i])
|
|
.sum();
|
|
if peso > 0.0 {
|
|
let deficit = -spazio;
|
|
for (i, v) in linea.iter().enumerate() {
|
|
let taglio = deficit * (v.shrink * main[i]) / peso;
|
|
let minimo = if riga { v.m[3] + v.m[1] } else { 0.0 };
|
|
main[i] = (main[i] - taglio).max(minimo);
|
|
}
|
|
}
|
|
spazio = (content_w
|
|
- n_gap
|
|
- main.iter().sum::<f32>()
|
|
- linea.iter().map(|v| v.m[3] + v.m[1]).sum::<f32>())
|
|
.min(0.0);
|
|
}
|
|
|
|
// posizione iniziale sull'asse principale
|
|
let mut cursore = match st.justify_content {
|
|
JustifyContent::FlexStart => 0.0,
|
|
JustifyContent::Center => (spazio / 2.0).max(0.0),
|
|
JustifyContent::FlexEnd => spazio.max(0.0),
|
|
_ => 0.0,
|
|
};
|
|
let extra_gap = match st.justify_content {
|
|
JustifyContent::SpaceBetween if n > 1 => spazio.max(0.0) / (n - 1) as f32,
|
|
JustifyContent::SpaceAround if n > 0 => spazio.max(0.0) / n as f32,
|
|
JustifyContent::SpaceEvenly if n > 0 => spazio.max(0.0) / (n + 1) as f32,
|
|
_ => 0.0,
|
|
};
|
|
if st.justify_content == JustifyContent::SpaceAround {
|
|
cursore = extra_gap / 2.0;
|
|
}
|
|
if st.justify_content == JustifyContent::SpaceEvenly {
|
|
cursore = extra_gap;
|
|
}
|
|
|
|
// prima passata: impagina ogni voce per conoscerne la dimensione trasversale
|
|
let mut scatole: Vec<LayoutBox> = Vec::with_capacity(n);
|
|
let mut cross_max = 0.0f32;
|
|
for (i, v) in linea.iter().enumerate() {
|
|
let cs = self.style_of(v.node);
|
|
let box_ = if riga {
|
|
let w = main[i].max(0.0);
|
|
self.layout_block(v.node, 0.0, 0.0, w + v.m[3] + v.m[1], false)
|
|
} else {
|
|
let larghezza = (content_w - v.m[3] - v.m[1]).max(0.0);
|
|
let mut b = self.layout_block(v.node, 0.0, 0.0, larghezza, false);
|
|
// in colonna l'asse principale è l'altezza: si fissa quella
|
|
if main[i] > 0.0 && cs.height.is_none() {
|
|
let h = main[i];
|
|
b.rect.h = h;
|
|
b.content.h = (h - (b.rect.h - b.content.h)).max(0.0);
|
|
}
|
|
b
|
|
};
|
|
cross_max = cross_max.max(box_.rect.h);
|
|
scatole.push(box_);
|
|
}
|
|
|
|
// altezza di riferimento della linea: l'altezza del contenitore se è
|
|
// dichiarata, altrimenti la più alta delle voci
|
|
let cross_linea = if riga {
|
|
st.height
|
|
.map(|h| h.resolve(content_w))
|
|
.unwrap_or(cross_max)
|
|
.max(cross_max.min(f32::MAX))
|
|
} else {
|
|
cross_max
|
|
};
|
|
if riga && st.height.is_some() {
|
|
cross_max = cross_linea;
|
|
}
|
|
|
|
// `stretch`: le voci senza altezza dichiarata prendono quella della linea
|
|
if riga && st.align_items == AlignItems::Stretch {
|
|
for (i, b) in scatole.iter_mut().enumerate() {
|
|
let cs = self.style_of(linea[i].node);
|
|
if cs.height.is_none() {
|
|
let h = (cross_max - linea[i].m[0] - linea[i].m[2]).max(0.0);
|
|
b.rect.h = h;
|
|
b.content.h = h;
|
|
}
|
|
}
|
|
}
|
|
|
|
// posizionamento definitivo
|
|
for (i, (v, mut b)) in linea.iter().zip(scatole.into_iter()).enumerate() {
|
|
let (dx, dy) = if riga {
|
|
let offset_cross = match st.align_items {
|
|
AlignItems::FlexStart | AlignItems::Stretch => v.m[0],
|
|
AlignItems::Center => {
|
|
v.m[0] + ((cross_max - b.rect.h - v.m[0] - v.m[2]) / 2.0).max(0.0)
|
|
}
|
|
AlignItems::FlexEnd => {
|
|
v.m[0] + (cross_max - b.rect.h - v.m[0] - v.m[2]).max(0.0)
|
|
}
|
|
};
|
|
if inverso {
|
|
let da_destra = cursore + v.m[1];
|
|
(
|
|
content_x + content_w - da_destra - b.rect.w,
|
|
y_linea + offset_cross,
|
|
)
|
|
} else {
|
|
(content_x + cursore + v.m[3], y_linea + offset_cross)
|
|
}
|
|
} else {
|
|
let offset_cross = match st.align_items {
|
|
AlignItems::Center => {
|
|
((content_w - b.rect.w - v.m[3] - v.m[1]) / 2.0).max(0.0)
|
|
}
|
|
AlignItems::FlexEnd => (content_w - b.rect.w - v.m[3] - v.m[1]).max(0.0),
|
|
_ => 0.0,
|
|
};
|
|
let y = y_linea + cursore + v.m[0];
|
|
(content_x + v.m[3] + offset_cross, y)
|
|
};
|
|
translate_box(&mut b, dx, dy);
|
|
figli.push(b);
|
|
cursore += main[i] + v.m[3] + v.m[1] + gap_main + extra_gap;
|
|
}
|
|
|
|
y_linea += cross_max + gap_cross;
|
|
}
|
|
|
|
// l'ultimo gap non si conta
|
|
let altezza = (y_linea - content_y - gap_cross).max(0.0);
|
|
(figli, altezza)
|
|
}
|
|
|
|
/// Impagina una tabella: righe, celle, `colspan`; larghezze di colonna
|
|
/// calcolate sul contenuto e poi adattate alla larghezza disponibile.
|
|
///
|
|
/// Sottoinsieme dichiarato: `table`/`tr`/`td`/`th`, gruppi (`thead`, `tbody`,
|
|
/// `tfoot`) con le righe sollevate, `colspan`, larghezze automatiche o
|
|
/// dichiarate. Fuori: `rowspan`, `border-collapse` (i bordi restano separati,
|
|
/// `border-spacing: 0`), allineamento verticale, `table-layout: fixed`.
|
|
fn layout_table(
|
|
&self,
|
|
node: NodeId,
|
|
border_x: f32,
|
|
border_y: f32,
|
|
available_w: f32,
|
|
st: &Arc<ComputedStyle>,
|
|
) -> LayoutBox {
|
|
let tag = self.doc.element_name(node).unwrap_or("?").to_string();
|
|
let bw = st.border_width;
|
|
let pl = st.padding[3].resolve(available_w);
|
|
let pr = st.padding[1].resolve(available_w);
|
|
let pt = st.padding[0].resolve(available_w);
|
|
let pb = st.padding[2].resolve(available_w);
|
|
let mut content_w = match st.width {
|
|
Some(l) => l.resolve(available_w),
|
|
None => (available_w - bw[1] - bw[3] - pl - pr).max(0.0),
|
|
};
|
|
// max-width: il contenuto non si stende oltre il limite dichiarato
|
|
if let Some(massimo) = st.max_width {
|
|
let m = massimo.resolve(available_w);
|
|
if m > 0.0 && content_w > m {
|
|
content_w = m;
|
|
}
|
|
}
|
|
let mut content_x = border_x + bw[3] + pl;
|
|
// margini automatici: lo spazio che avanza si divide a metà ai due lati
|
|
if st.margin_auto_x {
|
|
let spazio = available_w - (content_w + pl + pr + bw[1] + bw[3]);
|
|
if spazio > 0.0 {
|
|
content_x += spazio / 2.0;
|
|
}
|
|
}
|
|
let content_y = border_y + bw[0] + pt;
|
|
|
|
// 1) righe: i gruppi (thead/tbody/tfoot) vengono attraversati
|
|
let mut righe_nodi: Vec<NodeId> = Vec::new();
|
|
for &child in &self.doc.node(node).children {
|
|
if !matches!(self.doc.node(child).kind, NodeKind::Element(_)) {
|
|
continue;
|
|
}
|
|
let cs = self.style_of(child);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
if cs.display == Display::TableRow {
|
|
righe_nodi.push(child);
|
|
} else {
|
|
for &nipote in &self.doc.node(child).children {
|
|
if matches!(self.doc.node(nipote).kind, NodeKind::Element(_))
|
|
&& self.style_of(nipote).display == Display::TableRow
|
|
{
|
|
righe_nodi.push(nipote);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2) griglia: ogni cella occupa `colspan` colonne a partire dalla prima libera
|
|
struct Cella {
|
|
node: NodeId,
|
|
colonna: usize,
|
|
span: usize,
|
|
}
|
|
let mut griglia: Vec<Vec<Cella>> = Vec::new();
|
|
let mut colonne = 0usize;
|
|
for &riga in &righe_nodi {
|
|
let mut occupate = 0usize;
|
|
let mut celle: Vec<Cella> = Vec::new();
|
|
for &figlio in &self.doc.node(riga).children {
|
|
if !matches!(self.doc.node(figlio).kind, NodeKind::Element(_)) {
|
|
continue;
|
|
}
|
|
if self.style_of(figlio).display != Display::TableCell {
|
|
continue;
|
|
}
|
|
let span = self
|
|
.doc
|
|
.attr(figlio, "colspan")
|
|
.and_then(|v| v.trim().parse::<usize>().ok())
|
|
.unwrap_or(1)
|
|
.max(1);
|
|
celle.push(Cella {
|
|
node: figlio,
|
|
colonna: occupate,
|
|
span,
|
|
});
|
|
occupate += span;
|
|
}
|
|
colonne = colonne.max(occupate);
|
|
griglia.push(celle);
|
|
}
|
|
|
|
if colonne == 0 {
|
|
let content_h = 0.0;
|
|
return LayoutBox {
|
|
node,
|
|
tag,
|
|
rect: Rect::new(
|
|
border_x,
|
|
border_y,
|
|
content_w + pl + pr + bw[1] + bw[3],
|
|
content_h + pt + pb + bw[0] + bw[2],
|
|
),
|
|
content: Rect::new(content_x, content_y, content_w, content_h),
|
|
style: Arc::clone(st),
|
|
lines: Vec::new(),
|
|
children: Vec::new(),
|
|
marker: false,
|
|
replaced: None,
|
|
};
|
|
}
|
|
|
|
// 3) larghezza naturale delle colonne, misurata sul contenuto delle celle;
|
|
// le celle con larghezza dichiarata fissano un minimo rigido per la colonna
|
|
let mut larghezze = vec![0.0f32; colonne];
|
|
let mut rigide: Vec<Option<f32>> = vec![None; colonne];
|
|
for celle in &griglia {
|
|
for c in celle {
|
|
let misura = self.layout_block(c.node, 0.0, 0.0, 100000.0, false);
|
|
let padding_bordo = (misura.rect.w - misura.content.w).max(0.0);
|
|
let naturale = intrinsic_width(&misura) + padding_bordo;
|
|
if c.span == 1 {
|
|
larghezze[c.colonna] = larghezze[c.colonna].max(naturale);
|
|
if let Some(w) = self.style_of(c.node).width {
|
|
// le percentuali si risolvono sulla larghezza della tabella,
|
|
// non sullo spazio finto usato per misurare il contenuto
|
|
let dichiarata = w.resolve(content_w) + padding_bordo;
|
|
let slot = rigide[c.colonna].get_or_insert(dichiarata);
|
|
*slot = slot.max(dichiarata);
|
|
}
|
|
} else {
|
|
// una cella che occupa più colonne allarga solo quelle che non
|
|
// bastano già: si distribuisce il difetto in parti uguali
|
|
let gia: f32 = (0..c.span)
|
|
.map(|k| larghezze.get(c.colonna + k).copied().unwrap_or(0.0))
|
|
.sum();
|
|
if naturale > gia {
|
|
let quota = (naturale - gia) / c.span as f32;
|
|
for k in 0..c.span {
|
|
if let Some(slot) = larghezze.get_mut(c.colonna + k) {
|
|
*slot += quota;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// una colonna senza celle con contenuto resta a zero: le si dà un minimo
|
|
for l in larghezze.iter_mut() {
|
|
if *l <= 0.0 {
|
|
*l = 0.0;
|
|
}
|
|
}
|
|
|
|
// le colonne con larghezza dichiarata non scendono sotto quel valore
|
|
for (i, r) in rigide.iter().enumerate() {
|
|
if let Some(v) = r {
|
|
larghezze[i] = larghezze[i].max(*v);
|
|
}
|
|
}
|
|
|
|
// 4) adattamento alla larghezza disponibile
|
|
let somma: f32 = larghezze.iter().sum();
|
|
if somma <= 0.0 {
|
|
let quota = content_w / colonne as f32;
|
|
for l in larghezze.iter_mut() {
|
|
*l = quota;
|
|
}
|
|
} else if somma < content_w - 0.01 {
|
|
// spazio residuo: alle colonne senza vincolo, in proporzione al contenuto
|
|
let libere: Vec<usize> = (0..colonne).filter(|i| rigide[*i].is_none()).collect();
|
|
let residuo = content_w - somma;
|
|
if libere.is_empty() {
|
|
// tutte vincolate: si allargano in parti uguali
|
|
let quota = residuo / colonne as f32;
|
|
for l in larghezze.iter_mut() {
|
|
*l += quota;
|
|
}
|
|
} else {
|
|
let peso: f32 = libere.iter().map(|i| larghezze[*i]).sum();
|
|
for i in &libere {
|
|
let quota = if peso > 0.0 {
|
|
residuo * larghezze[*i] / peso
|
|
} else {
|
|
residuo / libere.len() as f32
|
|
};
|
|
larghezze[*i] += quota;
|
|
}
|
|
}
|
|
} else if somma > content_w + 0.01 {
|
|
// non si scende sotto i vincoli: si taglia il resto in proporzione
|
|
let mut fattore = content_w / somma;
|
|
for (i, l) in larghezze.iter_mut().enumerate() {
|
|
if let Some(v) = rigide[i] {
|
|
if *l * fattore < v {
|
|
fattore = (fattore).max(content_w / somma);
|
|
*l = v;
|
|
continue;
|
|
}
|
|
}
|
|
*l *= fattore;
|
|
}
|
|
}
|
|
|
|
if std::env::var("MOSAIC_DEBUG_TABLE").is_ok() {
|
|
eprintln!(
|
|
"tabella: colonne={} larghezze={:?} somma={} content_w={}",
|
|
colonne, larghezze, somma, content_w
|
|
);
|
|
}
|
|
// 5) posizioni orizzontali delle colonne
|
|
let mut xs = Vec::with_capacity(colonne + 1);
|
|
let mut accumulato = content_x;
|
|
xs.push(accumulato);
|
|
for l in &larghezze {
|
|
accumulato += *l;
|
|
xs.push(accumulato);
|
|
}
|
|
|
|
// 6) impaginazione delle righe
|
|
let mut figli: Vec<LayoutBox> = Vec::new();
|
|
let mut y = content_y;
|
|
for (i, celle) in griglia.iter().enumerate() {
|
|
let riga_node = righe_nodi[i];
|
|
let mut altezza_riga = 0.0f32;
|
|
let mut scatole: Vec<LayoutBox> = Vec::new();
|
|
for c in celle {
|
|
let x = xs[c.colonna];
|
|
let w = (xs[(c.colonna + c.span).min(colonne)] - x).max(0.0);
|
|
// Una cella dichiara la larghezza in percentuale *della tabella*:
|
|
// per farle riempire la colonna le si passa uno spazio tale che
|
|
// la sua percentuale dia proprio la larghezza della colonna.
|
|
let cs = self.style_of(c.node);
|
|
let spazio = match cs.width {
|
|
// la percentuale si applica al content box: si tolgono prima
|
|
// padding e bordo, così il box esterno coincide con la colonna
|
|
Some(crate::style::Len::Percent(p)) if p > 0.0 => {
|
|
let pad = cs.padding[3].resolve(w)
|
|
+ cs.padding[1].resolve(w)
|
|
+ cs.border_width[3]
|
|
+ cs.border_width[1];
|
|
(w - pad).max(0.0) * 100.0 / p
|
|
}
|
|
_ => w,
|
|
};
|
|
let b = self.layout_block(c.node, x, y, spazio, false);
|
|
altezza_riga = altezza_riga.max(b.rect.h);
|
|
scatole.push(b);
|
|
}
|
|
// le celle più basse non si allungano: il bordo resta dove finisce il testo
|
|
let st_riga = self.style_of(riga_node);
|
|
let riga_box = LayoutBox {
|
|
node: riga_node,
|
|
tag: self.doc.element_name(riga_node).unwrap_or("tr").to_string(),
|
|
rect: Rect::new(content_x, y, content_w, altezza_riga),
|
|
content: Rect::new(content_x, y, content_w, altezza_riga),
|
|
style: st_riga,
|
|
lines: Vec::new(),
|
|
children: scatole,
|
|
marker: false,
|
|
replaced: None,
|
|
};
|
|
figli.push(riga_box);
|
|
y += altezza_riga;
|
|
}
|
|
|
|
let content_h = match st.height {
|
|
Some(h) => h.resolve(available_w),
|
|
None => (y - content_y).max(0.0),
|
|
};
|
|
LayoutBox {
|
|
node,
|
|
tag,
|
|
rect: Rect::new(
|
|
border_x,
|
|
border_y,
|
|
content_w + pl + pr + bw[1] + bw[3],
|
|
content_h + pt + pb + bw[0] + bw[2],
|
|
),
|
|
content: Rect::new(content_x, content_y, content_w, content_h),
|
|
style: Arc::clone(st),
|
|
lines: Vec::new(),
|
|
children: figli,
|
|
marker: false,
|
|
replaced: None,
|
|
}
|
|
}
|
|
|
|
fn has_block_child(&self, node: NodeId) -> bool {
|
|
self.doc.node(node).children.iter().any(|&c| {
|
|
matches!(self.doc.node(c).kind, NodeKind::Element(_))
|
|
&& matches!(
|
|
self.style_of(c).display,
|
|
Display::Block | Display::ListItem | Display::Flex | Display::Table
|
|
)
|
|
})
|
|
}
|
|
|
|
/// Float: un'immagine diventa un box sostituito della sua dimensione, un
|
|
/// altro elemento si impagina come blocco nella larghezza disponibile.
|
|
fn layout_float(&self, node: NodeId, x: f32, y: f32, avail: f32) -> LayoutBox {
|
|
let st = self.style_of(node);
|
|
let tag = self.doc.element_name(node).unwrap_or("?").to_string();
|
|
if tag == "img" {
|
|
if let Some((data, w, h)) = self.image_size(node) {
|
|
return LayoutBox {
|
|
node,
|
|
tag,
|
|
rect: Rect::new(x, y, w, h),
|
|
content: Rect::new(x, y, w, h),
|
|
style: st,
|
|
lines: Vec::new(),
|
|
children: Vec::new(),
|
|
marker: false,
|
|
replaced: Some((data, w, h)),
|
|
};
|
|
}
|
|
}
|
|
let w = st.width.map(|l| l.resolve(avail)).unwrap_or(avail);
|
|
self.layout_block(node, x, y, w, false)
|
|
}
|
|
|
|
/// Dimensioni di un'immagine secondo CSS, attributi e dimensioni intrinseche.
|
|
fn image_size(&self, node: NodeId) -> Option<(Arc<ImageData>, f32, f32)> {
|
|
let src = self.doc.attr(node, "src")?;
|
|
let data = self.images.borrow_mut().get(src)?;
|
|
let st = self.style_of(node);
|
|
let css_w = st.width.map(|l| l.resolve(1000.0));
|
|
let css_h = st.height.map(|l| l.resolve(1000.0));
|
|
let attr_w = self
|
|
.doc
|
|
.attr(node, "width")
|
|
.and_then(|v| v.trim().parse::<f32>().ok());
|
|
let attr_h = self
|
|
.doc
|
|
.attr(node, "height")
|
|
.and_then(|v| v.trim().parse::<f32>().ok());
|
|
let iw = data.width as f32;
|
|
let ih = data.height as f32;
|
|
let (w, h) = match (css_w.or(attr_w), css_h.or(attr_h)) {
|
|
(Some(w), Some(h)) => (w, h),
|
|
(Some(w), None) => (w, w * ih / iw),
|
|
(None, Some(h)) => (h * iw / ih, h),
|
|
(None, None) => (iw, ih),
|
|
};
|
|
if w > 0.0 && h > 0.0 {
|
|
Some((data, w, h))
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// `<img>`: dimensioni da CSS, poi dagli attributi, poi intrinseche; con una
|
|
/// sola dimensione nota si conserva la proporzione.
|
|
fn push_image(&self, node: NodeId, items: &mut Vec<InlineItem>) {
|
|
let Some(src) = self.doc.attr(node, "src") else {
|
|
return;
|
|
};
|
|
let Some(data) = self.images.borrow_mut().get(src) else {
|
|
return;
|
|
};
|
|
let st = self.style_of(node);
|
|
let css_w = st.width.map(|l| l.resolve(1000.0));
|
|
let css_h = st.height.map(|l| l.resolve(1000.0));
|
|
let attr_w = self
|
|
.doc
|
|
.attr(node, "width")
|
|
.and_then(|v| v.trim().parse::<f32>().ok());
|
|
let attr_h = self
|
|
.doc
|
|
.attr(node, "height")
|
|
.and_then(|v| v.trim().parse::<f32>().ok());
|
|
let iw = data.width as f32;
|
|
let ih = data.height as f32;
|
|
let (w, h) = match (css_w.or(attr_w), css_h.or(attr_h)) {
|
|
(Some(w), Some(h)) => (w, h),
|
|
(Some(w), None) => (w, w * ih / iw),
|
|
(None, Some(h)) => (h * iw / ih, h),
|
|
(None, None) => (iw, ih),
|
|
};
|
|
if w > 0.0 && h > 0.0 {
|
|
items.push(InlineItem::Image(data, w, h));
|
|
}
|
|
}
|
|
|
|
/// Margine superiore che esce da questo box: se non c'è bordo/padding/altezza
|
|
/// a trattenerlo, è il massimo fra il proprio margine e quello del primo
|
|
/// discendente in flow (catena dei margini collassanti).
|
|
fn collapsed_top(&self, node: NodeId, avail: f32) -> f32 {
|
|
let st = self.style_of(node);
|
|
let own = st.margin[0].resolve(avail);
|
|
let can_escape =
|
|
st.border_width[0] == 0.0 && st.padding[0].resolve(avail) == 0.0 && st.height.is_none();
|
|
if !can_escape {
|
|
return own;
|
|
}
|
|
for &c in &self.doc.node(node).children {
|
|
match &self.doc.node(c).kind {
|
|
NodeKind::Element(_) => {
|
|
let cs = self.style_of(c);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
if matches!(cs.display, Display::Block | Display::ListItem) {
|
|
return own.max(self.collapsed_top(c, avail));
|
|
}
|
|
return own;
|
|
}
|
|
NodeKind::Text(t) => {
|
|
if !t.trim().is_empty() {
|
|
return own;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
own
|
|
}
|
|
|
|
/// Come `collapsed_top`, ma per il margine inferiore.
|
|
fn collapsed_bottom(&self, node: NodeId, avail: f32) -> f32 {
|
|
let st = self.style_of(node);
|
|
let own = st.margin[2].resolve(avail);
|
|
let can_escape =
|
|
st.border_width[2] == 0.0 && st.padding[2].resolve(avail) == 0.0 && st.height.is_none();
|
|
if !can_escape {
|
|
return own;
|
|
}
|
|
for &c in self.doc.node(node).children.iter().rev() {
|
|
match &self.doc.node(c).kind {
|
|
NodeKind::Element(_) => {
|
|
let cs = self.style_of(c);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
if matches!(cs.display, Display::Block | Display::ListItem) {
|
|
return own.max(self.collapsed_bottom(c, avail));
|
|
}
|
|
return own;
|
|
}
|
|
NodeKind::Text(t) => {
|
|
if !t.trim().is_empty() {
|
|
return own;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
own
|
|
}
|
|
|
|
/// Costruisce la specifica di un controllo di modulo, con chiave stabile,
|
|
/// valore corrente e dimensione secondo CSS o valori predefiniti.
|
|
fn control_spec(&self, node: NodeId, cs: &Arc<ComputedStyle>) -> Option<ControlSpec> {
|
|
let tag = self.doc.element_name(node)?;
|
|
let tipo = self.doc.attr(node, "type").unwrap_or("text").trim();
|
|
let kind = match tag {
|
|
"input" => match tipo {
|
|
"password" => ControlKind::Password,
|
|
"checkbox" => ControlKind::Checkbox,
|
|
"radio" => ControlKind::Radio,
|
|
"submit" | "button" | "reset" => ControlKind::Button,
|
|
_ => ControlKind::Text,
|
|
},
|
|
"select" => ControlKind::Select,
|
|
"textarea" => ControlKind::Textarea,
|
|
"button" => ControlKind::Button,
|
|
_ => return None,
|
|
};
|
|
let key = self.paths.get(node).cloned().flatten()?;
|
|
let font = self.fonts.resolve(cs.font_family.as_deref());
|
|
let fs = cs.font_size;
|
|
let riga = cs.line_height.max(fs * 1.2);
|
|
let testo = self.control_text(node, kind, &key);
|
|
let larghezza_dichiarata = cs.width.map(|l| l.resolve(1000.0));
|
|
let (width, height) = match kind {
|
|
ControlKind::Checkbox | ControlKind::Radio => (13.0, 13.0),
|
|
ControlKind::Text | ControlKind::Password => {
|
|
(larghezza_dichiarata.unwrap_or(160.0), riga + 8.0)
|
|
}
|
|
ControlKind::Textarea => (
|
|
larghezza_dichiarata.unwrap_or(200.0),
|
|
cs.height
|
|
.map(|l| l.resolve(1000.0))
|
|
.unwrap_or(riga * 3.0 + 8.0),
|
|
),
|
|
ControlKind::Button => (
|
|
larghezza_dichiarata.unwrap_or_else(|| font.advance(&testo, fs) + 18.0),
|
|
riga + 8.0,
|
|
),
|
|
ControlKind::Select => (
|
|
larghezza_dichiarata.unwrap_or_else(|| font.advance(&testo, fs) + 34.0),
|
|
riga + 8.0,
|
|
),
|
|
};
|
|
let checked = match self.form.values.get(&key) {
|
|
Some(v) => v == "on" || v == "true" || v == "1",
|
|
None => self.doc.attr(node, "checked").is_some(),
|
|
};
|
|
let focused = self.form.focus.as_deref() == Some(key.as_str());
|
|
if self.doc.attr(node, "disabled").is_none() {
|
|
let mut lista = self.focusables.borrow_mut();
|
|
if !lista.iter().any(|f| f.key == key) {
|
|
lista.push(Focusable {
|
|
key: key.clone(),
|
|
node,
|
|
kind,
|
|
rect: Rect::new(0.0, 0.0, 0.0, 0.0),
|
|
options: Vec::new(),
|
|
selected: 0,
|
|
popup: None,
|
|
row_height: 0.0,
|
|
font_size: 0.0,
|
|
text: String::new(),
|
|
});
|
|
}
|
|
}
|
|
// centro del controllo allineato al centro del testo: metà altezza più
|
|
// circa il centro dell'occhio medio del carattere (0,35 em)
|
|
let above = (height / 2.0 + fs * 0.35).clamp(0.0, height);
|
|
|
|
// cursore e selezione: si misura il testo che precede, così il cursore
|
|
// cade esattamente dove finisce quel testo
|
|
let caratteri = testo.chars().count();
|
|
let larghezza_fino = |n: usize| -> f32 {
|
|
let prefisso: String = testo.chars().take(n).collect();
|
|
font.advance(&prefisso, fs)
|
|
};
|
|
let modificabile = matches!(
|
|
kind,
|
|
ControlKind::Text | ControlKind::Password | ControlKind::Textarea
|
|
);
|
|
let caret_x = if modificabile && focused {
|
|
self.form.caret.map(|c| larghezza_fino(c.min(caratteri)))
|
|
} else {
|
|
None
|
|
};
|
|
// textarea: righe separate da \n, cursore con riga e colonna
|
|
let mut righe: Vec<String> = Vec::new();
|
|
let mut caret_line = 0usize;
|
|
let mut caret_x = caret_x;
|
|
if kind == ControlKind::Textarea {
|
|
righe = testo.split('\n').map(|r| r.to_string()).collect();
|
|
if righe.is_empty() {
|
|
righe.push(String::new());
|
|
}
|
|
if focused {
|
|
if let Some(c) = self.form.caret {
|
|
let mut resto = c;
|
|
for (i, riga) in righe.iter().enumerate() {
|
|
let n = riga.chars().count();
|
|
if resto <= n {
|
|
caret_line = i;
|
|
caret_x = Some(
|
|
font.advance(&riga.chars().take(resto).collect::<String>(), fs),
|
|
);
|
|
break;
|
|
}
|
|
resto -= n + 1; // il carattere di a capo
|
|
caret_line = i;
|
|
caret_x = Some(font.advance(riga, fs));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// campi a riga singola: se il cursore esce si fa scorrere il testo
|
|
let text_offset = match (kind, caret_x) {
|
|
(ControlKind::Text | ControlKind::Password, Some(cx)) => {
|
|
let visibile = (width - 12.0).max(0.0);
|
|
(cx - visibile).max(0.0)
|
|
}
|
|
_ => 0.0,
|
|
};
|
|
|
|
// selezione su più righe: un intervallo per riga
|
|
let mut line_sel: Vec<Option<(f32, f32)>> = vec![None; righe.len()];
|
|
if kind == ControlKind::Textarea && focused {
|
|
if let Some((a, b)) = self.form.selection {
|
|
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
|
let mut base = 0usize;
|
|
for (i, riga) in righe.iter().enumerate() {
|
|
let n = riga.chars().count();
|
|
let da = lo.saturating_sub(base).min(n);
|
|
let a_fine = hi.saturating_sub(base).min(n);
|
|
if hi > base && lo <= base + n {
|
|
let x0 = font.advance(&riga.chars().take(da).collect::<String>(), fs);
|
|
let x1 = font.advance(&riga.chars().take(a_fine).collect::<String>(), fs);
|
|
line_sel[i] = Some((x0, x1));
|
|
}
|
|
base += n + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
let selection = if modificabile && focused {
|
|
self.form.selection.map(|(a, b)| {
|
|
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
|
(
|
|
larghezza_fino(lo.min(caratteri)),
|
|
larghezza_fino(hi.min(caratteri)),
|
|
)
|
|
})
|
|
} else {
|
|
None
|
|
};
|
|
// opzioni del menu a tendina, con la scelta corrente
|
|
let mut options: Vec<(String, String)> = Vec::new();
|
|
let mut selected = 0usize;
|
|
if kind == ControlKind::Select {
|
|
let scelto = self.form.values.get(&key).cloned().unwrap_or_default();
|
|
for &opt in &self.doc.node(node).children {
|
|
if self.doc.element_name(opt) != Some("option") {
|
|
continue;
|
|
}
|
|
let etichetta = testo_discendenti(self.doc, opt);
|
|
let valore = self
|
|
.doc
|
|
.attr(opt, "value")
|
|
.map(|v| v.to_string())
|
|
.unwrap_or_else(|| etichetta.clone());
|
|
if !scelto.is_empty() && scelto == valore {
|
|
selected = options.len();
|
|
} else if scelto.is_empty()
|
|
&& options.is_empty()
|
|
&& self.doc.attr(opt, "selected").is_some()
|
|
{
|
|
selected = 0;
|
|
}
|
|
options.push((etichetta, valore));
|
|
}
|
|
}
|
|
let open = self.form.open_select.as_deref() == Some(key.as_str());
|
|
let highlight = if open {
|
|
self.form.select_highlight
|
|
} else {
|
|
None
|
|
};
|
|
let popup_width = {
|
|
let larghezza_max = options
|
|
.iter()
|
|
.map(|(e, _)| font.advance(e, fs) + 20.0)
|
|
.fold(width, f32::max);
|
|
larghezza_max.max(width)
|
|
};
|
|
|
|
Some(ControlSpec {
|
|
key,
|
|
node,
|
|
kind,
|
|
width,
|
|
height,
|
|
text: testo,
|
|
checked,
|
|
focused,
|
|
font_size: fs,
|
|
color: cs.color,
|
|
above,
|
|
caret_x,
|
|
selection,
|
|
options,
|
|
selected,
|
|
open,
|
|
highlight,
|
|
popup_width,
|
|
popup_above: false,
|
|
text_offset,
|
|
caret_line,
|
|
lines: righe,
|
|
line_sel,
|
|
})
|
|
}
|
|
|
|
/// Testo mostrato dal controllo: valore digitato, etichetta o opzione scelta.
|
|
fn control_text(&self, node: NodeId, kind: ControlKind, key: &str) -> String {
|
|
let digitato = self.form.values.get(key).cloned();
|
|
match kind {
|
|
ControlKind::Password => digitato
|
|
.or_else(|| self.doc.attr(node, "value").map(|v| v.to_string()))
|
|
.map(|v| "\u{2022}".repeat(v.chars().count()))
|
|
.unwrap_or_default(),
|
|
ControlKind::Text | ControlKind::Textarea => digitato
|
|
.or_else(|| self.doc.attr(node, "value").map(|v| v.to_string()))
|
|
// in HTML il valore iniziale di una textarea è il suo testo
|
|
.unwrap_or_else(|| {
|
|
if kind == ControlKind::Textarea {
|
|
testo_discendenti(self.doc, node)
|
|
} else {
|
|
String::new()
|
|
}
|
|
}),
|
|
ControlKind::Button => digitato
|
|
.or_else(|| self.doc.attr(node, "value").map(|v| v.to_string()))
|
|
.unwrap_or_else(|| testo_discendenti(self.doc, node)),
|
|
ControlKind::Select => {
|
|
// La scelta arriva dal guscio come **valore** dell'opzione: è
|
|
// l'attributo `value` se c'è, altrimenti il testo dell'opzione
|
|
// (in HTML `<option>due</option>` vale "due"). Confrontare solo
|
|
// l'attributo lasciava il menù fermo sulla voce dell'HTML.
|
|
let scelta = digitato.unwrap_or_default();
|
|
let mut prima: Option<String> = None;
|
|
let mut scelta_testo: Option<String> = None;
|
|
let mut selezionata_html: Option<String> = None;
|
|
for &opt in &self.doc.node(node).children {
|
|
if self.doc.element_name(opt) != Some("option") {
|
|
continue;
|
|
}
|
|
let testo = testo_discendenti(self.doc, opt);
|
|
let valore = self
|
|
.doc
|
|
.attr(opt, "value")
|
|
.map(|v| v.to_string())
|
|
.unwrap_or_else(|| testo.clone());
|
|
if prima.is_none() {
|
|
prima = Some(testo.clone());
|
|
}
|
|
if !scelta.is_empty() && scelta == valore {
|
|
scelta_testo = Some(testo.clone());
|
|
}
|
|
if self.doc.attr(opt, "selected").is_some() {
|
|
selezionata_html = Some(testo.clone());
|
|
}
|
|
}
|
|
scelta_testo
|
|
.or(selezionata_html)
|
|
.or(prima)
|
|
.unwrap_or_default()
|
|
}
|
|
ControlKind::Checkbox | ControlKind::Radio => String::new(),
|
|
}
|
|
}
|
|
|
|
fn collect_inline(&self, node: NodeId, items: &mut Vec<InlineItem>) {
|
|
if let Some(name) = self.doc.element_name(node) {
|
|
if name == "br" {
|
|
items.push(InlineItem::Break);
|
|
return;
|
|
}
|
|
if name == "img" {
|
|
self.push_image(node, items);
|
|
return;
|
|
}
|
|
if is_control_tag(name) {
|
|
if let Some(spec) = self.control_spec(node, &self.style_of(node)) {
|
|
items.push(InlineItem::Control(spec));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
for &child in &self.doc.node(node).children {
|
|
match &self.doc.node(child).kind {
|
|
NodeKind::Text(t) => items.push(InlineItem::Text(t.clone(), self.style_of(child))),
|
|
NodeKind::Element(_) => {
|
|
let cs = self.style_of(child);
|
|
if cs.display == Display::None {
|
|
continue;
|
|
}
|
|
if let Some(name) = self.doc.element_name(child) {
|
|
if name == "br" {
|
|
items.push(InlineItem::Break);
|
|
continue;
|
|
}
|
|
if name == "img" {
|
|
self.push_image(child, items);
|
|
continue;
|
|
}
|
|
if is_control_tag(name) {
|
|
if let Some(spec) = self.control_spec(child, &cs) {
|
|
items.push(InlineItem::Control(spec));
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
self.collect_inline(child, items);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Indice di carattere più vicino all'ascissa `x`, misurata dall'inizio del testo.
|
|
/// Serve al guscio per posizionare il cursore dove si è cliccato.
|
|
pub fn caret_index_at(font: &FontHolder, text: &str, size: f32, x: f32) -> usize {
|
|
let mut pen = 0.0f32;
|
|
for (i, c) in text.chars().enumerate() {
|
|
let avanzo = font.advance(&c.to_string(), size);
|
|
if x < pen + avanzo / 2.0 {
|
|
return i;
|
|
}
|
|
pen += avanzo;
|
|
}
|
|
text.chars().count()
|
|
}
|
|
|
|
/// Come `caret_index_at`, ma per una textarea: `y` è la coordinata verticale
|
|
/// relativa all'inizio del testo (px CSS).
|
|
pub fn caret_index_in_lines(font: &FontHolder, text: &str, size: f32, x: f32, y: f32) -> usize {
|
|
let interlinea = size * 1.35;
|
|
let riga = (y / interlinea).floor().max(0.0) as usize;
|
|
let mut indice = 0usize;
|
|
for (i, contenuto) in text.split('\n').enumerate() {
|
|
if i == riga {
|
|
return indice + caret_index_at(font, contenuto, size, x);
|
|
}
|
|
indice += contenuto.chars().count() + 1;
|
|
}
|
|
text.chars().count()
|
|
}
|
|
|
|
/// Intervallo (inizio, fine) della parola che contiene `index`: si allarga sui
|
|
/// caratteri alfanumerici vicini, come fa il doppio clic.
|
|
pub fn word_range(text: &str, index: usize) -> (usize, usize) {
|
|
let caratteri: Vec<char> = text.chars().collect();
|
|
if caratteri.is_empty() {
|
|
return (0, 0);
|
|
}
|
|
let idx = index.min(caratteri.len() - 1);
|
|
let dentro = |c: char| c.is_alphanumeric() || c == '_';
|
|
if !dentro(caratteri[idx]) {
|
|
return (idx, (idx + 1).min(caratteri.len()));
|
|
}
|
|
let mut inizio = idx;
|
|
while inizio > 0 && dentro(caratteri[inizio - 1]) {
|
|
inizio -= 1;
|
|
}
|
|
let mut fine = idx + 1;
|
|
while fine < caratteri.len() && dentro(caratteri[fine]) {
|
|
fine += 1;
|
|
}
|
|
(inizio, fine)
|
|
}
|
|
|
|
/// Altezza di una voce nell'elenco aperto di un `select` (px CSS).
|
|
pub fn select_row_height(font_size: f32) -> f32 {
|
|
font_size * 1.4 + 6.0
|
|
}
|
|
|
|
/// Chiave stabile del controllo corrispondente a un nodo (la stessa che il
|
|
/// motore usa per fuoco e valori): serve all'invio dei formulari.
|
|
pub fn chiave_del_controllo(doc: &Document, node: NodeId) -> Option<String> {
|
|
node_paths(doc).get(node).cloned().flatten()
|
|
}
|
|
|
|
/// Elenca i controlli nell'ordine del documento, con il rettangolo occupato:
|
|
/// serve al guscio per portare il fuoco al tocco o al clic.
|
|
fn raccogli_controlli(b: &LayoutBox, altezza_viewport: f32) -> Vec<Focusable> {
|
|
let mut out = Vec::new();
|
|
// altezza del viewport: decide se l'elenco si apre sotto o sopra il controllo
|
|
let altezza_documento = if altezza_viewport > 0.0 {
|
|
altezza_viewport
|
|
} else {
|
|
b.rect.h
|
|
};
|
|
raccogli_controlli_in(b, &mut out, altezza_documento);
|
|
out
|
|
}
|
|
|
|
fn raccogli_controlli_in(b: &LayoutBox, out: &mut Vec<Focusable>, altezza_documento: f32) {
|
|
for linea in &b.lines {
|
|
for run in &linea.runs {
|
|
if let Some(c) = &run.control {
|
|
let rect = Rect::new(run.x, run.baseline - c.above, c.width, c.height);
|
|
let popup = if c.open && !c.options.is_empty() {
|
|
let riga = select_row_height(c.font_size);
|
|
let altezza = riga * c.options.len() as f32;
|
|
if rect.bottom() + altezza > altezza_documento {
|
|
// non c'è spazio sotto: l'elenco si apre verso l'alto
|
|
Some(Rect::new(
|
|
rect.x,
|
|
(rect.y - altezza).max(0.0),
|
|
c.popup_width,
|
|
altezza,
|
|
))
|
|
} else {
|
|
Some(Rect::new(rect.x, rect.bottom(), c.popup_width, altezza))
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
out.push(Focusable {
|
|
key: c.key.clone(),
|
|
node: c.node,
|
|
kind: c.kind,
|
|
rect,
|
|
options: c.options.clone(),
|
|
selected: c.selected,
|
|
popup,
|
|
row_height: if c.options.is_empty() {
|
|
0.0
|
|
} else {
|
|
select_row_height(c.font_size)
|
|
},
|
|
font_size: c.font_size,
|
|
text: c.text.clone(),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
for c in &b.children {
|
|
raccogli_controlli_in(c, out, altezza_documento);
|
|
}
|
|
}
|
|
|
|
/// Vero se il tag è un controllo di modulo disegnato dal motore.
|
|
fn is_control_tag(name: &str) -> bool {
|
|
matches!(name, "input" | "select" | "textarea" | "button")
|
|
}
|
|
|
|
/// Testo dei nodi discendenti, concatenato (etichette di opzioni e pulsanti).
|
|
fn testo_discendenti(doc: &Document, node: NodeId) -> String {
|
|
let mut out = String::new();
|
|
for &c in &doc.node(node).children {
|
|
match &doc.node(c).kind {
|
|
NodeKind::Text(t) => out.push_str(t),
|
|
NodeKind::Element(_) => out.push_str(&testo_discendenti(doc, c)),
|
|
_ => {}
|
|
}
|
|
}
|
|
out.trim().to_string()
|
|
}
|
|
|
|
/// Cerca un box per NodeId nell'albero già impaginato.
|
|
fn find_box_mut<'b>(b: &'b mut LayoutBox, node: NodeId) -> Option<&'b mut LayoutBox> {
|
|
if b.node == node {
|
|
return Some(b);
|
|
}
|
|
for c in b.children.iter_mut() {
|
|
if let Some(found) = find_box_mut(c, node) {
|
|
return Some(found);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Sposta un box già impaginato (posizionamento relativo, float a destra).
|
|
fn translate_box(b: &mut LayoutBox, dx: f32, dy: f32) {
|
|
if dx == 0.0 && dy == 0.0 {
|
|
return;
|
|
}
|
|
b.rect.x += dx;
|
|
b.rect.y += dy;
|
|
b.content.x += dx;
|
|
b.content.y += dy;
|
|
for line in &mut b.lines {
|
|
line.y += dy;
|
|
for run in &mut line.runs {
|
|
run.x += dx;
|
|
run.baseline += dy;
|
|
}
|
|
}
|
|
for c in &mut b.children {
|
|
translate_box(c, dx, dy);
|
|
}
|
|
}
|
|
|
|
/// Stile neutro per i run che non sono testo (immagini).
|
|
fn default_style() -> Arc<ComputedStyle> {
|
|
Arc::new(ComputedStyle::default())
|
|
}
|
|
|
|
/// Larghezza disponibile per un figlio, dati i suoi margini orizzontali.
|
|
fn child_avail_hint(content_w: f32, ml: f32, mr: f32) -> f32 {
|
|
(content_w - ml - mr).max(0.0)
|
|
}
|
|
|
|
/// Sposta righe e run dall'origine del contenuto alla posizione assoluta.
|
|
fn offset_lines(ls: &mut [Line], dx: f32, dy: f32) {
|
|
for l in ls.iter_mut() {
|
|
l.y += dy;
|
|
for r in &mut l.runs {
|
|
r.x += dx;
|
|
r.baseline += dy;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Impagina item inline in righe: collasso degli spazi, `white-space`, a capo sulle
|
|
/// parole, shaping per parola (kerning e legature dal font).
|
|
fn layout_lines(
|
|
items: &[InlineItem],
|
|
width: f32,
|
|
fonts: &Fonts,
|
|
align: TextAlign,
|
|
default_line_height: f32,
|
|
ws: WhiteSpace,
|
|
base_level: u8,
|
|
) -> (Vec<Line>, f32) {
|
|
let preserve_spaces = matches!(ws, WhiteSpace::Pre | WhiteSpace::PreWrap);
|
|
let preserve_newlines = matches!(
|
|
ws,
|
|
WhiteSpace::Pre | WhiteSpace::PreWrap | WhiteSpace::PreLine
|
|
);
|
|
let can_wrap = matches!(
|
|
ws,
|
|
WhiteSpace::Normal | WhiteSpace::PreWrap | WhiteSpace::PreLine
|
|
);
|
|
let wrap_width = if can_wrap { width } else { f32::INFINITY };
|
|
|
|
let mut out: Vec<Line> = Vec::new();
|
|
let mut cur: Vec<PendingWord> = Vec::new();
|
|
let mut x = 0.0f32;
|
|
let mut last_space = true;
|
|
let mut max_size = 0.0f32;
|
|
let mut max_line_height = 0.0f32;
|
|
// altezza massima delle immagini nella riga: alza la baseline, così
|
|
// l'immagine appoggia sulla baseline come un elemento sostituito inline
|
|
let mut max_image_h = 0.0f32;
|
|
// contributo sotto la baseline: i controlli centrati scendono di metà altezza
|
|
let mut max_below = 0.0f32;
|
|
let mut total_y = 0.0f32;
|
|
// spazio consumato subito prima della parola corrente: serve a ricostruire
|
|
// i distacchi quando le parole vengono riordinate in ordine visivo (bidi)
|
|
let mut pending_space = 0.0f32;
|
|
|
|
macro_rules! flush_line {
|
|
() => {{
|
|
if !cur.is_empty() {
|
|
// metriche per run: due famiglie diverse hanno ascendenti diversi
|
|
let mut ascent = 0.0f32;
|
|
let mut descent = 0.0f32;
|
|
for p in &cur {
|
|
ascent = ascent.max(p.font.ascent(p.style.font_size));
|
|
descent = descent.max(p.font.descent(p.style.font_size));
|
|
}
|
|
let ascent = ascent.max(max_image_h);
|
|
let descent = descent.max(max_below);
|
|
let line_h = (ascent + descent)
|
|
.max(max_line_height)
|
|
.max(default_line_height);
|
|
let (runs, _line_w) = build_runs(&cur, width, align, total_y + ascent);
|
|
cur.clear();
|
|
out.push(Line {
|
|
y: total_y,
|
|
height: line_h,
|
|
runs,
|
|
});
|
|
total_y += line_h;
|
|
}
|
|
cur.clear();
|
|
}};
|
|
}
|
|
|
|
macro_rules! finish_line {
|
|
() => {{
|
|
flush_line!();
|
|
x = 0.0;
|
|
// `pending_space` e `last_space` si riscrivono prima della prossima
|
|
// lettura: azzerarli qui sarebbe una scrittura morta.
|
|
max_size = 0.0;
|
|
max_line_height = 0.0;
|
|
max_image_h = 0.0;
|
|
max_below = 0.0;
|
|
}};
|
|
}
|
|
|
|
for item in items {
|
|
match item {
|
|
InlineItem::Image(data, w, h) => {
|
|
if x + *w > wrap_width && !cur.is_empty() {
|
|
finish_line!();
|
|
}
|
|
cur.push(PendingWord {
|
|
font: fonts.default_font(),
|
|
shaped: ShapedText::default(),
|
|
image: Some((Arc::clone(data), *w, *h)),
|
|
text: String::new(),
|
|
width: *w,
|
|
style: default_style(),
|
|
level: 0,
|
|
space_before: 0.0,
|
|
control: None,
|
|
});
|
|
x += *w;
|
|
max_line_height = max_line_height.max(*h);
|
|
max_image_h = max_image_h.max(*h);
|
|
}
|
|
InlineItem::Control(spec) => {
|
|
let (w, h) = (spec.width, spec.height);
|
|
if x + w > wrap_width && !cur.is_empty() {
|
|
finish_line!();
|
|
}
|
|
cur.push(PendingWord {
|
|
font: fonts.default_font(),
|
|
shaped: ShapedText::default(),
|
|
image: None,
|
|
text: spec.text.clone(),
|
|
width: w,
|
|
style: default_style(),
|
|
level: 0,
|
|
space_before: 0.0,
|
|
control: Some(spec.clone()),
|
|
});
|
|
x += w;
|
|
max_line_height = max_line_height.max(h);
|
|
max_image_h = max_image_h.max(spec.above);
|
|
max_below = max_below.max((h - spec.above).max(0.0));
|
|
}
|
|
InlineItem::Break => {
|
|
if cur.is_empty() {
|
|
// riga vuota esplicita: mantiene l'altezza
|
|
out.push(Line {
|
|
y: total_y,
|
|
height: default_line_height,
|
|
runs: Vec::new(),
|
|
});
|
|
total_y += default_line_height;
|
|
} else {
|
|
finish_line!();
|
|
}
|
|
}
|
|
InlineItem::Text(text, style) => {
|
|
let run_font = fonts.resolve(style.font_family.as_deref());
|
|
let mut word = String::new();
|
|
for ch in text.chars() {
|
|
let is_space = ch.is_whitespace();
|
|
if is_space {
|
|
if !word.is_empty() {
|
|
place_word(
|
|
&mut cur,
|
|
&mut x,
|
|
&mut max_size,
|
|
&mut max_line_height,
|
|
&word,
|
|
style,
|
|
wrap_width,
|
|
width,
|
|
align,
|
|
fonts,
|
|
&run_font,
|
|
&mut out,
|
|
&mut total_y,
|
|
base_level,
|
|
pending_space,
|
|
);
|
|
pending_space = 0.0;
|
|
word.clear();
|
|
}
|
|
if ch == '\n' && preserve_newlines {
|
|
finish_line!();
|
|
continue;
|
|
}
|
|
let space = run_font.space_width(style.font_size);
|
|
if preserve_spaces {
|
|
// gli spazi si contano uno per uno, anche a inizio riga
|
|
x += space;
|
|
pending_space += space;
|
|
last_space = true;
|
|
} else if !last_space {
|
|
if x + space > wrap_width && !cur.is_empty() {
|
|
finish_line!();
|
|
pending_space = 0.0;
|
|
} else {
|
|
x += space;
|
|
pending_space = space;
|
|
}
|
|
last_space = true;
|
|
}
|
|
continue;
|
|
}
|
|
last_space = false;
|
|
word.push(ch);
|
|
}
|
|
if !word.is_empty() {
|
|
place_word(
|
|
&mut cur,
|
|
&mut x,
|
|
&mut max_size,
|
|
&mut max_line_height,
|
|
&word,
|
|
style,
|
|
wrap_width,
|
|
width,
|
|
align,
|
|
fonts,
|
|
&run_font,
|
|
&mut out,
|
|
&mut total_y,
|
|
base_level,
|
|
pending_space,
|
|
);
|
|
pending_space = 0.0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
flush_line!();
|
|
|
|
(out, total_y)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn place_word(
|
|
cur: &mut Vec<PendingWord>,
|
|
x: &mut f32,
|
|
max_size: &mut f32,
|
|
max_line_height: &mut f32,
|
|
word: &str,
|
|
style: &Arc<ComputedStyle>,
|
|
wrap_width: f32,
|
|
width: f32,
|
|
align: TextAlign,
|
|
fonts: &Fonts,
|
|
font: &std::rc::Rc<FontHolder>,
|
|
out: &mut Vec<Line>,
|
|
total_y: &mut f32,
|
|
base_level: u8,
|
|
space_before: f32,
|
|
) {
|
|
// livello bidi della parola: dispari = si scrive da destra a sinistra
|
|
let level = bidi::word_level(word, base_level);
|
|
let rtl = level % 2 == 1;
|
|
// Fallback di font: se la faccia scelta non ha i glifi (glifo 0 = .notdef) la
|
|
// parola si compone con il font predefinito. Serve per i testi misti: il corsivo
|
|
// o il serif spesso non coprono ebraico o arabo.
|
|
let mut run_font = std::rc::Rc::clone(font);
|
|
let mut shaped = run_font.shape_dir(word, style.font_size, rtl);
|
|
if shaped.glyphs.iter().any(|g| g.id == 0) && !word.is_empty() {
|
|
let ripiego = fonts.default_font();
|
|
if !std::rc::Rc::ptr_eq(&ripiego, font) {
|
|
let alt = ripiego.shape_dir(word, style.font_size, rtl);
|
|
if !alt.glyphs.iter().any(|g| g.id == 0) {
|
|
run_font = ripiego;
|
|
shaped = alt;
|
|
}
|
|
}
|
|
}
|
|
let w = shaped.width;
|
|
if *x + w > wrap_width && !cur.is_empty() {
|
|
let size = (*max_size).max(1.0);
|
|
let ascent = font.ascent(size);
|
|
let descent = font.descent(size);
|
|
let line_h = (ascent + descent)
|
|
.max(*max_line_height)
|
|
.max(style.line_height);
|
|
let (runs, _line_w) = build_runs(cur, width, align, *total_y + ascent);
|
|
cur.clear();
|
|
out.push(Line {
|
|
y: *total_y,
|
|
height: line_h,
|
|
runs,
|
|
});
|
|
*total_y += line_h;
|
|
*x = 0.0;
|
|
*max_size = 0.0;
|
|
*max_line_height = 0.0;
|
|
}
|
|
cur.push(PendingWord {
|
|
font: run_font,
|
|
shaped,
|
|
image: None,
|
|
text: word.to_string(),
|
|
width: w,
|
|
style: style.clone(),
|
|
level,
|
|
space_before,
|
|
control: None,
|
|
});
|
|
*x += w;
|
|
*max_size = max_size.max(style.font_size);
|
|
*max_line_height = max_line_height.max(style.line_height);
|
|
}
|
|
|
|
/// Larghezza "naturale" del contenuto di un box (max-content).
|
|
///
|
|
/// Si misura l'estensione dei run di ogni riga, non il loro bordo destro: con
|
|
/// `text-align: center` o `right` il bordo destro dipende dallo spazio finto
|
|
/// usato per la misura e gonfierebbe il risultato (era il caso delle `th`).
|
|
fn intrinsic_width(b: &LayoutBox) -> f32 {
|
|
let mut m = 0.0f32;
|
|
for l in &b.lines {
|
|
if l.runs.is_empty() {
|
|
continue;
|
|
}
|
|
let lo = l.runs.iter().map(|r| r.x).fold(f32::MAX, f32::min);
|
|
let hi = l
|
|
.runs
|
|
.iter()
|
|
.map(|r| r.x + r.width)
|
|
.fold(f32::MIN, f32::max);
|
|
m = m.max(hi - lo);
|
|
}
|
|
for c in &b.children {
|
|
let contorno = (c.rect.w - c.content.w).max(0.0);
|
|
m = m.max(intrinsic_width(c) + contorno);
|
|
}
|
|
m
|
|
}
|
|
|
|
struct PendingWord {
|
|
font: std::rc::Rc<FontHolder>,
|
|
shaped: ShapedText,
|
|
image: Option<(Arc<ImageData>, f32, f32)>,
|
|
text: String,
|
|
width: f32,
|
|
style: Arc<ComputedStyle>,
|
|
/// livello bidi: dispari = la parola si scrive da destra
|
|
level: u8,
|
|
/// spazio che precede la parola nel flusso logico
|
|
space_before: f32,
|
|
control: Option<ControlSpec>,
|
|
}
|
|
|
|
/// Costruisce i run di una riga nell'ordine visivo (regola L2 dell'UBA) e
|
|
/// applica l'allineamento. Le parole arrivano in ordine logico con il proprio
|
|
/// livello bidi: qui si riordinano e si riassegnano le ascisse.
|
|
fn build_runs(
|
|
cur: &[PendingWord],
|
|
width: f32,
|
|
align: TextAlign,
|
|
baseline: f32,
|
|
) -> (Vec<TextRun>, f32) {
|
|
let livelli: Vec<u8> = cur.iter().map(|p| p.level).collect();
|
|
let ordine = bidi::visual_order(&livelli);
|
|
let mut pos = 0.0f32;
|
|
let mut posti: Vec<(usize, f32)> = Vec::with_capacity(ordine.len());
|
|
for (k, &idx) in ordine.iter().enumerate() {
|
|
if k > 0 {
|
|
pos += cur[idx].space_before;
|
|
}
|
|
posti.push((idx, pos));
|
|
pos += cur[idx].width;
|
|
}
|
|
let line_w = pos;
|
|
let offset = match align {
|
|
TextAlign::Left => 0.0,
|
|
TextAlign::Center => ((width - line_w) / 2.0).max(0.0),
|
|
TextAlign::Right => (width - line_w).max(0.0),
|
|
};
|
|
let mut runs = Vec::with_capacity(posti.len());
|
|
for (idx, x) in posti {
|
|
let p = &cur[idx];
|
|
runs.push(TextRun {
|
|
font: std::rc::Rc::clone(&p.font),
|
|
shaped: p.shaped.clone(),
|
|
image: p.image.clone(),
|
|
text: p.text.clone(),
|
|
x: x + offset,
|
|
baseline,
|
|
width: p.width,
|
|
color: p.style.color,
|
|
font_size: p.style.font_size,
|
|
font_weight: p.style.font_weight,
|
|
control: p.control.clone(),
|
|
});
|
|
}
|
|
(runs, line_w)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn confini_di_parola() {
|
|
let testo = "alfa beta gamma";
|
|
assert_eq!(word_range(testo, 0), (0, 4));
|
|
assert_eq!(word_range(testo, 3), (0, 4));
|
|
assert_eq!(word_range(testo, 5), (5, 9));
|
|
assert_eq!(word_range(testo, 12), (10, 15));
|
|
}
|
|
|
|
#[test]
|
|
fn parola_su_punteggiatura_seleziona_un_carattere() {
|
|
let testo = "alfa, beta";
|
|
assert_eq!(word_range(testo, 4), (4, 5));
|
|
}
|
|
|
|
#[test]
|
|
fn cursore_da_ascissa() {
|
|
let font = FontHolder::load(std::path::Path::new(
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
))
|
|
.expect("font di sistema");
|
|
let testo = "abcdef";
|
|
// a inizio testo
|
|
assert_eq!(caret_index_at(&font, testo, 16.0, 0.0), 0);
|
|
// oltre la fine: in fondo
|
|
assert_eq!(caret_index_at(&font, testo, 16.0, 10_000.0), 6);
|
|
// a metà del terzo carattere si resta prima di quello successivo
|
|
let meta = font.advance("ab", 16.0) + font.advance("c", 16.0) / 2.0 + 0.5;
|
|
assert_eq!(caret_index_at(&font, testo, 16.0, meta), 3);
|
|
}
|
|
|
|
#[test]
|
|
fn cursore_dentro_una_textarea_multiriga() {
|
|
let font = FontHolder::load(std::path::Path::new(
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
))
|
|
.expect("font di sistema");
|
|
let testo = "alfa\nbeta";
|
|
let interlinea = 16.0 * 1.35;
|
|
// inizio della seconda riga: indice 5 (dopo "alfa" + a capo)
|
|
assert_eq!(
|
|
caret_index_in_lines(&font, testo, 16.0, 0.0, interlinea + 1.0),
|
|
5
|
|
);
|
|
// fine della seconda riga
|
|
assert_eq!(
|
|
caret_index_in_lines(&font, testo, 16.0, 10_000.0, interlinea + 1.0),
|
|
9
|
|
);
|
|
}
|
|
}
|