//! SVG in linea, per le icone (M2.15).
//!
//! Non è l'intero SVG: niente trasformazioni, gradienti, testo, filtri, maschere
//! o animazioni. È il sottoinsieme con cui quasi ogni sito disegna le icone:
//! ` ` con riempimento, tratto e le
//! forme base.
//!
//! Le figure escono già **appiattite** in segmenti e scalate al riquadro del box:
//! chi disegna non deve sapere cosa sia una curva di Bézier.
use crate::dom::{Document, NodeId, NodeKind};
use crate::style::Color;
/// Una figura pronta da disegnare: contorni chiusi o aperti, riempimento e tratto.
#[derive(Debug, Clone)]
pub struct Figura {
/// contorni in pixel CSS, relativi all'angolo in alto a sinistra del box
pub contorni: Vec>,
pub riempimento: Option,
pub tratto: Option<(Color, f32)>,
}
/// Trasformazione da unità `viewBox` a pixel del box.
#[derive(Debug, Clone, Copy)]
struct Scala {
x: f32,
y: f32,
sx: f32,
sy: f32,
}
impl Scala {
fn applica(&self, p: (f32, f32)) -> (f32, f32) {
(self.x + p.0 * self.sx, self.y + p.1 * self.sy)
}
}
/// Costruisce le figure di un ``. `lato` è il riquadro in pixel CSS,
/// `colore` serve a risolvere `currentColor`.
pub fn figure(
doc: &Document,
node: NodeId,
larghezza: f32,
altezza: f32,
colore: Color,
) -> Vec {
let scala = scala_di(doc, node, larghezza, altezza);
let mut out = Vec::new();
let stile_radice = Stile::da_nodo(doc, node, colore);
raccogli(doc, node, &scala, &stile_radice, &mut out);
out
}
/// `viewBox="minx miny larghezza altezza"` mappato sul riquadro del box.
fn scala_di(doc: &Document, node: NodeId, larghezza: f32, altezza: f32) -> Scala {
let vb = doc
.attr(node, "viewBox")
.or_else(|| doc.attr(node, "viewbox"))
.map(|v| {
v.split(|c: char| c == ',' || c.is_whitespace())
.filter(|p| !p.is_empty())
.filter_map(|p| p.parse::().ok())
.collect::>()
})
.filter(|v| v.len() == 4);
match vb {
Some(v) => {
let (mut minx, mut miny, mut w, mut h) = (v[0], v[1], v[2], v[3]);
if w <= 0.0 {
w = larghezza.max(1.0);
}
if h <= 0.0 {
h = altezza.max(1.0);
}
if minx.is_nan() {
minx = 0.0;
}
if miny.is_nan() {
miny = 0.0;
}
// `preserveAspectRatio` di default: si mantiene la proporzione e si
// centra (xMidYMid meet)
let sx = larghezza / w;
let sy = altezza / h;
let s = sx.min(sy);
Scala {
x: (larghezza - w * s) / 2.0 - minx * s,
y: (altezza - h * s) / 2.0 - miny * s,
sx: s,
sy: s,
}
}
None => Scala {
x: 0.0,
y: 0.0,
sx: larghezza.max(1.0) / 24.0,
sy: altezza.max(1.0) / 24.0,
},
}
}
/// Attributi di presentazione che si ereditano lungo l'albero.
#[derive(Debug, Clone, Copy)]
struct Stile {
riempimento: Option,
tratto: Option<(Color, f32)>,
/// colore del testo, per `currentColor`
testo: Color,
}
impl Stile {
fn da_nodo(doc: &Document, node: NodeId, colore_testo: Color) -> Stile {
let leggi_colore = |nome: &str| -> Option> {
let v = doc.attr(node, nome)?;
let v = v.trim();
if v.eq_ignore_ascii_case("none") || v.is_empty() {
return Some(None);
}
if v.eq_ignore_ascii_case("currentColor") {
return Some(Some(colore_testo));
}
crate::style::parse_color(v).map(Some)
};
// i CSS in linea (`style="fill: …"`) vincono sugli attributi
let mut riempimento = leggi_colore("fill");
let mut tratto = leggi_colore("stroke");
if let Some(inline) = doc.attr(node, "style") {
for parte in inline.split(';') {
let Some((k, v)) = parte.split_once(':') else {
continue;
};
let k = k.trim().to_ascii_lowercase();
let v = v.trim();
let colore = if v.eq_ignore_ascii_case("none") {
None
} else if v.eq_ignore_ascii_case("currentColor") {
Some(colore_testo)
} else {
crate::style::parse_color(v)
};
match k.as_str() {
"fill" => riempimento = Some(colore),
"stroke" => tratto = Some(colore),
_ => {}
}
}
}
let spessore = doc
.attr(node, "stroke-width")
.and_then(|v| v.trim().parse::().ok())
.unwrap_or(1.0);
Stile {
riempimento: riempimento.unwrap_or(Some(Color {
r: 0,
g: 0,
b: 0,
a: 255,
})),
tratto: match tratto {
Some(Some(c)) => Some((c, spessore)),
_ => None,
},
testo: colore_testo,
}
}
}
fn raccogli(doc: &Document, node: NodeId, scala: &Scala, eredita: &Stile, out: &mut Vec) {
for &child in &doc.node(node).children {
let NodeKind::Element(e) = &doc.node(child).kind else {
continue;
};
let nome = e.name.to_ascii_lowercase();
let stile = Stile::da_nodo(doc, child, eredita.testo);
// `fill`/`stroke` si ereditano: se il figlio non li dichiara valgono quelli
// del genitore — è così che un `` colora tutti i percorsi
let stile = Stile {
riempimento: if doc.attr(child, "fill").is_some() || ha_inline(child, doc, "fill") {
stile.riempimento
} else {
eredita.riempimento
},
tratto: if doc.attr(child, "stroke").is_some() || ha_inline(child, doc, "stroke") {
stile.tratto
} else {
eredita.tratto
},
testo: eredita.testo,
};
let mut contorni: Vec> = Vec::new();
match nome.as_str() {
"g" | "svg" | "a" => {
raccogli(doc, child, scala, &stile, out);
continue;
}
"path" => {
if let Some(d) = doc.attr(child, "d") {
contorni = percorsi(d);
}
}
"rect" => {
let n = |a: &str, d: f32| {
doc.attr(child, a)
.and_then(|v| v.trim().trim_end_matches("px").parse::().ok())
.unwrap_or(d)
};
let (x, y, w, h) = (n("x", 0.0), n("y", 0.0), n("width", 0.0), n("height", 0.0));
if w > 0.0 && h > 0.0 {
contorni.push(vec![(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
}
}
"circle" => {
let n = |a: &str, d: f32| {
doc.attr(child, a)
.and_then(|v| v.trim().parse::().ok())
.unwrap_or(d)
};
let (cx, cy, r) = (n("cx", 0.0), n("cy", 0.0), n("r", 0.0));
if r > 0.0 {
contorni.push(cerchio(cx, cy, r, r));
}
}
"ellipse" => {
let n = |a: &str, d: f32| {
doc.attr(child, a)
.and_then(|v| v.trim().parse::().ok())
.unwrap_or(d)
};
let (cx, cy) = (n("cx", 0.0), n("cy", 0.0));
let (rx, ry) = (n("rx", 0.0), n("ry", 0.0));
if rx > 0.0 && ry > 0.0 {
contorni.push(cerchio(cx, cy, rx, ry));
}
}
"line" => {
let n = |a: &str, d: f32| {
doc.attr(child, a)
.and_then(|v| v.trim().parse::().ok())
.unwrap_or(d)
};
contorni.push(vec![
(n("x1", 0.0), n("y1", 0.0)),
(n("x2", 0.0), n("y2", 0.0)),
]);
}
"polyline" | "polygon" => {
if let Some(punti) = doc.attr(child, "points") {
let nums: Vec = punti
.split(|c: char| c == ',' || c.is_whitespace())
.filter(|p| !p.is_empty())
.filter_map(|p| p.parse::().ok())
.collect();
let punti: Vec<(f32, f32)> = nums
.chunks_exact(2)
.map(|c| scala.applica((c[0], c[1])))
.collect();
if punti.len() >= 2 {
contorni.push(punti);
}
}
}
_ => {}
}
if contorni.is_empty() {
// un `` vuoto o una forma senza geometria: si scende comunque
raccogli(doc, child, scala, &stile, out);
continue;
}
out.push(Figura {
contorni: contorni
.into_iter()
.map(|c| c.into_iter().map(|p| scala.applica(p)).collect())
.collect(),
riempimento: stile.riempimento,
tratto: stile.tratto,
});
}
}
fn ha_inline(node: NodeId, doc: &Document, proprieta: &str) -> bool {
doc.attr(node, "style")
.map(|s| {
s.split(';').any(|p| {
p.split_once(':')
.map(|(k, _)| k.trim().eq_ignore_ascii_case(proprieta))
.unwrap_or(false)
})
})
.unwrap_or(false)
}
fn cerchio(cx: f32, cy: f32, rx: f32, ry: f32) -> Vec<(f32, f32)> {
let passi = 32usize;
(0..passi)
.map(|i| {
let a = std::f32::consts::TAU * i as f32 / passi as f32;
(cx + rx * a.cos(), cy + ry * a.sin())
})
.collect()
}
/// Appiattisce un attributo `d` in contorni di segmenti, già scalati.
pub fn percorsi(d: &str) -> Vec> {
let mut out: Vec> = Vec::new();
let mut corrente: Vec<(f32, f32)> = Vec::new();
let mut p = (0.0f32, 0.0f32);
let mut inizio = (0.0f32, 0.0f32);
// ultimo punto di controllo, per le forme riflesse S/T
let mut ctrl: Option<(f32, f32)> = None;
let mut prec: u8 = 0;
let mut i = 0usize;
let b: Vec = d.chars().collect();
let mut comando: u8 = 0;
let numero = |i: &mut usize| -> Option {
while *i < b.len() && (b[*i] == ',' || b[*i].is_whitespace()) {
*i += 1;
}
let inizio = *i;
if *i < b.len() && (b[*i] == '-' || b[*i] == '+') {
*i += 1;
}
let mut visto_punto = false;
while *i < b.len() {
let c = b[*i];
if c.is_ascii_digit() {
*i += 1;
} else if c == '.' && !visto_punto {
visto_punto = true;
*i += 1;
} else if c == 'e' || c == 'E' {
*i += 1;
if *i < b.len() && (b[*i] == '-' || b[*i] == '+') {
*i += 1;
}
} else {
break;
}
}
if *i == inizio {
return None;
}
b[inizio..*i].iter().collect::().parse::().ok()
};
while i < b.len() {
let c = b[i];
if c.is_ascii_alphabetic() {
comando = c as u8;
i += 1;
if comando == b'Z' || comando == b'z' {
if !corrente.is_empty() {
corrente.push(inizio);
out.push(std::mem::take(&mut corrente));
}
p = inizio;
ctrl = None;
prec = comando;
continue;
}
} else if c == ',' || c.is_whitespace() {
i += 1;
continue;
}
let rel = comando.is_ascii_lowercase();
let base = |p: (f32, f32)| if rel { (p.0, p.1) } else { (0.0, 0.0) };
match comando.to_ascii_uppercase() {
b'M' => {
let (Some(x), Some(y)) = (numero(&mut i), numero(&mut i)) else {
break;
};
let o = base(p);
let nuovo = (o.0 + x, o.1 + y);
if !corrente.is_empty() {
out.push(std::mem::take(&mut corrente));
}
corrente.push(nuovo);
p = nuovo;
inizio = nuovo;
ctrl = None;
// dopo una M le coppie successive sono L
comando = if rel { b'l' } else { b'L' };
}
b'L' => {
let (Some(x), Some(y)) = (numero(&mut i), numero(&mut i)) else {
break;
};
let o = base(p);
p = (o.0 + x, o.1 + y);
if corrente.is_empty() {
corrente.push(p);
inizio = p;
} else {
corrente.push(p);
}
ctrl = None;
}
b'H' => {
let Some(x) = numero(&mut i) else { break };
p = (if rel { p.0 + x } else { x }, p.1);
if corrente.is_empty() {
corrente.push(p);
inizio = p;
} else {
corrente.push(p);
}
ctrl = None;
}
b'V' => {
let Some(y) = numero(&mut i) else { break };
p = (p.0, if rel { p.1 + y } else { y });
if corrente.is_empty() {
corrente.push(p);
inizio = p;
} else {
corrente.push(p);
}
ctrl = None;
}
b'C' | b'S' => {
let (c1, c2, fine) = if comando.to_ascii_uppercase() == b'C' {
let (Some(x1), Some(y1), Some(x2), Some(y2), Some(x), Some(y)) = (
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
) else {
break;
};
let o = base(p);
(
(o.0 + x1, o.1 + y1),
(o.0 + x2, o.1 + y2),
(o.0 + x, o.1 + y),
)
} else {
let (Some(x2), Some(y2), Some(x), Some(y)) = (
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
) else {
break;
};
let o = base(p);
let c1 = if prec == b'C' || prec == b'S' {
match ctrl {
Some(k) => (2.0 * p.0 - k.0, 2.0 * p.1 - k.1),
None => p,
}
} else {
p
};
(c1, (o.0 + x2, o.1 + y2), (o.0 + x, o.1 + y))
};
if corrente.is_empty() {
corrente.push(p);
inizio = p;
}
cubica(p, c1, c2, fine, &mut corrente);
ctrl = Some(c2);
p = fine;
}
b'Q' | b'T' => {
let (c1, fine) = if comando.to_ascii_uppercase() == b'Q' {
let (Some(x1), Some(y1), Some(x), Some(y)) = (
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
) else {
break;
};
let o = base(p);
((o.0 + x1, o.1 + y1), (o.0 + x, o.1 + y))
} else {
let (Some(x), Some(y)) = (numero(&mut i), numero(&mut i)) else {
break;
};
let o = base(p);
let c1 = if prec == b'Q' || prec == b'T' {
match ctrl {
Some(k) => (2.0 * p.0 - k.0, 2.0 * p.1 - k.1),
None => p,
}
} else {
p
};
(c1, (o.0 + x, o.1 + y))
};
if corrente.is_empty() {
corrente.push(p);
inizio = p;
}
quadratica(p, c1, fine, &mut corrente);
ctrl = Some(c1);
p = fine;
}
b'A' => {
// archi ellittici: si approssimano con una spezzata tra i due
// estremi. Un'icona fatta di archi resta riconoscibile; una
// formula completa sarebbe sproporzionata qui.
let (
Some(_rx),
Some(_ry),
Some(_rot),
Some(_large),
Some(_sweep),
Some(x),
Some(y),
) = (
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
numero(&mut i),
)
else {
break;
};
let o = base(p);
let fine = (o.0 + x, o.1 + y);
if corrente.is_empty() {
corrente.push(p);
inizio = p;
}
corrente.push(fine);
p = fine;
ctrl = None;
}
_ => break,
}
prec = comando;
}
if !corrente.is_empty() {
out.push(corrente);
}
out
}
fn cubica(
p0: (f32, f32),
c1: (f32, f32),
c2: (f32, f32),
p3: (f32, f32),
out: &mut Vec<(f32, f32)>,
) {
let passi = 16;
for k in 1..=passi {
let t = k as f32 / passi as f32;
let u = 1.0 - t;
let x =
u * u * u * p0.0 + 3.0 * u * u * t * c1.0 + 3.0 * u * t * t * c2.0 + t * t * t * p3.0;
let y =
u * u * u * p0.1 + 3.0 * u * u * t * c1.1 + 3.0 * u * t * t * c2.1 + t * t * t * p3.1;
out.push((x, y));
}
}
fn quadratica(p0: (f32, f32), c1: (f32, f32), p2: (f32, f32), out: &mut Vec<(f32, f32)>) {
let passi = 12;
for k in 1..=passi {
let t = k as f32 / passi as f32;
let u = 1.0 - t;
let x = u * u * p0.0 + 2.0 * u * t * c1.0 + t * t * p2.0;
let y = u * u * p0.1 + 2.0 * u * t * c1.1 + t * t * p2.1;
out.push((x, y));
}
}
/// Rasterizza le figure in una bitmap RGBA alla densità richiesta.
///
/// Serve al caso **in linea**: un'icona dentro un paragrafo passa per il
/// percorso delle immagini sostituite, che è già scritto e provato. Il caso
/// blocco usa invece i percorsi vettoriali (`Cmd::Path`), nitidi a ogni zoom.
pub fn rasterizza(
figure: &[Figura],
larghezza: f32,
altezza: f32,
scala: f32,
) -> crate::img::ImageData {
let scala = scala.max(0.5);
let w = ((larghezza * scala).round() as u32).max(1);
let h = ((altezza * scala).round() as u32).max(1);
let mut buf = vec![0u8; (w as usize) * (h as usize) * 4];
for figura in figure {
let contorni: Vec> = figura
.contorni
.iter()
.map(|c| c.iter().map(|(x, y)| (x * scala, y * scala)).collect())
.collect();
if let Some(colore) = figura.riempimento {
crate::paint::riempi_contorni(&mut buf, w, h, &contorni, colore);
}
if let Some((colore, spessore)) = figura.tratto {
crate::paint::traccia_contorni(&mut buf, w, h, &contorni, colore, spessore * scala);
}
}
crate::img::ImageData {
width: w,
height: h,
rgba: buf,
}
}