1use std::borrow::ToOwned;
6use std::collections::HashMap;
7use std::hash::Hash;
8use std::ops::Deref;
9use std::sync::{Arc, OnceLock};
10use std::{iter, str};
11
12use app_units::Au;
13use atomic_refcell::AtomicRef;
14use bitflags::bitflags;
15use euclid::default::{Point2D, Rect};
16use euclid::num::Zero;
17use font_types::NameId;
18use fonts_traits::FontDescriptor;
19use icu_locale_core::subtags::Language;
20use icu_properties::props::{EnumeratedProperty, GeneralCategory};
21use log::debug;
22use malloc_size_of_derive::MallocSizeOf;
23use parking_lot::RwLock;
24use read_fonts::collections::int_set::Domain;
25use read_fonts::tables::fvar::Fvar;
26use read_fonts::tables::name::Name as NameTable;
27use read_fonts::tables::os2::{Os2, SelectionFlags};
28use read_fonts::types::Tag;
29use read_fonts::{FontRead, ReadError};
30use rustc_hash::FxHashMap;
31use serde::{Deserialize, Serialize};
32use servo_base::id::PainterId;
33use servo_base::text::{UnicodeBlock, UnicodeBlockMethod};
34use skrifa::string::LocalizedString;
35use smallvec::SmallVec;
36use style::Atom;
37use style::computed_values::font_optical_sizing::T as FontOpticalSizing;
38use style::computed_values::font_variant_caps;
39use style::computed_values::font_variant_position::T as FontVariantPosition;
40use style::properties::style_structs::Font as FontStyleStruct;
41use style::values::computed::font::{
42 FamilyName, FontFamilyNameSyntax, GenericFontFamily, SingleFontFamily,
43};
44use style::values::computed::{
45 FontFeatureSettings, FontStyle, FontSynthesis, FontVariantEastAsian, FontVariantLigatures,
46 FontVariantNumeric, FontWeight, FontWidth,
47};
48use unicode_script::Script;
49use webrender_api::{
50 FontInstanceFlags, FontInstanceKey, FontInstancePlatformOptions, FontVariation,
51};
52
53use crate::font_feature_values::ResolvedFontVariantAlternates;
54use crate::platform::font::{FontTable, PlatformFont};
55use crate::platform::font_list::fallback_font_families;
56use crate::{
57 EmojiPresentationPreference, FallbackFontSelectionOptions, FontContext, FontData,
58 FontDataAndIndex, FontDataError, FontIdentifier, FontTemplateDescriptor, FontTemplateRef,
59 FontTemplateRefMethods, GlyphId, LocalFontIdentifier, ShapedGlyph, ShapedText, Shaper,
60 compute_used_font_features,
61};
62
63pub(crate) const AFRC: Tag = Tag::new(b"afrc");
64pub(crate) const BASE: Tag = Tag::new(b"BASE");
65pub(crate) const CALT: Tag = Tag::new(b"calt");
66pub(crate) const CBDT: Tag = Tag::new(b"CBDT");
67pub(crate) const CLIG: Tag = Tag::new(b"clig");
68pub(crate) const COLR: Tag = Tag::new(b"COLR");
69pub(crate) const CWSH: Tag = Tag::new(b"cwsh");
70pub(crate) const FRAC: Tag = Tag::new(b"frac");
71pub(crate) const DLIG: Tag = Tag::new(b"dlig");
72pub(crate) const FVAR: Tag = Tag::new(b"fvar");
73pub(crate) const FWID: Tag = Tag::new(b"fwid");
74pub(crate) const GPOS: Tag = Tag::new(b"GPOS");
75pub(crate) const GSUB: Tag = Tag::new(b"GSUB");
76pub(crate) const HIST: Tag = Tag::new(b"hist");
77pub(crate) const HLIG: Tag = Tag::new(b"hlig");
78pub(crate) const ITAL: Tag = Tag::new(b"ital");
79pub(crate) const JP04: Tag = Tag::new(b"jp04");
80pub(crate) const JP78: Tag = Tag::new(b"jp78");
81pub(crate) const JP83: Tag = Tag::new(b"jp83");
82pub(crate) const JP90: Tag = Tag::new(b"jp90");
83pub(crate) const KERN: Tag = Tag::new(b"kern");
84pub(crate) const LIGA: Tag = Tag::new(b"liga");
85pub(crate) const LNUM: Tag = Tag::new(b"lnum");
86pub(crate) const NALT: Tag = Tag::new(b"nalt");
87pub(crate) const NAME: Tag = Tag::new(b"name");
88pub(crate) const ONUM: Tag = Tag::new(b"onum");
89pub(crate) const ORNM: Tag = Tag::new(b"ornm");
90pub(crate) const ORDN: Tag = Tag::new(b"ordn");
91pub(crate) const PNUM: Tag = Tag::new(b"pnum");
92pub(crate) const PWID: Tag = Tag::new(b"pwid");
93pub(crate) const RUBY: Tag = Tag::new(b"ruby");
94pub(crate) const SALT: Tag = Tag::new(b"salt");
95pub(crate) const SBIX: Tag = Tag::new(b"sbix");
96pub(crate) const SLNT: Tag = Tag::new(b"slnt");
97pub(crate) const SMPL: Tag = Tag::new(b"smpl");
98pub(crate) const SUBS: Tag = Tag::new(b"subs");
99pub(crate) const SUPS: Tag = Tag::new(b"sups");
100pub(crate) const SWSH: Tag = Tag::new(b"swsh");
101pub(crate) const TNUM: Tag = Tag::new(b"tnum");
102pub(crate) const TRAD: Tag = Tag::new(b"trad");
103pub(crate) const ZERO: Tag = Tag::new(b"zero");
104
105pub const LAST_RESORT_GLYPH_ADVANCE: FractionalPixel = 10.0;
106
107pub trait PlatformFontMethods: Sized {
113 #[servo_tracing::instrument(name = "PlatformFontMethods::new_from_template", skip_all)]
114 fn new_from_template(
115 template: FontTemplateRef,
116 pt_size: Option<Au>,
117 data: &Option<FontData>,
118 synthetic_bold: bool,
119 ) -> Result<PlatformFont, &'static str> {
120 let template = template.borrow();
121 let font_identifier = template.identifier.clone();
122
123 match font_identifier {
124 FontIdentifier::Local(font_identifier) => {
125 Self::new_from_local_font_identifier(font_identifier, pt_size, synthetic_bold)
126 },
127 FontIdentifier::Web(_) | FontIdentifier::ArrayBuffer(_) => Self::new_from_data(
128 font_identifier,
129 data.as_ref()
130 .expect("Should never create a web font without data."),
131 pt_size,
132 synthetic_bold,
133 ),
134 }
135 }
136
137 fn new_from_local_font_identifier(
138 font_identifier: LocalFontIdentifier,
139 pt_size: Option<Au>,
140 synthetic_bold: bool,
141 ) -> Result<PlatformFont, &'static str>;
142
143 fn new_from_data(
144 font_identifier: FontIdentifier,
145 data: &FontData,
146 pt_size: Option<Au>,
147 synthetic_bold: bool,
148 ) -> Result<PlatformFont, &'static str>;
149
150 fn copy_with_variations(
156 self,
157 _font_identifer: &FontIdentifier,
158 _variations: &[FontVariation],
159 ) -> Result<Self, &'static str>;
160
161 fn descriptor(&self) -> FontTemplateDescriptor;
164
165 fn glyph_index(&self, codepoint: char) -> Option<GlyphId>;
166 fn glyph_h_advance(&self, _: GlyphId) -> Option<FractionalPixel>;
167 fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel;
168
169 fn metrics(&self) -> FontMetrics;
170 fn table_for_tag(&self, _: Tag) -> Option<FontTable>;
171 fn typographic_bounds(&self, _: GlyphId) -> Rect<f32>;
172
173 fn webrender_font_instance_flags(&self) -> FontInstanceFlags;
175
176 fn webrender_font_instance_platform_options(&self) -> FontInstancePlatformOptions {
178 Default::default()
179 }
180
181 fn variations(&self) -> &[FontVariation];
183
184 fn descriptor_from_os2_table(os2: &Os2) -> FontTemplateDescriptor {
185 let mut style = FontStyle::NORMAL;
186 if os2.fs_selection().contains(SelectionFlags::ITALIC) {
187 style = FontStyle::ITALIC;
188 }
189
190 let weight = FontWeight::from_float(os2.us_weight_class() as f32);
191 let width = match os2.us_width_class() {
192 1 => FontWidth::ULTRA_CONDENSED,
193 2 => FontWidth::EXTRA_CONDENSED,
194 3 => FontWidth::CONDENSED,
195 4 => FontWidth::SEMI_CONDENSED,
196 5 => FontWidth::NORMAL,
197 6 => FontWidth::SEMI_EXPANDED,
198 7 => FontWidth::EXPANDED,
199 8 => FontWidth::EXTRA_EXPANDED,
200 9 => FontWidth::ULTRA_EXPANDED,
201 _ => FontWidth::NORMAL,
202 };
203
204 FontTemplateDescriptor::new(weight, width, style)
205 }
206}
207
208pub(crate) type FractionalPixel = f64;
210
211pub(crate) trait FontTableMethods {
212 fn buffer(&self) -> &[u8];
213 fn parse_as_specific_table<'a, Table>(&'a self) -> Result<Table, ReadError>
214 where
215 Table: FontRead<'a, Args = ()>,
216 {
217 Table::read(read_fonts::FontData::new(self.buffer()))
218 }
219}
220
221#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
222pub struct FontMetrics {
223 pub underline_size: Au,
224 pub underline_offset: Au,
225 pub strikeout_size: Au,
226 pub strikeout_offset: Au,
227 pub leading: Au,
228 pub x_height: Au,
229 pub em_size: Au,
230 pub ascent: Au,
231 pub descent: Au,
232 pub max_advance: Au,
233 pub average_advance: Au,
234 pub line_gap: Au,
235 pub zero_horizontal_advance: Option<Au>,
236 pub ic_horizontal_advance: Option<Au>,
237 pub space_advance: Au,
240}
241
242impl FontMetrics {
243 pub fn empty() -> Arc<Self> {
246 static EMPTY: OnceLock<Arc<FontMetrics>> = OnceLock::new();
247 EMPTY.get_or_init(Default::default).clone()
248 }
249
250 pub fn block_metrics_meaningfully_differ(&self, other: &Self) -> bool {
253 self.ascent != other.ascent ||
254 self.descent != other.descent ||
255 self.line_gap != other.line_gap
256 }
257}
258
259#[derive(Debug, Default)]
260struct CachedShapeData {
261 glyph_advances: FxHashMap<GlyphId, FractionalPixel>,
262 glyph_indices: FxHashMap<char, Option<GlyphId>>,
263 shaped_text: HashMap<ShapeCacheEntry, Arc<ShapedText>>,
264}
265
266impl malloc_size_of::MallocSizeOf for CachedShapeData {
267 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
268 let shaped_text_size = self
271 .shaped_text
272 .iter()
273 .map(|(key, value)| key.size_of(ops) + (*value).size_of(ops))
274 .sum::<usize>();
275 self.glyph_advances.size_of(ops) + self.glyph_indices.size_of(ops) + shaped_text_size
276 }
277}
278
279pub struct Font {
280 pub(crate) handle: PlatformFont,
281 pub(crate) template: FontTemplateRef,
282 pub metrics: OnceLock<Arc<FontMetrics>>,
283 pub descriptor: FontDescriptor,
284
285 data_and_index: OnceLock<FontDataAndIndex>,
288
289 shaper: OnceLock<Shaper>,
290 cached_shape_data: RwLock<CachedShapeData>,
291 font_instance_key: RwLock<FxHashMap<PainterId, FontInstanceKey>>,
292
293 pub(crate) synthesized_small_caps: Option<FontRef>,
297
298 has_color_bitmap_or_colr_table: OnceLock<bool>,
302
303 can_do_fast_shaping: OnceLock<bool>,
310
311 family_name: OnceLock<Result<Atom, NoUsableFamilyName>>,
316}
317
318#[derive(Clone)]
322struct NoUsableFamilyName;
323
324impl std::fmt::Debug for Font {
325 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326 f.debug_struct("Font")
327 .field("template", &self.template)
328 .field("descriptor", &self.descriptor)
329 .finish()
330 }
331}
332
333impl malloc_size_of::MallocSizeOf for Font {
334 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
335 let metrics_size = self.metrics.get().map_or(0, |metrics| metrics.size_of(ops));
339 metrics_size +
340 self.descriptor.size_of(ops) +
341 self.cached_shape_data.read().size_of(ops) +
342 self.font_instance_key
343 .read()
344 .values()
345 .map(|key| key.size_of(ops))
346 .sum::<usize>()
347 }
348}
349
350impl Font {
351 pub fn new(
352 template: FontTemplateRef,
353 descriptor: FontDescriptor,
354 data: Option<FontData>,
355 synthesized_small_caps: Option<FontRef>,
356 ) -> Result<Font, &'static str> {
357 let synthetic_bold = {
358 let is_bold = descriptor.weight >= FontWeight::BOLD_THRESHOLD;
359 let allows_synthetic_bold = matches!(descriptor.synthesis_weight, FontSynthesis::Auto);
360
361 is_bold && allows_synthetic_bold
362 };
363
364 let handle = PlatformFont::new_from_template(
365 template.clone(),
366 Some(descriptor.pt_size),
367 &data,
368 synthetic_bold,
369 )?;
370 let variation_axes = VariationAxes::from_platform_font(&handle);
371
372 let handle = if servo_config::pref!(layout_css_font_variations_enabled) &&
374 variation_axes.contains(VariationAxes::IS_VARIABLE)
375 {
376 let used_variations = compute_variations(&descriptor, &template, variation_axes);
377 handle.copy_with_variations(&template.identifier(), &used_variations)?
378 } else {
379 handle
380 };
381
382 Ok(Font {
383 handle,
384 template,
385 metrics: OnceLock::new(),
386 descriptor,
387 data_and_index: data
388 .map(|data| OnceLock::from(FontDataAndIndex { data, index: 0 }))
389 .unwrap_or_default(),
390 shaper: OnceLock::new(),
391 cached_shape_data: Default::default(),
392 font_instance_key: Default::default(),
393 synthesized_small_caps,
394 has_color_bitmap_or_colr_table: OnceLock::new(),
395 can_do_fast_shaping: OnceLock::new(),
396 family_name: Default::default(),
397 })
398 }
399
400 pub fn identifier(&self) -> AtomicRef<'_, FontIdentifier> {
402 self.template.identifier()
403 }
404
405 pub fn metrics(&self) -> &Arc<FontMetrics> {
406 self.metrics.get_or_init(|| Arc::new(self.handle.metrics()))
407 }
408
409 pub(crate) fn webrender_font_instance_flags(&self) -> FontInstanceFlags {
410 self.handle.webrender_font_instance_flags()
411 }
412
413 pub(crate) fn webrender_font_instance_platform_options(&self) -> FontInstancePlatformOptions {
414 self.handle.webrender_font_instance_platform_options()
415 }
416
417 pub(crate) fn has_color_bitmap_or_colr_table(&self) -> bool {
418 *self.has_color_bitmap_or_colr_table.get_or_init(|| {
419 self.table_for_tag(SBIX).is_some() ||
420 self.table_for_tag(CBDT).is_some() ||
421 self.table_for_tag(COLR).is_some()
422 })
423 }
424
425 pub fn key(&self, painter_id: PainterId, font_context: &FontContext) -> FontInstanceKey {
426 *self
427 .font_instance_key
428 .write()
429 .entry(painter_id)
430 .or_insert_with(|| font_context.create_font_instance_key(self, painter_id))
431 }
432
433 pub fn font_data_and_index(&self) -> Result<&FontDataAndIndex, FontDataError> {
436 if let Some(data_and_index) = self.data_and_index.get() {
437 return Ok(data_and_index);
438 }
439
440 let FontIdentifier::Local(local_font_identifier) = &*self.identifier() else {
441 unreachable!("All web fonts should already have initialized data");
442 };
443 let Some(data_and_index) = local_font_identifier.font_data_and_index() else {
444 return Err(FontDataError::FailedToLoad);
445 };
446
447 let data_and_index = self.data_and_index.get_or_init(move || data_and_index);
448 Ok(data_and_index)
449 }
450
451 pub(crate) fn variations(&self) -> &[FontVariation] {
452 self.handle.variations()
453 }
454}
455
456bitflags! {
457 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
458 pub struct ShapingFlags: u8 {
459 const DISABLE_KERNING_SHAPING_FLAG = 1 << 3;
461 const RTL_FLAG = 1 << 4;
463 const KEEP_ALL_FLAG = 1 << 5;
465 }
466}
467
468#[derive(Clone, Debug, Eq, Hash, PartialEq)]
470pub struct ShapingOptions {
471 pub letter_spacing: Au,
476 pub word_spacing: Au,
478 pub script: Script,
480 pub language: Atom,
482 pub language_override: Option<Tag>,
485 pub ligatures: FontVariantLigatures,
487 pub numeric: FontVariantNumeric,
489 pub east_asian: FontVariantEastAsian,
491 pub feature_settings: FontFeatureSettings,
493 pub position: FontVariantPosition,
495 pub alternates: ResolvedFontVariantAlternates,
497 pub flags: ShapingFlags,
499}
500
501impl ShapingOptions {
502 pub(crate) fn letter_spacing_for_character(&self, character: char) -> Au {
503 if GeneralCategory::for_char(character) == GeneralCategory::Format {
507 return Au::zero();
508 }
509 self.letter_spacing
510 }
511}
512
513#[derive(Clone, Debug, Eq, Hash, PartialEq)]
515struct ShapeCacheEntry {
516 text: String,
517 letter_spacing: Au,
518 word_spacing: Au,
519 script: Script,
520 language: Atom,
521 language_override: Option<Tag>,
522 font_features: Box<[(Tag, u32)]>,
523 flags: ShapingFlags,
524}
525
526impl Font {
527 #[servo_tracing::instrument(name = "Font::shape_text", skip_all)]
528 pub fn shape_text(&self, text: &str, options: &ShapingOptions) -> Arc<ShapedText> {
529 let font_features =
530 compute_used_font_features(options, self.template.borrow().font_face_rule.as_deref())
531 .collect();
532 let lookup_key = ShapeCacheEntry {
533 text: text.to_owned(),
534 letter_spacing: options.letter_spacing,
535 word_spacing: options.word_spacing,
536 script: options.script,
537 language: options.language.clone(),
538 language_override: options.language_override,
539 flags: options.flags,
540 font_features,
541 };
542
543 if let Some(shaped_text) = self.cached_shape_data.read().shaped_text.get(&lookup_key) {
544 return shaped_text.clone();
545 }
546
547 let glyphs = if self.can_do_fast_shaping(text, options) {
548 debug!("shape_text: Using ASCII fast path.");
549 self.shape_text_fast(text, options)
550 } else {
551 debug!("shape_text: Using Harfbuzz.");
552 self.shaper.get_or_init(|| Shaper::new(self)).shape_text(
553 text,
554 options,
555 &lookup_key.font_features,
556 )
557 };
558
559 let shaped_text = Arc::new(glyphs);
560 let mut cache = self.cached_shape_data.write();
561 cache.shaped_text.insert(lookup_key, shaped_text.clone());
562
563 shaped_text
564 }
565
566 pub fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool {
571 options.script == Script::Latin &&
572 !options.flags.contains(ShapingFlags::RTL_FLAG) &&
573 *self.can_do_fast_shaping.get_or_init(|| {
574 self.table_for_tag(KERN).is_some() &&
575 self.table_for_tag(GPOS).is_none() &&
576 self.table_for_tag(GSUB).is_none()
577 }) &&
578 text.is_ascii()
579 }
580
581 fn shape_text_fast(&self, text: &str, options: &ShapingOptions) -> ShapedText {
583 let mut glyph_store = ShapedText::new(text.len(), false );
584 let mut prev_glyph_id = None;
585 for (string_byte_offset, byte) in text.bytes().enumerate() {
586 let character = byte as char;
587 let Some(glyph_id) = self.glyph_index(character) else {
588 continue;
589 };
590
591 let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id));
592 let offset = prev_glyph_id.map(|prev| {
593 let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id));
594 advance += h_kerning;
595 Point2D::new(h_kerning, Au::zero())
596 });
597
598 let mut glyph = ShapedGlyph {
599 glyph_id,
600 string_byte_offset,
601 advance,
602 offset,
603 };
604 glyph.adjust_for_character(character, options);
605
606 glyph_store.add_glyph(character, &glyph);
607 prev_glyph_id = Some(glyph_id);
608 }
609 glyph_store
610 }
611
612 pub(crate) fn table_for_tag(&self, tag: Tag) -> Option<FontTable> {
613 let result = self.handle.table_for_tag(tag);
614 let status = if result.is_some() {
615 "Found"
616 } else {
617 "Didn't find"
618 };
619
620 debug!(
621 "{} font table[{}] in {:?},",
622 status,
623 str::from_utf8(tag.as_ref()).unwrap(),
624 self.identifier()
625 );
626 result
627 }
628
629 #[inline]
630 pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
631 {
632 let cache = self.cached_shape_data.read();
633 if let Some(glyph) = cache.glyph_indices.get(&codepoint) {
634 return *glyph;
635 }
636 }
637 let codepoint = match self.descriptor.variant {
638 font_variant_caps::T::SmallCaps => codepoint.to_ascii_uppercase(),
639 font_variant_caps::T::Normal => codepoint,
640 font_variant_caps::T::AllSmallCaps |
643 font_variant_caps::T::PetiteCaps |
644 font_variant_caps::T::AllPetiteCaps |
645 font_variant_caps::T::Unicase |
646 font_variant_caps::T::TitlingCaps => unreachable!(),
647 };
648 let glyph_index = self.handle.glyph_index(codepoint);
649
650 let mut cache = self.cached_shape_data.write();
651 cache.glyph_indices.insert(codepoint, glyph_index);
652 glyph_index
653 }
654
655 pub fn has_glyph_for(&self, codepoint: char) -> bool {
656 self.glyph_index(codepoint).is_some()
657 }
658
659 pub(crate) fn glyph_h_kerning(
660 &self,
661 first_glyph: GlyphId,
662 second_glyph: GlyphId,
663 ) -> FractionalPixel {
664 self.handle.glyph_h_kerning(first_glyph, second_glyph)
665 }
666
667 pub fn glyph_h_advance(&self, glyph_id: GlyphId) -> FractionalPixel {
668 {
669 let cache = self.cached_shape_data.read();
670 if let Some(width) = cache.glyph_advances.get(&glyph_id) {
671 return *width;
672 }
673 }
674
675 let new_width = self
676 .handle
677 .glyph_h_advance(glyph_id)
678 .unwrap_or(LAST_RESORT_GLYPH_ADVANCE as FractionalPixel);
679 let mut cache = self.cached_shape_data.write();
680 cache.glyph_advances.insert(glyph_id, new_width);
681 new_width
682 }
683
684 pub fn typographic_bounds(&self, glyph_id: GlyphId) -> Rect<f32> {
685 self.handle.typographic_bounds(glyph_id)
686 }
687
688 pub fn baseline(&self) -> Option<FontBaseline> {
690 self.shaper.get_or_init(|| Shaper::new(self)).baseline()
691 }
692
693 #[cfg(not(target_os = "macos"))]
694 pub(crate) fn find_fallback_using_system_font_api(
695 &self,
696 _: &FallbackFontSelectionOptions,
697 ) -> Option<FontRef> {
698 None
699 }
700
701 fn get_family_name_from_font_data(&self) -> Result<Atom, NoUsableFamilyName> {
702 let name_table = self.table_for_tag(NAME).ok_or(NoUsableFamilyName)?;
703 let name_table = NameTable::read(read_fonts::FontData::new(name_table.buffer()))
704 .map_err(|_| NoUsableFamilyName)?;
705
706 let mut best_rank = -1;
712 let mut best_string = None;
713 for (index, name_record) in name_table
714 .name_record()
715 .iter()
716 .filter(|name_record| name_record.name_id() == NameId::FAMILY_NAME)
717 .enumerate()
718 {
719 let localized_string = LocalizedString::new(&name_table, name_record);
720 let rank = match (index, localized_string.language()) {
721 (_, Some("en-US")) => {
722 best_string = Some(localized_string);
723 break;
724 },
725 (_, Some("en")) => 2,
726 (_, None) => 1,
727 (0, _) => 0,
728 _ => continue,
729 };
730 if rank > best_rank {
731 best_rank = rank;
732 best_string = Some(localized_string);
733 }
734 }
735
736 best_string
737 .map(|best_string| best_string.chars().collect::<String>().into())
738 .ok_or(NoUsableFamilyName)
739 }
740
741 pub fn family_name(&self) -> Option<Atom> {
746 self.template
747 .font_face_rule()
748 .and_then(|font_face_rule| {
749 AtomicRef::filter_map(font_face_rule, |rule| rule.descriptors.font_family.as_ref())
750 })
751 .map(|font_family| font_family.name.clone())
752 .or_else(|| {
753 self.family_name
754 .get_or_init(|| self.get_family_name_from_font_data())
755 .clone()
756 .ok()
757 })
758 }
759}
760
761#[derive(Clone, Debug, MallocSizeOf)]
762pub struct FontRef(#[conditional_malloc_size_of] pub(crate) Arc<Font>);
763
764impl PartialEq for FontRef {
765 fn eq(&self, other: &Self) -> bool {
766 Arc::ptr_eq(self, other)
767 }
768}
769
770impl Deref for FontRef {
771 type Target = Arc<Font>;
772 fn deref(&self) -> &Self::Target {
773 &self.0
774 }
775}
776
777#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
778pub struct FallbackKey {
779 script: Script,
780 unicode_block: Option<UnicodeBlock>,
781 language: Language,
782}
783
784impl FallbackKey {
785 fn new(options: &FallbackFontSelectionOptions) -> Self {
786 Self {
787 script: Script::from(options.character),
788 unicode_block: options.character.block(),
789 language: options.language,
790 }
791 }
792}
793
794#[derive(MallocSizeOf)]
798pub struct FontGroup {
799 descriptor: FontDescriptor,
802 families: SmallVec<[FontGroupFamily; 8]>,
805 fallbacks: RwLock<HashMap<FallbackKey, FontRef>>,
810}
811
812impl FontGroup {
813 pub(crate) fn new(style: &FontStyleStruct, descriptor: FontDescriptor) -> FontGroup {
814 let families: SmallVec<[FontGroupFamily; 8]> = style
815 .font_family
816 .families
817 .iter()
818 .map(FontGroupFamily::local_or_web)
819 .collect();
820
821 FontGroup {
822 descriptor,
823 families,
824 fallbacks: Default::default(),
825 }
826 }
827
828 pub fn find_by_codepoint(
833 &self,
834 font_context: &FontContext,
835 codepoint: char,
836 next_codepoint: Option<char>,
837 language: Language,
838 ) -> Option<FontRef> {
839 let codepoint = match codepoint {
843 '\t' => ' ',
844 _ => codepoint,
845 };
846
847 let options = FallbackFontSelectionOptions::new(codepoint, next_codepoint, language);
848
849 let should_look_for_small_caps = self.descriptor.variant == font_variant_caps::T::SmallCaps &&
850 options.character.is_ascii_lowercase();
851 let font_or_synthesized_small_caps = |font: FontRef| {
852 if should_look_for_small_caps && font.synthesized_small_caps.is_some() {
853 return font.synthesized_small_caps.clone();
854 }
855 Some(font)
856 };
857
858 let font_has_glyph_and_presentation = |font: &FontRef| {
859 match options.presentation_preference {
861 EmojiPresentationPreference::Text if font.has_color_bitmap_or_colr_table() => {
862 return false;
863 },
864 EmojiPresentationPreference::Emoji if !font.has_color_bitmap_or_colr_table() => {
865 return false;
866 },
867 _ => {},
868 }
869 font.has_glyph_for(options.character)
870 };
871
872 let char_in_template =
873 |template: FontTemplateRef| template.char_in_unicode_range(options.character);
874
875 if let Some(font) = self.find(
876 font_context,
877 &char_in_template,
878 &font_has_glyph_and_presentation,
879 ) {
880 return font_or_synthesized_small_caps(font);
881 }
882
883 let fallback_key = FallbackKey::new(&options);
884 if let Some(fallback) = self.fallbacks.read().get(&fallback_key) &&
885 char_in_template(fallback.template.clone()) &&
886 font_has_glyph_and_presentation(fallback)
887 {
888 return font_or_synthesized_small_caps(fallback.clone());
889 }
890
891 if let Some(font) = self.find_fallback_using_system_font_list(
892 font_context,
893 options.clone(),
894 &char_in_template,
895 &font_has_glyph_and_presentation,
896 ) {
897 let fallback = font_or_synthesized_small_caps(font);
898 if let Some(fallback) = fallback.clone() {
899 self.fallbacks.write().insert(fallback_key, fallback);
900 }
901 return fallback;
902 }
903
904 let first_font = self.first(font_context);
905 if let Some(fallback) = first_font
906 .as_ref()
907 .and_then(|font| font.find_fallback_using_system_font_api(&options)) &&
908 font_has_glyph_and_presentation(&fallback)
909 {
910 return Some(fallback);
911 }
912
913 first_font
914 }
915
916 pub fn first(&self, font_context: &FontContext) -> Option<FontRef> {
918 let space_in_template = |template: FontTemplateRef| template.char_in_unicode_range(' ');
926 let font_predicate = |_: &FontRef| true;
927 self.find(font_context, &space_in_template, &font_predicate)
928 .or_else(|| {
929 self.find_fallback_using_system_font_list(
930 font_context,
931 FallbackFontSelectionOptions::default(),
932 &space_in_template,
933 &font_predicate,
934 )
935 })
936 }
937
938 fn find(
942 &self,
943 font_context: &FontContext,
944 template_predicate: &impl Fn(FontTemplateRef) -> bool,
945 font_predicate: &impl Fn(&FontRef) -> bool,
946 ) -> Option<FontRef> {
947 self.families
948 .iter()
949 .flat_map(|family| family.templates(font_context, &self.descriptor))
950 .find_map(|template| {
951 template.font_if_matches(
952 font_context,
953 &self.descriptor,
954 template_predicate,
955 font_predicate,
956 )
957 })
958 }
959
960 fn find_fallback_using_system_font_list(
966 &self,
967 font_context: &FontContext,
968 options: FallbackFontSelectionOptions,
969 template_predicate: &impl Fn(FontTemplateRef) -> bool,
970 font_predicate: &impl Fn(&FontRef) -> bool,
971 ) -> Option<FontRef> {
972 iter::once(FontFamilyDescriptor::default())
973 .chain(
974 fallback_font_families(options)
975 .into_iter()
976 .map(|family_name| {
977 let family = SingleFontFamily::FamilyName(FamilyName {
978 name: family_name.into(),
979 syntax: FontFamilyNameSyntax::Quoted,
980 });
981 FontFamilyDescriptor::new(family, FontSearchScope::Local)
982 }),
983 )
984 .find_map(|family_descriptor| {
985 FontGroupFamily::from(family_descriptor)
986 .templates(font_context, &self.descriptor)
987 .find_map(|template| {
988 template.font_if_matches(
989 font_context,
990 &self.descriptor,
991 template_predicate,
992 font_predicate,
993 )
994 })
995 })
996 }
997}
998
999#[derive(MallocSizeOf)]
1006struct FontGroupFamilyTemplate {
1007 #[ignore_malloc_size_of = "This measured in the FontContext template cache."]
1008 template: FontTemplateRef,
1009 #[ignore_malloc_size_of = "This measured in the FontContext font cache."]
1010 font: OnceLock<Option<FontRef>>,
1011}
1012
1013impl From<FontTemplateRef> for FontGroupFamilyTemplate {
1014 fn from(template: FontTemplateRef) -> Self {
1015 Self {
1016 template,
1017 font: Default::default(),
1018 }
1019 }
1020}
1021
1022impl FontGroupFamilyTemplate {
1023 fn font(
1024 &self,
1025 font_context: &FontContext,
1026 font_descriptor: &FontDescriptor,
1027 ) -> Option<FontRef> {
1028 self.font
1029 .get_or_init(|| font_context.font(self.template.clone(), font_descriptor))
1030 .clone()
1031 }
1032
1033 fn font_if_matches(
1034 &self,
1035 font_context: &FontContext,
1036 font_descriptor: &FontDescriptor,
1037 template_predicate: &impl Fn(FontTemplateRef) -> bool,
1038 font_predicate: &impl Fn(&FontRef) -> bool,
1039 ) -> Option<FontRef> {
1040 if !template_predicate(self.template.clone()) {
1041 return None;
1042 }
1043 self.font(font_context, font_descriptor)
1044 .filter(font_predicate)
1045 }
1046}
1047
1048#[derive(MallocSizeOf)]
1053struct FontGroupFamily {
1054 family_descriptor: FontFamilyDescriptor,
1055 members: OnceLock<Vec<FontGroupFamilyTemplate>>,
1056}
1057
1058impl From<FontFamilyDescriptor> for FontGroupFamily {
1059 fn from(family_descriptor: FontFamilyDescriptor) -> Self {
1060 Self {
1061 family_descriptor,
1062 members: Default::default(),
1063 }
1064 }
1065}
1066
1067impl FontGroupFamily {
1068 fn local_or_web(family: &SingleFontFamily) -> FontGroupFamily {
1069 FontFamilyDescriptor::new(family.clone(), FontSearchScope::Any).into()
1070 }
1071
1072 fn templates(
1073 &self,
1074 font_context: &FontContext,
1075 font_descriptor: &FontDescriptor,
1076 ) -> impl Iterator<Item = &FontGroupFamilyTemplate> {
1077 self.members
1078 .get_or_init(|| {
1079 font_context
1080 .matching_templates(font_descriptor, &self.family_descriptor)
1081 .into_iter()
1082 .map(Into::into)
1083 .collect()
1084 })
1085 .iter()
1086 }
1087}
1088
1089#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
1091pub enum FontSearchScope {
1092 Any,
1094
1095 Local,
1097}
1098
1099#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
1101pub struct FontFamilyDescriptor {
1102 pub(crate) family: SingleFontFamily,
1103 pub(crate) scope: FontSearchScope,
1104}
1105
1106impl FontFamilyDescriptor {
1107 pub fn new(family: SingleFontFamily, scope: FontSearchScope) -> FontFamilyDescriptor {
1108 FontFamilyDescriptor { family, scope }
1109 }
1110
1111 fn default() -> FontFamilyDescriptor {
1112 FontFamilyDescriptor {
1113 family: SingleFontFamily::Generic(GenericFontFamily::None),
1114 scope: FontSearchScope::Local,
1115 }
1116 }
1117}
1118
1119pub struct FontBaseline {
1120 pub ideographic_baseline: f32,
1121 pub alphabetic_baseline: f32,
1122 pub hanging_baseline: f32,
1123}
1124
1125#[cfg(all(
1141 any(target_os = "linux", target_os = "macos", target_os = "freebsd"),
1142 not(target_env = "ohos")
1143))]
1144pub(crate) fn map_platform_values_to_style_values(mapping: &[(f64, f64)], value: f64) -> f64 {
1145 if value < mapping[0].0 {
1146 return mapping[0].1;
1147 }
1148
1149 for window in mapping.windows(2) {
1150 let (font_config_value_a, css_value_a) = window[0];
1151 let (font_config_value_b, css_value_b) = window[1];
1152
1153 if value >= font_config_value_a && value <= font_config_value_b {
1154 let ratio = (value - font_config_value_a) / (font_config_value_b - font_config_value_a);
1155 return css_value_a + ((css_value_b - css_value_a) * ratio);
1156 }
1157 }
1158
1159 mapping[mapping.len() - 1].1
1160}
1161
1162fn compute_variations(
1164 descriptor: &FontDescriptor,
1165 template: &FontTemplateRef,
1166 variation_axes: VariationAxes,
1167) -> Vec<FontVariation> {
1168 let font_face_rule = template.font_face_rule();
1169
1170 let mut variations: Vec<FontVariation> = vec![];
1172
1173 let mut add_variation = |variation: FontVariation| {
1174 if !variations
1175 .iter()
1176 .any(|existing_variation| existing_variation.tag == variation.tag)
1177 {
1178 variations.push(variation);
1179 }
1180 };
1181
1182 descriptor
1186 .variation_settings
1187 .iter()
1188 .copied()
1189 .for_each(&mut add_variation);
1190
1191 if let Some(font_face_rule) = &font_face_rule {
1197 if let Some(variation_settings) =
1200 font_face_rule.descriptors.font_variation_settings.as_ref()
1201 {
1202 variation_settings
1203 .0
1204 .iter()
1205 .map(|variation| FontVariation {
1206 tag: variation.tag.0,
1207 value: variation.value.get().expect(
1208 "The value is enforced to be resolvable at parse time \
1209 (see FontVariationSettings::parse_for_font_face_rule).",
1210 ),
1211 })
1212 .for_each(&mut add_variation);
1213 }
1214 }
1215
1216 add_variation(FontVariation {
1227 tag: Tag::new(b"wght").to_u32(),
1228 value: descriptor.weight.value(),
1229 });
1230
1231 add_variation(FontVariation {
1232 tag: Tag::new(b"wdth").to_u32(),
1233 value: descriptor.width.0.to_float(),
1234 });
1235
1236 if variation_axes.intersects(VariationAxes::ITAL | VariationAxes::SLNT) {
1237 let clamped_font_style = font_face_rule
1238 .as_ref()
1239 .and_then(|font_face_rule| font_face_rule.descriptors.font_style.as_ref())
1240 .map(|font_style_range| {
1241 let computed_font_style_range =
1242 font_style_range.compute().expect("never returns None");
1243
1244 if computed_font_style_range.0 == FontStyle::ITALIC {
1245 debug_assert_eq!(computed_font_style_range.1, FontStyle::ITALIC);
1246 return FontStyle::ITALIC;
1247 }
1248 debug_assert_ne!(computed_font_style_range.1, FontStyle::ITALIC);
1249
1250 let specified_angle = if descriptor.style == FontStyle::ITALIC {
1251 FontStyle::DEFAULT_OBLIQUE_DEGREES as f32
1252 } else {
1253 descriptor.style.oblique_degrees()
1254 };
1255
1256 let clamped_angle = specified_angle
1257 .min(computed_font_style_range.1.oblique_degrees())
1258 .max(computed_font_style_range.0.oblique_degrees());
1259 FontStyle::oblique(clamped_angle)
1260 })
1261 .unwrap_or(descriptor.style);
1262
1263 let use_ital_axis = (variation_axes.contains(VariationAxes::ITAL) &&
1269 clamped_font_style == FontStyle::ITALIC) ||
1270 !variation_axes.contains(VariationAxes::SLNT);
1271 if use_ital_axis {
1272 add_variation(FontVariation {
1273 tag: ITAL.to_u32(),
1274 value: (clamped_font_style != FontStyle::NORMAL) as u32 as f32,
1275 });
1276 } else {
1277 if clamped_font_style == FontStyle::ITALIC {
1280 add_variation(FontVariation {
1281 tag: SLNT.to_u32(),
1282 value: (-FontStyle::DEFAULT_OBLIQUE_DEGREES) as f32,
1283 });
1284 } else {
1285 add_variation(FontVariation {
1286 tag: SLNT.to_u32(),
1287 value: -clamped_font_style.oblique_degrees(),
1288 });
1289 }
1290 }
1291 }
1292
1293 if descriptor.optical_sizing == FontOpticalSizing::Auto {
1295 add_variation(FontVariation {
1296 tag: Tag::new(b"opsz").to_u32(),
1297 value: descriptor.pt_size.to_f32_px(),
1298 });
1299 }
1300
1301 variations
1302}
1303
1304bitflags! {
1305 #[derive(Clone, Copy, Debug)]
1306 struct VariationAxes: u8 {
1307 const IS_VARIABLE = 1;
1309
1310 const ITAL = 1 << 1;
1314
1315 const SLNT = 1 << 2;
1319 }
1320}
1321
1322impl VariationAxes {
1323 fn from_platform_font(platform_font: &PlatformFont) -> Self {
1324 let Some(fvar_table) = platform_font.table_for_tag(FVAR) else {
1325 return VariationAxes::empty();
1327 };
1328
1329 let Some(variation_axes) = fvar_table
1330 .parse_as_specific_table::<Fvar<'_>>()
1331 .ok()
1332 .and_then(|fvar: Fvar<'_>| fvar.axis_instance_arrays().ok())
1333 .map(|instance_arrays| instance_arrays.axes())
1334 else {
1335 return VariationAxes::empty();
1337 };
1338
1339 if variation_axes.is_empty() {
1340 return VariationAxes::empty();
1341 }
1342
1343 let mut result = VariationAxes::IS_VARIABLE;
1344 for axis in variation_axes {
1345 match axis.axis_tag() {
1346 ITAL => result |= VariationAxes::ITAL,
1347 SLNT => result |= VariationAxes::SLNT,
1348 _ => {},
1349 }
1350 }
1351
1352 result
1353 }
1354}