Skip to main content

usvg/text/
cache.rs

1// Copyright 2026 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::collections::HashMap;
5use std::sync::Arc;
6
7use fontdb::{Database, ID};
8use skrifa::font::Variation;
9use skrifa::font::glyph::bitmap::{BitmapSource, Pixels};
10use skrifa::font::glyph::outline::{DrawOptions, PathSink};
11use skrifa::raw::TableProvider as _;
12use skrifa::raw::types::{Matrix, NameId};
13use skrifa::{DrawMemory, Tag};
14use svgtypes::Color;
15use tiny_skia_path::{NonZeroRect, Size, Transform};
16use xmlwriter::XmlWriter;
17
18use super::colr::GlyphPainter;
19use super::layout::ResolvedFont;
20use crate::parser::OptionLog;
21use crate::{
22    Font, FontOpticalSizing, FontVariation, GlyphId, Image, ImageKind, ImageRendering, Node,
23    Options, Tree,
24};
25
26pub(crate) struct FontCache {
27    /// This fontdb is initialized from [`Options::fontdb`](crate::Options::fontdb) and then
28    /// populated over the course of conversion.
29    pub(crate) fontdb: Arc<Database>,
30    pub(crate) resolved: HashMap<Font, Arc<ResolvedFont>>,
31    // `None` marks faces that failed to load, so they are not read again.
32    loaded: HashMap<ID, Option<LoadedFont>>,
33}
34
35pub(crate) struct LoadedFont {
36    font: skrifa::Font,
37    instances: HashMap<Vec<FontVariation>, FontInstance>,
38    svg: HashMap<GlyphId, Option<Node>>,
39    raster: HashMap<GlyphId, Option<BitmapImage>>,
40}
41
42pub(crate) struct FontInstance {
43    pub(crate) font: skrifa::Font,
44    pub(crate) plans: Vec<harfrust::ShapePlan>,
45    outlines: HashMap<GlyphId, Option<tiny_skia_path::Path>>,
46    colr: HashMap<GlyphId, Option<Tree>>,
47}
48
49#[derive(Clone)]
50pub(crate) struct BitmapImage {
51    pub(crate) image: Image,
52    pub(crate) x: i16,
53    pub(crate) y: i16,
54    pub(crate) pixels_per_em: u16,
55    pub(crate) bearing_x: f32,
56    pub(crate) bearing_y: f32,
57    pub(crate) is_sbix: bool,
58}
59
60impl FontCache {
61    pub(crate) fn new(fontdb: Arc<Database>) -> Self {
62        Self {
63            fontdb,
64            resolved: HashMap::new(),
65            loaded: HashMap::new(),
66        }
67    }
68
69    pub(crate) fn load(&mut self, id: ID) -> Option<&mut LoadedFont> {
70        let fontdb = &self.fontdb;
71        self.loaded
72            .entry(id)
73            .or_insert_with(|| LoadedFont::new(id, fontdb))
74            .as_mut()
75    }
76
77    pub(crate) fn outline(
78        &mut self,
79        id: ID,
80        glyph: GlyphId,
81        variations: impl IntoIterator<Item = FontVariation>,
82    ) -> Option<tiny_skia_path::Path> {
83        let instance = self.load(id)?.instance(variations);
84        instance
85            .outlines
86            .entry(glyph)
87            .or_insert_with(|| outline(&instance.font, glyph))
88            .clone()
89    }
90
91    pub(crate) fn colr(
92        &mut self,
93        id: ID,
94        glyph: GlyphId,
95        variations: impl IntoIterator<Item = FontVariation>,
96    ) -> Option<Tree> {
97        let loaded = self.load(id)?;
98        if loaded.font.color_glyphs().is_empty() {
99            return None;
100        }
101
102        let instance = loaded.instance(variations);
103        instance
104            .colr
105            .entry(glyph)
106            .or_insert_with(|| colr(&instance.font, glyph))
107            .clone()
108    }
109
110    pub(crate) fn svg(&mut self, id: ID, glyph: GlyphId) -> Option<Node> {
111        let loaded = self.load(id)?;
112        if loaded.font.tables().svg().is_err() {
113            return None;
114        }
115
116        let font = &loaded.font;
117        loaded
118            .svg
119            .entry(glyph)
120            .or_insert_with(|| svg(font, glyph))
121            .clone()
122    }
123
124    pub(crate) fn raster(&mut self, id: ID, glyph: GlyphId) -> Option<BitmapImage> {
125        let loaded = self.load(id)?;
126        if loaded.font.bitmap_strikes().is_empty() {
127            return None;
128        }
129
130        let font = &loaded.font;
131        loaded
132            .raster
133            .entry(glyph)
134            .or_insert_with(|| raster(font, glyph))
135            .clone()
136    }
137}
138
139impl LoadedFont {
140    fn new(id: ID, fontdb: &Database) -> Option<Self> {
141        // Share the font data if it is already in memory, otherwise copy it.
142        let font = match fontdb.face_source(id)? {
143            (fontdb::Source::Binary(data), face_index) => skrifa::Font::new(data, face_index),
144            #[cfg(feature = "memmap-fonts")]
145            (fontdb::Source::SharedFile(_, data), face_index) => {
146                skrifa::Font::new(data, face_index)
147            }
148            #[allow(unreachable_patterns)]
149            _ => fontdb.with_face_data(id, |data, face_index| {
150                skrifa::Font::new(data.to_vec(), face_index)
151            })?,
152        }?;
153
154        Some(Self {
155            font,
156            instances: HashMap::new(),
157            svg: HashMap::new(),
158            raster: HashMap::new(),
159        })
160    }
161
162    pub(crate) fn instance(
163        &mut self,
164        variations: impl IntoIterator<Item = FontVariation>,
165    ) -> &mut FontInstance {
166        let key: Vec<FontVariation> = self
167            .font
168            .axes()
169            .filter(variations.into_iter().map(to_skrifa_variation))
170            .map(|v| FontVariation::new(v.tag.to_be_bytes(), v.value))
171            .collect();
172
173        let font = &self.font;
174        self.instances.entry(key).or_insert_with_key(|key| {
175            let font = if key.is_empty() {
176                font.clone()
177            } else {
178                font.instance_builder()
179                    .variations(key.iter().copied().map(to_skrifa_variation))
180                    .build()
181            };
182
183            FontInstance {
184                font,
185                plans: Vec::new(),
186                outlines: HashMap::new(),
187                colr: HashMap::new(),
188            }
189        })
190    }
191}
192
193fn to_skrifa_variation(v: FontVariation) -> Variation {
194    Variation::new(Tag::from_be_bytes(v.tag), v.value)
195}
196
197/// Adds the `opsz` value that `font-optical-sizing: auto` implies, like browsers do.
198///
199/// It comes first, so that an `opsz` in `variations` overrides it.
200pub(crate) fn with_optical_sizing(
201    variations: &[FontVariation],
202    optical_sizing: FontOpticalSizing,
203    font_size: f32,
204) -> impl Iterator<Item = FontVariation> + Clone + '_ {
205    let auto_opsz = (optical_sizing == FontOpticalSizing::Auto)
206        .then(|| FontVariation::new(*b"opsz", font_size));
207    auto_opsz.into_iter().chain(variations.iter().copied())
208}
209
210#[derive(Default)]
211struct PathBuilder {
212    builder: tiny_skia_path::PathBuilder,
213}
214
215impl PathSink for PathBuilder {
216    fn move_to(&mut self, x: f32, y: f32) {
217        self.builder.move_to(x, y);
218    }
219
220    fn line_to(&mut self, x: f32, y: f32) {
221        self.builder.line_to(x, y);
222    }
223
224    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
225        self.builder.quad_to(cx0, cy0, x, y);
226    }
227
228    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
229        self.builder.cubic_to(cx0, cy0, cx1, cy1, x, y);
230    }
231
232    fn close(&mut self) {
233        self.builder.close();
234    }
235}
236
237#[inline(never)]
238fn outline(font: &skrifa::Font, glyph_id: GlyphId) -> Option<tiny_skia_path::Path> {
239    let outline = font.outline_glyphs().get(glyph_id.into())?;
240
241    let mut builder = PathBuilder::default();
242    outline
243        .draw(&DrawOptions::default(), DrawMemory::Scratch, &mut builder)
244        .ok()?;
245
246    builder.builder.finish()
247}
248
249fn raster(font: &skrifa::Font, glyph_id: GlyphId) -> Option<BitmapImage> {
250    // No size selects the largest image available.
251    let image = font.bitmap_strikes().select_bitmap(glyph_id.into(), None)?;
252
253    // Follows vello:
254    // https://github.com/linebender/vello/blob/717a485dabd16249fae739a755a3da3ea4a8f69a/glifo/src/glyph.rs#L1322-L1367
255    let (bearing_x, bearing_y) = if is_apple_color_emoji(font) {
256        (0.0, -(font.metrics().units_per_em as f32) / 8.0)
257    } else {
258        (image.x_bearing() as f32, image.y_bearing() as f32)
259    };
260
261    match image.pixels() {
262        Pixels::Png(data) => Some(BitmapImage {
263            image: Image {
264                id: String::new(),
265                visible: true,
266                size: Size::from_wh(image.width() as f32, image.height() as f32)?,
267                rendering_mode: ImageRendering::OptimizeQuality,
268                kind: ImageKind::PNG(Arc::new(data.to_vec())),
269                abs_transform: Transform::default(),
270                abs_bounding_box: NonZeroRect::from_xywh(
271                    0.0,
272                    0.0,
273                    image.width() as f32,
274                    image.height() as f32,
275                )?,
276            },
277            x: image.inner_x_bearing() as i16,
278            y: image.inner_y_bearing() as i16,
279            pixels_per_em: image.ppem_x(),
280            bearing_x,
281            bearing_y,
282            is_sbix: image.source() == BitmapSource::Sbix,
283        }),
284        // TODO: implement other bitmap formats
285        Pixels::Bgra(_) | Pixels::Mask(_) => None,
286    }
287}
288
289fn is_apple_color_emoji(font: &skrifa::Font) -> bool {
290    font.names()
291        .get(NameId::POSTSCRIPT_NAME)
292        .is_some_and(|name| {
293            name.iter()
294                .any(|name| name.name().chars().eq("AppleColorEmoji".chars()))
295        })
296}
297
298fn svg(font: &skrifa::Font, glyph_id: GlyphId) -> Option<Node> {
299    // SEE: https://docs.rs/read-fonts/latest/read_fonts/tables/svg/type.Svg.html
300
301    // TODO: Technically not 100% accurate because the SVG format in a OTF font
302    // is actually a subset/superset of a normal SVG, but it seems to work fine
303    // for Twitter Color Emoji, so might as well use what we already have.
304
305    // TODO: Glyph records can contain the data for multiple glyphs. We should
306    // add a cache so we don't need to reparse the data every time.
307    let svg_table = font.tables().svg().ok()?;
308    let image_data = svg_table.glyph_data(glyph_id.into())?;
309    let tree = Tree::from_data(image_data, &Options::default()).ok()?;
310
311    // Twitter Color Emoji seems to always have one SVG record per glyph,
312    // while Noto Color Emoji sometimes contains multiple ones. It's kind of hacky,
313    // but the best we have for now.
314    let document_list = svg_table.svg_document_list().ok()?;
315    let doc_record = document_list.document_records().iter().find(|r| {
316        (r.start_glyph_id.get().to_u32()..=r.end_glyph_id.get().to_u32()).contains(&glyph_id.0)
317    })?;
318    let node = if doc_record.start_glyph_id == doc_record.end_glyph_id {
319        Node::Group(Box::new(tree.root))
320    } else {
321        tree.node_by_id(&format!("glyph{}", glyph_id.0))
322            .log_none(|| {
323                log::warn!("Failed to find SVG glyph node for glyph {}", glyph_id.0);
324            })
325            .cloned()?
326    };
327
328    Some(node)
329}
330
331fn colr(font: &skrifa::Font, glyph_id: GlyphId) -> Option<Tree> {
332    let color_glyph = font.color_glyphs().get(glyph_id.into())?;
333
334    let mut svg = XmlWriter::new(xmlwriter::Options::default());
335
336    svg.start_element("svg");
337    svg.write_attribute("xmlns", "http://www.w3.org/2000/svg");
338    svg.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
339
340    let mut path_buf = String::with_capacity(256);
341
342    svg.start_element("g");
343
344    let mut glyph_painter = GlyphPainter {
345        font,
346        svg: &mut svg,
347        path_buf: &mut path_buf,
348        gradient_index: 1,
349        clip_path_index: 1,
350        foreground_color: Color::new_rgba(0, 0, 0, 255),
351        transform: Matrix::default(),
352        outline_transform: Matrix::default(),
353        transforms_stack: vec![Matrix::default()],
354        clip_stack: Vec::new(),
355    };
356
357    color_glyph.paint(&mut glyph_painter).ok()?;
358    svg.end_element();
359
360    Tree::from_data(svg.end_document().as_bytes(), &Options::default()).ok()
361}