valo_text/font.rs
1use std::collections::HashMap;
2use std::sync::Arc;
3
4use skrifa::metrics::Metrics;
5use skrifa::prelude::Size;
6use skrifa::MetadataProvider;
7
8use crate::face_cache;
9
10/// `FontId` identifies a registered font within a [`FaceSet`] or [`FontCollection`].
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub struct FontId(
13 /// The zero-based registration index.
14 pub u32,
15);
16
17/// `FontData` is shared, immutable font-file storage supplied by the host.
18///
19/// It may wrap owned bytes or memory-mapped data and must remain readable for
20/// the lifetime of every [`Font`] created from it.
21pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;
22
23/// `FontAttrs` describes a face's position within a font family.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct FontAttrs {
26 /// `weight` is the CSS font weight, conventionally from 100 to 900.
27 pub weight: u16,
28 /// `italic` indicates whether the face uses an italic or oblique style.
29 pub italic: bool,
30 /// `stretch` is the CSS font-width percentage, where 100 is normal.
31 pub stretch: f32,
32}
33
34/// `NORMAL_STRETCH` is the CSS normal font-width percentage.
35pub const NORMAL_STRETCH: f32 = 100.0;
36
37impl Default for FontAttrs {
38 fn default() -> Self {
39 Self {
40 weight: 400,
41 italic: false,
42 stretch: NORMAL_STRETCH,
43 }
44 }
45}
46
47/// The instance-independent half of a parsed face: bytes, coverage, and
48/// the compiled shaping caches are IDENTICAL across a variable font's
49/// named instances, so every instance shares one of these (DirectWrite's
50/// model: instances enumerate separately, file state is shared).
51struct SharedFace {
52 data: FontData,
53 /// Which face inside `data` — TrueType collections (.ttc) pack
54 /// several; 0 for single-face files.
55 face_index: u32,
56 /// The face's id in the process that renders its glyphs, which every
57 /// instance answers alike; None when glyphs render from `data`.
58 remote_id: Option<u64>,
59 /// cmap materialized ONCE — fallback resolution is per-character and
60 /// must never re-parse the font (Skia caches per-typeface the same way).
61 charmap: HashMap<u32, u32>,
62 /// HarfBuzz's compiled shaping caches (GSUB/GDEF/cmap), built once —
63 /// the FontRef itself is cheap to reconstruct per shape (Skia's analog:
64 /// HB faces cached per typeface).
65 shaper_data: harfrust::ShaperData,
66}
67
68/// `FontUid` is the process-unique identity of one font instance.
69///
70/// Glyph caches may use it as a stable key because equal identifiers imply
71/// equal outlines and variation coordinates.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
73pub struct FontUid(
74 /// The process-unique numeric identity.
75 pub u64,
76);
77
78impl FontUid {
79 fn next() -> FontUid {
80 use std::sync::atomic::{AtomicU64, Ordering};
81 static COUNTER: AtomicU64 = AtomicU64::new(1);
82 FontUid(COUNTER.fetch_add(1, Ordering::Relaxed))
83 }
84}
85
86/// `Font` is one parsed font face or named variable-font instance.
87///
88/// It retains immutable source bytes and exposes the names, attributes,
89/// coverage, and metrics needed for shaping and rendering.
90///
91/// A clone shares the parsed file and keeps the identifier: it is the same
92/// face at the same instance, as Skia shares an `SkTypeface` by reference.
93#[derive(Clone)]
94pub struct Font {
95 uid: FontUid,
96 shared: Arc<SharedFace>,
97 /// User-space variation coordinates when this font is a named instance
98 /// of a variable font ((axis tag, value) per axis); empty = the
99 /// file's default instance.
100 variation_coordinates: Vec<([u8; 4], f32)>,
101 /// The same coordinates in normalized variation space, for the skrifa
102 /// views (metrics, COLR paint graphs).
103 variation_location: skrifa::instance::Location,
104 /// HarfBuzz's compiled per-instance data (None = default instance).
105 shaper_instance: Option<harfrust::ShaperInstance>,
106 family: String,
107 /// Other names this face answers to: the file's localized family names
108 /// (fontdb keeps all of them) plus any host-registered alias (Skia's
109 /// `registerTypeface(typeface, familyName)`).
110 aliases: Vec<String>,
111 attrs: FontAttrs,
112 units_per_em: f32,
113 /// Font-unit metrics, y-up (ascent positive, descent negative).
114 ascent: f32,
115 descent: f32,
116 line_gap: f32,
117 /// The height of capital letters above the baseline in font units, 0 when the font does not
118 /// say (Skia's `fCapHeight`).
119 cap_height: f32,
120 /// Union of all glyph ink, font units y-up — Skia's fXMin/fXMax family.
121 bounds: Option<(f32, f32, f32, f32)>,
122 /// (offset from baseline, thickness) in font units, when the font says.
123 underline: Option<(f32, f32)>,
124 strikeout: Option<(f32, f32)>,
125}
126
127impl std::fmt::Debug for Font {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 f.debug_struct("Font")
130 .field("uid", &self.uid)
131 .field("family", &self.family)
132 .field("attrs", &self.attrs)
133 .finish_non_exhaustive()
134 }
135}
136
137/// Two fonts are equal when they are the same face at the same instance, which is what
138/// their identifiers say; equal identifiers imply equal outlines and coordinates.
139impl PartialEq for Font {
140 fn eq(&self, other: &Font) -> bool {
141 self.uid == other.uid
142 }
143}
144
145impl Font {
146 fn parse(
147 family: &str,
148 attrs: FontAttrs,
149 data: FontData,
150 face_index: u32,
151 variation_coordinates: Vec<([u8; 4], f32)>,
152 ) -> Option<Self> {
153 let shared = SharedFace::parse(data, face_index, None)?;
154 Self::at_coordinates(shared, family, attrs, variation_coordinates)
155 }
156
157 /// One instance over already-parsed shared state — metrics and shaping
158 /// instance data are the only per-instance work.
159 fn at_coordinates(
160 shared: Arc<SharedFace>,
161 family: &str,
162 attrs: FontAttrs,
163 variation_coordinates: Vec<([u8; 4], f32)>,
164 ) -> Option<Self> {
165 let bytes: &[u8] = (*shared.data).as_ref();
166 let font = skrifa::FontRef::from_index(bytes, shared.face_index).ok()?;
167 let variation_location = font.axes().location(
168 variation_coordinates
169 .iter()
170 .map(|(tag, value)| (skrifa::Tag::new(tag), *value)),
171 );
172 let metrics = Metrics::new(&font, Size::unscaled(), &variation_location);
173 let shaper_instance = (!variation_coordinates.is_empty()).then(|| {
174 let harf = harfrust::FontRef::from_index(bytes, shared.face_index).ok();
175 harf.map(|harf| {
176 harfrust::ShaperInstance::from_variations(
177 &harf,
178 variation_coordinates
179 .iter()
180 .map(|(tag, value)| harfrust::Variation {
181 tag: harfrust::Tag::new(tag),
182 value: *value,
183 }),
184 )
185 })
186 });
187 Some(Self {
188 uid: FontUid::next(),
189 family: family.to_owned(),
190 aliases: Vec::new(),
191 attrs,
192 units_per_em: metrics.units_per_em as f32,
193 ascent: metrics.ascent,
194 descent: metrics.descent,
195 line_gap: metrics.leading,
196 cap_height: metrics.cap_height.unwrap_or(0.0),
197 bounds: metrics.bounds.map(|b| (b.x_min, b.y_min, b.x_max, b.y_max)),
198 underline: metrics.underline.map(|d| (d.offset, d.thickness)),
199 strikeout: metrics.strikeout.map(|d| (d.offset, d.thickness)),
200 shared,
201 variation_coordinates,
202 variation_location,
203 shaper_instance: shaper_instance.flatten(),
204 })
205 }
206
207 /// `data` returns the source font-file bytes.
208 ///
209 /// For a font collection file, use [`Self::face_index`] to select this face.
210 pub fn data(&self) -> &[u8] {
211 (*self.shared.data).as_ref()
212 }
213
214 /// `face_index` returns this face's index within [`Self::data`].
215 pub fn face_index(&self) -> u32 {
216 self.shared.face_index
217 }
218
219 /// `remote_id` returns this face's id in the process that renders its glyphs.
220 ///
221 /// It is Skia's `SkTypefaceProxy::remoteTypefaceID`. A host whose glyphs are
222 /// rendered by another process makes its fonts with
223 /// [`Self::from_data_with_remote_id`] or [`Self::instances_from_data_with_remote_id`],
224 /// and its [`GlyphRaster`](crate::GlyphRaster) reads the id back to name the face to
225 /// that process, with [`Self::variation_coordinates`] naming the instance: every
226 /// named instance of a face answers the face's id. It is `None` for a font rendered
227 /// from its own bytes, and valo itself never reads it.
228 pub fn remote_id(&self) -> Option<u64> {
229 self.shared.remote_id
230 }
231
232 /// `variation_coordinates` returns user-space axis tags and values.
233 ///
234 /// It is empty for static fonts and default variable-font instances.
235 pub fn variation_coordinates(&self) -> &[([u8; 4], f32)] {
236 &self.variation_coordinates
237 }
238
239 pub(crate) fn variation_location(&self) -> &skrifa::instance::Location {
240 &self.variation_location
241 }
242
243 pub(crate) fn shaper_instance(&self) -> Option<&harfrust::ShaperInstance> {
244 self.shaper_instance.as_ref()
245 }
246
247 /// `uid` returns the process-unique identity of this font instance.
248 pub fn uid(&self) -> FontUid {
249 self.uid
250 }
251
252 /// `family` returns the font's primary family name.
253 pub fn family(&self) -> &str {
254 &self.family
255 }
256
257 /// `aliases` returns additional family names recognized for this font.
258 pub fn aliases(&self) -> &[String] {
259 &self.aliases
260 }
261
262 /// `matches` reports whether `name` matches the family or an alias.
263 ///
264 /// Matching is ASCII case-insensitive.
265 pub fn matches(&self, name: &str) -> bool {
266 self.family.eq_ignore_ascii_case(name)
267 || self.aliases.iter().any(|a| a.eq_ignore_ascii_case(name))
268 }
269
270 /// `add_alias` registers another family name if it is not already recognized.
271 pub fn add_alias(&mut self, name: &str) {
272 if !self.matches(name) {
273 self.aliases.push(name.to_owned());
274 }
275 }
276
277 /// `attrs` returns the face-selection attributes of this font.
278 pub fn attrs(&self) -> FontAttrs {
279 self.attrs
280 }
281
282 /// `ascent_px` returns the positive distance above the baseline at `size`.
283 pub fn ascent_px(&self, size: f32) -> f32 {
284 self.ascent * size / self.units_per_em
285 }
286
287 /// `cap_height_px` returns the height of capital letters above the baseline at `size`, 0
288 /// when the font does not say.
289 pub fn cap_height_px(&self, size: f32) -> f32 {
290 self.cap_height * size / self.units_per_em
291 }
292
293 /// `descent_px` returns the positive distance below the baseline at `size`.
294 pub fn descent_px(&self, size: f32) -> f32 {
295 -self.descent * size / self.units_per_em
296 }
297
298 /// `line_height_px` returns the font's default line height at `size`.
299 pub fn line_height_px(&self, size: f32) -> f32 {
300 (self.ascent - self.descent + self.line_gap) * size / self.units_per_em
301 }
302
303 /// `units_per_em` returns the font's design-space units per em.
304 pub fn units_per_em(&self) -> f32 {
305 self.units_per_em
306 }
307
308 /// `ink_box_px` returns the font-wide ink bounds at `size`.
309 ///
310 /// The tuple is `(x_min, y_min, x_max, y_max)` in y-up coordinates around
311 /// the glyph origin. It returns `None` when the font provides no bounds.
312 pub fn ink_box_px(&self, size: f32) -> Option<(f32, f32, f32, f32)> {
313 let k = size / self.units_per_em;
314 self.bounds
315 .map(|(x0, y0, x1, y1)| (x0 * k, y0 * k, x1 * k, y1 * k))
316 }
317
318 /// `covers` reports whether the font maps a character to a glyph.
319 pub fn covers(&self, ch: char) -> bool {
320 self.shared.charmap.contains_key(&(ch as u32))
321 }
322
323 /// `glyph_for` returns the glyph identifier mapped from a character.
324 pub fn glyph_for(&self, ch: char) -> Option<u32> {
325 self.shared.charmap.get(&(ch as u32)).copied()
326 }
327
328 pub(crate) fn shaper_data(&self) -> &harfrust::ShaperData {
329 &self.shared.shaper_data
330 }
331
332 /// `underline_px` returns underline offset and thickness at `size`.
333 ///
334 /// The offset is positive below the baseline. Conventional values are used
335 /// when the font omits underline metrics.
336 pub fn underline_px(&self, size: f32) -> (f32, f32) {
337 self.decoration_px(self.underline, size, -0.1, 0.05)
338 }
339
340 /// `strikeout_px` returns strikeout offset and thickness at `size`.
341 ///
342 /// The offset is positive above the baseline. Conventional values are used
343 /// when the font omits strikeout metrics.
344 pub fn strikeout_px(&self, size: f32) -> (f32, f32) {
345 self.decoration_px(self.strikeout, size, 0.3, 0.05)
346 }
347
348 fn decoration_px(
349 &self,
350 metric: Option<(f32, f32)>,
351 size: f32,
352 default_offset: f32,
353 default_thickness: f32,
354 ) -> (f32, f32) {
355 match metric {
356 // Font units are y-up: positive offsets sit above the baseline.
357 Some((offset, thickness)) => (
358 offset * size / self.units_per_em,
359 (thickness * size / self.units_per_em).max(0.5),
360 ),
361 None => (size * default_offset, (size * default_thickness).max(0.5)),
362 }
363 }
364}
365
366/// `FontDemand` describes font requests that no registered face could satisfy.
367///
368/// Hosts can use it to load additional fonts and lay out affected text again.
369#[derive(Clone, Debug, Default, PartialEq)]
370pub struct FontDemand {
371 /// `families` lists requested family names with no registered match.
372 pub families: Vec<String>,
373 /// `codepoints` lists uncovered characters and their requested attributes.
374 pub codepoints: Vec<(char, FontAttrs)>,
375}
376
377impl FontDemand {
378 /// `is_empty` reports whether every font request was satisfied.
379 pub fn is_empty(&self) -> bool {
380 self.families.is_empty() && self.codepoints.is_empty()
381 }
382
383 /// `add_family` records a family name no face answered, once.
384 pub fn add_family(&mut self, name: &str) {
385 if !self.families.iter().any(|f| f == name) {
386 self.families.push(name.to_owned());
387 }
388 }
389
390 /// `add_codepoint` records a character no face covered at `attrs`, once.
391 pub fn add_codepoint(&mut self, ch: char, attrs: FontAttrs) {
392 if !self.codepoints.contains(&(ch, attrs)) {
393 self.codepoints.push((ch, attrs));
394 }
395 }
396}
397
398/// `FontSource` locates fonts that are not already registered.
399///
400/// A source may consult installed fonts, downloaded assets, or another
401/// host-owned repository. [`FontCollection`] consults sources in registration
402/// order.
403pub trait FontSource {
404 /// `family` returns every available face matching a family name.
405 fn family(&mut self, name: &str) -> Vec<Font>;
406
407 /// `face_for_codepoint` returns a covering face nearest to `attrs`.
408 fn face_for_codepoint(&mut self, codepoint: char, attrs: FontAttrs) -> Option<Font>;
409
410 /// `default_face` returns the source's default face nearest to `attrs`, the face text
411 /// is set in when no family it asks for has one: Skia's
412 /// `SkFontMgr::legacyMakeTypeface(nullptr, style)`. A collection asks for it only while
413 /// it has no face at all.
414 ///
415 /// The default answers `None`: a source without a default leaves an empty collection's
416 /// text to its character lookup, and what that misses to the collection's demand, for a
417 /// host that loads fonts asynchronously.
418 fn default_face(&mut self, attrs: FontAttrs) -> Option<Font> {
419 let _ = attrs;
420 None
421 }
422}
423
424/// `match_style` returns the font nearest `attrs` among `fonts`, by CSS font
425/// matching's precedence: width, then style, then weight; ties to the first.
426///
427/// It is Skia's `SkFontStyleSet::matchStyle`, for a [`FontSource`] choosing
428/// among a family's faces, or among a variable face's named instances, so that
429/// a bold span's fallback arrives bold. The distances are plain absolute
430/// differences rather than CSS's directional walk: a request between two
431/// weights takes the closer, not the one CSS's direction prefers. It returns
432/// `None` when `fonts` is empty.
433pub fn match_style<'a>(
434 fonts: impl IntoIterator<Item = &'a Font>,
435 attrs: FontAttrs,
436) -> Option<&'a Font> {
437 fonts
438 .into_iter()
439 .min_by_key(|font| style_distance(font.attrs, attrs))
440}
441
442/// `FaceSet` stores registered fonts and their global fallback order.
443///
444/// Cloning a face set shares parsed fonts, allowing callers to grow a snapshot
445/// without modifying existing holders.
446#[derive(Default, Clone)]
447pub struct FaceSet {
448 /// `Arc` per face: adding a font clones N pointers, never re-parses
449 /// (Skia registers typefaces incrementally).
450 fonts: Vec<Arc<Font>>,
451 fallbacks: Vec<FontId>,
452 /// The faces answering to each name, keyed as [`name_key`] spells it, in
453 /// registration order. Resolution asks per character, so a name is a
454 /// lookup rather than a walk over every face comparing strings.
455 by_name: HashMap<String, Vec<FontId>>,
456 /// The sources' default face, once [`FontCollection::require_default_face`] has
457 /// asked for it: the face a style none of whose families has a face is set in.
458 default_face: Option<FontId>,
459}
460
461/// `StyleFaces` is one text style's font resolution, prepared by
462/// [`FaceSet::style_faces`].
463///
464/// It holds face identifiers only, ordered for [`FaceSet::resolve_prepared`];
465/// it is stale once a face is added to the set it came from.
466#[derive(Clone, Debug)]
467pub struct StyleFaces {
468 /// The requested families' faces, in request order, nearest-first; the
469 /// set's default face alone when none of them has a face.
470 families: Vec<Vec<FontId>>,
471 /// The fallback chain, nearest-first.
472 fallbacks: Vec<FontId>,
473 /// Where tofu renders when nothing covers: the style's best variant,
474 /// else the default face, else the first fallback, else the first face;
475 /// `None` on an empty set.
476 tofu: Option<FontId>,
477}
478
479impl StyleFaces {
480 /// `style_face` is the face the style tries first, whatever a character
481 /// needs: its first present family's nearest variant, else the set's
482 /// default face, else the first fallback, else the set's first face;
483 /// `None` on an empty set. It is
484 /// skparagraph's first typeface for a style, in which a control
485 /// character such as a hard line break is always resolved
486 /// (`OneLineShaper::sortOutGlyphs` never counts one as unresolved), so
487 /// no fallback face takes it.
488 pub fn style_face(&self) -> Option<FontId> {
489 self.tofu
490 }
491}
492
493impl FaceSet {
494 /// `new` creates an empty face set.
495 pub fn new() -> Self {
496 Self::default()
497 }
498
499 /// `register` adds font bytes under a family, with the weight, slant and width the file
500 /// declares.
501 ///
502 /// The face answers only to `family`, not to the names inside the file, as Flutter
503 /// registers a font under the family a host gives it, so the four static faces of one
504 /// family registered under its name select by weight like one family. It returns `None`
505 /// when face zero cannot be parsed.
506 pub fn register(&mut self, family: &str, bytes: Vec<u8>) -> Option<FontId> {
507 let (data, face_index) = unwrapped(Arc::new(bytes), 0)?;
508 let attrs = embedded_attrs((*data).as_ref(), face_index);
509 let font = Font::parse(family, attrs, data, face_index, Vec::new())?;
510 Some(self.add(font))
511 }
512
513 /// `register_with` adds font bytes under a family with explicit attributes.
514 ///
515 /// It returns `None` when face zero cannot be parsed.
516 pub fn register_with(
517 &mut self,
518 family: &str,
519 attrs: FontAttrs,
520 bytes: Vec<u8>,
521 ) -> Option<FontId> {
522 let (data, face_index) = unwrapped(Arc::new(bytes), 0)?;
523 let font = Font::parse(family, attrs, data, face_index, Vec::new())?;
524 Some(self.add(font))
525 }
526
527 /// `add` registers an already parsed font under its embedded names and attributes.
528 pub fn add(&mut self, font: Font) -> FontId {
529 let id = FontId(self.fonts.len() as u32);
530 let aliases = font.aliases().iter().map(String::as_str);
531 for name in std::iter::once(font.family()).chain(aliases) {
532 let ids = self.by_name.entry(name_key(name)).or_default();
533 if ids.last() != Some(&id) {
534 ids.push(id);
535 }
536 }
537 self.fonts.push(Arc::new(font));
538 id
539 }
540
541 /// `with_font` returns a cloned face set containing one additional font.
542 ///
543 /// Existing fonts remain shared and are not reparsed.
544 pub fn with_font(&self, font: Font) -> (FaceSet, FontId) {
545 let mut next = self.clone();
546 let id = next.add(font);
547 (next, id)
548 }
549
550 /// `with_fallbacks` returns a clone with its global fallback order replaced.
551 ///
552 /// Every identifier must belong to this face set.
553 pub fn with_fallbacks(&self, fallbacks: Vec<FontId>) -> FaceSet {
554 let mut next = self.clone();
555 next.fallbacks = fallbacks;
556 next
557 }
558
559 /// `add_fallback` appends a registered font to the global fallback order.
560 ///
561 /// Requested families are searched before this chain. `id` must belong to
562 /// this face set.
563 pub fn add_fallback(&mut self, id: FontId) {
564 self.fallbacks.push(id);
565 }
566
567 /// `grown_by` returns a clone extended with answers from a font source.
568 ///
569 /// Requested families are also registered under the requested name.
570 /// Uncovered codepoints add matching faces to the fallback chain. It returns
571 /// `None` when the source supplies nothing new.
572 pub fn grown_by(&self, source: &mut dyn FontSource, demand: &FontDemand) -> Option<FaceSet> {
573 let mut next = self.clone();
574 let mut grew = false;
575 for name in &demand.families {
576 if next.family(name).is_some() {
577 // Answered already (a stale demand) — resolution matches
578 // it now; asking the source again would duplicate faces.
579 continue;
580 }
581 grew |= next.register_answers(source.family(name), name);
582 }
583 for &(codepoint, attrs) in &demand.codepoints {
584 grew |= next.register_fallback_answer(source, codepoint, attrs);
585 }
586 grew.then_some(next)
587 }
588
589 fn register_answers(&mut self, faces: Vec<Font>, requested_name: &str) -> bool {
590 let mut added = false;
591 for mut font in faces {
592 font.add_alias(requested_name);
593 self.add(font);
594 added = true;
595 }
596 added
597 }
598
599 fn register_fallback_answer(
600 &mut self,
601 source: &mut dyn FontSource,
602 codepoint: char,
603 attrs: FontAttrs,
604 ) -> bool {
605 if is_private_use(codepoint) {
606 // Icon fonts resolve by their REGISTERED family name; a
607 // generic source "covering" the Private Use Area paints some
608 // vendor's glyphs where tofu is the honest render.
609 return false;
610 }
611 if self.fallbacks_cover(codepoint) {
612 // Already in the chain — resolution will find that face without
613 // a second copy of it.
614 return false;
615 }
616 let Some(font) = source.face_for_codepoint(codepoint, attrs) else {
617 return false;
618 };
619 let id = self.add(font);
620 self.add_fallback(id);
621 true
622 }
623
624 /// Whether the global fallback chain covers `codepoint`.
625 ///
626 /// A fallback answer is only ever reached through this chain, so this —
627 /// not "some registered face" — decides whether another one is needed.
628 fn fallbacks_cover(&self, codepoint: char) -> bool {
629 self.fallbacks
630 .iter()
631 .any(|id| self.get(*id).covers(codepoint))
632 }
633
634 /// Whether resolution finds a face covering `ch`.
635 ///
636 /// This is the walk [`Self::resolve_covered`] makes, so a face resolution
637 /// cannot reach — registered under a name nobody asked for and absent from
638 /// the fallback chain, as an icon font is — does not pass for coverage it
639 /// will never supply. Asking "does some registered face cover it" instead
640 /// lets such a font suppress the fallback the text actually needs.
641 pub(crate) fn covered_by_resolution(
642 &self,
643 families: &[String],
644 attrs: FontAttrs,
645 ch: char,
646 ) -> bool {
647 matches!(
648 self.resolve_covered_opt(families, attrs, ch),
649 Some((_, true))
650 )
651 }
652
653 /// `is_empty` reports whether no fonts are registered.
654 pub fn is_empty(&self) -> bool {
655 self.fonts.is_empty()
656 }
657
658 /// `len` returns the number of registered fonts.
659 pub fn len(&self) -> usize {
660 self.fonts.len()
661 }
662
663 /// `get_arc` returns a shared handle to a registered font.
664 ///
665 /// # Panics
666 ///
667 /// Panics if `id` does not belong to this face set.
668 pub fn get_arc(&self, id: FontId) -> Arc<Font> {
669 self.fonts[id.0 as usize].clone()
670 }
671
672 /// `get` returns a registered font by identifier.
673 ///
674 /// # Panics
675 ///
676 /// Panics if `id` does not belong to this face set.
677 pub fn get(&self, id: FontId) -> &Font {
678 &self.fonts[id.0 as usize]
679 }
680
681 /// `family` returns the first registered font matching a family name or alias.
682 pub fn family(&self, name: &str) -> Option<FontId> {
683 self.by_name.get(&name_key(name))?.first().copied()
684 }
685
686 /// `faces` iterates over every font matching a family name or alias.
687 ///
688 /// Results follow registration order and include separate subset faces.
689 pub fn faces<'a>(&'a self, name: &'a str) -> impl Iterator<Item = FontId> + 'a {
690 self.variants(name).map(|(id, _)| id)
691 }
692
693 /// `family_variant` returns the family face nearest to requested attributes.
694 ///
695 /// Faces are matched as [`match_style`] matches them: width first, then
696 /// italic style and weight. Registration order breaks ties.
697 pub fn family_variant(&self, name: &str, attrs: FontAttrs) -> Option<FontId> {
698 let nearest = match_style(self.variants(name).map(|(_, font)| font), attrs)?;
699 self.faces(name).find(|id| self.get(*id) == nearest)
700 }
701
702 /// `resolve` selects a font for a character and requested style.
703 ///
704 /// It searches requested families in order, then global fallbacks. If no
705 /// font covers the character, it returns a font suitable for rendering
706 /// `.notdef`.
707 ///
708 /// # Panics
709 ///
710 /// Panics when the face set is empty.
711 pub fn resolve(&self, families: &[String], attrs: FontAttrs, ch: char) -> FontId {
712 self.resolve_covered(families, attrs, ch).0
713 }
714
715 /// `resolve_covered` selects a font and reports whether it covers the character.
716 ///
717 /// A `false` flag means the returned font will render `.notdef`.
718 ///
719 /// # Panics
720 ///
721 /// Panics when the face set is empty.
722 pub fn resolve_covered(
723 &self,
724 families: &[String],
725 attrs: FontAttrs,
726 ch: char,
727 ) -> (FontId, bool) {
728 let faces = self.style_faces(families, attrs);
729 self.resolve_prepared(&faces, ch).unwrap_or_else(|| {
730 panic!(
731 "FontCollection has no fonts registered — register() one before building paragraphs"
732 );
733 })
734 }
735
736 /// `style_faces` prepares one style's resolution: the faces of each
737 /// requested family and of the fallback chain, nearest-first to `attrs`.
738 ///
739 /// A run of text asks for a font per character; prepared once per style,
740 /// each character is a coverage walk over these lists and no name lookup
741 /// (Skia's `SkFontCollection::findTypefaces`, done once per text style).
742 /// When no requested family has a face, the set's default face stands in
743 /// for them, as `findTypefaces` answers with the default typeface; a style
744 /// whose family has a face never resolves in the default face.
745 pub fn style_faces(&self, families: &[String], attrs: FontAttrs) -> StyleFaces {
746 let fallbacks = self.fallbacks.iter().map(|id| (*id, self.get(*id)));
747 let mut requested: Vec<Vec<FontId>> = families
748 .iter()
749 .map(|name| self.nearest_first(self.variants(name), attrs))
750 .collect();
751 if let Some(default_face) = self.default_face {
752 if requested.iter().all(Vec::is_empty) {
753 requested = vec![vec![default_face]];
754 }
755 }
756 StyleFaces {
757 families: requested,
758 fallbacks: self.nearest_first(fallbacks, attrs),
759 tofu: self.tofu_face_opt(families, attrs),
760 }
761 }
762
763 /// `resolve_prepared` selects a font for `ch` from a prepared style.
764 ///
765 /// The first covering face of the first requested family that has one
766 /// wins, then the fallback chain's; the flag is `false` when nothing
767 /// covers and the returned font renders `.notdef`. `None` when the face
768 /// set is empty.
769 pub fn resolve_prepared(&self, faces: &StyleFaces, ch: char) -> Option<(FontId, bool)> {
770 let covering = faces
771 .families
772 .iter()
773 .chain(std::iter::once(&faces.fallbacks))
774 .flatten()
775 .find(|id| self.get(**id).covers(ch));
776 match covering {
777 Some(id) => Some((*id, true)),
778 None => faces.tofu.map(|id| (id, false)),
779 }
780 }
781
782 /// Every face answering to `name`, with its id, in registration order.
783 fn variants<'a>(&'a self, name: &str) -> impl Iterator<Item = (FontId, &'a Font)> + 'a {
784 self.by_name
785 .get(&name_key(name))
786 .into_iter()
787 .flatten()
788 .map(|id| (*id, self.get(*id)))
789 }
790
791 /// `faces` in [`match_style`]'s order: the face it would pick first, and
792 /// so on, with ties in registration order.
793 fn nearest_first<'a>(
794 &self,
795 faces: impl Iterator<Item = (FontId, &'a Font)>,
796 attrs: FontAttrs,
797 ) -> Vec<FontId> {
798 let mut faces: Vec<(FontId, &Font)> = faces.collect();
799 faces.sort_by_key(|(_, f)| style_distance(f.attrs, attrs));
800 faces.into_iter().map(|(id, _)| id).collect()
801 }
802
803 /// [`Self::tofu_face`] that reports an EMPTY collection instead of
804 /// panicking — the `build_with` path, where an empty start is valid
805 /// (the chain is asked first; a char no source can render is skipped
806 /// and reported through the demand).
807 pub(crate) fn tofu_face_opt(&self, families: &[String], attrs: FontAttrs) -> Option<FontId> {
808 families
809 .iter()
810 .find_map(|name| self.family_variant(name, attrs))
811 .or(self.default_face)
812 .or_else(|| self.fallbacks.first().copied())
813 .or_else(|| (!self.fonts.is_empty()).then_some(FontId(0)))
814 }
815
816 /// [`Self::resolve_covered`] that can also report "no face exists at
817 /// all" (empty collection on the `build_with` path).
818 pub(crate) fn resolve_covered_opt(
819 &self,
820 families: &[String],
821 attrs: FontAttrs,
822 ch: char,
823 ) -> Option<(FontId, bool)> {
824 if self.fonts.is_empty() {
825 return None;
826 }
827 Some(self.resolve_covered(families, attrs, ch))
828 }
829}
830
831/// The spelling a family name or alias is indexed under: names match
832/// ASCII-case-insensitively (as [`Font::matches`] compares them).
833fn name_key(name: &str) -> String {
834 name.to_ascii_lowercase()
835}
836
837impl Font {
838 /// `from_bytes` parses face zero from owned font-file bytes.
839 ///
840 /// Family names and attributes come from the font. Localized family names
841 /// become aliases. It returns `None` when the bytes cannot be parsed.
842 pub fn from_bytes(bytes: Vec<u8>) -> Option<Font> {
843 Self::from_data(Arc::new(bytes), 0)
844 }
845
846 /// `from_data` parses one face from shared font-file storage.
847 ///
848 /// Use face index zero for a single-face file. It returns `None` when the
849 /// index or font data is invalid.
850 pub fn from_data(data: FontData, face_index: u32) -> Option<Font> {
851 Self::parse_face(data, face_index, None)
852 }
853
854 /// `from_data_with_remote_id` parses one face whose glyphs another process renders.
855 ///
856 /// It is [`Self::from_data`] for a font that names its face to that process by
857 /// `remote_id`, which [`Self::remote_id`] answers.
858 pub fn from_data_with_remote_id(
859 data: FontData,
860 face_index: u32,
861 remote_id: u64,
862 ) -> Option<Font> {
863 Self::parse_face(data, face_index, Some(remote_id))
864 }
865
866 /// `instances_from_data` parses the registrable instances of one face.
867 ///
868 /// Static fonts produce one item. Variable fonts with named instances
869 /// produce one [`Font`] per instance. Invalid data returns an empty vector.
870 pub fn instances_from_data(data: FontData, face_index: u32) -> Vec<Font> {
871 Self::parse_instances(data, face_index, None)
872 }
873
874 /// `instances_from_data_with_remote_id` parses the registrable instances of one face
875 /// whose glyphs another process renders.
876 ///
877 /// It is [`Self::instances_from_data`] for a face that [`Self::from_data_with_remote_id`]
878 /// describes: every instance answers `remote_id` from [`Self::remote_id`].
879 pub fn instances_from_data_with_remote_id(
880 data: FontData,
881 face_index: u32,
882 remote_id: u64,
883 ) -> Vec<Font> {
884 Self::parse_instances(data, face_index, Some(remote_id))
885 }
886
887 /// [`Self::from_data`], with the face's remote id if it has one.
888 fn parse_face(data: FontData, face_index: u32, remote_id: Option<u64>) -> Option<Font> {
889 let (data, face_index) = unwrapped(data, face_index)?;
890 Self::instance(data, face_index, remote_id, Vec::new())
891 }
892
893 /// [`Self::instances_from_data`], with the face's remote id if it has one: the fonts
894 /// already parsed of this face (`face_cache`), else parsed now and kept for the next
895 /// ask.
896 fn parse_instances(data: FontData, face_index: u32, remote_id: Option<u64>) -> Vec<Font> {
897 if let Some(instances) = face_cache::find(&data, face_index, remote_id) {
898 return instances;
899 }
900 let instances = Self::parsed_instances(Arc::clone(&data), face_index, remote_id);
901 if !instances.is_empty() {
902 face_cache::add(data, face_index, remote_id, instances.clone());
903 }
904 instances
905 }
906
907 /// Whether more than `inside` fonts share this one's parsed file: the fonts of one
908 /// face share it, so more than the face has means one is held elsewhere.
909 pub(crate) fn is_held_beyond(&self, inside: usize) -> bool {
910 Arc::strong_count(&self.shared) > inside
911 }
912
913 /// The registrable instances of one face, parsed now, whatever the cache has.
914 pub(crate) fn parsed_instances(
915 data: FontData,
916 face_index: u32,
917 remote_id: Option<u64>,
918 ) -> Vec<Font> {
919 let Some((data, face_index)) = unwrapped(data, face_index) else {
920 return Vec::new();
921 };
922 let instances = named_instance_coordinates((*data).as_ref(), face_index);
923 if instances.is_empty() {
924 return Self::instance(data, face_index, remote_id, Vec::new())
925 .into_iter()
926 .collect();
927 }
928 // The expensive halves (cmap, shaping caches) parse ONCE; each
929 // instance adds only its metrics and axis data.
930 let Some(shared) = SharedFace::parse(data, face_index, remote_id) else {
931 return Vec::new();
932 };
933 instances
934 .into_iter()
935 .filter_map(|coordinates| Self::shared_instance(shared.clone(), coordinates))
936 .collect()
937 }
938
939 /// One face at one set of coordinates, self-described from its tables
940 /// (attrs overridden by the coordinates' weight/italic axes).
941 fn instance(
942 data: FontData,
943 face_index: u32,
944 remote_id: Option<u64>,
945 coordinates: Vec<([u8; 4], f32)>,
946 ) -> Option<Font> {
947 let shared = SharedFace::parse(data, face_index, remote_id)?;
948 Self::shared_instance(shared, coordinates)
949 }
950
951 /// [`Self::instance`] over already-shared file state.
952 fn shared_instance(shared: Arc<SharedFace>, coordinates: Vec<([u8; 4], f32)>) -> Option<Font> {
953 let bytes: &[u8] = (*shared.data).as_ref();
954 let (family, aliases) = embedded_names(bytes, shared.face_index)?;
955 let attrs = instance_attrs(embedded_attrs(bytes, shared.face_index), &coordinates);
956 let mut font = Font::at_coordinates(shared, &family, attrs, coordinates)?;
957 for name in &aliases {
958 font.add_alias(name);
959 }
960 Some(font)
961 }
962}
963
964impl SharedFace {
965 fn parse(data: FontData, face_index: u32, remote_id: Option<u64>) -> Option<Arc<Self>> {
966 let bytes: &[u8] = (*data).as_ref();
967 let font = skrifa::FontRef::from_index(bytes, face_index).ok()?;
968 let charmap = font
969 .charmap()
970 .mappings()
971 .map(|(code, glyph)| (code, glyph.to_u32()))
972 .collect();
973 let harf = harfrust::FontRef::from_index(bytes, face_index).ok()?;
974 let shaper_data = harfrust::ShaperData::new(&harf);
975 Some(Arc::new(Self {
976 data,
977 face_index,
978 remote_id,
979 charmap,
980 shaper_data,
981 }))
982 }
983}
984
985/// The (tag, value) coordinate rows of every fvar named instance.
986fn named_instance_coordinates(bytes: &[u8], face_index: u32) -> Vec<Vec<([u8; 4], f32)>> {
987 let Ok(font) = skrifa::FontRef::from_index(bytes, face_index) else {
988 return Vec::new();
989 };
990 let axis_tags: Vec<[u8; 4]> = font
991 .axes()
992 .iter()
993 .map(|axis| axis.tag().to_be_bytes())
994 .collect();
995 font.named_instances()
996 .iter()
997 .map(|instance| {
998 axis_tags
999 .iter()
1000 .copied()
1001 .zip(instance.user_coords())
1002 .collect()
1003 })
1004 .collect()
1005}
1006
1007/// A named instance's place in its family: the weight/italic/width axes
1008/// override what the file's default-instance OS/2 table says.
1009fn instance_attrs(base: FontAttrs, coordinates: &[([u8; 4], f32)]) -> FontAttrs {
1010 let mut attrs = base;
1011 for (tag, value) in coordinates {
1012 match tag {
1013 b"wght" => attrs.weight = value.clamp(1.0, 1000.0) as u16,
1014 b"ital" => attrs.italic = *value >= 0.5,
1015 b"slnt" => attrs.italic = attrs.italic || *value < 0.0,
1016 // `wdth` is already a percentage, which is what CSS asks for.
1017 b"wdth" => attrs.stretch = value.clamp(1.0, 1000.0),
1018 _ => {}
1019 }
1020 }
1021 attrs
1022}
1023
1024/// How far `candidate` is from `wanted`, as the sort key of CSS font
1025/// matching's precedence: width, then style, then weight.
1026fn style_distance(candidate: FontAttrs, wanted: FontAttrs) -> (u32, bool, u16) {
1027 (
1028 stretch_distance(candidate.stretch, wanted.stretch),
1029 candidate.italic != wanted.italic,
1030 candidate.weight.abs_diff(wanted.weight),
1031 )
1032}
1033
1034/// Ordered width distance for variant matching. Quantized to 1/16 of a
1035/// percent so it can be an integer sort key without collapsing the named
1036/// widths (they are 12.5 apart at the closest).
1037fn stretch_distance(candidate: f32, wanted: f32) -> u32 {
1038 ((candidate - wanted).abs() * 16.0) as u32
1039}
1040
1041/// WOFF2 arrives brotli-wrapped; faces parse the unwrapped TrueType bytes
1042/// (icon and web fonts ship compressed — the CoreText managers accept
1043/// them, so registration here does too). Identity for everything else.
1044/// A collection face is emitted as its own single-face SFNT, so the
1045/// returned index is always zero after unwrap.
1046#[cfg(feature = "woff2")]
1047fn unwrapped(data: FontData, face_index: u32) -> Option<(FontData, u32)> {
1048 let bytes: &[u8] = (*data).as_ref();
1049 if !bytes.starts_with(b"wOF2") {
1050 return Some((data, face_index));
1051 }
1052 let unpacked = crate::woff2::to_sfnt(bytes, face_index)?;
1053 Some((Arc::new(unpacked), 0))
1054}
1055
1056#[cfg(not(feature = "woff2"))]
1057fn unwrapped(data: FontData, face_index: u32) -> Option<(FontData, u32)> {
1058 Some((data, face_index))
1059}
1060
1061/// name table: the primary is the en typographic family (then en family,
1062/// then any-language); every other family/typographic-family string rides
1063/// along as an alias.
1064fn embedded_names(data: &[u8], face_index: u32) -> Option<(String, Vec<String>)> {
1065 use swash::StringId;
1066 let font = swash::FontRef::from_index(data, face_index as usize)?;
1067 let strings = font.localized_strings();
1068 let pick = |id: StringId| {
1069 strings
1070 .find_by_id(id, Some("en"))
1071 .or_else(|| strings.find_by_id(id, None))
1072 .map(|s| s.to_string())
1073 };
1074 let primary = pick(StringId::TypographicFamily).or_else(|| pick(StringId::Family))?;
1075 let aliases = strings
1076 .filter(|s| matches!(s.id(), StringId::Family | StringId::TypographicFamily))
1077 .map(|s| s.to_string())
1078 .filter(|name| *name != primary)
1079 .collect();
1080 Some((primary, aliases))
1081}
1082
1083/// OS/2 weight + width + style flags via swash attributes.
1084fn embedded_attrs(data: &[u8], face_index: u32) -> FontAttrs {
1085 let Some(font) = swash::FontRef::from_index(data, face_index as usize) else {
1086 return FontAttrs::default();
1087 };
1088 let attrs = font.attributes();
1089 FontAttrs {
1090 weight: attrs.weight().0,
1091 italic: attrs.style() != swash::Style::Normal,
1092 stretch: attrs.stretch().to_percentage(),
1093 }
1094}
1095
1096/// Unicode Private Use Areas — codepoints whose meaning belongs to a
1097/// specific registered font, never to a generic fallback source.
1098fn is_private_use(codepoint: char) -> bool {
1099 matches!(
1100 codepoint,
1101 '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'
1102 )
1103}
1104
1105/// `FontCollection` owns registered faces and sources for resolving missing fonts.
1106///
1107/// Paragraph building consults sources in order and registers their answers.
1108/// Unanswered requests accumulate until [`Self::take_unanswered`] is called.
1109#[derive(Default)]
1110pub struct FontCollection {
1111 faces: FaceSet,
1112 /// Consulted in order, first answer wins (Skia's manager priority:
1113 /// registered bytes and downloaders before the platform database).
1114 sources: Vec<Box<dyn FontSource>>,
1115 /// Misses no source answered, since the last drain.
1116 unanswered: FontDemand,
1117}
1118
1119impl FontCollection {
1120 /// `new` creates an empty collection with no font sources.
1121 pub fn new() -> FontCollection {
1122 FontCollection::default()
1123 }
1124
1125 /// `faces` returns the faces currently registered in the collection.
1126 ///
1127 /// A built paragraph clones this set and remains independent of later changes.
1128 pub fn faces(&self) -> &FaceSet {
1129 &self.faces
1130 }
1131
1132 /// `register` adds font bytes under a family, with the weight, slant and width the file
1133 /// declares.
1134 ///
1135 /// The face answers only to `family`, as [`FaceSet::register`] describes. It returns
1136 /// `None` when face zero cannot be parsed.
1137 pub fn register(&mut self, family: &str, bytes: Vec<u8>) -> Option<FontId> {
1138 self.faces.register(family, bytes)
1139 }
1140
1141 /// `add` registers an already parsed font.
1142 pub fn add(&mut self, font: Font) -> FontId {
1143 self.faces.add(font)
1144 }
1145
1146 /// `add_fallback` appends a registered font to the global fallback order.
1147 ///
1148 /// `id` must belong to this collection.
1149 pub fn add_fallback(&mut self, id: FontId) {
1150 self.faces.add_fallback(id);
1151 }
1152
1153 /// `get` returns a registered font by identifier.
1154 ///
1155 /// # Panics
1156 ///
1157 /// Panics if `id` does not belong to this collection.
1158 pub fn get(&self, id: FontId) -> &Font {
1159 self.faces.get(id)
1160 }
1161
1162 /// `len` returns the number of registered fonts.
1163 pub fn len(&self) -> usize {
1164 self.faces.len()
1165 }
1166
1167 /// `family` returns the first font matching a family name or alias.
1168 pub fn family(&self, name: &str) -> Option<FontId> {
1169 self.faces.family(name)
1170 }
1171
1172 /// `add_source` appends a source consulted when registered fonts cannot satisfy a request.
1173 pub fn add_source(&mut self, source: impl FontSource + 'static) {
1174 self.sources.push(Box::new(source));
1175 }
1176
1177 /// `add_boxed_source` appends an already boxed font source.
1178 pub fn add_boxed_source(&mut self, source: Box<dyn FontSource>) {
1179 self.sources.push(source);
1180 }
1181
1182 /// `is_empty` reports whether no fonts are currently registered.
1183 pub fn is_empty(&self) -> bool {
1184 self.faces.is_empty()
1185 }
1186
1187 /// `adopt_faces` replaces the registered faces with a prepared set.
1188 ///
1189 /// This supports hosts that answer [`FontDemand`] using [`FaceSet::grown_by`].
1190 pub fn adopt_faces(&mut self, faces: FaceSet) {
1191 self.faces = faces;
1192 }
1193
1194 /// `take_unanswered` drains font requests that no source could satisfy.
1195 ///
1196 /// Hosts may load and [`Self::register`] matching fonts before rebuilding
1197 /// affected paragraphs.
1198 pub fn take_unanswered(&mut self) -> FontDemand {
1199 std::mem::take(&mut self.unanswered)
1200 }
1201
1202 /// `require_family` makes sure the family `name` has a face, asking the
1203 /// sources when none is registered.
1204 ///
1205 /// The sources are asked in order and what they answer is registered
1206 /// (Skia's `findTypefaces` walking its managers). It returns `false` when
1207 /// nobody had the family, and records the miss for
1208 /// [`Self::take_unanswered`].
1209 pub fn require_family(&mut self, name: &str) -> bool {
1210 if self.faces.family(name).is_some() {
1211 return true;
1212 }
1213 for source in &mut self.sources {
1214 let faces = source.family(name);
1215 if self.faces.register_answers(faces, name) {
1216 return true;
1217 }
1218 }
1219 self.unanswered.add_family(name);
1220 false
1221 }
1222
1223 /// `require_default_face` makes sure the collection has a face for a style none of
1224 /// whose families answered, asking the sources for their default face when it has
1225 /// none.
1226 ///
1227 /// It is the end of Skia's `findTypefaces`, which, when no requested family matched,
1228 /// asks each font manager in order for `legacyMakeTypeface(nullptr, style)`. The
1229 /// registered faces come first, as Skia's registered-font provider answers with its
1230 /// first family, so the sources are asked only while the collection is empty. Their
1231 /// answer becomes the set's default face, which [`FaceSet::style_faces`] gives a
1232 /// style only when none of its families has a face, and never joins the fallback
1233 /// chain: a character the style's faces miss goes to the sources' character
1234 /// lookup, as skparagraph's `defaultFallback(unicode, ..)`. It returns `false` when
1235 /// the collection and every source have no face at all.
1236 pub fn require_default_face(&mut self, attrs: FontAttrs) -> bool {
1237 if !self.faces.is_empty() {
1238 return true;
1239 }
1240 let Some(font) = self
1241 .sources
1242 .iter_mut()
1243 .find_map(|source| source.default_face(attrs))
1244 else {
1245 return false;
1246 };
1247 let id = self.faces.add(font);
1248 self.faces.default_face = Some(id);
1249 true
1250 }
1251
1252 /// `require_codepoint` makes sure a face that `families` and `attrs`
1253 /// resolve to covers `codepoint`, asking the sources for a fallback face
1254 /// when none does.
1255 ///
1256 /// It is the per-character half of [`Self::require_family`] (Skia's
1257 /// `defaultFallback(unicode, ..)`): `false` means no source covered the
1258 /// character, and the miss is recorded for [`Self::take_unanswered`].
1259 pub fn require_codepoint(
1260 &mut self,
1261 families: &[String],
1262 codepoint: char,
1263 attrs: FontAttrs,
1264 ) -> bool {
1265 if self.faces.covered_by_resolution(families, attrs, codepoint) {
1266 return true;
1267 }
1268 for index in 0..self.sources.len() {
1269 let (head, tail) = self.sources.split_at_mut(index);
1270 let _ = head;
1271 let source = &mut tail[0];
1272 if self
1273 .faces
1274 .register_fallback_answer(source.as_mut(), codepoint, attrs)
1275 {
1276 return true;
1277 }
1278 }
1279 self.unanswered.add_codepoint(codepoint, attrs);
1280 false
1281 }
1282}
1283
1284#[cfg(test)]
1285mod tests {
1286 use super::*;
1287
1288 fn fira() -> FontData {
1289 let path = concat!(
1290 env!("CARGO_MANIFEST_DIR"),
1291 "/../../assets/fonts/fira_sans.ttf"
1292 );
1293 Arc::new(std::fs::read(path).unwrap())
1294 }
1295
1296 /// A variable face's named instances are built over its one shared
1297 /// parse, each at its own coordinates — the path `parse_instances`
1298 /// takes, driven here directly because no test font is variable. The
1299 /// process rendering the glyphs tells instances apart by their
1300 /// coordinates, so every one must still name the face it came from.
1301 #[test]
1302 fn named_instances_answer_their_face_remote_id() {
1303 let shared = SharedFace::parse(fira(), 0, Some(7)).unwrap();
1304 for weight in [300.0, 700.0] {
1305 let instance = Font::shared_instance(shared.clone(), vec![(*b"wght", weight)]).unwrap();
1306 assert_eq!(instance.remote_id(), Some(7));
1307 assert_eq!(instance.variation_coordinates(), &[(*b"wght", weight)]);
1308 }
1309 }
1310}