Skip to main content

usvg/text/
mod.rs

1// Copyright 2024 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::sync::Arc;
5
6use fontdb::{Database, ID};
7use svgtypes::FontFamily;
8
9use crate::{Cache, Font, FontStretch, FontStyle, Text};
10
11pub(crate) mod cache;
12pub(crate) mod flatten;
13
14mod colr;
15/// Provides access to the layout of a text node.
16pub mod layout;
17
18/// The ID of a glyph within a font
19#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
20pub struct GlyphId(pub u32);
21
22impl From<GlyphId> for skrifa::raw::types::GlyphId {
23    fn from(value: GlyphId) -> Self {
24        Self::new(value.0)
25    }
26}
27
28/// A shorthand for [FontResolver]'s font selection function.
29///
30/// This function receives a font specification (families + a style, weight,
31/// stretch triple) and a font database and should return the ID of the font
32/// that shall be used (if any).
33///
34/// In the basic case, the function will search the existing fonts in the
35/// database to find a good match, e.g. via
36/// [`Database::query`](fontdb::Database::query). This is what the [default
37/// implementation](FontResolver::default_font_selector) does.
38///
39/// Users with more complex requirements can mutate the database to load
40/// additional fonts dynamically. To perform mutation, it is recommended to call
41/// `Arc::make_mut` on the provided database. (This call is not done outside of
42/// the callback to not needless clone an underlying shared database if no
43/// mutation will be performed.) It is important that the database is only
44/// mutated additively. Removing fonts or replacing the entire database will
45/// break things.
46pub type FontSelectionFn<'a> =
47    Box<dyn Fn(&Font, &mut Arc<Database>) -> Option<ID> + Send + Sync + 'a>;
48
49/// A shorthand for [FontResolver]'s fallback selection function.
50///
51/// This function receives a specific character, a list of already used fonts,
52/// and a font database. It should return the ID of a font that
53/// - is not any of the already used fonts
54/// - is as close as possible to the first already used font (if any)
55/// - supports the given character
56///
57/// The function can search the existing database, but can also load additional
58/// fonts dynamically. See the documentation of [`FontSelectionFn`] for more
59/// details.
60pub type FallbackSelectionFn<'a> =
61    Box<dyn Fn(char, &[ID], &mut Arc<Database>) -> Option<ID> + Send + Sync + 'a>;
62
63/// A font resolver for `<text>` elements.
64///
65/// This type can be useful if you want to have an alternative font handling to
66/// the default one. By default, only fonts specified upfront in
67/// [`Options::fontdb`](crate::Options::fontdb) will be used. This type allows
68/// you to load additional fonts on-demand and customize the font selection
69/// process.
70pub struct FontResolver<'a> {
71    /// Resolver function that will be used when selecting a specific font
72    /// for a generic [`Font`] specification.
73    pub select_font: FontSelectionFn<'a>,
74
75    /// Resolver function that will be used when selecting a fallback font for a
76    /// character.
77    pub select_fallback: FallbackSelectionFn<'a>,
78}
79
80impl Default for FontResolver<'_> {
81    fn default() -> Self {
82        FontResolver {
83            select_font: FontResolver::default_font_selector(),
84            select_fallback: FontResolver::default_fallback_selector(),
85        }
86    }
87}
88
89impl FontResolver<'_> {
90    /// Creates a default font selection resolver.
91    ///
92    /// The default implementation forwards to
93    /// [`query`](fontdb::Database::query) on the font database specified in the
94    /// [`Options`](crate::Options).
95    pub fn default_font_selector() -> FontSelectionFn<'static> {
96        Box::new(move |font, fontdb| {
97            let mut name_list = Vec::new();
98            for family in &font.families {
99                name_list.push(match family {
100                    FontFamily::Serif => fontdb::Family::Serif,
101                    FontFamily::SansSerif => fontdb::Family::SansSerif,
102                    FontFamily::Cursive => fontdb::Family::Cursive,
103                    FontFamily::Fantasy => fontdb::Family::Fantasy,
104                    FontFamily::Monospace => fontdb::Family::Monospace,
105                    FontFamily::Named(s) => fontdb::Family::Name(s),
106                });
107            }
108
109            // Use the default font as fallback.
110            name_list.push(fontdb::Family::Serif);
111
112            let stretch = match font.stretch {
113                FontStretch::UltraCondensed => fontdb::Stretch::UltraCondensed,
114                FontStretch::ExtraCondensed => fontdb::Stretch::ExtraCondensed,
115                FontStretch::Condensed => fontdb::Stretch::Condensed,
116                FontStretch::SemiCondensed => fontdb::Stretch::SemiCondensed,
117                FontStretch::Normal => fontdb::Stretch::Normal,
118                FontStretch::SemiExpanded => fontdb::Stretch::SemiExpanded,
119                FontStretch::Expanded => fontdb::Stretch::Expanded,
120                FontStretch::ExtraExpanded => fontdb::Stretch::ExtraExpanded,
121                FontStretch::UltraExpanded => fontdb::Stretch::UltraExpanded,
122            };
123
124            let style = match font.style {
125                FontStyle::Normal => fontdb::Style::Normal,
126                FontStyle::Italic => fontdb::Style::Italic,
127                FontStyle::Oblique => fontdb::Style::Oblique,
128            };
129
130            let query = fontdb::Query {
131                families: &name_list,
132                weight: fontdb::Weight(font.weight),
133                stretch,
134                style,
135            };
136
137            let id = fontdb.query(&query);
138            if id.is_none() {
139                log::warn!(
140                    "No match for '{}' font-family.",
141                    font.families
142                        .iter()
143                        .map(|f| f.to_string())
144                        .collect::<Vec<_>>()
145                        .join(", ")
146                );
147            }
148
149            id
150        })
151    }
152
153    /// Creates a default font fallback selection resolver.
154    ///
155    /// The default implementation searches through the entire `fontdb`
156    /// to find a font that has the correct style and supports the character.
157    pub fn default_fallback_selector() -> FallbackSelectionFn<'static> {
158        Box::new(|c, exclude_fonts, fontdb| {
159            let base_font_id = exclude_fonts[0];
160            let base_face = fontdb.face(base_font_id)?;
161
162            // Iterate over fonts and check if any of them support the specified char.
163            for face in fontdb.faces() {
164                // Ignore fonts, that were used for shaping already.
165                if exclude_fonts.contains(&face.id) {
166                    continue;
167                }
168
169                // Check that the new face has the same style.
170                if base_face.style != face.style
171                    && base_face.weight != face.weight
172                    && base_face.stretch != face.stretch
173                {
174                    continue;
175                }
176
177                if !has_char(fontdb, face.id, c) {
178                    continue;
179                }
180
181                let base_family = base_face
182                    .families
183                    .iter()
184                    .find(|f| f.1 == fontdb::Language::English_UnitedStates)
185                    .unwrap_or(&base_face.families[0]);
186
187                let new_family = face
188                    .families
189                    .iter()
190                    .find(|f| f.1 == fontdb::Language::English_UnitedStates)
191                    .unwrap_or(&face.families[0]);
192
193                log::warn!("Fallback from {} to {}.", base_family.0, new_family.0);
194                return Some(face.id);
195            }
196
197            None
198        })
199    }
200}
201
202impl std::fmt::Debug for FontResolver<'_> {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        f.write_str("FontResolver { .. }")
205    }
206}
207
208/// Convert a text into its paths. This is done in two steps:
209/// 1. We convert the text into glyphs and position them according to the rules specified
210///    in the SVG specification. While doing so, we also calculate the text bbox (which
211///    is not based on the outlines of a glyph, but instead the glyph metrics as well
212///    as decoration spans).
213/// 2. We convert all of the positioned glyphs into outlines.
214pub(crate) fn convert(text: &mut Text, resolver: &FontResolver, cache: &mut Cache) -> Option<()> {
215    let (text_fragments, bbox) = layout::layout_text(text, resolver, &mut cache.fonts)?;
216    text.layouted = text_fragments;
217    text.bounding_box = bbox.to_rect();
218    text.abs_bounding_box = bbox.transform(text.abs_transform)?.to_rect();
219
220    let (group, stroke_bbox) = flatten::flatten(text, &mut cache.fonts)?;
221    text.flattened = Box::new(group);
222    text.stroke_bounding_box = stroke_bbox.to_rect();
223    text.abs_stroke_bounding_box = stroke_bbox.transform(text.abs_transform)?.to_rect();
224
225    Some(())
226}
227
228#[inline(never)]
229fn has_char(fontdb: &Database, id: ID, c: char) -> bool {
230    // Unlike for the main fonts where we use skrifa's owned font abstraction,
231    // here we just call `with_face_data` repeatedly so we don't need to call `to_vec`
232    // for all fallback fonts.
233    // TODO: Cache the charmaps of fallback candidates, building one for every lookup is expensive.
234    fontdb
235        .with_face_data(id, |data, face_index| {
236            let font = skrifa::FontRef::from_index(data, face_index).ok()?;
237            skrifa::charmap::Charmap::new(&font).map(c)
238        })
239        .flatten()
240        .is_some()
241}