Skip to main content

script/event_loop/
svg_font.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::sync::{Arc, Mutex};
6
7use app_units::Au;
8use fonts::{
9    FallbackFontSelectionOptions, FontContext, FontDescriptor, FontFamilyDescriptor,
10    FontSearchScope, fallback_font_families,
11};
12use icu_locale_core::subtags::Language;
13use net_traits::image_cache::FontResolver;
14use resvg::usvg::{Font, FontFamily, FontStretch, FontStyle, fontdb};
15use rustc_hash::FxHashMap;
16use style::computed_values::font_optical_sizing::T as FontOpticalSizing;
17use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps;
18use style::values::computed::font::{
19    FamilyName, FontFamilyNameSyntax, GenericFontFamily, SingleFontFamily,
20};
21use style::values::computed::{
22    FontStyle as ServoFontStyle, FontSynthesis, FontWeight, FontWidth as ServoFontWidth,
23};
24use webrender_api::FontVariation;
25
26/// Used to dynamically query fonts used in SVGs and insert them into the fontDB used when rasterizing.
27#[derive(MallocSizeOf)]
28pub struct SvgFontResolver {
29    /// Cache for Font to ID
30    font_id_cache: Mutex<FxHashMap<Font, fontdb::ID>>,
31    fallback_id_cache: Mutex<FxHashMap<char, Vec<fontdb::ID>>>,
32    #[conditional_malloc_size_of]
33    context: Arc<FontContext>,
34}
35
36impl SvgFontResolver {
37    pub(crate) fn new(context: Arc<FontContext>) -> Self {
38        Self {
39            font_id_cache: Mutex::new(FxHashMap::default()),
40            fallback_id_cache: Mutex::new(FxHashMap::default()),
41            context,
42        }
43    }
44
45    /// Insert the font into the database in [`SvgFontResolver`] and into the cache.
46    fn insert_into_database(
47        &self,
48        font: &Font,
49        database: &mut Arc<fontdb::Database>,
50    ) -> Option<fontdb::ID> {
51        let font_descriptor = font_to_fontdescriptor(font);
52
53        for family in font.families() {
54            let family_descriptor = FontFamilyDescriptor::new(
55                fontfamily_to_singlefontfamily(family),
56                FontSearchScope::Any,
57            );
58
59            let Some(font_template) = self
60                .context
61                .matching_templates(&font_descriptor, &family_descriptor)
62                .into_iter()
63                .next()
64            else {
65                log::debug!(
66                    "Cannot find matching font_template from font {font:?}, font-descriptor {font_descriptor:?}, family_descriptor: {family_descriptor:?} for this family {family:?}"
67                );
68                continue;
69            };
70
71            let Some(font_ref) = self.context.font(font_template, &font_descriptor) else {
72                continue;
73            };
74
75            let Ok(data_and_index) = font_ref.font_data_and_index() else {
76                continue;
77            };
78            let ids = Arc::make_mut(database).load_font_source(fontdb::Source::Binary(Arc::new(
79                data_and_index.data.clone(),
80            )));
81
82            if let Some(id) = ids.get(data_and_index.index as usize).copied() {
83                self.font_id_cache.lock().unwrap().insert(font.clone(), id);
84                return Some(id);
85            }
86        }
87
88        None
89    }
90}
91
92fn font_to_fontdescriptor(font: &Font) -> FontDescriptor {
93    let style = match font.style() {
94        FontStyle::Normal => ServoFontStyle::normal(),
95        FontStyle::Italic => ServoFontStyle::ITALIC,
96        FontStyle::Oblique => ServoFontStyle::OBLIQUE,
97    };
98
99    let width = match font.stretch() {
100        FontStretch::UltraCondensed => ServoFontWidth::ULTRA_CONDENSED,
101        FontStretch::ExtraCondensed => ServoFontWidth::EXTRA_CONDENSED,
102        FontStretch::Condensed => ServoFontWidth::CONDENSED,
103        FontStretch::SemiCondensed => ServoFontWidth::SEMI_CONDENSED,
104        FontStretch::Normal => ServoFontWidth::NORMAL,
105        FontStretch::SemiExpanded => ServoFontWidth::SEMI_EXPANDED,
106        FontStretch::Expanded => ServoFontWidth::EXPANDED,
107        FontStretch::ExtraExpanded => ServoFontWidth::EXTRA_EXPANDED,
108        FontStretch::UltraExpanded => ServoFontWidth::ULTRA_EXPANDED,
109    };
110
111    let variation_settings = font
112        .variations()
113        .iter()
114        .map(|variation| FontVariation {
115            tag: u32::from_be_bytes(variation.tag),
116            value: variation.value,
117        })
118        .collect();
119
120    FontDescriptor {
121        weight: FontWeight::from_float(font.weight() as f32),
122        width,
123        style,
124        variant: FontVariantCaps::Normal,
125        pt_size: Au::from_px(16),
126        variation_settings,
127        synthesis_weight: FontSynthesis::Auto,
128        optical_sizing: FontOpticalSizing::Auto,
129    }
130}
131
132fn fallback_descriptor() -> FontDescriptor {
133    FontDescriptor {
134        weight: FontWeight::normal(),
135        width: ServoFontWidth::hundred(),
136        style: ServoFontStyle::normal(),
137        variant: FontVariantCaps::Normal,
138        pt_size: Au::from_px(16),
139        variation_settings: vec![],
140        synthesis_weight: FontSynthesis::Auto,
141        optical_sizing: FontOpticalSizing::Auto,
142    }
143}
144
145fn fontfamily_to_singlefontfamily(family: &FontFamily) -> SingleFontFamily {
146    match family {
147        FontFamily::Serif => SingleFontFamily::Generic(GenericFontFamily::Serif),
148        FontFamily::SansSerif => SingleFontFamily::Generic(GenericFontFamily::SansSerif),
149        FontFamily::Cursive => SingleFontFamily::Generic(GenericFontFamily::Cursive),
150        FontFamily::Fantasy => SingleFontFamily::Generic(GenericFontFamily::Fantasy),
151        FontFamily::Monospace => SingleFontFamily::Generic(GenericFontFamily::Monospace),
152        FontFamily::Named(name) => SingleFontFamily::FamilyName(FamilyName {
153            name: name.as_str().into(),
154            syntax: FontFamilyNameSyntax::Quoted,
155        }),
156    }
157}
158
159impl FontResolver for SvgFontResolver {
160    fn resolve(&self, font: &Font, database: &mut Arc<fontdb::Database>) -> Option<fontdb::ID> {
161        {
162            let id_cache = self.font_id_cache.lock().unwrap();
163            if let Some(font_id) = id_cache.get(font) {
164                return Some(*font_id);
165            }
166        }
167        self.insert_into_database(font, database)
168    }
169
170    fn resolve_fallback(
171        &self,
172        character: char,
173        excluded: &[fontdb::ID],
174        database: &mut Arc<fontdb::Database>,
175    ) -> Option<fontdb::ID> {
176        {
177            let id_cache = self.fallback_id_cache.lock().unwrap();
178            if let Some(font_id) = id_cache
179                .get(&character)
180                .and_then(|font_ids| font_ids.iter().find(|font_id| !excluded.contains(font_id)))
181            {
182                return Some(*font_id);
183            }
184        }
185        let fallback_options =
186            FallbackFontSelectionOptions::new(character, None, Language::UNKNOWN);
187
188        for family in fallback_font_families(fallback_options) {
189            let family = FontFamilyDescriptor::new(
190                SingleFontFamily::FamilyName(FamilyName {
191                    name: family.into(),
192                    syntax: FontFamilyNameSyntax::Quoted,
193                }),
194                FontSearchScope::Any,
195            );
196            let fallback_descriptor = fallback_descriptor();
197
198            let font_templates = self
199                .context
200                .matching_templates(&fallback_descriptor, &family);
201
202            for font_template in font_templates {
203                let Some(font_ref) = self.context.font(font_template, &fallback_descriptor) else {
204                    continue;
205                };
206                if !font_ref.has_glyph_for(character) {
207                    continue;
208                }
209
210                let Ok(data_and_index) = font_ref.font_data_and_index() else {
211                    continue;
212                };
213
214                let ids = Arc::make_mut(database).load_font_source(fontdb::Source::Binary(
215                    Arc::new(data_and_index.data.clone()),
216                ));
217
218                let Some(id) = ids.get(data_and_index.index as usize) else {
219                    continue;
220                };
221
222                if excluded.contains(id) {
223                    continue;
224                }
225
226                self.fallback_id_cache
227                    .lock()
228                    .unwrap()
229                    .entry(character)
230                    .or_default()
231                    .push(*id);
232                return Some(*id);
233            }
234        }
235        None
236    }
237}