//! Testo: shaping, misura e raster. //! //! Lo shaping usa `rustybuzz` (port Rust di HarfBuzz, nessuna dipendenza C): kerning, //! legature e posizionamento dei glifi escono dal font, non da una somma di avanzamenti. //! Il raster usa `ab_glyph` per gli outline, con cache condivisa nel processo. use std::cell::RefCell; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::rc::Rc; use ab_glyph::{Font, FontVec, PxScale, ScaleFont}; use crate::style::Color; /// Dimensione effettiva usata per misura e raster: 0,5 px di quantizzazione sono /// invisibili e limitano le varianti in cache. fn quantize(px: f32) -> f32 { ((px * 2.0).round() / 2.0).max(1.0) } #[derive(Clone, Copy, Debug)] pub struct ShapedGlyph { pub id: u16, pub advance: f32, pub x_offset: f32, pub y_offset: f32, } #[derive(Clone, Debug, Default)] pub struct ShapedText { pub glyphs: Vec, pub width: f32, } #[derive(Clone)] struct GlyphBitmap { /// offset rispetto al punto di penna (x) e alla baseline (y) left: i32, top: i32, w: u32, h: u32, coverage: Vec, } thread_local! { /// Cache condivisa da tutte le istanze nel processo: un cambio di zoom ripete /// le stesse lettere alle stesse dimensioni, e senza condivisione ogni render /// ripartirebbe da zero rasterizzando le curve. static GLYPH_CACHE: RefCell>> = RefCell::new(HashMap::new()); } pub struct FontHolder { font: FontVec, /// `Face` presta i byte del font: caricati una volta e tenuti per tutta la /// vita del processo (un font per documento). face: rustybuzz::Face<'static>, path: PathBuf, hash: u64, } impl std::fmt::Debug for FontHolder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "FontHolder({})", self.path.display()) } } impl FontHolder { pub fn load(path: &Path) -> Result { 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) -> Result { // 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) .ok_or_else(|| "font non leggibile da rustybuzz".to_string())?; let mut hash = leaked.len() as u64; for b in leaked.iter().step_by(4097) { hash = hash.wrapping_mul(31).wrapping_add(*b as u64); } Ok(FontHolder { font, face, path: nome.to_path_buf(), hash, }) } pub fn path(&self) -> &Path { &self.path } pub fn ascent(&self, px: f32) -> f32 { self.font.as_scaled(PxScale::from(quantize(px))).ascent() } /// Positivo, come ascendente. pub fn descent(&self, px: f32) -> f32 { -self.font.as_scaled(PxScale::from(quantize(px))).descent() } /// Shaping di una parola o frammento: gli avanzamenti includono il kerning. pub fn shape(&self, text: &str, px: f32) -> ShapedText { self.shape_dir(text, px, false) } /// Shaping con `letter-spacing`: la spaziatura si aggiunge agli avanzamenti, /// così misura e disegno restano d'accordo (il CSS la conta dopo ogni glifo). pub fn shape_spaced(&self, text: &str, px: f32, rtl: bool, spaziatura: f32) -> ShapedText { let mut shaped = self.shape_dir(text, px, rtl); if spaziatura != 0.0 && !shaped.glyphs.is_empty() { for g in &mut shaped.glyphs { g.advance += spaziatura; } shaped.width += spaziatura * shaped.glyphs.len() as f32; shaped.width = shaped.width.max(0.0); } shaped } /// Shaping con direzione: `rtl` inverte l'ordine dei glifi (testo ebraico, /// arabo). I glifi tornano in ordine visivo, quindi si disegnano da sinistra. pub fn shape_dir(&self, text: &str, px: f32, rtl: bool) -> ShapedText { if text.is_empty() { return ShapedText::default(); } let size = quantize(px); let mut buf = rustybuzz::UnicodeBuffer::new(); buf.push_str(text); if rtl { buf.set_direction(rustybuzz::Direction::RightToLeft); } else { buf.set_direction(rustybuzz::Direction::LeftToRight); } let out = rustybuzz::shape(&self.face, &[], buf); let upem = self.face.units_per_em().max(1) as f32; let k = size / upem; let infos = out.glyph_infos(); let positions = out.glyph_positions(); let mut glyphs = Vec::with_capacity(infos.len()); let mut width = 0.0f32; for (info, pos) in infos.iter().zip(positions.iter()) { let advance = pos.x_advance as f32 * k; glyphs.push(ShapedGlyph { id: info.glyph_id as u16, advance, x_offset: pos.x_offset as f32 * k, y_offset: pos.y_offset as f32 * k, }); width += advance; } ShapedText { glyphs, width } } pub fn space_width(&self, px: f32) -> f32 { self.shape("\u{00a0}", px).width } /// Avanzamento con direzione (per misurare parole RTL). pub fn advance_dir(&self, text: &str, px: f32, rtl: bool) -> f32 { self.shape_dir(text, px, rtl).width } /// Larghezza di un testo su una riga. pub fn advance(&self, text: &str, px: f32) -> f32 { self.shape(text, px).width } /// Disegna glifi già posizionati. /// /// `size_css` è la dimensione con cui è stato fatto lo shaping (px CSS) e /// `px` quella del dispositivo: gli avanzamenti vanno riscalati, altrimenti /// a zoom > 1 i glifi crescono ma la penna avanza come a zoom 1 e le lettere /// si sovrappongono. #[allow(clippy::too_many_arguments)] pub fn draw_shaped( &self, buf: &mut [u8], width: u32, height: u32, x: f32, baseline: f32, shaped: &ShapedText, size_css: f32, px: f32, color: Color, weight: u16, italic: bool, ) { self.draw_shaped_in( buf, width, height, x, baseline, shaped, size_css, px, color, weight, italic, None, ); } /// Come `draw_shaped`, ma con un ritaglio orizzontale: i glifi fuori /// dall'intervallo `clip` (in pixel del dispositivo) non vengono disegnati. /// Serve ai campi di testo, dove il contenuto non deve uscire dal riquadro. #[allow(clippy::too_many_arguments)] pub fn draw_shaped_in( &self, buf: &mut [u8], width: u32, height: u32, x: f32, baseline: f32, shaped: &ShapedText, size_css: f32, px: f32, color: Color, weight: u16, italic: bool, clip: Option<(f32, f32)>, ) { const INV255: f32 = 1.0 / 255.0; let alpha = color.a as f32 * INV255; let (cr, cg, cb) = (color.r as f32, color.g as f32, color.b as f32); // fattore CSS -> dispositivo: shaping e raster devono muoversi insieme let k = if size_css > 0.0 { px / size_css } else { 1.0 }; let bold = weight >= 600; // grassetto sintetico: seconda passata spostata di ~1 px dispositivo let smears: &[f32] = if bold { &[0.0, 0.9] } else { &[0.0] }; for &smear in smears { let mut pen = x + smear; for g in &shaped.glyphs { let bmp = self.glyph_bitmap(g.id, px, bold, italic); let mut fuori = false; if let Some((lo, hi)) = clip { let glifo = pen + g.x_offset * k; fuori = glifo + g.advance * k <= lo || glifo >= hi; } if fuori { pen += g.advance * k; continue; } let dx = (pen + g.x_offset * k).round() as i32 + bmp.left; let dy = (baseline - g.y_offset * k).round() as i32 + bmp.top; pen += g.advance * k; if dx < 0 || dy < 0 { continue; } let (dx, dy) = (dx as u32, dy as u32); if dx + bmp.w > width || dy + bmp.h > height { continue; } for gy in 0..bmp.h { let row = ((dy + gy) * width + dx) as usize * 4; let cov_row = (gy * bmp.w) as usize; for gx in 0..bmp.w { let cov = bmp.coverage[cov_row + gx as usize]; if cov == 0 { continue; } let a = cov as f32 * INV255 * alpha; let ia = 1.0 - a; let i = row + gx as usize * 4; buf[i] = (cr * a + buf[i] as f32 * ia) as u8; buf[i + 1] = (cg * a + buf[i + 1] as f32 * ia) as u8; buf[i + 2] = (cb * a + buf[i + 2] as f32 * ia) as u8; } } } } } fn glyph_bitmap(&self, id: u16, px: f32, bold: bool, italic: bool) -> Rc { let size = quantize(px); let key = (self.hash, id, (size * 2.0) as u32, bold, italic); if let Some(b) = GLYPH_CACHE.with(|c| c.borrow().get(&key).cloned()) { return b; } let bitmap = Rc::new(self.rasterize(id, size, bold, italic)); GLYPH_CACHE.with(|c| c.borrow_mut().insert(key, Rc::clone(&bitmap))); bitmap } fn rasterize(&self, id: u16, size: f32, bold: bool, italic: bool) -> GlyphBitmap { // grassetto sintetico: seconda passata a +0,6 px disegnata sopra let smear = if bold { 1 } else { 0 }; let glyph = ab_glyph::Glyph { id: ab_glyph::GlyphId(id), scale: PxScale::from(size), position: ab_glyph::point(0.0, 0.0), }; let Some(outline) = self.font.outline_glyph(glyph) else { return GlyphBitmap { left: 0, top: 0, w: 0, h: 0, coverage: Vec::new(), }; }; let bounds = outline.px_bounds(); let w = (bounds.max.x.ceil() - bounds.min.x.floor()) as i32 + smear; let h = (bounds.max.y.ceil() - bounds.min.y.floor()) as i32; if w <= 0 || h <= 0 { return GlyphBitmap { left: 0, top: 0, w: 0, h: 0, coverage: Vec::new(), }; } let left = bounds.min.x.floor() as i32; let top = bounds.min.y.floor() as i32; let mut coverage = vec![0u8; (w * h) as usize]; outline.draw(|gx, gy, cov| { let gx = gx as i32 + smear; let gy = gy as i32; if gx < 0 || gy < 0 || gx >= w || gy >= h { return; } let idx = (gy * w + gx) as usize; let v = (cov * 255.0).round().clamp(0.0, 255.0) as u8; if v > coverage[idx] { coverage[idx] = v; } }); let mut bitmap = GlyphBitmap { left, top, w: w as u32, h: h as u32, coverage, }; if italic { bitmap = inclina(bitmap); } bitmap } } /// Corsivo sintetico: inclina la mappa di copertura di circa 14°, come fanno i /// programmi di impaginazione quando la famiglia non ha una faccia inclinata. /// Le righe in alto si spostano a destra, quelle in basso restano ferme. fn inclina(bitmap: GlyphBitmap) -> GlyphBitmap { const PENDENZA: f32 = 0.25; let h = bitmap.h as usize; let w = bitmap.w as usize; if h == 0 || w == 0 { return bitmap; } let scarto = (PENDENZA * h as f32).ceil() as usize; let nuova_w = w + scarto; let mut copertura = vec![0u8; nuova_w * h]; for y in 0..h { // y conta dall'alto: il massimo spostamento è in cima let offset = scarto * (h - 1 - y) / (h - 1).max(1); for x in 0..w { let v = bitmap.coverage[y * w + x]; if v != 0 { copertura[y * nuova_w + x + offset] = v; } } } GlyphBitmap { left: bitmap.left, top: bitmap.top, w: nuova_w as u32, h: bitmap.h, coverage: copertura, } } /// `@font-face`: una famiglia dichiarata dal foglio e il file da caricare. #[derive(Clone, Debug, PartialEq)] pub struct FontFaceSpec { pub family: String, pub src: String, } fn normalize_family(name: &str) -> String { name.trim() .trim_matches('"') .trim_matches('\'') .to_ascii_lowercase() } /// Font disponibili per un documento: quello predefinito più le facce `@font-face` /// caricate dal disco. Le facce che non si caricano non bloccano il rendering: /// si annotano e si ricade sul predefinito. pub struct Fonts { default: Rc, faces: HashMap>, } impl Fonts { pub fn new( default: FontHolder, base_dir: &Path, specs: &[FontFaceSpec], risorse: Option<&crate::resource::Risorse>, ) -> (Fonts, Vec) { let mut faces: HashMap> = HashMap::new(); let mut errors = Vec::new(); for spec in specs { // `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 caricato { Ok(f) => { faces.insert(normalize_family(&spec.family), Rc::new(f)); } Err(e) => errors.push(format!( "@font-face '{}' ({}): {}", spec.family, path.display(), e )), } } ( Fonts { default: Rc::new(default), faces, }, errors, ) } pub fn default_font(&self) -> Rc { Rc::clone(&self.default) } pub fn resolve(&self, family: Option<&str>) -> Rc { match family { Some(f) => self .faces .get(&normalize_family(f)) .cloned() .unwrap_or_else(|| Rc::clone(&self.default)), None => Rc::clone(&self.default), } } pub fn face_count(&self) -> usize { self.faces.len() } } #[cfg(test)] mod tests { use super::*; fn font() -> Option { for p in [ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf", ] { if Path::new(p).exists() { return FontHolder::load(Path::new(p)).ok(); } } None } #[test] #[ignore] fn banco_shaping() { let Some(f) = font() else { return }; let t = std::time::Instant::now(); let n = 2000; for _ in 0..n { let _ = f.shape("parola", 16.0); } let per = t.elapsed().as_secs_f64() * 1e6 / n as f64; println!("shaping: {:.1} us per parola", per); } #[test] fn shaping_produce_glifi_e_larghezza() { let Some(f) = font() else { return }; let s = f.shape("Avviso", 20.0); assert!(!s.glyphs.is_empty()); assert!(s.width > 20.0 && s.width < 120.0, "larghezza {}", s.width); let sp = f.space_width(20.0); assert!(sp > 3.0 && sp < 20.0, "spazio {}", sp); } #[test] fn i_glifi_vengono_messi_in_cache() { let Some(f) = font() else { return }; let len = || GLYPH_CACHE.with(|c| c.borrow().len()); let before = len(); let _ = f.glyph_bitmap(42, 33.0, false, false); let _ = f.glyph_bitmap(42, 33.0, false, false); assert_eq!(len(), before + 1, "stesso glifo e dimensione: una voce"); let _ = f.glyph_bitmap(42, 35.0, false, false); assert_eq!(len(), before + 2); // il corsivo è una voce di cache distinta: glifi diversi, stessa chiave let _ = f.glyph_bitmap(42, 35.0, false, true); assert_eq!(len(), before + 3); } #[test] fn il_disegno_produce_pixel_scuri() { let Some(f) = font() else { return }; let shaped = f.shape("Prova", 20.0); let mut buf = vec![255u8; 200 * 40 * 4]; f.draw_shaped( &mut buf, 200, 40, 4.0, 25.0, &shaped, 20.0, 20.0, Color::BLACK, 400, false, ); let dark = buf.chunks(4).filter(|p| p[0] < 128).count(); assert!(dark > 50, "pixel scuri: {}", dark); // corsivo sintetico: inclinato, quindi l'inchiostro si sposta a destra in // alto e la larghezza cresce rispetto al tondo let mut buf_corsivo = vec![255u8; 200 * 40 * 4]; f.draw_shaped( &mut buf_corsivo, 200, 40, 4.0, 25.0, &shaped, 20.0, 20.0, Color::BLACK, 400, true, ); let dark_corsivo = buf_corsivo.chunks(4).filter(|p| p[0] < 128).count(); assert!(dark_corsivo > 50, "corsivo: pixel scuri {}", dark_corsivo); assert_ne!( buf, buf_corsivo, "il corsivo deve produrre un disegno diverso dal tondo" ); } }