Skip to main content

aylis_core/
fonts.rs

1//! Fontes de arquivo (TTF, OTF, TTC) usadas pelo app além das do sistema: as do projeto
2//! (`assets/fonts/`) ou registradas por código. O registro é do processo inteiro: os
3//! renderizadores (Skia, Direct2D, navegador) conferem a [`generation`] e carregam as novas.
4//!
5//! ```ignore
6//! let family = aylis_core::fonts::register(std::fs::read("Inter.ttf")?);   // Some("Inter")
7//! // depois: FontSpec::new("Inter", 14.0)
8//! ```
9
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::{Arc, Mutex};
12
13/// Uma fonte registrada.
14#[derive(Clone, Debug)]
15pub struct FontFile {
16    /// Família (lida do próprio arquivo).
17    pub family: String,
18    pub data: Arc<Vec<u8>>,
19}
20
21static FONTS: Mutex<Vec<FontFile>> = Mutex::new(Vec::new());
22static GENERATION: AtomicU64 = AtomicU64::new(0);
23
24/// Registra uma fonte (o arquivo inteiro). Devolve a família, ou `None` se não for uma
25/// fonte. Registrar o mesmo arquivo de novo não duplica.
26pub fn register(data: Vec<u8>) -> Option<String> {
27    let family = family_name(&data)?;
28    let mut fonts = FONTS.lock().ok()?;
29    if fonts.iter().any(|f| f.family == family && f.data.len() == data.len() && *f.data == data) {
30        return Some(family);
31    }
32    fonts.push(FontFile { family: family.clone(), data: Arc::new(data) });
33    GENERATION.fetch_add(1, Ordering::SeqCst);
34    Some(family)
35}
36
37/// As fontes registradas.
38pub fn registered() -> Vec<FontFile> {
39    FONTS.lock().map(|f| f.clone()).unwrap_or_default()
40}
41
42/// As famílias registradas, sem repetir.
43pub fn families() -> Vec<String> {
44    let mut list: Vec<String> = registered().into_iter().map(|f| f.family).collect();
45    list.sort();
46    list.dedup();
47    list
48}
49
50/// Muda a cada fonte nova: os renderizadores recarregam quando ela muda.
51pub fn generation() -> u64 {
52    GENERATION.load(Ordering::SeqCst)
53}
54
55fn u16_at(d: &[u8], i: usize) -> Option<u16> {
56    Some(u16::from_be_bytes([*d.get(i)?, *d.get(i + 1)?]))
57}
58
59fn u32_at(d: &[u8], i: usize) -> Option<u32> {
60    Some(u32::from_be_bytes([*d.get(i)?, *d.get(i + 1)?, *d.get(i + 2)?, *d.get(i + 3)?]))
61}
62
63/// A família de um arquivo de fonte (tabela `name`: a família "tipográfica" se houver,
64/// senão a comum). Num TTC, a da primeira fonte.
65pub fn family_name(data: &[u8]) -> Option<String> {
66    let mut offset = 0usize;
67    if data.get(0..4) == Some(b"ttcf") {
68        offset = u32_at(data, 12)? as usize;
69    }
70    let tag = u32_at(data, offset)?;
71    // TrueType (0x00010000, "true") ou OpenType com CFF ("OTTO").
72    if tag != 0x0001_0000 && tag != u32::from_be_bytes(*b"OTTO") && tag != u32::from_be_bytes(*b"true") {
73        return None;
74    }
75    let tables = u16_at(data, offset + 4)? as usize;
76    let name_table = (0..tables).find_map(|i| {
77        let rec = offset + 12 + i * 16;
78        (data.get(rec..rec + 4)? == b"name").then(|| u32_at(data, rec + 8)).flatten()
79    })? as usize;
80    let count = u16_at(data, name_table + 2)? as usize;
81    let strings = name_table + u16_at(data, name_table + 4)? as usize;
82    let mut best: Option<(u8, String)> = None;
83    for i in 0..count {
84        let rec = name_table + 6 + i * 12;
85        let (platform, encoding, language, name_id) = (u16_at(data, rec)?, u16_at(data, rec + 2)?, u16_at(data, rec + 4)?, u16_at(data, rec + 6)?);
86        if name_id != 1 && name_id != 16 {
87            continue;
88        }
89        let (len, off) = (u16_at(data, rec + 8)? as usize, u16_at(data, rec + 10)? as usize);
90        let raw = data.get(strings + off..strings + off + len)?;
91        let text = match (platform, encoding) {
92            (3, 1) | (3, 10) | (0, _) => {
93                let units: Vec<u16> = raw.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
94                String::from_utf16_lossy(&units)
95            }
96            (1, 0) => raw.iter().map(|&b| b as char).collect(),
97            _ => continue,
98        };
99        // Prioridade: típográfica (16) em inglês do Windows, depois a comum (1).
100        let english = language == 0x0409 || platform != 3;
101        let score = (if name_id == 16 { 2 } else { 0 }) + u8::from(english) + u8::from(platform == 3);
102        if best.as_ref().is_none_or(|(s, _)| score > *s) && !text.trim().is_empty() {
103            best = Some((score, text.trim().to_string()));
104        }
105    }
106    best.map(|(_, t)| t)
107}