@import, srcset e font da rete: le sotto-risorse che mancavano
Tre cose dichiarate «fuori ambito» e mai fatte, che si vedevano su metà dei siti veri: fogli importati non applicati, immagine sbagliata, tipografia mai caricata. - @import (src/resource.rs): espansione ricorsiva con la base giusta, cioè l'indirizzo *del foglio* e non della pagina; rilevamento dei cicli con un elenco di visitati; media query valutata (`print` ignorato, `screen`/`all` applicati); funziona anche dentro gli <style> inline, dove la base è il documento - srcset (src/layout.rs): `Nx` sceglie il candidato più piccolo che copre la densità dello schermo, altrimenti il più definito; `Nw` usa la larghezza dichiarata per CSS o attributo moltiplicata per la densità. La densità arriva al layout con un thread_local, come il viewport - @font-face con url() remoto o relativo al documento (src/font.rs): si scarica come una sotto-risorsa, con FontHolder::load_bytes per caricare da memoria Difetto trovato provando sul blog vero: gli url() dei font venivano trattati come percorsi di disco, quindi ogni sito dichiarava "No such file or directory" per un file che stava su un server. Era il mio elenco a chiamarla «mancante»; ora si scarica. WOFF e WOFF2 restano non supportati, e ora lo dicono: sono contenitori compressi (WOFF2 con brotli) che vanno ricostruiti tabella per tabella, non solo decompressi. Il messaggio è "WOFF2 non supportato (serve brotli): usare TTF o OTF", non "font illeggibile", che manderebbe a cercare un difetto inesistente. 7 test nuovi (tests/import_srcset.rs): import annidato, import risolto sulla cartella del foglio, ciclo che termina, import per la stampa ignorato, srcset per densità, srcset per larghezza, font remoto caricato con WOFF2 riconosciuto. Verificato sul blog dell'utente: resource_errors vuoto, e i 10 font dichiarati WOFF2 riportano il messaggio giusto invece di un errore di file mancante.
This commit is contained in:
1 parent
e138e01974
commit
318384472a
8 files changed
+675
-18
No files matched your search
+39
-6
@@ -69,6 +69,21 @@ impl std::fmt::Debug for FontHolder {
|
||||
impl FontHolder {
|
||||
pub fn load(path: &Path) -> Result<Self, String> {
|
||||
let data = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
Self::load_bytes(path, data)
|
||||
}
|
||||
|
||||
/// Carica una faccia già in memoria: serve ai font che arrivano dalla rete,
|
||||
/// dove non c'è un percorso di file.
|
||||
pub fn load_bytes(nome: &Path, data: Vec<u8>) -> Result<Self, String> {
|
||||
// WOFF e WOFF2 sono contenitori compressi: servirebbe un decompressore
|
||||
// (brotli per WOFF2). Meglio dirlo che riportare «font illeggibile», che
|
||||
// manda a cercare un difetto dove c'è solo una funzionalità assente.
|
||||
if data.starts_with(b"wOF2") {
|
||||
return Err("WOFF2 non supportato (serve brotli): usare TTF o OTF".to_string());
|
||||
}
|
||||
if data.starts_with(b"wOFF") {
|
||||
return Err("WOFF non supportato: usare TTF o OTF".to_string());
|
||||
}
|
||||
let font = FontVec::try_from_vec(data.clone()).map_err(|e| format!("{:?}", e))?;
|
||||
let leaked: &'static [u8] = Box::leak(data.into_boxed_slice());
|
||||
let face = rustybuzz::Face::from_slice(leaked, 0)
|
||||
@@ -81,7 +96,7 @@ impl FontHolder {
|
||||
Ok(FontHolder {
|
||||
font,
|
||||
face,
|
||||
path: path.to_path_buf(),
|
||||
path: nome.to_path_buf(),
|
||||
hash,
|
||||
})
|
||||
}
|
||||
@@ -338,16 +353,34 @@ impl Fonts {
|
||||
default: FontHolder,
|
||||
base_dir: &Path,
|
||||
specs: &[FontFaceSpec],
|
||||
risorse: Option<&crate::resource::Risorse>,
|
||||
) -> (Fonts, Vec<String>) {
|
||||
let mut faces: HashMap<String, Rc<FontHolder>> = HashMap::new();
|
||||
let mut errors = Vec::new();
|
||||
for spec in specs {
|
||||
let path = if Path::new(&spec.src).is_absolute() {
|
||||
PathBuf::from(&spec.src)
|
||||
} else {
|
||||
base_dir.join(&spec.src)
|
||||
// `src: url(...)` può essere assoluto, relativo al documento (se il
|
||||
// documento viene dalla rete) o un file: si prova nell'ordine giusto
|
||||
let assoluto = risorse.and_then(|r| r.risolvi(&spec.src));
|
||||
let (path, caricato) = match &assoluto {
|
||||
Some(url) if url.starts_with("http://") || url.starts_with("https://") => {
|
||||
let percorso = PathBuf::from(url);
|
||||
let esito = match risorse.and_then(|r| r.leggi(url, Path::new("."))) {
|
||||
Some(byte) => FontHolder::load_bytes(&percorso, byte),
|
||||
None => Err(format!("scaricamento fallito ({})", url)),
|
||||
};
|
||||
(percorso, esito)
|
||||
}
|
||||
_ => {
|
||||
let percorso = if Path::new(&spec.src).is_absolute() {
|
||||
PathBuf::from(&spec.src)
|
||||
} else {
|
||||
base_dir.join(&spec.src)
|
||||
};
|
||||
let esito = FontHolder::load(&percorso);
|
||||
(percorso, esito)
|
||||
}
|
||||
};
|
||||
match FontHolder::load(&path) {
|
||||
match caricato {
|
||||
Ok(f) => {
|
||||
faces.insert(normalize_family(&spec.family), Rc::new(f));
|
||||
}
|
||||
|
||||
+133
-4
@@ -13,6 +13,21 @@ use crate::style::{
|
||||
Position, TextAlign, Traccia, WhiteSpace,
|
||||
};
|
||||
|
||||
thread_local! {
|
||||
/// densità dello schermo (1.0 = un pixel CSS per pixel del dispositivo).
|
||||
/// Serve a `srcset`: con schermo denso si sceglie l'immagine più definita.
|
||||
static SCALA: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
|
||||
}
|
||||
|
||||
/// Dichiara la densità dello schermo per il layout corrente.
|
||||
pub fn set_scala(valore: f32) {
|
||||
SCALA.with(|c| c.set(if valore > 0.0 { valore } else { 1.0 }));
|
||||
}
|
||||
|
||||
fn scala() -> f32 {
|
||||
SCALA.with(|c| c.get())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Rect {
|
||||
pub x: f32,
|
||||
@@ -1478,10 +1493,31 @@ impl<'a> Ctx<'a> {
|
||||
self.layout_block(node, x, y, w, false)
|
||||
}
|
||||
|
||||
/// Indirizzo dell'immagine da usare: `srcset` sceglie il candidato adatto
|
||||
/// alla densità dello schermo, `src` resta il ripiego.
|
||||
fn src_immagine(&self, node: NodeId) -> Option<String> {
|
||||
let src = self.doc.attr(node, "src").unwrap_or("").trim().to_string();
|
||||
let srcset = self.doc.attr(node, "srcset");
|
||||
let Some(srcset) = srcset else {
|
||||
return if src.is_empty() { None } else { Some(src) };
|
||||
};
|
||||
let st = self.style_of(node);
|
||||
let larghezza = st.width.map(|l| l.resolve(1000.0)).or_else(|| {
|
||||
self.doc
|
||||
.attr(node, "width")
|
||||
.and_then(|v| v.trim().parse::<f32>().ok())
|
||||
});
|
||||
match scegli_srcset(srcset, larghezza, scala()) {
|
||||
Some(scelto) => Some(scelto),
|
||||
None if src.is_empty() => None,
|
||||
None => Some(src),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 src = self.src_immagine(node)?;
|
||||
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));
|
||||
@@ -1511,10 +1547,10 @@ impl<'a> Ctx<'a> {
|
||||
/// `<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 {
|
||||
let Some(src) = self.src_immagine(node) else {
|
||||
return;
|
||||
};
|
||||
let Some(data) = self.images.borrow_mut().get(src) else {
|
||||
let Some(data) = self.images.borrow_mut().get(&src) else {
|
||||
return;
|
||||
};
|
||||
let st = self.style_of(node);
|
||||
@@ -2619,3 +2655,96 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sceglie un candidato di `srcset`.
|
||||
///
|
||||
/// `Nx` è la densità: si prende il più piccolo che copre lo schermo, altrimenti
|
||||
/// il più grande (meglio definito che sgranato). `Nw` è la larghezza: si usa
|
||||
/// quella dichiarata nello stile o nell'attributo `width`, moltiplicata per la
|
||||
/// densità; se la larghezza non si conosce, con schermo denso si prende il più
|
||||
/// grande. Senza descrittore vale `1x`.
|
||||
fn scegli_srcset(srcset: &str, larghezza_css: Option<f32>, scala: f32) -> Option<String> {
|
||||
struct Candidato {
|
||||
url: String,
|
||||
densita: Option<f32>,
|
||||
larghezza: Option<f32>,
|
||||
}
|
||||
let mut candidati: Vec<Candidato> = Vec::new();
|
||||
for voce in srcset.split(',') {
|
||||
let mut parti = voce.split_whitespace();
|
||||
let Some(url) = parti.next() else { continue };
|
||||
if url.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let descrittore = parti.next().unwrap_or("").to_ascii_lowercase();
|
||||
let densita = descrittore
|
||||
.strip_suffix('x')
|
||||
.and_then(|n| n.parse::<f32>().ok());
|
||||
let larghezza = descrittore
|
||||
.strip_suffix('w')
|
||||
.and_then(|n| n.parse::<f32>().ok());
|
||||
candidati.push(Candidato {
|
||||
url: url.to_string(),
|
||||
densita,
|
||||
larghezza,
|
||||
});
|
||||
}
|
||||
if candidati.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let con_densita: Vec<&Candidato> = candidati.iter().filter(|c| c.densita.is_some()).collect();
|
||||
if !con_densita.is_empty() {
|
||||
let mut scelto = con_densita[0];
|
||||
let mut migliore = f32::MAX;
|
||||
for c in &con_densita {
|
||||
let d = c.densita.unwrap_or(1.0);
|
||||
if d >= scala && d < migliore {
|
||||
migliore = d;
|
||||
scelto = c;
|
||||
}
|
||||
}
|
||||
if migliore == f32::MAX {
|
||||
// nessuno copre lo schermo: il più definito disponibile
|
||||
scelto = con_densita.iter().copied().fold(con_densita[0], |acc, c| {
|
||||
if c.densita.unwrap_or(1.0) > acc.densita.unwrap_or(1.0) {
|
||||
c
|
||||
} else {
|
||||
acc
|
||||
}
|
||||
});
|
||||
}
|
||||
return Some(scelto.url.clone());
|
||||
}
|
||||
|
||||
let con_larghezza: Vec<&Candidato> =
|
||||
candidati.iter().filter(|c| c.larghezza.is_some()).collect();
|
||||
if let Some(base) = larghezza_css {
|
||||
let obiettivo = base * scala.max(1.0);
|
||||
let mut scelto = con_larghezza.first().copied()?;
|
||||
let mut migliore = f32::MAX;
|
||||
for c in &con_larghezza {
|
||||
let w = c.larghezza.unwrap_or(0.0);
|
||||
if w >= obiettivo && w < migliore {
|
||||
migliore = w;
|
||||
scelto = c;
|
||||
}
|
||||
}
|
||||
if migliore < f32::MAX {
|
||||
return Some(scelto.url.clone());
|
||||
}
|
||||
}
|
||||
// larghezza ignota: si prende il più grande se lo schermo è denso
|
||||
let mut scelto = candidati[0].url.clone();
|
||||
if scala > 1.5 {
|
||||
let mut massimo = 0.0;
|
||||
for c in &con_larghezza {
|
||||
let w = c.larghezza.unwrap_or(0.0);
|
||||
if w >= massimo {
|
||||
massimo = w;
|
||||
scelto = c.url.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(scelto)
|
||||
}
|
||||
+21
-3
@@ -190,7 +190,15 @@ fn render_pezzi(
|
||||
let risorse =
|
||||
std::rc::Rc::new(resource::Risorse::new(opts.base_url.clone()).con_client(client));
|
||||
let fogli = fogli_esterni(doc, &risorse);
|
||||
let author_css = format!("{}\n{}\n{}", fogli, fogli_inline, css);
|
||||
// gli `<style>` inline possono contenere `@import`, che si risolve sull'indirizzo
|
||||
// del documento; senza questo, il foglio importato veniva perso in silenzio
|
||||
let inline_espanso = {
|
||||
let mut visitati: Vec<String> = Vec::new();
|
||||
risorse.espandi_import(fogli_inline, opts.base_url.as_deref(), 0, &mut visitati)
|
||||
};
|
||||
let author_css = format!("{}\n{}\n{}", fogli, inline_espanso, css);
|
||||
// `srcset` si sceglie in base alla densità dello schermo: il layout deve saperla
|
||||
layout::set_scala(opts.dpi_scale);
|
||||
let css_viewport = opts.viewport.0 as f32 / opts.dpi_scale;
|
||||
// vh/vw si risolvono durante la cascata: il viewport va noto prima
|
||||
style::set_viewport(css_viewport, opts.viewport.1 as f32 / opts.dpi_scale);
|
||||
@@ -209,7 +217,8 @@ fn render_pezzi(
|
||||
.map_err(|e| format!("font non caricabile ({}): {}", opts.font_path.display(), e))?;
|
||||
// @font-face: le facce dichiarate dal foglio, caricate una volta per render
|
||||
let face_specs = css::parse_font_faces(&author_css);
|
||||
let (fonts, face_errors) = font::Fonts::new(default_font, &opts.base_dir, &face_specs);
|
||||
let (fonts, face_errors) =
|
||||
font::Fonts::new(default_font, &opts.base_dir, &face_specs, Some(&risorse));
|
||||
|
||||
let mut images = img::ImageCache::new(&opts.base_dir, Some(risorse.clone()));
|
||||
let t2 = std::time::Instant::now();
|
||||
@@ -322,7 +331,16 @@ fn fogli_esterni(doc: &dom::Document, risorse: &resource::Risorse) -> String {
|
||||
if rel.split_whitespace().any(|r| r == "stylesheet") && tipo.contains("css") {
|
||||
if let Some(href) = doc.attr(id, "href") {
|
||||
if let Some(byte) = risorse.leggi(href, std::path::Path::new(".")) {
|
||||
out.push_str(&String::from_utf8_lossy(&byte));
|
||||
let testo = String::from_utf8_lossy(&byte).to_string();
|
||||
// gli `@import` si risolvono rispetto al foglio, non alla pagina
|
||||
let base = risorse.risolvi(href);
|
||||
let mut visitati = vec![base.clone().unwrap_or_default()];
|
||||
out.push_str(&risorse.espandi_import(
|
||||
&testo,
|
||||
base.as_deref(),
|
||||
0,
|
||||
&mut visitati,
|
||||
));
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
+129
-3
@@ -4,9 +4,10 @@
|
||||
//! immagini, perché il motore sapeva leggere solo dal disco. Qui si risolve un
|
||||
//! riferimento (`href`/`src`) rispetto all'indirizzo del documento e si scarica.
|
||||
//!
|
||||
//! Ambito: `link[rel=stylesheet]` e `img[src]` su `http`/`https`, con cache per
|
||||
//! singolo render e limiti di dimensione. Fuori ambito, dichiarato: `@import`,
|
||||
//! `srcset`, `style` esterni annidati, cookie, cache fra render diversi.
|
||||
//! Ambito: `link[rel=stylesheet]`, `@import` (anche annidati, con rilevamento dei
|
||||
//! cicli), `img[src]` e `img[srcset]` su `http`/`https`, con cache per singolo
|
||||
//! render e limiti di dimensione. Fuori ambito, dichiarato: `@import` con
|
||||
//! `layer()`/`supports()`, `image-set()`, cache fra render diversi.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
@@ -105,6 +106,101 @@ impl Risorse {
|
||||
}
|
||||
})
|
||||
}
|
||||
/// Espande gli `@import` di un foglio, sostituendoli con il contenuto
|
||||
/// importato: la cascata li vede nell'ordine giusto senza che il parser CSS
|
||||
/// debba sapere che esistono.
|
||||
///
|
||||
/// `base` è l'indirizzo *del foglio*, non del documento: un `@import` dentro
|
||||
/// `css/tema.css` si risolve rispetto a `css/`, non alla pagina.
|
||||
pub fn espandi_import(
|
||||
&self,
|
||||
testo: &str,
|
||||
base: Option<&str>,
|
||||
profondita: usize,
|
||||
visitati: &mut Vec<String>,
|
||||
) -> String {
|
||||
const PROFONDITA_MAX: usize = 4;
|
||||
if profondita > PROFONDITA_MAX {
|
||||
return testo.to_string();
|
||||
}
|
||||
let mut out = String::with_capacity(testo.len());
|
||||
let mut i = 0usize;
|
||||
let byte = testo.as_bytes();
|
||||
while i < testo.len() {
|
||||
// commenti: copiati interi, così `@import` dentro un commento non conta
|
||||
if testo[i..].starts_with("/*") {
|
||||
match testo[i + 2..].find("*/") {
|
||||
Some(fine) => {
|
||||
out.push_str(&testo[i..i + 2 + fine + 2]);
|
||||
i += 2 + fine + 2;
|
||||
continue;
|
||||
}
|
||||
None => {
|
||||
out.push_str(&testo[i..]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// stringhe: copiate intere
|
||||
if byte[i] == b'"' || byte[i] == b'\'' {
|
||||
let virgoletta = byte[i] as char;
|
||||
let inizio = i;
|
||||
i += 1;
|
||||
while i < testo.len() && byte[i] as char != virgoletta {
|
||||
if byte[i] == b'\\' {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
i = (i + 1).min(testo.len());
|
||||
out.push_str(&testo[inizio..i]);
|
||||
continue;
|
||||
}
|
||||
if testo[i..].starts_with("@import") {
|
||||
let resto = &testo[i + 7..];
|
||||
let Some(fine) = resto.find(';') else {
|
||||
out.push_str(&testo[i..]);
|
||||
break;
|
||||
};
|
||||
if let Some((riferimento, media_ok)) = analizza_import(&resto[..fine]) {
|
||||
if media_ok {
|
||||
if let Some(assoluto) = risolvi_url(base, &riferimento) {
|
||||
if !visitati.iter().any(|v| v == &assoluto) {
|
||||
visitati.push(assoluto.clone());
|
||||
if let Some(contenuto) =
|
||||
self.leggi(&assoluto, std::path::Path::new("."))
|
||||
{
|
||||
let interno = String::from_utf8_lossy(&contenuto).to_string();
|
||||
out.push_str(&self.espandi_import(
|
||||
&interno,
|
||||
Some(&assoluto),
|
||||
profondita + 1,
|
||||
visitati,
|
||||
));
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 7 + fine + 1;
|
||||
continue;
|
||||
}
|
||||
// copia fino al prossimo carattere interessante
|
||||
let resto = &testo[i..];
|
||||
let prossimo = resto
|
||||
.find(|c| c == '@' || c == '/' || c == '"' || c == '\'')
|
||||
.unwrap_or(resto.len());
|
||||
if prossimo == 0 {
|
||||
out.push(byte[i] as char);
|
||||
i += 1;
|
||||
} else {
|
||||
out.push_str(&testo[i..i + prossimo]);
|
||||
i += prossimo;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn limiti() -> net::Limiti {
|
||||
@@ -239,3 +335,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Riconosce la parte utile di una dichiarazione `@import`:
|
||||
/// `url("x.css")`, `"x.css"`, `'x.css'`, con una media query facoltativa.
|
||||
/// Restituisce il riferimento e se la media query ci riguarda (`screen`/`all`
|
||||
/// sì, `print` no: stampiamo a schermo).
|
||||
fn analizza_import(dichiarazione: &str) -> Option<(String, bool)> {
|
||||
let testo = dichiarazione.trim();
|
||||
let (riferimento, resto) = if let Some(dopo) = testo.strip_prefix("url(") {
|
||||
let chiusa = dopo.find(')')?;
|
||||
let dentro = dopo[..chiusa]
|
||||
.trim()
|
||||
.trim_matches(|c| c == '"' || c == '\'');
|
||||
(dentro.to_string(), &dopo[chiusa + 1..])
|
||||
} else if testo.starts_with('"') || testo.starts_with('\'') {
|
||||
let virgoletta = testo.chars().next()?;
|
||||
let chiusa = testo[1..].find(virgoletta)? + 1;
|
||||
(testo[1..chiusa].to_string(), &testo[chiusa + 1..])
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
if riferimento.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let media = resto.trim().to_ascii_lowercase();
|
||||
let ci_riguarda = media.is_empty()
|
||||
|| media.contains("all")
|
||||
|| media.contains("screen")
|
||||
|| !media.contains("print");
|
||||
Some((riferimento, ci_riguarda))
|
||||
}
|
||||
Reference in new issue
Block a user