Mosaic: motore di rendering proprio, gusci desktop e Sailfish
Primo commit del progetto: motore Rust con parser HTML, cascata CSS, layout, raster CPU, formulari, bidi, flex, tabelle, JavaScript (Boa) con eventi e costruzione di nodi, rete HTTP/HTTPS con TLS, sotto-risorse, invio dei formulari; guscio grafico per Sailfish (QML/Silica) e per desktop (minifb, distribuito come AppImage), con 11 documenti di specifica e 91 casi di reftest.
This commit is contained in:
commit
577682ae22
173 files changed
+23685
No files matched your search
@@ -0,0 +1,462 @@
|
||||
//! 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<ShapedGlyph>,
|
||||
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<u8>,
|
||||
}
|
||||
|
||||
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<HashMap<(u64, u16, u32, bool), Rc<GlyphBitmap>>> =
|
||||
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<Self, String> {
|
||||
let data = std::fs::read(path).map_err(|e| e.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: path.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 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.
|
||||
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,
|
||||
) {
|
||||
self.draw_shaped_in(
|
||||
buf, width, height, x, baseline, shaped, size_css, px, color, weight, 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,
|
||||
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);
|
||||
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) -> Rc<GlyphBitmap> {
|
||||
let size = quantize(px);
|
||||
let key = (self.hash, id, (size * 2.0) as u32, bold);
|
||||
if let Some(b) = GLYPH_CACHE.with(|c| c.borrow().get(&key).cloned()) {
|
||||
return b;
|
||||
}
|
||||
let bitmap = Rc::new(self.rasterize(id, size, bold));
|
||||
GLYPH_CACHE.with(|c| c.borrow_mut().insert(key, Rc::clone(&bitmap)));
|
||||
bitmap
|
||||
}
|
||||
|
||||
fn rasterize(&self, id: u16, size: f32, bold: 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;
|
||||
}
|
||||
});
|
||||
GlyphBitmap {
|
||||
left,
|
||||
top,
|
||||
w: w as u32,
|
||||
h: h as u32,
|
||||
coverage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `@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<FontHolder>,
|
||||
faces: HashMap<String, Rc<FontHolder>>,
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
pub fn new(
|
||||
default: FontHolder,
|
||||
base_dir: &Path,
|
||||
specs: &[FontFaceSpec],
|
||||
) -> (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)
|
||||
};
|
||||
match FontHolder::load(&path) {
|
||||
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<FontHolder> {
|
||||
Rc::clone(&self.default)
|
||||
}
|
||||
|
||||
pub fn resolve(&self, family: Option<&str>) -> Rc<FontHolder> {
|
||||
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<FontHolder> {
|
||||
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);
|
||||
let _ = f.glyph_bitmap(42, 33.0, false);
|
||||
assert_eq!(len(), before + 1, "stesso glifo e dimensione: una voce");
|
||||
let _ = f.glyph_bitmap(42, 35.0, false);
|
||||
assert_eq!(len(), before + 2);
|
||||
}
|
||||
|
||||
#[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,
|
||||
);
|
||||
let dark = buf.chunks(4).filter(|p| p[0] < 128).count();
|
||||
assert!(dark > 50, "pixel scuri: {}", dark);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user