Skip to main content

lichtung_plot/font/
canonical.rs

1// This is the private T5a3 integration surface; later text planning consumes it.
2#![allow(dead_code)]
3
4use std::borrow::Cow;
5use std::cmp::Ordering;
6use std::fmt::Write as _;
7use std::fs::{self, File};
8use std::io::Read;
9use std::path::{Path, PathBuf};
10use std::str::FromStr;
11use std::sync::{Arc, Mutex, RwLock, Weak};
12
13use fontdb::{Database, Family, Source, Stretch, Style, ID};
14use sha2::{Digest, Sha256};
15use unicode_properties::UnicodeGeneralCategory;
16use unicode_segmentation::UnicodeSegmentation;
17
18use crate::text::{is_nonpainting_control, is_nonrendering_mandatory_break};
19
20mod admission;
21mod index;
22use admission::FontScanIssue;
23
24#[cfg(test)]
25thread_local! {
26    pub(crate) static FONT_DISCOVERY_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
27    pub(crate) static FONT_PAIR_RESOLUTION_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
28    static FONT_NORMALIZATION_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
29    pub(crate) static FONT_SELECTION_PROBES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
30    pub(crate) static FONT_SOURCE_ADMISSIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
31    pub(crate) static FONT_FINAL_SEALS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
32    pub(crate) static FONT_SHAPE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
33    pub(crate) static FONT_OUTLINE_GLYPHS: std::cell::RefCell<Vec<(FaceIdentity, u16)>> = const { std::cell::RefCell::new(Vec::new()) };
34    pub(crate) static FONT_METRIC_QUERIES: std::cell::RefCell<Vec<FaceIdentity>> = const { std::cell::RefCell::new(Vec::new()) };
35    static LOAD_OBSERVATIONS: std::cell::RefCell<LoadObservations> = std::cell::RefCell::new(LoadObservations::default());
36}
37
38#[cfg(test)]
39#[derive(Debug, Default, Clone, PartialEq, Eq)]
40struct LoadObservations {
41    metadata_bytes: std::collections::BTreeMap<PathBuf, usize>,
42    full_bytes: usize,
43    hash_bytes: usize,
44    materialized: Vec<(PathBuf, usize)>,
45    face_checks: Vec<(PathBuf, u32)>,
46    frozen_files: Vec<(PathBuf, usize)>,
47}
48
49#[cfg(test)]
50pub(crate) fn planning_counts() -> [usize; 6] {
51    [
52        FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
53        FONT_PAIR_RESOLUTION_CALLS.with(std::cell::Cell::get),
54        FONT_SELECTION_PROBES.with(std::cell::Cell::get),
55        FONT_SOURCE_ADMISSIONS.with(std::cell::Cell::get),
56        FONT_FINAL_SEALS.with(std::cell::Cell::get),
57        FONT_SHAPE_CALLS.with(std::cell::Cell::get),
58    ]
59}
60
61const SCALAR_MAP_WORDS: usize = 0x11_0000 / u64::BITS as usize;
62
63/// Census producers can lend text or defer formatting until root preparation.
64pub(crate) enum CensusSource<'a> {
65    Text(Cow<'a, str>),
66    Formatted(std::fmt::Arguments<'a>),
67}
68
69impl<'a> From<Cow<'a, str>> for CensusSource<'a> {
70    fn from(source: Cow<'a, str>) -> Self {
71        Self::Text(source)
72    }
73}
74impl<'a> From<&'a str> for CensusSource<'a> {
75    fn from(source: &'a str) -> Self {
76        Self::Text(Cow::Borrowed(source))
77    }
78}
79impl<'a> From<&'a String> for CensusSource<'a> {
80    fn from(source: &'a String) -> Self {
81        Self::Text(Cow::Borrowed(source))
82    }
83}
84impl From<String> for CensusSource<'_> {
85    fn from(source: String) -> Self {
86        Self::Text(Cow::Owned(source))
87    }
88}
89impl<'a> From<std::fmt::Arguments<'a>> for CensusSource<'a> {
90    fn from(source: std::fmt::Arguments<'a>) -> Self {
91        Self::Formatted(source)
92    }
93}
94
95#[derive(Default)]
96struct CensusFormatCount {
97    bytes: usize,
98}
99
100impl std::fmt::Write for CensusFormatCount {
101    fn write_str(&mut self, text: &str) -> std::fmt::Result {
102        self.bytes = self.bytes.checked_add(text.len()).ok_or(std::fmt::Error)?;
103        Ok(())
104    }
105}
106
107pub(crate) fn format_census_source(
108    arguments: std::fmt::Arguments<'_>,
109    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
110) -> Result<String, FontError> {
111    struct ReservedOutput<'a> {
112        output: &'a mut String,
113        length: usize,
114    }
115    impl std::fmt::Write for ReservedOutput<'_> {
116        fn write_str(&mut self, text: &str) -> std::fmt::Result {
117            if text.len() > self.length.saturating_sub(self.output.len()) {
118                return Err(std::fmt::Error);
119            }
120            self.output.push_str(text);
121            Ok(())
122        }
123    }
124    #[cfg(not(test))]
125    if prepared_stage.is_none() {
126        return Err(FontError::Reservation(
127            "production census formatting requires the root prepared stage".into(),
128        ));
129    }
130    let mut count = CensusFormatCount::default();
131    count
132        .write_fmt(arguments)
133        .map_err(|_| FontError::Arithmetic("formatted census source count"))?;
134
135    let mut output = String::new();
136    reserve_string_prepared_or_local(
137        &mut output,
138        count.bytes,
139        "formatted census source",
140        prepared_stage,
141    )?;
142    ReservedOutput {
143        output: &mut output,
144        length: count.bytes,
145    }
146    .write_fmt(arguments)
147    .map_err(|_| FontError::Arithmetic("formatted census source materialization"))?;
148    if output.len() != count.bytes {
149        return Err(FontError::Arithmetic(
150            "formatted census source count/materialization mismatch",
151        ));
152    }
153    Ok(output)
154}
155
156#[derive(Debug, thiserror::Error)]
157pub(crate) enum FontError {
158    #[error("font preflight arithmetic overflow while calculating {0}")]
159    Arithmetic(&'static str),
160    #[error("font preflight allocation refused for {0}")]
161    Allocation(&'static str),
162    #[error("{0}")]
163    Reservation(String),
164    #[error("{operation} '{path}': {source}")]
165    Io {
166        operation: &'static str,
167        path: PathBuf,
168        source: std::io::Error,
169    },
170    #[error("font source changed during indexing or materialization: '{0}'")]
171    ChangedFile(PathBuf),
172    #[error("cannot parse fontconfig file '{path}': {reason}")]
173    ParseFontConfig { path: PathBuf, reason: String },
174    #[error("cannot parse face index {index} in '{path}': {reason}")]
175    ParseFace {
176        path: PathBuf,
177        index: u32,
178        reason: String,
179    },
180    #[error("{context}: {source}")]
181    Admission {
182        context: String,
183        #[source]
184        source: Box<Self>,
185    },
186    #[error("font candidate list is empty for pair {pair_ordinal}")]
187    MissingFamily { pair_ordinal: u32 },
188    #[error("font candidates for pair {pair_ordinal} do not contain U+{scalar:04X}")]
189    MissingGlyph { pair_ordinal: u32, scalar: u32 },
190    #[error("font pair {pair_ordinal} was prepared more than once")]
191    DuplicatePreparedPair { pair_ordinal: u32 },
192    #[error("font pair {pair_ordinal} was prepared after the root's fonts were sealed")]
193    PreparedPairAfterSeal { pair_ordinal: u32 },
194    #[error("font operation is already sealed")]
195    OperationSealed,
196    #[error("frozen text does not match admitted font pair {pair_ordinal}")]
197    UnadmittedText { pair_ordinal: u32 },
198    #[error("font unit was not admitted in pair {pair_ordinal}")]
199    UnknownUnit { pair_ordinal: u32 },
200    #[error("unsupported text control U+{scalar:04X}")]
201    UnsupportedControl { scalar: u32 },
202    #[error("face {identity:?} has invalid design metrics")]
203    InvalidMetrics { identity: FaceIdentity },
204    #[error("shape face {identity:?}: {reason}")]
205    Shape {
206        identity: FaceIdentity,
207        reason: &'static str,
208    },
209    #[error("outline glyph {glyph_id} from face {identity:?}: {reason}")]
210    Outline {
211        identity: FaceIdentity,
212        glyph_id: u16,
213        reason: &'static str,
214    },
215    #[error("selected glyph {glyph_id} from face {identity:?} requires unsupported {paint:?} paint without a usable outline")]
216    UnsupportedGlyphPaint {
217        identity: FaceIdentity,
218        glyph_id: u16,
219        paint: GlyphPaint,
220    },
221    #[error("canonical font environment synchronization was poisoned")]
222    Synchronization,
223}
224
225#[derive(Debug)]
226struct FontPreparation {
227    operation: OperationContext,
228    normalized_stacks: Vec<NormalizedStack>,
229}
230
231#[derive(Debug)]
232struct NormalizedStack {
233    source: FontStack,
234    names: Vec<String>,
235}
236
237impl FontPreparation {
238    fn new() -> Self {
239        Self {
240            operation: OperationContext::new(),
241            normalized_stacks: Vec::new(),
242        }
243    }
244
245    fn for_operation(operation: OperationContext) -> Self {
246        Self {
247            operation,
248            normalized_stacks: Vec::new(),
249        }
250    }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
254pub(crate) struct FaceIdentity {
255    pub(crate) sha256: [u8; 32],
256    pub(crate) face_index: u32,
257}
258
259#[derive(Debug, Clone)]
260pub(crate) struct RetainedFontFile {
261    pub(crate) root_ordinal: u32,
262    pub(crate) canonical_path: PathBuf,
263    pub(crate) bytes: Arc<Vec<u8>>,
264    pub(crate) sha256: [u8; 32],
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub(crate) struct NameOccurrence {
269    pub(crate) value: String,
270    pub(crate) folded: String,
271    pub(crate) record_ordinal: u16,
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub(crate) enum MetricSource {
276    Typographic,
277    Hhea,
278    InkOnly,
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub(crate) struct DesignMetrics {
283    pub(crate) units_per_em: u16,
284    pub(crate) ascender: i16,
285    pub(crate) descender: i16,
286    pub(crate) source: MetricSource,
287}
288
289impl DesignMetrics {
290    fn validate(self, identity: FaceIdentity) -> Result<Self, FontError> {
291        if !(16..=16384).contains(&self.units_per_em) {
292            return Err(FontError::InvalidMetrics { identity });
293        }
294        Ok(self)
295    }
296}
297
298#[derive(Debug, Clone)]
299pub(crate) struct FaceMetadata {
300    pub(crate) identity: FaceIdentity,
301    pub(crate) file_ordinal: usize,
302    pub(crate) database_id: ID,
303    pub(crate) names: Vec<NameOccurrence>,
304    pub(crate) style: Style,
305    pub(crate) stretch: Stretch,
306    pub(crate) weight: u16,
307    pub(crate) metrics: DesignMetrics,
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub(crate) struct CandidateOccurrence {
312    pub(crate) stack_entry_index: u32,
313    pub(crate) style_distance: u8,
314    pub(crate) stretch_distance: u8,
315    pub(crate) weight_distance: u16,
316    pub(crate) identity: FaceIdentity,
317}
318
319impl CandidateOccurrence {
320    fn canonical_cmp(&self, other: &Self) -> Ordering {
321        (
322            self.stack_entry_index,
323            self.style_distance,
324            self.stretch_distance,
325            self.weight_distance,
326            self.identity,
327        )
328            .cmp(&(
329                other.stack_entry_index,
330                other.style_distance,
331                other.stretch_distance,
332                other.weight_distance,
333                other.identity,
334            ))
335    }
336}
337
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339struct CandidateFace {
340    occurrence: CandidateOccurrence,
341    face_ordinal: usize,
342}
343
344#[derive(Debug, Clone, Copy)]
345struct GlyphProbe {
346    scalar: char,
347    identity: FaceIdentity,
348    covered: bool,
349}
350
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub(crate) enum RequestedWeight {
353    Normal,
354    Semibold,
355    Bold,
356}
357
358impl RequestedWeight {
359    const fn value(self) -> u16 {
360        match self {
361            Self::Normal => 400,
362            Self::Semibold => 600,
363            Self::Bold => 700,
364        }
365    }
366}
367
368impl From<crate::TextWeight> for RequestedWeight {
369    fn from(weight: crate::TextWeight) -> Self {
370        match weight {
371            crate::TextWeight::Normal => Self::Normal,
372            crate::TextWeight::Semibold => Self::Semibold,
373            crate::TextWeight::Bold => Self::Bold,
374        }
375    }
376}
377
378/// Closed host-resolved generic font preferences, distinct from literal names.
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum GenericFontFamily {
381    /// Host serif preference.
382    Serif,
383    /// Host sans-serif preference.
384    SansSerif,
385    /// Host monospace preference.
386    Monospace,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq)]
390enum FontFamilyKind {
391    Named(String),
392    Generic(GenericFontFamily),
393}
394
395/// A literal family identity or one of the three host generic preferences.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct FontFamily {
398    kind: FontFamilyKind,
399}
400
401impl FontFamily {
402    /// Construct a nonempty, already trimmed, control-free literal family name.
403    /// Punctuation and CSS generic spellings remain part of this one literal name.
404    pub fn named(name: impl Into<String>) -> crate::Result<Self> {
405        let name = name.into();
406        if name.is_empty() {
407            return Err(crate::Error::Data("font family name is empty".into()));
408        }
409        if name.chars().any(char::is_control) {
410            return Err(crate::Error::Data(
411                "font family name contains a control character".into(),
412            ));
413        }
414        if name.trim() != name {
415            return Err(crate::Error::Data(
416                "font family name must already be trimmed".into(),
417            ));
418        }
419        Ok(Self {
420            kind: FontFamilyKind::Named(name),
421        })
422    }
423    /// Construct a host generic preference without parsing a string.
424    pub const fn generic(family: GenericFontFamily) -> Self {
425        Self {
426            kind: FontFamilyKind::Generic(family),
427        }
428    }
429    /// Borrow the literal name, or None for a generic preference.
430    pub fn name(&self) -> Option<&str> {
431        match &self.kind {
432            FontFamilyKind::Named(name) => Some(name),
433            FontFamilyKind::Generic(_) => None,
434        }
435    }
436    /// Inspect the generic preference, or None for a literal name.
437    pub const fn generic_family(&self) -> Option<GenericFontFamily> {
438        match self.kind {
439            FontFamilyKind::Generic(family) => Some(family),
440            FontFamilyKind::Named(_) => None,
441        }
442    }
443}
444
445/// Nonempty, ordered preferences; original named bytes and duplicates are retained.
446///
447/// Obtain a built-in profile from a complete text role, or construct typed entries:
448/// ```
449/// use lichtung_plot::{FontFamily, FontStack, GenericFontFamily, Theme};
450/// let profile = Theme::publication().typography().get_root().get_title().get_stack().clone();
451/// assert_eq!(profile.families()[0].name(), Some("Noto Sans"));
452/// let stack = FontStack::new([
453///     FontFamily::named("A, B")?, // One literal identity, not two CSS entries.
454///     FontFamily::generic(GenericFontFamily::SansSerif),
455/// ])?;
456/// assert_eq!(stack.families().len(), 2);
457/// # Ok::<(), lichtung_plot::Error>(())
458/// ```
459///
460/// No raw stack parser or default-font constant is public:
461/// ```compile_fail
462/// let _ = lichtung_plot::FontStack::new(["Arial, sans-serif"]);
463/// ```
464/// ```compile_fail
465/// use lichtung_plot::DEFAULT_FONT_FAMILY;
466/// ```
467/// ```compile_fail
468/// use lichtung_plot::DEFAULT_FONT_FAMILY_STACK;
469/// ```
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct FontStack {
472    families: Arc<Vec<FontFamily>>,
473}
474
475impl FontStack {
476    /// Retain a nonempty ordered sequence, preserving literal bytes and duplicates.
477    pub fn new(families: impl IntoIterator<Item = FontFamily>) -> crate::Result<Self> {
478        let mut retained = Vec::new();
479        for family in families {
480            retained
481                .try_reserve(1)
482                .map_err(|_| crate::Error::Data("font stack allocation refused".into()))?;
483            retained.push(family);
484        }
485        if retained.is_empty() {
486            return Err(crate::Error::Data("font stack is empty".into()));
487        }
488        Ok(Self {
489            families: Arc::new(retained),
490        })
491    }
492    /// Borrow the complete ordered preference sequence.
493    pub fn families(&self) -> &[FontFamily] {
494        &self.families
495    }
496
497    pub(crate) fn same(&self, other: &Self) -> bool {
498        if Arc::ptr_eq(&self.families, &other.families) {
499            return true;
500        }
501        if self.len() != other.len() {
502            return false;
503        }
504        for (left, right) in self.families.iter().zip(other.families.iter()) {
505            match (&left.kind, &right.kind) {
506                (FontFamilyKind::Named(left), FontFamilyKind::Named(right)) => {
507                    if !same_bytes(left, right) {
508                        return false;
509                    }
510                }
511                (FontFamilyKind::Generic(left), FontFamilyKind::Generic(right))
512                    if left == right => {}
513                _ => return false,
514            }
515        }
516        true
517    }
518
519    pub(crate) fn hash_into(&self, hash: &mut Sha256) {
520        hash.update((self.len() as u64).to_le_bytes());
521        for family in self.families.iter() {
522            match &family.kind {
523                FontFamilyKind::Named(name) => {
524                    hash.update([0]);
525                    hash.update((name.len() as u64).to_le_bytes());
526                    hash.update(name.as_bytes());
527                }
528                FontFamilyKind::Generic(family) => {
529                    hash.update([1, *family as u8]);
530                }
531            }
532        }
533    }
534
535    pub(crate) fn try_copy(&self) -> Result<Self, FontError> {
536        let mut families = Vec::new();
537        families
538            .try_reserve_exact(self.len())
539            .map_err(|_| FontError::Allocation("font stack entries"))?;
540        for family in self {
541            let kind = match &family.kind {
542                FontFamilyKind::Named(name) => {
543                    let mut retained = String::new();
544                    retained
545                        .try_reserve_exact(name.len())
546                        .map_err(|_| FontError::Allocation("font family name"))?;
547                    retained.push_str(name);
548                    FontFamilyKind::Named(retained)
549                }
550                FontFamilyKind::Generic(family) => FontFamilyKind::Generic(*family),
551            };
552            families.push(FontFamily { kind });
553        }
554        Ok(Self {
555            families: Arc::new(families),
556        })
557    }
558
559    pub(crate) fn copy_with_stage(
560        &self,
561
562        stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
563    ) -> Result<Self, FontError> {
564        copy_stack_with_stage(self, stage)
565    }
566
567    fn write_css(&self, output: &mut impl std::fmt::Write) -> std::fmt::Result {
568        for (index, family) in self.families.iter().enumerate() {
569            if index != 0 {
570                output.write_str(", ")?;
571            }
572            match &family.kind {
573                FontFamilyKind::Generic(family) => output.write_str(match family {
574                    GenericFontFamily::Serif => "serif",
575                    GenericFontFamily::SansSerif => "sans-serif",
576                    GenericFontFamily::Monospace => "monospace",
577                })?,
578                FontFamilyKind::Named(name) => {
579                    if css_unquoted_family(name) {
580                        output.write_str(name)?;
581                    } else {
582                        output.write_char('"')?;
583                        for scalar in name.chars() {
584                            if matches!(scalar, '"' | '\\') {
585                                output.write_char('\\')?;
586                            }
587                            output.write_char(scalar)?;
588                        }
589                        output.write_char('"')?;
590                    }
591                }
592            }
593        }
594        Ok(())
595    }
596
597    pub(crate) fn css(&self) -> Result<String, FontError> {
598        // Count and materialization each consume the known UTF-8 input once.
599
600        let mut count = CssCount(0);
601        self.write_css(&mut count)
602            .map_err(|_| FontError::Arithmetic("font stack CSS bytes"))?;
603
604        let mut output = String::new();
605        output
606            .try_reserve_exact(count.0)
607            .map_err(|_| FontError::Allocation("font stack CSS"))?;
608        self.write_css(&mut output)
609            .map_err(|_| FontError::Arithmetic("font stack CSS"))?;
610        Ok(output)
611    }
612}
613
614struct CssCount(usize);
615impl std::fmt::Write for CssCount {
616    fn write_str(&mut self, text: &str) -> std::fmt::Result {
617        self.0 = self.0.checked_add(text.len()).ok_or(std::fmt::Error)?;
618        Ok(())
619    }
620}
621
622fn css_unquoted_family(name: &str) -> bool {
623    ![
624        "serif",
625        "sans-serif",
626        "monospace",
627        "cursive",
628        "fantasy",
629        "system-ui",
630        "ui-serif",
631        "ui-sans-serif",
632        "ui-monospace",
633        "ui-rounded",
634        "math",
635        "fangsong",
636        "emoji",
637        "inherit",
638        "initial",
639        "unset",
640        "revert",
641        "revert-layer",
642        "default",
643    ]
644    .iter()
645    .any(|keyword| {
646        name.split(' ')
647            .any(|word| word.eq_ignore_ascii_case(keyword))
648    }) && name.split(' ').all(css_identifier)
649}
650
651fn css_identifier(word: &str) -> bool {
652    let start = |c: char| c.is_ascii_alphabetic() || c == '_' || !c.is_ascii();
653    let mut chars = word.chars();
654    let valid_start = match chars.next() {
655        Some('-') => chars.next().is_some_and(|c| start(c) || c == '-'),
656        Some(c) => start(c),
657        None => false,
658    };
659    valid_start && chars.all(|c| start(c) || c.is_ascii_digit() || c == '-')
660}
661
662impl std::ops::Deref for FontStack {
663    type Target = [FontFamily];
664    fn deref(&self) -> &Self::Target {
665        self.families()
666    }
667}
668
669impl<'a> IntoIterator for &'a FontStack {
670    type Item = &'a FontFamily;
671    type IntoIter = std::slice::Iter<'a, FontFamily>;
672    fn into_iter(self) -> Self::IntoIter {
673        self.families.iter()
674    }
675}
676
677pub(crate) fn same_bytes(left: &str, right: &str) -> bool {
678    // Concurrent immutable borrows of this exact range already denote the same bytes.
679    if std::ptr::eq(left, right) {
680        return true;
681    }
682    if left.len() != right.len() {
683        return false;
684    }
685    for index in 0..left.len() {
686        if left.as_bytes()[index] != right.as_bytes()[index] {
687            return false;
688        }
689    }
690    true
691}
692
693pub(crate) fn builtin_font_stack() -> FontStack {
694    FontStack::new(
695        [
696            "Noto Sans",
697            "Noto Sans CJK SC",
698            "DejaVu Sans",
699            "Liberation Sans",
700            "Arial",
701        ]
702        .into_iter()
703        .map(|name| FontFamily::named(name).expect("built-in literal family"))
704        .chain([FontFamily::generic(GenericFontFamily::SansSerif)]),
705    )
706    .expect("nonempty built-in font preferences")
707}
708
709#[cfg(test)]
710pub(crate) fn named_stack(names: &[&str]) -> FontStack {
711    FontStack::new(names.iter().map(|name| FontFamily::named(*name).unwrap())).unwrap()
712}
713
714#[cfg(test)]
715pub(crate) fn test_sans_stack() -> &'static FontStack {
716    static STACK: std::sync::OnceLock<FontStack> = std::sync::OnceLock::new();
717    STACK.get_or_init(|| named_stack(&["Test Sans"]))
718}
719
720#[derive(Debug, Clone, PartialEq, Eq)]
721pub(crate) struct PairProvenance {
722    pub(crate) pair_ordinal: u32,
723    pub(crate) weight: RequestedWeight,
724    pub(crate) candidates: Vec<FaceIdentity>,
725}
726
727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
728pub(crate) enum ScalarFaceSelection {
729    Face(FaceIdentity),
730    NonRenderingMandatoryBreak,
731}
732
733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
734pub(crate) struct SelectedScalarFace {
735    pub(crate) scalar: char,
736    pub(crate) selection: ScalarFaceSelection,
737}
738
739#[derive(Debug, Clone, PartialEq, Eq)]
740pub(crate) struct SelectedScalarFaces(Vec<SelectedScalarFace>);
741
742impl SelectedScalarFaces {
743    #[expect(
744        clippy::trivially_copy_pass_by_ref,
745        reason = "matches slice binary_search_by_key call sites"
746    )]
747    pub(crate) fn binary_search_by_key<F>(&self, scalar: &char, mut key: F) -> Result<usize, usize>
748    where
749        F: FnMut(&SelectedScalarFace) -> char,
750    {
751        // Storage follows first observation rather than scalar-value order.
752        self.0
753            .iter()
754            .position(|selected| key(selected) == *scalar)
755            .ok_or(self.0.len())
756    }
757}
758
759impl std::ops::Deref for SelectedScalarFaces {
760    type Target = [SelectedScalarFace];
761
762    fn deref(&self) -> &Self::Target {
763        &self.0
764    }
765}
766
767#[derive(Debug, Clone, PartialEq, Eq)]
768pub(crate) struct ResolvedFontPair {
769    pub(crate) provenance: PairProvenance,
770    pub(crate) primary: FaceIdentity,
771    pub(crate) selected_scalars: SelectedScalarFaces,
772    pub(crate) selected_units: Vec<SelectedFontUnit>,
773}
774
775#[derive(Debug, Clone, PartialEq, Eq)]
776pub(crate) struct SelectedFontUnit {
777    pub(crate) source: String,
778    pub(crate) face: Option<FaceIdentity>,
779}
780
781impl ResolvedFontPair {
782    fn covers_source(&self, source: &str) -> bool {
783        source
784            .chars()
785            .chain(source.contains('\u{ad}').then_some('-'))
786            .all(|scalar| {
787                self.selected_scalars
788                    .iter()
789                    .any(|entry| entry.scalar == scalar)
790            })
791            && selection_units(source)
792                .filter(|unit| unit.chars().count() > 1 && unit.chars().any(is_visible_mark))
793                .all(|unit| self.selected_units.iter().any(|entry| entry.source == unit))
794    }
795
796    fn try_copy(
797        &self,
798        mut stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
799    ) -> Result<Self, FontError> {
800        let mut candidates = Vec::new();
801        reserve_cached_with_stage(
802            &mut candidates,
803            self.provenance.candidates.len(),
804            stage.as_deref_mut(),
805        )?;
806        candidates.extend_from_slice(&self.provenance.candidates);
807        let mut selected_scalars = Vec::new();
808        reserve_cached_with_stage(
809            &mut selected_scalars,
810            self.selected_scalars.len(),
811            stage.as_deref_mut(),
812        )?;
813        selected_scalars.extend_from_slice(&self.selected_scalars);
814        let mut selected_units = Vec::new();
815        reserve_cached_with_stage(
816            &mut selected_units,
817            self.selected_units.len(),
818            stage.as_deref_mut(),
819        )?;
820        for unit in &self.selected_units {
821            let mut source = String::new();
822            if let Some(stage) = stage.as_deref_mut() {
823                stage
824                    .reserve_prepared_string(
825                        &mut source,
826                        unit.source.len(),
827                        "font unit source copy",
828                    )
829                    .map_err(|error| FontError::Reservation(error.to_string()))?;
830            } else {
831                source
832                    .try_reserve_exact(unit.source.len())
833                    .map_err(|_| FontError::Allocation("font unit source copy"))?;
834            }
835            source.push_str(&unit.source);
836            selected_units.push(SelectedFontUnit {
837                source,
838                face: unit.face,
839            });
840        }
841        Ok(Self {
842            provenance: PairProvenance {
843                pair_ordinal: self.provenance.pair_ordinal,
844                weight: self.provenance.weight,
845                candidates,
846            },
847            primary: self.primary,
848            selected_scalars: SelectedScalarFaces(selected_scalars),
849            selected_units,
850        })
851    }
852
853    pub(crate) fn selection_for_unit(
854        &self,
855        unit: &str,
856        scalar: char,
857    ) -> Result<ScalarFaceSelection, FontError> {
858        if unit.chars().count() > 1 && unit.chars().any(is_visible_mark) {
859            let retained = self
860                .selected_units
861                .iter()
862                .find(|entry| entry.source == unit)
863                .ok_or(FontError::UnknownUnit {
864                    pair_ordinal: self.provenance.pair_ordinal,
865                })?;
866            if let Some(face) = retained.face {
867                return Ok(ScalarFaceSelection::Face(face));
868            }
869        }
870        self.selected_scalars
871            .iter()
872            .find(|entry| entry.scalar == scalar)
873            .map(|entry| entry.selection)
874            .ok_or(FontError::MissingGlyph {
875                pair_ordinal: self.provenance.pair_ordinal,
876                scalar: scalar as u32,
877            })
878    }
879}
880
881fn is_visible_mark(scalar: char) -> bool {
882    matches!(
883        scalar.general_category(),
884        unicode_properties::GeneralCategory::NonspacingMark
885            | unicode_properties::GeneralCategory::SpacingMark
886            | unicode_properties::GeneralCategory::EnclosingMark
887    ) && !is_nonpainting_control(scalar)
888}
889
890/// Narrow base-plus-mark units, never whole emoji sequences or words.
891pub(crate) fn selection_units(source: &str) -> impl Iterator<Item = &str> {
892    source.graphemes(true).flat_map(|grapheme| {
893        let mut remaining = grapheme;
894        std::iter::from_fn(move || {
895            let first = remaining.chars().next()?;
896            let end = remaining
897                .char_indices()
898                .skip(1)
899                .find(|(_, scalar)| {
900                    !is_visible_mark(*scalar)
901                        || is_visible_mark(first)
902                        || is_nonpainting_control(first)
903                })
904                .map_or(remaining.len(), |(index, _)| index);
905            let (unit, rest) = remaining.split_at(end);
906            remaining = rest;
907            Some(unit)
908        })
909    })
910}
911
912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub(crate) enum ShapingDirection {
914    LeftToRight,
915    RightToLeft,
916}
917
918impl From<ShapingDirection> for rustybuzz::Direction {
919    fn from(value: ShapingDirection) -> Self {
920        match value {
921            ShapingDirection::LeftToRight => Self::LeftToRight,
922            ShapingDirection::RightToLeft => Self::RightToLeft,
923        }
924    }
925}
926
927#[derive(Debug, Clone, Copy, PartialEq, Eq)]
928pub(crate) enum GlyphPaint {
929    RasterImage,
930    SvgImage,
931    ColorLayers,
932}
933
934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
935pub(crate) struct GlyphInk {
936    pub(crate) x_min: i16,
937    pub(crate) y_min: i16,
938    pub(crate) x_max: i16,
939    pub(crate) y_max: i16,
940}
941
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943pub(crate) struct ShapedGlyph {
944    pub(crate) glyph_id: u16,
945    pub(crate) cluster: u32,
946    pub(crate) x_advance: i32,
947    pub(crate) y_advance: i32,
948    pub(crate) x_offset: i32,
949    pub(crate) y_offset: i32,
950    pub(crate) ink: Option<GlyphInk>,
951}
952
953#[derive(Debug, Clone)]
954pub(crate) struct ShapedRun {
955    pub(crate) identity: FaceIdentity,
956    pub(crate) direction: ShapingDirection,
957    pub(crate) script: rustybuzz::Script,
958    pub(crate) metrics: DesignMetrics,
959    pub(crate) glyphs: Vec<ShapedGlyph>,
960}
961
962#[derive(Debug)]
963struct BinarySource(Arc<Vec<u8>>);
964
965impl AsRef<[u8]> for BinarySource {
966    fn as_ref(&self) -> &[u8] {
967        &self.0
968    }
969}
970
971#[derive(Debug, Clone)]
972struct SourceRoot {
973    ordinal: u32,
974    path: PathBuf,
975    entry_prefix: Option<&'static str>,
976}
977
978#[derive(Debug, Default)]
979struct HostGenericNames {
980    serif: Option<String>,
981    sans_serif: Option<String>,
982    cursive: Option<String>,
983    fantasy: Option<String>,
984    monospace: Option<String>,
985}
986
987#[derive(Debug)]
988struct HostSources {
989    roots: Vec<SourceRoot>,
990    generics: HostGenericNames,
991}
992
993#[derive(Debug)]
994struct DiscoveryRecord {
995    root_ordinal: u32,
996    path: PathBuf,
997    entry_prefix: Option<&'static str>,
998    admit_file: bool,
999}
1000
1001struct DiscoveryFontHandle {
1002    file: File,
1003}
1004
1005#[cfg(test)]
1006thread_local! {
1007    // Live handles, peak handles, opens (metadata and materialization).
1008    static DISCOVERY_HANDLES: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
1009    static DISCOVERY_AFTER_ADMISSION: std::cell::Cell<Option<fn(&Path)>> = const { std::cell::Cell::new(None) };
1010}
1011
1012#[cfg(test)]
1013impl Drop for DiscoveryFontHandle {
1014    fn drop(&mut self) {
1015        DISCOVERY_HANDLES.with(|state| {
1016            let mut counts = state.get();
1017            counts[0] -= 1;
1018            state.set(counts);
1019        });
1020    }
1021}
1022
1023#[derive(Debug)]
1024pub(crate) struct CanonicalFontCore {
1025    database: Database,
1026    index: Vec<index::IndexedFontFile>,
1027    // Unique while admission is open; shared read-only only after sealing.
1028    fonts: Arc<FrozenFontRegistry>,
1029    scalar_presence: Vec<u64>,
1030    prepared_pairs: Vec<PreparedPair>,
1031    prepared_pairs_sealed: bool,
1032    operation: OperationContext,
1033    preparation: FontPreparation,
1034}
1035
1036#[derive(Debug)]
1037struct PreparedPair {
1038    stack: FontStack,
1039    weight: RequestedWeight,
1040    candidates: Vec<CandidateFace>,
1041    resolved: ResolvedFontPair,
1042    sources: Vec<String>,
1043}
1044
1045#[derive(Debug, Clone, Copy)]
1046pub(crate) struct FontPairPreparationRequest<'a> {
1047    pair_ordinal: u32,
1048    stack: &'a FontStack,
1049    weight: RequestedWeight,
1050    required_scalars: &'a [char],
1051}
1052
1053impl<'a> FontPairPreparationRequest<'a> {
1054    pub(crate) const fn new(
1055        pair_ordinal: u32,
1056        stack: &'a FontStack,
1057        weight: RequestedWeight,
1058        required_scalars: &'a [char],
1059    ) -> Self {
1060        Self {
1061            pair_ordinal,
1062            stack,
1063            weight,
1064            required_scalars,
1065        }
1066    }
1067}
1068
1069struct PairPreparation<'a> {
1070    request: FontPairPreparationRequest<'a>,
1071    resolved_names: Vec<String>,
1072    raw_candidate_count: usize,
1073    candidate_count: usize,
1074    scalar_count: usize,
1075    maximum_probes: usize,
1076    candidates: Vec<CandidateFace>,
1077    provenance: Vec<FaceIdentity>,
1078    selected_scalars: Vec<SelectedScalarFace>,
1079    probes: Vec<GlyphProbe>,
1080    retained_stack: Vec<FontFamily>,
1081}
1082
1083impl<'a> PairPreparation<'a> {
1084    fn new(request: FontPairPreparationRequest<'a>) -> Self {
1085        Self {
1086            request,
1087            resolved_names: Vec::new(),
1088            raw_candidate_count: 0,
1089            candidate_count: 0,
1090            scalar_count: 0,
1091            maximum_probes: 0,
1092            candidates: Vec::new(),
1093            provenance: Vec::new(),
1094            selected_scalars: Vec::new(),
1095            probes: Vec::new(),
1096            retained_stack: Vec::new(),
1097        }
1098    }
1099
1100    fn storage_is_reserved(&self) -> bool {
1101        self.resolved_names.capacity() >= self.request.stack.len()
1102            && self.candidates.capacity() >= self.raw_candidate_count
1103            && self.provenance.capacity() >= self.candidate_count
1104            && self.selected_scalars.capacity() >= self.scalar_count
1105            && self.probes.capacity() >= self.maximum_probes
1106            && self.retained_stack.capacity() >= self.request.stack.len()
1107            && self.retained_stack.len() == self.request.stack.len()
1108            && self
1109                .retained_stack
1110                .iter()
1111                .zip(self.request.stack)
1112                .all(|(retained, source)| match (&retained.kind, &source.kind) {
1113                    (FontFamilyKind::Named(retained), FontFamilyKind::Named(source)) => {
1114                        retained.capacity() >= source.len()
1115                    }
1116                    (FontFamilyKind::Generic(retained), FontFamilyKind::Generic(source)) => {
1117                        retained == source
1118                    }
1119                    _ => false,
1120                })
1121    }
1122}
1123
1124/// One operation's retained font database and exact source bytes.
1125#[derive(Debug, Clone)]
1126pub(crate) struct PreparedFontEnvironment {
1127    core: Arc<RwLock<CanonicalFontCore>>,
1128}
1129
1130/// The materialized candidate file/face collection. Uniquely owned while open,
1131/// shared with Output only after sealing, without index/source/operation state.
1132#[derive(Debug)]
1133pub(crate) struct FrozenFontRegistry {
1134    files: Vec<RetainedFontFile>,
1135    faces: Vec<FaceMetadata>,
1136    issues: Vec<FontScanIssue>,
1137}
1138
1139pub(crate) struct SealedTextVerifier<'a> {
1140    environment: &'a PreparedFontEnvironment,
1141}
1142
1143impl<'a> SealedTextVerifier<'a> {
1144    pub(crate) fn new(environment: &'a PreparedFontEnvironment) -> Self {
1145        Self { environment }
1146    }
1147}
1148
1149impl SealedTextVerifier<'_> {
1150    pub(crate) fn validate_measured(
1151        &self,
1152        text: &crate::layout::ResolvedTextPlan,
1153    ) -> Result<(), FontError> {
1154        self.environment.validate_admitted_text(
1155            &text.style.stack,
1156            &text.pair_provenance,
1157            &text.source,
1158        )
1159    }
1160
1161    pub(crate) fn retain_fonts(&self) -> Result<Arc<FrozenFontRegistry>, FontError> {
1162        let core = self
1163            .environment
1164            .core
1165            .read()
1166            .map_err(|_| FontError::Synchronization)?;
1167        if !core.prepared_pairs_sealed {
1168            return Err(FontError::Arithmetic("font registry shared before sealing"));
1169        }
1170        #[cfg(test)]
1171        LOAD_OBSERVATIONS.with_borrow_mut(|observed| {
1172            observed.frozen_files = core
1173                .fonts
1174                .files
1175                .iter()
1176                .map(|file| (file.canonical_path.clone(), file.bytes.len()))
1177                .collect();
1178        });
1179        Ok(Arc::clone(&core.fonts))
1180    }
1181}
1182
1183#[derive(Debug, Clone)]
1184pub(crate) struct OperationContext {
1185    // Shared by clones independently of accounting and mutable cache contents.
1186    identity: Arc<()>,
1187    pub(crate) palette_cache: Arc<Mutex<crate::theme::PaletteCache>>,
1188    fonts: Arc<Mutex<FontOperation>>,
1189    pub(crate) numeric_presentations: Arc<Mutex<crate::numeric::table::PresentationTable>>,
1190    pub(crate) tick_positions: Arc<Mutex<crate::spec::ticks::function::PositionTable>>,
1191}
1192
1193#[derive(Debug, Default)]
1194struct FontOperation {
1195    environments: Vec<Weak<RwLock<CanonicalFontCore>>>,
1196    sealed: bool,
1197}
1198
1199impl OperationContext {
1200    #[cfg(test)]
1201    pub(crate) fn liveness_probe(&self) -> impl Fn() -> bool + use<> {
1202        let palettes = Arc::downgrade(&self.palette_cache);
1203        let fonts = Arc::downgrade(&self.fonts);
1204        let numbers = Arc::downgrade(&self.numeric_presentations);
1205        let positions = Arc::downgrade(&self.tick_positions);
1206        move || {
1207            palettes.strong_count() != 0
1208                || fonts.strong_count() != 0
1209                || numbers.strong_count() != 0
1210                || positions.strong_count() != 0
1211        }
1212    }
1213
1214    pub(crate) fn seal_fonts(&self) -> Result<(), FontError> {
1215        self.tick_positions
1216            .lock()
1217            .map_err(|_| FontError::Synchronization)?
1218            .seal();
1219        self.numeric_presentations
1220            .lock()
1221            .map_err(|_| FontError::Synchronization)?
1222            .seal();
1223        let mut fonts = self.fonts.lock().map_err(|_| FontError::Synchronization)?;
1224        if fonts.sealed {
1225            return Err(FontError::OperationSealed);
1226        }
1227        for environment in fonts.environments.iter().filter_map(Weak::upgrade) {
1228            let mut core = environment
1229                .write()
1230                .map_err(|_| FontError::Synchronization)?;
1231            core.prepared_pairs_sealed = true;
1232            #[cfg(test)]
1233            FONT_FINAL_SEALS.with(|calls| calls.set(calls.get() + 1));
1234        }
1235        fonts.sealed = true;
1236        Ok(())
1237    }
1238
1239    pub(crate) fn same_operation(&self, other: &Self) -> bool {
1240        Arc::ptr_eq(&self.identity, &other.identity)
1241    }
1242
1243    pub(crate) fn root_identity(&self) -> crate::orchestrator::registration::RootIdentity {
1244        crate::orchestrator::registration::RootIdentity(Arc::clone(&self.identity))
1245    }
1246
1247    pub(crate) fn new() -> Self {
1248        Self {
1249            identity: Arc::new(()),
1250            palette_cache: Arc::default(),
1251            fonts: Arc::default(),
1252            numeric_presentations: Arc::default(),
1253            tick_positions: Arc::default(),
1254        }
1255    }
1256}
1257
1258impl PreparedFontEnvironment {
1259    /// Geometry fixtures can serialize an already measured plan while continuing
1260    /// to measure other sources. Fork only the materialized immutable sources;
1261    /// unlike production capture this does not share the open registry or seal
1262    /// its operation, and cannot discover or load another font.
1263    #[cfg(test)]
1264    pub(crate) fn materialized_snapshot_for_test(&self) -> Arc<FrozenFontRegistry> {
1265        let core = self.core.read().unwrap();
1266        Arc::new(FrozenFontRegistry {
1267            files: core.fonts.files.clone(),
1268            faces: core.fonts.faces.clone(),
1269            issues: Vec::new(),
1270        })
1271    }
1272
1273    #[cfg(test)]
1274    pub(crate) fn liveness_probe(&self) -> impl Fn() -> bool + use<> {
1275        let core = Arc::downgrade(&self.core);
1276        move || core.strong_count() != 0
1277    }
1278
1279    /// Verify frozen source coverage and pair provenance without adding fonts,
1280    /// copying selections, probing faces or shaping text.
1281    pub(crate) fn validate_admitted_text(
1282        &self,
1283        stack: &FontStack,
1284        provenance: &PairProvenance,
1285        source: &str,
1286    ) -> Result<(), FontError> {
1287        let core = self.core.read().map_err(|_| FontError::Synchronization)?;
1288        if core.prepared_pairs_sealed
1289            && core.prepared_pairs.iter().any(|pair| {
1290                pair.stack.same(stack)
1291                    && pair.resolved.provenance == *provenance
1292                    && pair.resolved.covers_source(source)
1293            })
1294        {
1295            Ok(())
1296        } else {
1297            Err(FontError::UnadmittedText {
1298                pair_ordinal: provenance.pair_ordinal,
1299            })
1300        }
1301    }
1302
1303    /// Admit one reached source into this operation before any metric or shaping
1304    /// query. Both initial census and bounded planning use this same transaction.
1305    pub(crate) fn admit_text(
1306        &self,
1307        stack: &FontStack,
1308        weight: RequestedWeight,
1309        source: &str,
1310        mut stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1311    ) -> Result<u32, FontError> {
1312        u32::try_from(source.len())
1313            .map_err(|_| FontError::Arithmetic("admitted text source byte range"))?;
1314        let mut core = self.core.write().map_err(|_| FontError::Synchronization)?;
1315        if let Some(stage) = stage.as_ref() {
1316            if !core.operation.same_operation(&stage.operation()) {
1317                return Err(FontError::Arithmetic(
1318                    "cannot replace a prepared font operation",
1319                ));
1320            }
1321        }
1322        let existing = core
1323            .prepared_pairs
1324            .iter()
1325            .position(|pair| pair.weight == weight && pair.stack.same(stack));
1326        if let Some(index) = existing {
1327            if core.prepared_pairs[index]
1328                .sources
1329                .iter()
1330                .any(|known| known == source)
1331            {
1332                return Ok(core.prepared_pairs[index].resolved.provenance.pair_ordinal);
1333            }
1334        }
1335        let ordinal = if let Some(index) = existing {
1336            core.prepared_pairs[index].resolved.provenance.pair_ordinal
1337        } else {
1338            core.prepared_pairs
1339                .iter()
1340                .map(|pair| pair.resolved.provenance.pair_ordinal)
1341                .max()
1342                .map_or(Ok(0), |ordinal| {
1343                    ordinal
1344                        .checked_add(1)
1345                        .ok_or(FontError::Arithmetic("font pair ordinal overflow"))
1346                })?
1347        };
1348        if core.prepared_pairs_sealed {
1349            return if existing
1350                .is_some_and(|index| core.prepared_pairs[index].resolved.covers_source(source))
1351            {
1352                Ok(ordinal)
1353            } else {
1354                Err(FontError::PreparedPairAfterSeal {
1355                    pair_ordinal: ordinal,
1356                })
1357            };
1358        }
1359        let count = source
1360            .chars()
1361            .count()
1362            .checked_add(usize::from(source.contains('\u{ad}')))
1363            .ok_or(FontError::Arithmetic("font source scalar count overflow"))?;
1364        let mut scalars = Vec::new();
1365        reserve_cached_with_stage(&mut scalars, count, stage.as_deref_mut())?;
1366        scalars.extend(source.chars());
1367        if source.contains('\u{ad}') {
1368            scalars.push('-');
1369        }
1370        let index = core
1371            .admit_scalars_in(ordinal, stack, weight, &scalars, stage.as_deref_mut())
1372            .map_err(|error| core.admission_error(error, Some(stack)))?;
1373        core.prepare_source_units(ordinal, source, stage.as_deref_mut())?;
1374        let mut retained = String::new();
1375        if let Some(stage) = stage.as_deref_mut() {
1376            stage
1377                .reserve_prepared_string(&mut retained, source.len(), "admitted text source")
1378                .map_err(|error| FontError::Reservation(error.to_string()))?;
1379        } else {
1380            retained
1381                .try_reserve_exact(source.len())
1382                .map_err(|_| FontError::Allocation("admitted text source"))?;
1383        }
1384        reserve_cached_with_stage(&mut core.prepared_pairs[index].sources, 1, stage)?;
1385        retained.push_str(source);
1386        core.prepared_pairs[index].sources.push(retained);
1387        #[cfg(test)]
1388        FONT_SOURCE_ADMISSIONS.with(|calls| calls.set(calls.get() + 1));
1389        Ok(ordinal)
1390    }
1391
1392    fn for_core(core: CanonicalFontCore) -> Result<Self, FontError> {
1393        let operation = core.operation.clone();
1394        let core = Arc::new(RwLock::new(core));
1395        let mut fonts = operation
1396            .fonts
1397            .lock()
1398            .map_err(|_| FontError::Synchronization)?;
1399        if fonts.sealed {
1400            return Err(FontError::OperationSealed);
1401        }
1402        fonts
1403            .environments
1404            .try_reserve(1)
1405            .map_err(|_| FontError::Allocation("operation font environments"))?;
1406        fonts.environments.push(Arc::downgrade(&core));
1407        Ok(Self { core })
1408    }
1409
1410    #[cfg(test)]
1411    pub(crate) fn discover_system() -> Result<Self, FontError> {
1412        #[cfg(test)]
1413        FONT_DISCOVERY_CALLS.with(|calls| calls.set(calls.get() + 1));
1414        let scalar_presence = scalar_presence_map()?;
1415        Self::for_core(CanonicalFontCore::discover_prepared(
1416            FontPreparation::new(),
1417            scalar_presence,
1418            None,
1419        )?)
1420    }
1421
1422    pub(crate) fn discover_for_operation(
1423        scalar_presence: Vec<u64>,
1424        prepared_stage: &mut crate::layout::kernel::PreparedStage<'_>,
1425    ) -> Result<Self, FontError> {
1426        let operation = prepared_stage.operation();
1427        if operation
1428            .fonts
1429            .lock()
1430            .map_err(|_| FontError::Synchronization)?
1431            .sealed
1432        {
1433            return Err(FontError::OperationSealed);
1434        }
1435        #[cfg(test)]
1436        FONT_DISCOVERY_CALLS.with(|calls| calls.set(calls.get() + 1));
1437        let preparation = FontPreparation::for_operation(operation);
1438        Self::for_core(CanonicalFontCore::discover_prepared(
1439            preparation,
1440            scalar_presence,
1441            Some(prepared_stage),
1442        )?)
1443    }
1444
1445    #[cfg(test)]
1446    pub(crate) fn resolve_pair(
1447        &self,
1448        pair_ordinal: u32,
1449        stack: &FontStack,
1450        weight: RequestedWeight,
1451        required_scalars: &[char],
1452    ) -> Result<ResolvedFontPair, FontError> {
1453        let mut core = self.core.write().map_err(|_| FontError::Synchronization)?;
1454        if core.prepared_pairs_sealed {
1455            return Err(FontError::PreparedPairAfterSeal { pair_ordinal });
1456        }
1457        core.resolve_pair(pair_ordinal, stack, weight, required_scalars)
1458    }
1459
1460    pub(crate) fn validate_operation(&self, resources: &OperationContext) -> Result<(), FontError> {
1461        let core = self.core.read().map_err(|_| FontError::Synchronization)?;
1462        // Prepared fonts and their clones remain bound to their original operation.
1463        if !core.operation.same_operation(resources) {
1464            return Err(FontError::Arithmetic(
1465                "cannot replace a prepared font operation",
1466            ));
1467        }
1468        Ok(())
1469    }
1470
1471    pub(crate) fn operation(&self) -> Result<OperationContext, FontError> {
1472        Ok(self
1473            .core
1474            .read()
1475            .map_err(|_| FontError::Synchronization)?
1476            .operation
1477            .clone())
1478    }
1479
1480    #[cfg(test)]
1481    pub(crate) fn reserve_prepared_pairs(
1482        &self,
1483        count: usize,
1484        prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1485    ) -> Result<(), FontError> {
1486        let mut core = self.core.write().map_err(|_| FontError::Synchronization)?;
1487        reserve_prepared_or_local(
1488            &mut core.prepared_pairs,
1489            count,
1490            "prepared font pairs",
1491            prepared_stage,
1492        )
1493    }
1494
1495    pub(crate) fn prepare_pairs<'a>(
1496        &self,
1497        requests: impl ExactSizeIterator<Item = FontPairPreparationRequest<'a>>,
1498        prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1499    ) -> Result<(), FontError> {
1500        let mut core = self.core.write().map_err(|_| FontError::Synchronization)?;
1501        core.prepare_pairs_with_stage(requests, prepared_stage)
1502            .map_err(|error| core.admission_error(error, None))
1503    }
1504
1505    #[cfg(test)]
1506    pub(crate) fn prepare_pair(
1507        &self,
1508        pair_ordinal: u32,
1509        stack: &FontStack,
1510        weight: RequestedWeight,
1511        required_scalars: &[char],
1512        prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1513    ) -> Result<(), FontError> {
1514        self.prepare_pairs(
1515            std::iter::once(FontPairPreparationRequest::new(
1516                pair_ordinal,
1517                stack,
1518                weight,
1519                required_scalars,
1520            )),
1521            prepared_stage,
1522        )
1523    }
1524
1525    #[cfg(test)]
1526    pub(crate) fn prepare_source_units(
1527        &self,
1528        pair_ordinal: u32,
1529        source: &str,
1530        prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1531    ) -> Result<(), FontError> {
1532        let mut core = self.core.write().map_err(|_| FontError::Synchronization)?;
1533        core.prepare_source_units(pair_ordinal, source, prepared_stage)
1534    }
1535}
1536
1537impl CanonicalFontCore {
1538    fn prepare_source_units(
1539        &mut self,
1540        pair_ordinal: u32,
1541        source: &str,
1542        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1543    ) -> Result<(), FontError> {
1544        if self.prepared_pairs_sealed {
1545            return Err(FontError::PreparedPairAfterSeal { pair_ordinal });
1546        }
1547        // Scalar coverage is complete before whole combining units are selected.
1548        let index = self
1549            .prepared_pairs
1550            .iter()
1551            .position(|pair| pair.resolved.provenance.pair_ordinal == pair_ordinal)
1552            .ok_or(FontError::MissingFamily { pair_ordinal })?;
1553        for unit in selection_units(source)
1554            .filter(|unit| unit.chars().count() > 1 && unit.chars().any(is_visible_mark))
1555        {
1556            let pair = &self.prepared_pairs[index].resolved;
1557            let mut found = false;
1558            for entry in &pair.selected_units {
1559                if entry.source == unit {
1560                    found = true;
1561                    break;
1562                }
1563            }
1564            if found {
1565                continue;
1566            }
1567            let mut selected = None;
1568            for identity in &pair.provenance.candidates {
1569                let mut metadata = None;
1570                for face in &self.fonts.faces {
1571                    if face.identity == *identity {
1572                        metadata = Some(face);
1573                        break;
1574                    }
1575                }
1576                let metadata = metadata.ok_or(FontError::InvalidMetrics {
1577                    identity: *identity,
1578                })?;
1579                let file = &self.fonts.files[metadata.file_ordinal];
1580                let parsed =
1581                    ttf_parser::Face::parse(&file.bytes, identity.face_index).map_err(|error| {
1582                        FontError::ParseFace {
1583                            path: file.canonical_path.clone(),
1584                            index: identity.face_index,
1585                            reason: error.to_string(),
1586                        }
1587                    })?;
1588                let mut covered = true;
1589                for scalar in unit.chars() {
1590                    #[cfg(test)]
1591                    FONT_SELECTION_PROBES.with(|calls| calls.set(calls.get() + 1));
1592                    if !is_nonpainting_control(scalar) && parsed.glyph_index(scalar).is_none() {
1593                        covered = false;
1594                        break;
1595                    }
1596                }
1597                if covered {
1598                    selected = Some(*identity);
1599                    break;
1600                }
1601            }
1602            let mut retained = String::new();
1603
1604            if let Some(stage) = prepared_stage.as_deref_mut() {
1605                stage
1606                    .reserve_prepared_string(&mut retained, unit.len(), "font unit source")
1607                    .map_err(|error| FontError::Reservation(error.to_string()))?;
1608            } else {
1609                retained
1610                    .try_reserve_exact(unit.len())
1611                    .map_err(|_| FontError::Allocation("font unit source"))?;
1612            }
1613
1614            reserve_cached_with_stage(
1615                &mut self.prepared_pairs[index].resolved.selected_units,
1616                1,
1617                prepared_stage.as_deref_mut(),
1618            )?;
1619            retained.push_str(unit);
1620            self.prepared_pairs[index]
1621                .resolved
1622                .selected_units
1623                .push(SelectedFontUnit {
1624                    source: retained,
1625                    face: selected,
1626                });
1627        }
1628        Ok(())
1629    }
1630}
1631
1632impl PreparedFontEnvironment {
1633    pub(crate) fn prepared_pairs_are_sealed(&self) -> Result<bool, FontError> {
1634        Ok(self
1635            .core
1636            .read()
1637            .map_err(|_| FontError::Synchronization)?
1638            .prepared_pairs_sealed)
1639    }
1640
1641    pub(crate) fn prepared_pair(
1642        &self,
1643        stack: &FontStack,
1644        weight: RequestedWeight,
1645    ) -> Result<Option<ResolvedFontPair>, FontError> {
1646        let core = self.core.read().map_err(|_| FontError::Synchronization)?;
1647        for prepared in &core.prepared_pairs {
1648            if prepared.weight == weight && prepared.stack.same(stack) {
1649                return prepared.resolved.try_copy(None).map(Some);
1650            }
1651        }
1652        Ok(None)
1653    }
1654
1655    pub(crate) fn shape_run(
1656        &self,
1657        identity: FaceIdentity,
1658        text: &str,
1659        direction: ShapingDirection,
1660        script: rustybuzz::Script,
1661    ) -> Result<ShapedRun, FontError> {
1662        self.shape_run_with_context(identity, text, direction, script, ShapingContext::default())
1663    }
1664
1665    pub(crate) fn shape_run_with_context(
1666        &self,
1667        identity: FaceIdentity,
1668        text: &str,
1669        direction: ShapingDirection,
1670        script: rustybuzz::Script,
1671        context: ShapingContext<'_>,
1672    ) -> Result<ShapedRun, FontError> {
1673        self.core
1674            .read()
1675            .map_err(|_| FontError::Synchronization)?
1676            .shape_run_with_context(identity, text, direction, script, context)
1677    }
1678
1679    /// Extract one planned glyph from the exact retained face bytes.
1680    pub(crate) fn outline_glyph(
1681        &self,
1682        identity: FaceIdentity,
1683        glyph_id: u16,
1684        builder: &mut dyn ttf_parser::OutlineBuilder,
1685    ) -> Result<(DesignMetrics, Option<GlyphInk>), FontError> {
1686        self.core
1687            .read()
1688            .map_err(|_| FontError::Synchronization)?
1689            .fonts
1690            .outline_glyph(identity, glyph_id, builder)
1691    }
1692
1693    pub(crate) fn face_metrics(&self, identity: FaceIdentity) -> Result<DesignMetrics, FontError> {
1694        self.core
1695            .read()
1696            .map_err(|_| FontError::Synchronization)?
1697            .face_metrics(identity)
1698    }
1699
1700    /// Replays the retained binary sources and generic-family state exactly; it
1701    /// never consults the host filesystem again.
1702    #[cfg(test)]
1703    pub(crate) fn populate_database(&self, database: &mut Database) -> Result<(), FontError> {
1704        *database = self
1705            .core
1706            .read()
1707            .map_err(|_| FontError::Synchronization)?
1708            .database
1709            .clone();
1710        Ok(())
1711    }
1712
1713    #[cfg(test)]
1714    pub(crate) fn synthetic() -> Self {
1715        Self::for_core(tests::generated_core()).unwrap()
1716    }
1717
1718    /// Retain generated OpenType layout tables for shaping conformance tests.
1719    #[cfg(test)]
1720    pub(crate) fn synthetic_shaping_fonts(fonts: Vec<Vec<u8>>) -> Self {
1721        Self::for_core(
1722            CanonicalFontCore::from_generated(
1723                fonts,
1724                &HostGenericNames::default(),
1725                FontPreparation::new(),
1726                scalar_presence_map().unwrap(),
1727            )
1728            .unwrap(),
1729        )
1730        .unwrap()
1731    }
1732
1733    /// Real retained SFNT faces with caller-chosen family names and cmap scalars.
1734    #[cfg(test)]
1735    pub(crate) fn synthetic_faces(faces: &[(&str, &[char])]) -> Self {
1736        let files = faces
1737            .iter()
1738            .map(|(family, coverage)| {
1739                let mut coverage = coverage.to_vec();
1740                coverage.sort_unstable();
1741                coverage.dedup();
1742                tests::build_test_font_with_coverage(family, &coverage)
1743            })
1744            .collect();
1745        Self::for_core(
1746            CanonicalFontCore::from_generated(
1747                files,
1748                &HostGenericNames::default(),
1749                FontPreparation::new(),
1750                scalar_presence_map().unwrap(),
1751            )
1752            .unwrap(),
1753        )
1754        .unwrap()
1755    }
1756}
1757
1758#[allow(dead_code)]
1759impl CanonicalFontCore {
1760    fn discover_prepared(
1761        preparation: FontPreparation,
1762        scalar_presence: Vec<u64>,
1763        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1764    ) -> Result<Self, FontError> {
1765        let sources = platform_sources(prepared_stage.as_deref_mut())?;
1766        let files = discover_indexed_files(&sources.roots, prepared_stage)?;
1767        Self::from_index(files, &sources.generics, preparation, scalar_presence)
1768    }
1769
1770    pub(crate) fn files(&self) -> &[RetainedFontFile] {
1771        &self.fonts.files
1772    }
1773
1774    pub(crate) fn faces(&self) -> &[FaceMetadata] {
1775        &self.fonts.faces
1776    }
1777
1778    #[expect(
1779        clippy::too_many_lines,
1780        reason = "one function keeps global counting, reservation, and pair-order materialization explicit"
1781    )]
1782    fn prepare_pairs_with_stage<'a>(
1783        &mut self,
1784        requests: impl ExactSizeIterator<Item = FontPairPreparationRequest<'a>>,
1785        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
1786    ) -> Result<(), FontError> {
1787        let pair_count = requests.len();
1788        let mut preparations = Vec::new();
1789        reserve_prepared_or_local(
1790            &mut preparations,
1791            pair_count,
1792            "font pair preparation storage",
1793            prepared_stage.as_deref_mut(),
1794        )?;
1795        reserve_prepared_or_local(
1796            &mut self.prepared_pairs,
1797            pair_count,
1798            "prepared font pairs",
1799            prepared_stage.as_deref_mut(),
1800        )?;
1801
1802        for request in requests {
1803            if self.prepared_pairs_sealed {
1804                return Err(FontError::PreparedPairAfterSeal {
1805                    pair_ordinal: request.pair_ordinal,
1806                });
1807            }
1808            for (ordinal, stack, weight) in self
1809                .prepared_pairs
1810                .iter()
1811                .map(|prepared| {
1812                    (
1813                        prepared.resolved.provenance.pair_ordinal,
1814                        &prepared.stack,
1815                        prepared.weight,
1816                    )
1817                })
1818                .chain(
1819                    preparations
1820                        .iter()
1821                        .map(|preparation: &PairPreparation<'_>| {
1822                            (
1823                                preparation.request.pair_ordinal,
1824                                preparation.request.stack,
1825                                preparation.request.weight,
1826                            )
1827                        }),
1828                )
1829            {
1830                if ordinal == request.pair_ordinal
1831                    || (weight == request.weight && stack.same(request.stack))
1832                {
1833                    return Err(FontError::DuplicatePreparedPair {
1834                        pair_ordinal: request.pair_ordinal,
1835                    });
1836                }
1837            }
1838            preparations.push(PairPreparation::new(request));
1839        }
1840        if preparations.len() != pair_count {
1841            return Err(FontError::Arithmetic(
1842                "font pair preparation count/materialization mismatch",
1843            ));
1844        }
1845
1846        for preparation in &mut preparations {
1847            reserve_prepared_or_local(
1848                &mut preparation.resolved_names,
1849                preparation.request.stack.len(),
1850                "resolved font stack",
1851                prepared_stage.as_deref_mut(),
1852            )?;
1853        }
1854        for preparation in &mut preparations {
1855            #[cfg(test)]
1856            FONT_PAIR_RESOLUTION_CALLS.with(|calls| calls.set(calls.get() + 1));
1857            resolve_stack_names_into(
1858                &self.database,
1859                preparation.request.stack,
1860                &mut preparation.resolved_names,
1861                &mut self.preparation,
1862                prepared_stage.as_deref_mut(),
1863            )?;
1864        }
1865        // Every relevant file is snapshotted and admitted before any published
1866        // pair is counted, ranked or selected. Later pairs can only append files;
1867        // this fixed index cannot introduce a new candidate into an old pair.
1868        for preparation in &preparations {
1869            self.materialize_matching(&preparation.resolved_names, prepared_stage.as_deref_mut())?;
1870        }
1871        for preparation in &mut preparations {
1872            preparation.raw_candidate_count =
1873                count_candidate_occurrences(&self.fonts.faces, &preparation.resolved_names);
1874            preparation.candidate_count =
1875                count_unique_candidate_survivors(&self.fonts.faces, &preparation.resolved_names)?;
1876            if preparation.candidate_count == 0 {
1877                return Err(self.admission_error(
1878                    FontError::MissingFamily {
1879                        pair_ordinal: preparation.request.pair_ordinal,
1880                    },
1881                    Some(preparation.request.stack),
1882                ));
1883            }
1884            let (scalar_count, rendering_scalar_count) = scalar_selection_capacities(
1885                preparation.request.required_scalars,
1886                &mut self.scalar_presence,
1887            )?;
1888            preparation.scalar_count = scalar_count;
1889            preparation.maximum_probes =
1890                maximum_glyph_probes(rendering_scalar_count, preparation.candidate_count)?;
1891        }
1892
1893        for preparation in &mut preparations {
1894            reserve_prepared_or_local(
1895                &mut preparation.candidates,
1896                preparation.raw_candidate_count,
1897                "font candidate occurrences",
1898                prepared_stage.as_deref_mut(),
1899            )?;
1900            reserve_prepared_or_local(
1901                &mut preparation.provenance,
1902                preparation.candidate_count,
1903                "font provenance",
1904                prepared_stage.as_deref_mut(),
1905            )?;
1906            reserve_prepared_or_local(
1907                &mut preparation.selected_scalars,
1908                preparation.scalar_count,
1909                "selected scalar faces",
1910                prepared_stage.as_deref_mut(),
1911            )?;
1912            reserve_prepared_or_local(
1913                &mut preparation.probes,
1914                preparation.maximum_probes,
1915                "font glyph probes",
1916                prepared_stage.as_deref_mut(),
1917            )?;
1918
1919            reserve_prepared_or_local(
1920                &mut preparation.retained_stack,
1921                preparation.request.stack.len(),
1922                "prepared font stack",
1923                prepared_stage.as_deref_mut(),
1924            )?;
1925            reserve_family_stack_names(
1926                &mut preparation.retained_stack,
1927                preparation.request.stack,
1928                prepared_stage.as_deref_mut(),
1929            )?;
1930        }
1931        if preparations
1932            .iter()
1933            .any(|preparation| !preparation.storage_is_reserved())
1934        {
1935            return Err(FontError::Arithmetic(
1936                "font pair storage reservation mismatch",
1937            ));
1938        }
1939
1940        for mut preparation in preparations {
1941            let request = preparation.request;
1942            materialize_candidate_occurrences(
1943                &self.fonts.faces,
1944                &preparation.resolved_names,
1945                request.weight,
1946                &mut preparation.candidates,
1947            )?;
1948            if preparation.candidates.len() != preparation.raw_candidate_count {
1949                return Err(FontError::Arithmetic(
1950                    "font candidate count/materialization mismatch",
1951                ));
1952            }
1953            canonicalize_candidate_occurrences(&mut preparation.candidates);
1954            if preparation.candidates.len() != preparation.candidate_count {
1955                return Err(FontError::Arithmetic(
1956                    "canonical candidate count/materialization mismatch",
1957                ));
1958            }
1959            preparation.provenance.extend(
1960                preparation
1961                    .candidates
1962                    .iter()
1963                    .map(|candidate| candidate.occurrence.identity),
1964            );
1965            let primary = preparation.provenance[0];
1966
1967            let (scalar_count, rendering_scalar_count) =
1968                scalar_selection_capacities(request.required_scalars, &mut self.scalar_presence)?;
1969            let maximum_probes =
1970                maximum_glyph_probes(rendering_scalar_count, preparation.candidates.len())?;
1971            if scalar_count != preparation.scalar_count
1972                || maximum_probes != preparation.maximum_probes
1973            {
1974                return Err(FontError::Arithmetic(
1975                    "font scalar capacity/materialization mismatch",
1976                ));
1977            }
1978            let files = &self.fonts.files;
1979            let faces = &self.fonts.faces;
1980            materialize_scalar_selection(
1981                request.pair_ordinal,
1982                &preparation.candidates,
1983                request.required_scalars,
1984                &mut self.scalar_presence,
1985                scalar_count,
1986                maximum_probes,
1987                &mut preparation.selected_scalars,
1988                &mut preparation.probes,
1989                |candidate, scalar| {
1990                    #[cfg(test)]
1991                    FONT_SELECTION_PROBES.with(|calls| calls.set(calls.get() + 1));
1992                    let face = &faces[candidate.face_ordinal];
1993                    let file = &files[face.file_ordinal];
1994                    let parsed = ttf_parser::Face::parse(&file.bytes, face.identity.face_index)
1995                        .map_err(|error| FontError::ParseFace {
1996                            path: file.canonical_path.clone(),
1997                            index: face.identity.face_index,
1998                            reason: error.to_string(),
1999                        })?;
2000                    Ok(parsed.glyph_index(scalar).is_some())
2001                },
2002            )?;
2003            fill_reserved_family_stack(&mut preparation.retained_stack, request.stack)?;
2004            self.prepared_pairs.push(PreparedPair {
2005                stack: FontStack {
2006                    families: { Arc::new(preparation.retained_stack) },
2007                },
2008                weight: request.weight,
2009                candidates: preparation.candidates,
2010                sources: Vec::new(),
2011                resolved: ResolvedFontPair {
2012                    provenance: PairProvenance {
2013                        pair_ordinal: request.pair_ordinal,
2014                        weight: request.weight,
2015                        candidates: preparation.provenance,
2016                    },
2017                    primary,
2018                    selected_scalars: SelectedScalarFaces(preparation.selected_scalars),
2019                    selected_units: Vec::new(),
2020                },
2021            });
2022        }
2023        Ok(())
2024    }
2025
2026    #[cfg(test)]
2027    pub(crate) fn resolve_pair(
2028        &mut self,
2029        pair_ordinal: u32,
2030        stack: &FontStack,
2031        weight: RequestedWeight,
2032        required_scalars: &[char],
2033    ) -> Result<ResolvedFontPair, FontError> {
2034        let index = self.admit_scalars_in(pair_ordinal, stack, weight, required_scalars, None)?;
2035        self.prepared_pairs[index].resolved.try_copy(None)
2036    }
2037
2038    fn admit_scalars_in(
2039        &mut self,
2040        pair_ordinal: u32,
2041        stack: &FontStack,
2042        weight: RequestedWeight,
2043        required_scalars: &[char],
2044
2045        mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2046    ) -> Result<usize, FontError> {
2047        let mut cached_index = None;
2048        for (index, cached) in self.prepared_pairs.iter().enumerate() {
2049            if cached.weight == weight && cached.stack.same(stack) {
2050                cached_index = Some(index);
2051                break;
2052            }
2053        }
2054        let Some(index) = cached_index else {
2055            let index = self.prepared_pairs.len();
2056            self.prepare_pairs_with_stage(
2057                std::iter::once(FontPairPreparationRequest::new(
2058                    pair_ordinal,
2059                    stack,
2060                    weight,
2061                    required_scalars,
2062                )),
2063                prepared_stage.as_deref_mut(),
2064            )?;
2065            return Ok(index);
2066        };
2067        let cached = &mut self.prepared_pairs[index];
2068        let mut missing = Vec::new();
2069
2070        for scalar in required_scalars {
2071            let mut found = false;
2072            for candidate in cached
2073                .resolved
2074                .selected_scalars
2075                .iter()
2076                .map(|selected| selected.scalar)
2077                .chain(missing.iter().copied())
2078            {
2079                if candidate == *scalar {
2080                    found = true;
2081                    break;
2082                }
2083            }
2084            if !found {
2085                reserve_cached_with_stage(&mut missing, 1, prepared_stage.as_deref_mut())?;
2086                missing.push(*scalar);
2087            }
2088        }
2089        if !missing.is_empty() {
2090            let files = &self.fonts.files;
2091            let faces = &self.fonts.faces;
2092            let selected = select_scalar_faces_with_stage(
2093                cached.resolved.provenance.pair_ordinal,
2094                &cached.candidates,
2095                &missing,
2096                &mut self.scalar_presence,
2097                prepared_stage.as_deref_mut(),
2098                |candidate, scalar| {
2099                    #[cfg(test)]
2100                    FONT_SELECTION_PROBES.with(|calls| calls.set(calls.get() + 1));
2101                    let face = &faces[candidate.face_ordinal];
2102                    let file = &files[face.file_ordinal];
2103                    let parsed = ttf_parser::Face::parse(&file.bytes, face.identity.face_index)
2104                        .map_err(|error| FontError::ParseFace {
2105                            path: file.canonical_path.clone(),
2106                            index: face.identity.face_index,
2107                            reason: error.to_string(),
2108                        })?;
2109                    Ok(parsed.glyph_index(scalar).is_some())
2110                },
2111            )?;
2112            reserve_cached_with_stage(
2113                &mut cached.resolved.selected_scalars.0,
2114                selected.len(),
2115                prepared_stage,
2116            )?;
2117
2118            cached.resolved.selected_scalars.0.extend(selected);
2119        }
2120        // Cached metadata and successful scalar selections are never recomputed.
2121        Ok(index)
2122    }
2123
2124    pub(crate) fn shape_run(
2125        &self,
2126        identity: FaceIdentity,
2127        text: &str,
2128        direction: ShapingDirection,
2129        script: rustybuzz::Script,
2130    ) -> Result<ShapedRun, FontError> {
2131        self.shape_run_with_context(identity, text, direction, script, ShapingContext::default())
2132    }
2133
2134    fn shape_run_with_context(
2135        &self,
2136        identity: FaceIdentity,
2137        text: &str,
2138        direction: ShapingDirection,
2139        script: rustybuzz::Script,
2140        context: ShapingContext<'_>,
2141    ) -> Result<ShapedRun, FontError> {
2142        let metadata = self.find_face(identity).ok_or(FontError::Shape {
2143            identity,
2144            reason: "identity is not retained",
2145        })?;
2146        let file = &self.fonts.files[metadata.file_ordinal];
2147        shape_retained_run(file, metadata, text, direction, script, context)
2148    }
2149
2150    pub(crate) fn face_metrics(&self, identity: FaceIdentity) -> Result<DesignMetrics, FontError> {
2151        #[cfg(test)]
2152        FONT_METRIC_QUERIES.with(|queries| queries.borrow_mut().push(identity));
2153        let face = self.find_face(identity).ok_or(FontError::Shape {
2154            identity,
2155            reason: "identity is not retained",
2156        })?;
2157        face.metrics.validate(identity)
2158    }
2159
2160    fn find_face(&self, identity: FaceIdentity) -> Option<&FaceMetadata> {
2161        self.fonts
2162            .faces
2163            .iter()
2164            .find(|&face| face.identity == identity)
2165            .map(|v| v as _)
2166    }
2167
2168    fn outline_glyph(
2169        &self,
2170        identity: FaceIdentity,
2171        glyph_id: u16,
2172        builder: &mut dyn ttf_parser::OutlineBuilder,
2173    ) -> Result<(DesignMetrics, Option<GlyphInk>), FontError> {
2174        self.fonts.outline_glyph(identity, glyph_id, builder)
2175    }
2176
2177    #[cfg(test)]
2178    fn from_generated(
2179        files: Vec<Vec<u8>>,
2180        generics: &HostGenericNames,
2181        preparation: FontPreparation,
2182        scalar_presence: Vec<u64>,
2183    ) -> Result<Self, FontError> {
2184        let index = files
2185            .into_iter()
2186            .map(index::generated)
2187            .collect::<Result<Vec<_>, _>>()?;
2188        let mut core = Self::from_index(index, generics, preparation, scalar_presence)?;
2189        // Parser/geometry fixtures explicitly request the complete generated
2190        // collection, through the same index/materialization/admission path.
2191        for ordinal in 0..core.index.len() {
2192            core.materialize_file(ordinal, None)?;
2193        }
2194        Ok(core)
2195    }
2196
2197    fn from_index(
2198        index: Vec<index::IndexedFontFile>,
2199        generics: &HostGenericNames,
2200        preparation: FontPreparation,
2201        scalar_presence: Vec<u64>,
2202    ) -> Result<Self, FontError> {
2203        let operation = preparation.operation.clone();
2204        let mut database = Database::new();
2205
2206        apply_host_generics(&mut database, generics);
2207
2208        if scalar_presence.len() != SCALAR_MAP_WORDS {
2209            return Err(FontError::Arithmetic("Unicode scalar presence map"));
2210        }
2211
2212        Ok(Self {
2213            database,
2214            index,
2215            fonts: Arc::new(FrozenFontRegistry {
2216                files: Vec::new(),
2217                faces: Vec::new(),
2218                issues: Vec::new(),
2219            }),
2220            scalar_presence,
2221            prepared_pairs: Vec::new(),
2222            prepared_pairs_sealed: false,
2223            operation,
2224            preparation,
2225        })
2226    }
2227
2228    fn materialize_matching(
2229        &mut self,
2230        names: &[String],
2231        mut stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2232    ) -> Result<(), FontError> {
2233        if self.prepared_pairs_sealed {
2234            return Err(FontError::OperationSealed);
2235        }
2236        for ordinal in 0..self.index.len() {
2237            if !self.index[ordinal].is_materialized() && self.index[ordinal].matches(names) {
2238                self.materialize_file(ordinal, stage.as_deref_mut())?;
2239            }
2240        }
2241        Ok(())
2242    }
2243
2244    fn materialize_file(
2245        &mut self,
2246        ordinal: usize,
2247        mut stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2248    ) -> Result<(), FontError> {
2249        if self.prepared_pairs_sealed {
2250            return Err(FontError::OperationSealed);
2251        }
2252        let indexed = self
2253            .index
2254            .get_mut(ordinal)
2255            .ok_or(FontError::Arithmetic("indexed font ordinal"))?;
2256        if indexed.is_materialized() {
2257            return Ok(());
2258        }
2259        let file = indexed.materialize(stage.as_deref_mut())?;
2260        let fonts = Arc::get_mut(&mut self.fonts)
2261            .ok_or(FontError::Arithmetic("font registry shared before sealing"))?;
2262        let face_start = fonts.faces.len();
2263        let file_ordinal = fonts.files.len();
2264        reserve_prepared_or_local(
2265            &mut fonts.files,
2266            1,
2267            "materialized font files",
2268            stage.as_deref_mut(),
2269        )?;
2270        admission::admit_file(
2271            &file,
2272            file_ordinal,
2273            &mut self.database,
2274            &mut fonts.faces,
2275            &mut fonts.issues,
2276            stage,
2277        )?;
2278        for face in &fonts.faces[face_start..] {
2279            if !indexed
2280                .faces
2281                .iter()
2282                .any(|entry| entry.index == face.identity.face_index && entry.names == face.names)
2283            {
2284                return Err(FontError::Arithmetic(
2285                    "font index/admission family mismatch",
2286                ));
2287            }
2288        }
2289        fonts.files.push(file);
2290        indexed.finish_materialization();
2291        // Read witnesses have served their purpose; the first complete snapshot
2292        // now owns every subsequent query. No reopening this path is permitted.
2293        Ok(())
2294    }
2295
2296    #[expect(
2297        clippy::unnecessary_debug_formatting,
2298        reason = "diagnostics preserve escaped lossless native paths"
2299    )]
2300    fn admission_error(&self, error: FontError, stack: Option<&FontStack>) -> FontError {
2301        if !matches!(
2302            error,
2303            FontError::MissingFamily { .. } | FontError::MissingGlyph { .. }
2304        ) {
2305            return error;
2306        }
2307        let mut error = self.fonts.admission_error(error, stack);
2308        if let FontError::Admission { context, .. } = &mut error {
2309            for indexed in self.index.iter().filter(|file| !file.is_materialized()) {
2310                for (index, reason) in &indexed.issues {
2311                    let entry = match admission::format_diagnostic(format_args!(
2312                        "; index {:?} index={index:?}: {reason} (not materialized; no full-file SHA)",
2313                        indexed.path,
2314                    )) {
2315                        Ok(entry) => entry,
2316                        Err(error) => return error,
2317                    };
2318                    if let Err(error) = reserve_string_prepared_or_local(
2319                        context,
2320                        entry.len(),
2321                        "font index diagnostics",
2322                        None,
2323                    ) {
2324                        return error;
2325                    }
2326                    context.push_str(&entry);
2327                }
2328            }
2329        }
2330        error
2331    }
2332}
2333
2334impl FrozenFontRegistry {
2335    #[expect(
2336        clippy::unnecessary_debug_formatting,
2337        reason = "diagnostics preserve escaped lossless native paths"
2338    )]
2339    fn admission_error(&self, error: FontError, stack: Option<&FontStack>) -> FontError {
2340        if !matches!(
2341            error,
2342            FontError::MissingFamily { .. } | FontError::MissingGlyph { .. }
2343        ) {
2344            return error;
2345        }
2346        let context = (|| {
2347            let mut context =
2348                admission::format_diagnostic(format_args!("requested stack {stack:?}"))?;
2349            for issue in &self.issues {
2350                let file = self
2351                    .files
2352                    .get(issue.file_ordinal)
2353                    .ok_or(FontError::Arithmetic("font diagnostic file identity"))?;
2354                let entry = admission::format_diagnostic(format_args!(
2355                    "; scan {:?} sha256={:02x?} index={:?}: {:?}",
2356                    file.canonical_path, file.sha256, issue.face_index, issue.reason,
2357                ))?;
2358                reserve_string_prepared_or_local(
2359                    &mut context,
2360                    entry.len(),
2361                    "font failure diagnostics",
2362                    None,
2363                )?;
2364                context.push_str(&entry);
2365            }
2366            Ok::<_, FontError>(context)
2367        })();
2368        match context {
2369            Ok(context) => FontError::Admission {
2370                context,
2371                source: Box::new(error),
2372            },
2373            Err(error) => error,
2374        }
2375    }
2376
2377    pub(crate) fn outline_glyph(
2378        &self,
2379        identity: FaceIdentity,
2380        glyph_id: u16,
2381        builder: &mut dyn ttf_parser::OutlineBuilder,
2382    ) -> Result<(DesignMetrics, Option<GlyphInk>), FontError> {
2383        #[cfg(test)]
2384        FONT_OUTLINE_GLYPHS.with(|glyphs| glyphs.borrow_mut().push((identity, glyph_id)));
2385        let metadata = self
2386            .faces
2387            .iter()
2388            .find(|face| face.identity == identity)
2389            .ok_or(FontError::Outline {
2390                identity,
2391                glyph_id,
2392                reason: "identity is not retained",
2393            })?;
2394        let file = &self.files[metadata.file_ordinal];
2395        let metrics = metadata.metrics.validate(identity)?;
2396        let face = ttf_parser::Face::parse(&file.bytes, identity.face_index).map_err(|_| {
2397            FontError::Outline {
2398                identity,
2399                glyph_id,
2400                reason: "ttf-parser rejected the retained face",
2401            }
2402        })?;
2403        let ink = face
2404            .outline_glyph(ttf_parser::GlyphId(glyph_id), builder)
2405            .map(|bounds| GlyphInk {
2406                x_min: bounds.x_min,
2407                y_min: bounds.y_min,
2408                x_max: bounds.x_max,
2409                y_max: bounds.y_max,
2410            });
2411        validate_selected_glyph_paint(&face, identity, glyph_id, ink.is_some())?;
2412        Ok((metrics, ink))
2413    }
2414}
2415
2416/// Only inspect paint for an actually used glyph with no outline result.
2417/// Paint queries expose declarations or encoded data, not a full validity proof.
2418fn validate_selected_glyph_paint(
2419    face: &ttf_parser::Face<'_>,
2420    identity: FaceIdentity,
2421    glyph_id: u16,
2422    has_outline: bool,
2423) -> Result<(), FontError> {
2424    if has_outline {
2425        return Ok(());
2426    }
2427    let glyph = ttf_parser::GlyphId(glyph_id);
2428    let paint = if face.glyph_raster_image(glyph, u16::MAX).is_some() {
2429        Some(GlyphPaint::RasterImage)
2430    } else if face.glyph_svg_image(glyph).is_some() {
2431        Some(GlyphPaint::SvgImage)
2432    } else if face.is_color_glyph(glyph) {
2433        Some(GlyphPaint::ColorLayers)
2434    } else {
2435        None
2436    };
2437    if let Some(paint) = paint {
2438        return Err(FontError::UnsupportedGlyphPaint {
2439            identity,
2440            glyph_id,
2441            paint,
2442        });
2443    }
2444    Ok(())
2445}
2446
2447fn design_metrics(face: &ttf_parser::Face<'_>) -> DesignMetrics {
2448    // Keep the existing typo-first policy without component-wise zero fallbacks.
2449    // No usable nominal interval is not proof that actual glyph ink is unusable.
2450    let typo = face
2451        .typographic_ascender()
2452        .zip(face.typographic_descender());
2453    let hhea = face.tables().hhea;
2454    let (ascender, descender, source) = if let Some((a, d)) = typo.filter(|(a, d)| a > d) {
2455        (a, d, MetricSource::Typographic)
2456    } else if hhea.ascender > hhea.descender {
2457        (hhea.ascender, hhea.descender, MetricSource::Hhea)
2458    } else {
2459        (0, 0, MetricSource::InkOnly)
2460    };
2461    DesignMetrics {
2462        units_per_em: face.units_per_em(),
2463        ascender,
2464        descender,
2465        source,
2466    }
2467}
2468
2469fn decode_family_names(
2470    names: ttf_parser::name::Names<'_>,
2471
2472    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2473) -> Result<Vec<NameOccurrence>, FontError> {
2474    let mut occurrence_count = 0;
2475    for ordinal in 0..names.len() {
2476        let Some(record) = names.get(ordinal) else {
2477            continue;
2478        };
2479        if matches!(
2480            record.name_id,
2481            ttf_parser::name_id::TYPOGRAPHIC_FAMILY | ttf_parser::name_id::FAMILY
2482        ) {
2483            occurrence_count += usize::from(decodes_like_ttf_parser(&record));
2484        }
2485    }
2486
2487    let mut occurrences = Vec::new();
2488    reserve_prepared_or_local(
2489        &mut occurrences,
2490        occurrence_count,
2491        "font family name occurrences",
2492        prepared_stage,
2493    )?;
2494
2495    for record_ordinal in 0..names.len() {
2496        let Some(record) = names.get(record_ordinal) else {
2497            continue;
2498        };
2499        if !matches!(
2500            record.name_id,
2501            ttf_parser::name_id::TYPOGRAPHIC_FAMILY | ttf_parser::name_id::FAMILY
2502        ) {
2503            continue;
2504        }
2505        let Some(value) = admission::decode_name(&record)? else {
2506            continue;
2507        };
2508        occurrences.push(NameOccurrence {
2509            folded: fold_family_name(&value)?,
2510            value,
2511            record_ordinal,
2512        });
2513    }
2514    if occurrences.len() != occurrence_count {
2515        return Err(FontError::Arithmetic(
2516            "font family-name count/materialization mismatch",
2517        ));
2518    }
2519    Ok(occurrences)
2520}
2521
2522fn decodes_like_ttf_parser(record: &ttf_parser::name::Name<'_>) -> bool {
2523    if !record.is_unicode() {
2524        return false;
2525    }
2526    for scalar in char::decode_utf16(
2527        record
2528            .name
2529            .chunks_exact(2)
2530            .map(|unit| u16::from_be_bytes([unit[0], unit[1]])),
2531    ) {
2532        if scalar.is_err() {
2533            return false;
2534        }
2535    }
2536    true
2537}
2538
2539fn resolve_stack_names_into(
2540    database: &Database,
2541    stack: &FontStack,
2542    resolved_names: &mut Vec<String>,
2543    preparation: &mut FontPreparation,
2544    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2545) -> Result<(), FontError> {
2546    for cached in &preparation.normalized_stacks {
2547        if cached.source.same(stack) {
2548            for name in &cached.names {
2549                resolved_names.push(copy_name_with_stage(name, prepared_stage.as_deref_mut())?);
2550            }
2551            return Ok(());
2552        }
2553    }
2554    for family in stack {
2555        let name = match &family.kind {
2556            FontFamilyKind::Named(name) => name.as_str(),
2557            FontFamilyKind::Generic(GenericFontFamily::Serif) => {
2558                database.family_name(&Family::Serif)
2559            }
2560            FontFamilyKind::Generic(GenericFontFamily::SansSerif) => {
2561                database.family_name(&Family::SansSerif)
2562            }
2563            FontFamilyKind::Generic(GenericFontFamily::Monospace) => {
2564                database.family_name(&Family::Monospace)
2565            }
2566        };
2567        resolved_names.push(fold_family_name(name)?);
2568    }
2569    if resolved_names.len() != stack.len() {
2570        return Err(FontError::Arithmetic(
2571            "resolved font stack count/materialization mismatch",
2572        ));
2573    }
2574    let source = copy_stack_with_stage(stack, prepared_stage.as_deref_mut())?;
2575    let mut names = Vec::new();
2576    reserve_cached_with_stage(
2577        &mut names,
2578        resolved_names.len(),
2579        prepared_stage.as_deref_mut(),
2580    )?;
2581    for name in resolved_names.iter() {
2582        names.push(copy_name_with_stage(name, prepared_stage.as_deref_mut())?);
2583    }
2584
2585    reserve_cached_with_stage(&mut preparation.normalized_stacks, 1, prepared_stage)?;
2586    preparation
2587        .normalized_stacks
2588        .push(NormalizedStack { source, names });
2589    Ok(())
2590}
2591
2592fn fold_family_name(value: &str) -> Result<String, FontError> {
2593    #[cfg(test)]
2594    FONT_NORMALIZATION_CALLS.with(|calls| calls.set(calls.get() + 1));
2595    super::unicode16::nfkc_casefold(value)
2596}
2597
2598fn reserve_cached<T>(values: &mut Vec<T>, additional: usize) -> Result<(), FontError> {
2599    reserve_cached_with_stage(values, additional, None)
2600}
2601
2602fn reserve_cached_with_stage<T>(
2603    values: &mut Vec<T>,
2604    additional: usize,
2605
2606    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2607) -> Result<(), FontError> {
2608    let required = values
2609        .len()
2610        .checked_add(additional)
2611        .ok_or(FontError::Arithmetic("font cache length"))?;
2612
2613    if required > values.capacity() {
2614        reserve_prepared_or_local(values, additional, "operation font cache", prepared_stage)?;
2615    }
2616    Ok(())
2617}
2618
2619fn copy_name_with_stage(
2620    source: &str,
2621
2622    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2623) -> Result<String, FontError> {
2624    let mut output = String::new();
2625    reserve_string_prepared_or_local(
2626        &mut output,
2627        source.len(),
2628        "cached font name",
2629        prepared_stage,
2630    )?;
2631    output.push_str(source);
2632    Ok(output)
2633}
2634
2635fn copy_stack_with_stage(
2636    source: &FontStack,
2637    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2638) -> Result<FontStack, FontError> {
2639    let mut output = Vec::new();
2640    reserve_cached_with_stage(&mut output, source.len(), prepared_stage.as_deref_mut())?;
2641    for entry in source {
2642        output.push(FontFamily {
2643            kind: match &entry.kind {
2644                FontFamilyKind::Named(name) => {
2645                    let mut retained = String::new();
2646
2647                    reserve_string_prepared_or_local(
2648                        &mut retained,
2649                        name.len(),
2650                        "cached font name",
2651                        prepared_stage.as_deref_mut(),
2652                    )?;
2653                    retained.push_str(name);
2654                    FontFamilyKind::Named(retained)
2655                }
2656                FontFamilyKind::Generic(family) => FontFamilyKind::Generic(*family),
2657            },
2658        });
2659    }
2660    Ok(FontStack {
2661        families: Arc::new(output),
2662    })
2663}
2664
2665fn materialize_candidate_occurrences(
2666    faces: &[FaceMetadata],
2667    resolved_names: &[String],
2668    requested_weight: RequestedWeight,
2669
2670    candidates: &mut Vec<CandidateFace>,
2671) -> Result<(), FontError> {
2672    for (face_ordinal, face) in faces.iter().enumerate() {
2673        let Some(stack_entry_index) = first_matching_stack_entry(&face.names, resolved_names)
2674        else {
2675            continue;
2676        };
2677        let stack_entry_index = u32::try_from(stack_entry_index)
2678            .map_err(|_| FontError::Arithmetic("font stack entry index"))?;
2679        let stretch_distance = u8::try_from(face.stretch.to_number().abs_diff(5))
2680            .map_err(|_| FontError::Arithmetic("font stretch distance"))?;
2681        candidates.push(CandidateFace {
2682            occurrence: CandidateOccurrence {
2683                stack_entry_index,
2684                style_distance: style_distance(face.style),
2685                stretch_distance,
2686                weight_distance: face.weight.abs_diff(requested_weight.value()),
2687                identity: face.identity,
2688            },
2689            face_ordinal,
2690        });
2691    }
2692    Ok(())
2693}
2694
2695fn count_candidate_occurrences(faces: &[FaceMetadata], resolved_names: &[String]) -> usize {
2696    faces
2697        .iter()
2698        .filter(|face| first_matching_stack_entry(&face.names, resolved_names).is_some())
2699        .count()
2700}
2701
2702fn count_unique_candidate_survivors(
2703    faces: &[FaceMetadata],
2704    resolved_names: &[String],
2705) -> Result<usize, FontError> {
2706    let mut count = 0_usize;
2707    for (face_index, face) in faces.iter().enumerate() {
2708        if first_matching_stack_entry(&face.names, resolved_names).is_none() {
2709            continue;
2710        }
2711        let mut duplicate = false;
2712        for earlier in &faces[..face_index] {
2713            if earlier.identity == face.identity
2714                && first_matching_stack_entry(&earlier.names, resolved_names).is_some()
2715            {
2716                duplicate = true;
2717                break;
2718            }
2719        }
2720        if duplicate {
2721            continue;
2722        }
2723        count = count
2724            .checked_add(1)
2725            .ok_or(FontError::Arithmetic("canonical font candidates"))?;
2726    }
2727    Ok(count)
2728}
2729
2730fn first_matching_stack_entry(
2731    names: &[NameOccurrence],
2732    resolved_names: &[String],
2733) -> Option<usize> {
2734    // Family records establish membership only. A face matching multiple names
2735    // belongs at its first matching stack position, regardless of name ID.
2736    resolved_names
2737        .iter()
2738        .position(|resolved| names.iter().any(|name| name.folded == *resolved))
2739}
2740
2741fn canonicalize_candidate_occurrences(candidates: &mut Vec<CandidateFace>) {
2742    candidates.sort_by(|left, right| {
2743        left.occurrence
2744            .identity
2745            .cmp(&right.occurrence.identity)
2746            .then_with(|| left.occurrence.canonical_cmp(&right.occurrence))
2747    });
2748
2749    candidates.dedup_by(|right, left| right.occurrence.identity == left.occurrence.identity);
2750
2751    candidates.sort_by(|left, right| left.occurrence.canonical_cmp(&right.occurrence));
2752}
2753
2754const fn style_distance(style: Style) -> u8 {
2755    match style {
2756        Style::Normal => 0,
2757        Style::Oblique => 1,
2758        Style::Italic => 2,
2759    }
2760}
2761
2762fn select_scalar_faces<F>(
2763    pair_ordinal: u32,
2764    candidates: &[CandidateFace],
2765    required_scalars: &[char],
2766    presence: &mut [u64],
2767
2768    has_glyph: F,
2769) -> Result<Vec<SelectedScalarFace>, FontError>
2770where
2771    F: FnMut(&CandidateFace, char) -> Result<bool, FontError>,
2772{
2773    select_scalar_faces_with_stage(
2774        pair_ordinal,
2775        candidates,
2776        required_scalars,
2777        presence,
2778        None,
2779        has_glyph,
2780    )
2781}
2782
2783fn select_scalar_faces_with_stage<F>(
2784    pair_ordinal: u32,
2785    candidates: &[CandidateFace],
2786    required_scalars: &[char],
2787    presence: &mut [u64],
2788
2789    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
2790    has_glyph: F,
2791) -> Result<Vec<SelectedScalarFace>, FontError>
2792where
2793    F: FnMut(&CandidateFace, char) -> Result<bool, FontError>,
2794{
2795    let (scalar_count, rendering_scalar_count) =
2796        scalar_selection_capacities(required_scalars, presence)?;
2797    let maximum_probes = maximum_glyph_probes(rendering_scalar_count, candidates.len())?;
2798
2799    let mut selected = Vec::new();
2800    reserve_prepared_or_local(
2801        &mut selected,
2802        scalar_count,
2803        "selected scalar faces",
2804        prepared_stage.as_deref_mut(),
2805    )?;
2806    let mut probes = Vec::new();
2807    reserve_prepared_or_local(
2808        &mut probes,
2809        maximum_probes,
2810        "font glyph probes",
2811        prepared_stage,
2812    )?;
2813    materialize_scalar_selection(
2814        pair_ordinal,
2815        candidates,
2816        required_scalars,
2817        presence,
2818        scalar_count,
2819        maximum_probes,
2820        &mut selected,
2821        &mut probes,
2822        has_glyph,
2823    )?;
2824    Ok(selected)
2825}
2826
2827fn scalar_selection_capacities(
2828    required_scalars: &[char],
2829    presence: &mut [u64],
2830) -> Result<(usize, usize), FontError> {
2831    if presence.len() != SCALAR_MAP_WORDS {
2832        return Err(FontError::Arithmetic("Unicode scalar presence map"));
2833    }
2834    presence.fill(0);
2835
2836    for scalar in required_scalars {
2837        if crate::text::is_unsupported_control(*scalar) {
2838            return Err(FontError::UnsupportedControl {
2839                scalar: *scalar as u32,
2840            });
2841        }
2842        let value = *scalar as usize;
2843        presence[value / u64::BITS as usize] |= 1_u64 << (value % u64::BITS as usize);
2844    }
2845
2846    let scalar_count = presence.iter().try_fold(0_usize, |total, word| {
2847        total
2848            .checked_add(word.count_ones() as usize)
2849            .ok_or(FontError::Arithmetic("required scalar count"))
2850    })?;
2851    let mandatory_break_count = presence
2852        .iter()
2853        .enumerate()
2854        .map(|(word_index, word)| {
2855            let mut bits = *word;
2856            let mut count = 0;
2857            while bits != 0 {
2858                let value = word_index * u64::BITS as usize + bits.trailing_zeros() as usize;
2859                if char::from_u32(u32::try_from(value).expect("Unicode scalar map index"))
2860                    .is_some_and(|scalar| {
2861                        is_nonrendering_mandatory_break(scalar) || is_nonpainting_control(scalar)
2862                    })
2863                {
2864                    count += 1;
2865                }
2866                bits &= bits - 1;
2867            }
2868            count
2869        })
2870        .sum::<usize>();
2871    let rendering_scalar_count = scalar_count
2872        .checked_sub(mandatory_break_count)
2873        .ok_or(FontError::Arithmetic("rendering scalar count"))?;
2874    Ok((scalar_count, rendering_scalar_count))
2875}
2876
2877fn maximum_glyph_probes(
2878    rendering_scalar_count: usize,
2879    candidate_count: usize,
2880) -> Result<usize, FontError> {
2881    let maximum_probes = rendering_scalar_count
2882        .checked_mul(candidate_count)
2883        .ok_or(FontError::Arithmetic("required scalar probes"))?;
2884    let _ = u64::try_from(maximum_probes)
2885        .map_err(|_| FontError::Arithmetic("required scalar probes"))?;
2886    Ok(maximum_probes)
2887}
2888
2889#[expect(
2890    clippy::too_many_arguments,
2891    reason = "materialization receives every pre-reserved payload and its exact census"
2892)]
2893fn materialize_scalar_selection<F>(
2894    pair_ordinal: u32,
2895    candidates: &[CandidateFace],
2896    required_scalars: &[char],
2897    presence: &mut [u64],
2898
2899    scalar_count: usize,
2900    maximum_probes: usize,
2901    selected: &mut Vec<SelectedScalarFace>,
2902    probes: &mut Vec<GlyphProbe>,
2903    mut has_glyph: F,
2904) -> Result<(), FontError>
2905where
2906    F: FnMut(&CandidateFace, char) -> Result<bool, FontError>,
2907{
2908    for scalar in required_scalars {
2909        let value = *scalar as usize;
2910        let word = &mut presence[value / u64::BITS as usize];
2911        let bit = 1_u64 << (value % u64::BITS as usize);
2912        if *word & bit == 0 {
2913            continue;
2914        }
2915        *word &= !bit;
2916        let scalar = *scalar;
2917        if is_nonrendering_mandatory_break(scalar) {
2918            selected.push(SelectedScalarFace {
2919                scalar,
2920                selection: ScalarFaceSelection::NonRenderingMandatoryBreak,
2921            });
2922            continue;
2923        }
2924        if is_nonpainting_control(scalar) {
2925            selected.push(SelectedScalarFace {
2926                scalar,
2927                selection: ScalarFaceSelection::Face(candidates[0].occurrence.identity),
2928            });
2929            continue;
2930        }
2931
2932        for candidate in candidates {
2933            probes.push(GlyphProbe {
2934                scalar,
2935                identity: candidate.occurrence.identity,
2936                covered: has_glyph(candidate, scalar)?,
2937            });
2938        }
2939        let identity = probes
2940            .iter()
2941            .rev()
2942            .take(candidates.len())
2943            .rev()
2944            .find(|probe| probe.scalar == scalar && probe.covered)
2945            .map(|probe| probe.identity)
2946            .ok_or(FontError::MissingGlyph {
2947                pair_ordinal,
2948                scalar: scalar as u32,
2949            })?;
2950        selected.push(SelectedScalarFace {
2951            scalar,
2952            selection: ScalarFaceSelection::Face(identity),
2953        });
2954    }
2955    if probes.len() != maximum_probes || selected.len() != scalar_count {
2956        return Err(FontError::Arithmetic(
2957            "glyph probe or scalar-face count/materialization mismatch",
2958        ));
2959    }
2960    Ok(())
2961}
2962
2963/// Context is clipped to the selected line, not to a font/script item. Empty
2964/// pre/post context denotes a real selected-line boundary (BOT/EOT).
2965#[derive(Debug, Clone, Copy, Default)]
2966pub(crate) struct ShapingContext<'a> {
2967    pub(crate) pre: &'a str,
2968    pub(crate) post: &'a str,
2969    /// Run-local source byte of a selected U+00AD, rendered as U+002D.
2970    pub(crate) soft_hyphen: Option<usize>,
2971}
2972
2973fn shape_retained_run(
2974    file: &RetainedFontFile,
2975    metadata: &FaceMetadata,
2976    text: &str,
2977    direction: ShapingDirection,
2978    script: rustybuzz::Script,
2979    context: ShapingContext<'_>,
2980) -> Result<ShapedRun, FontError> {
2981    if text.chars().any(is_nonrendering_mandatory_break) {
2982        return Err(FontError::Shape {
2983            identity: metadata.identity,
2984            reason: "run crosses a mandatory paragraph break",
2985        });
2986    }
2987    let metrics = metadata.metrics.validate(metadata.identity)?;
2988    let face = rustybuzz::Face::from_slice(&file.bytes, metadata.identity.face_index).ok_or(
2989        FontError::Shape {
2990            identity: metadata.identity,
2991            reason: "rustybuzz rejected the retained face",
2992        },
2993    )?;
2994    let mut buffer = rustybuzz::UnicodeBuffer::new();
2995    if let Some(replacement) = context.soft_hyphen {
2996        if !text
2997            .get(replacement..)
2998            .is_some_and(|suffix| suffix.starts_with('\u{ad}'))
2999        {
3000            return Err(FontError::Shape {
3001                identity: metadata.identity,
3002                reason: "invalid selected soft-hyphen source",
3003            });
3004        }
3005        for (index, scalar) in text.char_indices() {
3006            buffer.add(
3007                if index == replacement { '-' } else { scalar },
3008                u32::try_from(index)
3009                    .map_err(|_| FontError::Arithmetic("shaping source cluster"))?,
3010            );
3011        }
3012    } else {
3013        buffer.push_str(text);
3014    }
3015    buffer.set_pre_context(context.pre);
3016    buffer.set_post_context(context.post);
3017    let mut flags = rustybuzz::BufferFlags::empty();
3018    if context.pre.is_empty() {
3019        flags |= rustybuzz::BufferFlags::BEGINNING_OF_TEXT;
3020    }
3021    if context.post.is_empty() {
3022        flags |= rustybuzz::BufferFlags::END_OF_TEXT;
3023    }
3024    buffer.set_flags(flags);
3025    buffer.set_direction(direction.into());
3026    buffer.set_script(script);
3027    buffer.set_language(
3028        rustybuzz::Language::from_str("und").map_err(|_| FontError::Shape {
3029            identity: metadata.identity,
3030            reason: "invalid fixed shaping language",
3031        })?,
3032    );
3033    #[cfg(test)]
3034    FONT_SHAPE_CALLS.with(|calls| calls.set(calls.get() + 1));
3035    let shaped = rustybuzz::shape(&face, &[], buffer);
3036
3037    let mut glyphs = Vec::new();
3038    try_reserve_exact(&mut glyphs, shaped.len(), "shaped glyphs")?;
3039    for (info, position) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
3040        let glyph_id = u16::try_from(info.glyph_id).map_err(|_| FontError::Shape {
3041            identity: metadata.identity,
3042            reason: "shaper emitted an out-of-range glyph id",
3043        })?;
3044        if glyph_id == 0 && !text.is_empty() {
3045            return Err(FontError::Shape {
3046                identity: metadata.identity,
3047                reason: "shaper emitted the missing-glyph id",
3048            });
3049        }
3050        let ink = face
3051            .glyph_bounding_box(ttf_parser::GlyphId(glyph_id))
3052            .map(|rect| GlyphInk {
3053                x_min: rect.x_min,
3054                y_min: rect.y_min,
3055                x_max: rect.x_max,
3056                y_max: rect.y_max,
3057            });
3058        validate_selected_glyph_paint(&face, metadata.identity, glyph_id, ink.is_some())?;
3059        glyphs.push(ShapedGlyph {
3060            glyph_id,
3061            cluster: info.cluster,
3062            x_advance: position.x_advance,
3063            y_advance: position.y_advance,
3064            x_offset: position.x_offset,
3065            y_offset: position.y_offset,
3066            ink,
3067        });
3068    }
3069    Ok(ShapedRun {
3070        identity: metadata.identity,
3071        direction,
3072        script,
3073        metrics,
3074        glyphs,
3075    })
3076}
3077
3078#[allow(
3079    clippy::too_many_lines,
3080    reason = "discovery keeps traversal, retention, and mutation checks in one auditable path"
3081)]
3082fn discover_indexed_files(
3083    roots: &[SourceRoot],
3084    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3085) -> Result<Vec<index::IndexedFontFile>, FontError> {
3086    let mut discovered = Vec::new();
3087    for root in roots {
3088        match fs::symlink_metadata(&root.path) {
3089            Ok(_) => {
3090                reserve_discovery_record(&mut discovered, prepared_stage.as_deref_mut())?;
3091                discovered.push(DiscoveryRecord {
3092                    root_ordinal: root.ordinal,
3093                    path: root.path.clone(),
3094                    entry_prefix: root.entry_prefix,
3095                    admit_file: false,
3096                });
3097            }
3098            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
3099            Err(source) => {
3100                return Err(FontError::Io {
3101                    operation: "inspect font root",
3102                    path: root.path.clone(),
3103                    source,
3104                });
3105            }
3106        }
3107    }
3108
3109    let mut cursor = 0_usize;
3110    while cursor < discovered.len() {
3111        let root_ordinal = discovered[cursor].root_ordinal;
3112        let path = discovered[cursor].path.clone();
3113        let entry_prefix = discovered[cursor].entry_prefix;
3114        cursor = cursor
3115            .checked_add(1)
3116            .ok_or(FontError::Arithmetic("discovery cursor"))?;
3117        let metadata = fs::symlink_metadata(&path).map_err(|source| FontError::Io {
3118            operation: "inspect discovered font entry",
3119            path: path.clone(),
3120            source,
3121        })?;
3122        let file_type = metadata.file_type();
3123        let is_directory = if file_type.is_symlink() {
3124            fs::metadata(&path)
3125                .map_err(|source| FontError::Io {
3126                    operation: "inspect discovered font target",
3127                    path: path.clone(),
3128                    source,
3129                })?
3130                .is_dir()
3131        } else {
3132            file_type.is_dir()
3133        };
3134        if is_directory {
3135            if file_type.is_symlink() {
3136                continue;
3137            }
3138            let entries = fs::read_dir(&path).map_err(|source| FontError::Io {
3139                operation: "read font directory",
3140                path: path.clone(),
3141                source,
3142            })?;
3143            for entry in entries {
3144                let entry = entry.map_err(|source| FontError::Io {
3145                    operation: "read font directory entry",
3146                    path: path.clone(),
3147                    source,
3148                })?;
3149                if entry_prefix
3150                    .is_some_and(|prefix| !entry.file_name().to_string_lossy().starts_with(prefix))
3151                {
3152                    continue;
3153                }
3154                reserve_discovery_record(&mut discovered, prepared_stage.as_deref_mut())?;
3155                discovered.push(DiscoveryRecord {
3156                    root_ordinal,
3157                    path: entry.path(),
3158                    entry_prefix: None,
3159                    admit_file: true,
3160                });
3161            }
3162        }
3163    }
3164
3165    for record in &mut discovered {
3166        if !record.admit_file {
3167            continue;
3168        }
3169        let metadata = fs::metadata(&record.path).map_err(|source| FontError::Io {
3170            operation: "inspect discovered font target",
3171            path: record.path.clone(),
3172            source,
3173        })?;
3174        if !metadata.is_file() {
3175            record.admit_file = false;
3176            continue;
3177        }
3178        let canonical_path = fs::canonicalize(&record.path).map_err(|source| FontError::Io {
3179            operation: "canonicalize font file",
3180            path: record.path.clone(),
3181            source,
3182        })?;
3183        if !has_fontdb_extension(&canonical_path) {
3184            record.admit_file = false;
3185            continue;
3186        }
3187        record.path = canonical_path;
3188    }
3189    discovered.retain(|record| record.admit_file);
3190    discovered.sort_unstable_by(|left, right| {
3191        native_path_cmp(&left.path, &right.path)
3192            .then_with(|| left.root_ordinal.cmp(&right.root_ordinal))
3193    });
3194    discovered.dedup_by(|right, left| right.path == left.path);
3195    discovered.sort_unstable_by(|left, right| {
3196        left.root_ordinal
3197            .cmp(&right.root_ordinal)
3198            .then_with(|| native_path_cmp(&left.path, &right.path))
3199    });
3200
3201    let mut retained = Vec::new();
3202    reserve_prepared_or_local(
3203        &mut retained,
3204        discovered.len(),
3205        "indexed font files",
3206        prepared_stage.as_deref_mut(),
3207    )?;
3208    for record in discovered {
3209        retained.push(index::index_file(
3210            record.root_ordinal,
3211            record.path,
3212            prepared_stage.as_deref_mut(),
3213        )?);
3214    }
3215    Ok(retained)
3216}
3217
3218fn reserve_discovery_record(
3219    records: &mut Vec<DiscoveryRecord>,
3220    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3221) -> Result<(), FontError> {
3222    let required = records
3223        .len()
3224        .checked_add(1)
3225        .ok_or(FontError::Arithmetic("discovery record length"))?;
3226    if required > records.capacity() {
3227        let target = required.max(
3228            records
3229                .capacity()
3230                .checked_mul(2)
3231                .ok_or(FontError::Arithmetic("discovery record capacity"))?,
3232        );
3233        target
3234            .checked_mul(std::mem::size_of::<DiscoveryRecord>())
3235            .ok_or(FontError::Arithmetic("discovery record bytes"))?;
3236        reserve_prepared_or_local(
3237            records,
3238            target - records.len(),
3239            "discovery records",
3240            prepared_stage,
3241        )?;
3242    }
3243    Ok(())
3244}
3245
3246fn read_exact_font_bytes(
3247    reader: &mut impl Read,
3248    path: &Path,
3249    expected_length: usize,
3250    bytes: &mut Vec<u8>,
3251) -> Result<[u8; 32], FontError> {
3252    let mut hasher = Sha256::new();
3253    let mut scratch = [0_u8; 16 * 1024];
3254    while bytes.len() < expected_length {
3255        let remaining = expected_length - bytes.len();
3256        let read_length = remaining.min(scratch.len());
3257        let read = reader
3258            .read(&mut scratch[..read_length])
3259            .map_err(|source| FontError::Io {
3260                operation: "read font file",
3261                path: path.to_path_buf(),
3262                source,
3263            })?;
3264        if read == 0 {
3265            return Err(FontError::ChangedFile(path.to_path_buf()));
3266        }
3267        hasher.update(&scratch[..read]);
3268        #[cfg(test)]
3269        LOAD_OBSERVATIONS.with_borrow_mut(|observed| {
3270            observed.full_bytes += read;
3271            observed.hash_bytes += read;
3272        });
3273        bytes.extend_from_slice(&scratch[..read]);
3274    }
3275    Ok(hasher.finalize().into())
3276}
3277
3278fn has_fontdb_extension(path: &Path) -> bool {
3279    matches!(
3280        path.extension().and_then(std::ffi::OsStr::to_str),
3281        Some("ttf" | "ttc" | "TTF" | "TTC" | "otf" | "otc" | "OTF" | "OTC")
3282    )
3283}
3284
3285#[cfg(unix)]
3286fn native_path_cmp(left: &Path, right: &Path) -> Ordering {
3287    use std::os::unix::ffi::OsStrExt;
3288    left.as_os_str()
3289        .as_bytes()
3290        .cmp(right.as_os_str().as_bytes())
3291}
3292
3293#[cfg(windows)]
3294fn native_path_cmp(left: &Path, right: &Path) -> Ordering {
3295    use std::os::windows::ffi::OsStrExt;
3296    left.as_os_str()
3297        .encode_wide()
3298        .cmp(right.as_os_str().encode_wide())
3299}
3300
3301#[cfg(not(any(unix, windows)))]
3302fn native_path_cmp(left: &Path, right: &Path) -> Ordering {
3303    left.as_os_str().cmp(right.as_os_str())
3304}
3305
3306fn try_reserve_exact<T>(
3307    values: &mut Vec<T>,
3308    additional: usize,
3309    resource: &'static str,
3310) -> Result<(), FontError> {
3311    values
3312        .try_reserve_exact(additional)
3313        .map_err(|_| FontError::Allocation(resource))
3314}
3315
3316fn reserve_prepared_or_local<T>(
3317    values: &mut Vec<T>,
3318    additional: usize,
3319    resource: &'static str,
3320    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3321) -> Result<(), FontError> {
3322    if let Some(stage) = prepared_stage {
3323        stage
3324            .reserve_prepared(values, additional, resource)
3325            .map_err(|error| FontError::Reservation(error.to_string()))
3326    } else {
3327        try_reserve_exact(values, additional, resource)
3328    }
3329}
3330
3331fn reserve_string_prepared_or_local(
3332    value: &mut String,
3333    additional: usize,
3334    resource: &'static str,
3335    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3336) -> Result<(), FontError> {
3337    if let Some(stage) = prepared_stage {
3338        stage
3339            .reserve_prepared_string(value, additional, resource)
3340            .map_err(|error| FontError::Reservation(error.to_string()))
3341    } else {
3342        value
3343            .try_reserve_exact(additional)
3344            .map_err(|_| FontError::Allocation(resource))
3345    }
3346}
3347
3348fn reserve_family_stack_names(
3349    retained: &mut Vec<FontFamily>,
3350    source: &FontStack,
3351
3352    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3353) -> Result<(), FontError> {
3354    for preference in source {
3355        retained.push(FontFamily {
3356            kind: match &preference.kind {
3357                FontFamilyKind::Named(name) => {
3358                    let mut reserved = String::new();
3359                    if let Some(stage) = prepared_stage.as_deref_mut() {
3360                        stage
3361                            .reserve_prepared_string(
3362                                &mut reserved,
3363                                name.len(),
3364                                "prepared font family name",
3365                            )
3366                            .map_err(|error| FontError::Reservation(error.to_string()))?;
3367                    } else {
3368                        reserved
3369                            .try_reserve_exact(name.len())
3370                            .map_err(|_| FontError::Allocation("prepared font family name"))?;
3371                    }
3372                    FontFamilyKind::Named(reserved)
3373                }
3374                FontFamilyKind::Generic(family) => FontFamilyKind::Generic(*family),
3375            },
3376        });
3377    }
3378    Ok(())
3379}
3380
3381fn fill_reserved_family_stack(
3382    retained: &mut [FontFamily],
3383    source: &FontStack,
3384) -> Result<(), FontError> {
3385    if retained.len() != source.len() {
3386        return Err(FontError::Arithmetic(
3387            "prepared font stack count/materialization mismatch",
3388        ));
3389    }
3390    for (retained, source) in retained.iter_mut().zip(source) {
3391        match (&mut retained.kind, &source.kind) {
3392            (FontFamilyKind::Named(retained), FontFamilyKind::Named(source)) => {
3393                if retained.capacity() < source.len() || !retained.is_empty() {
3394                    return Err(FontError::Arithmetic(
3395                        "prepared font family reservation mismatch",
3396                    ));
3397                }
3398                retained.push_str(source);
3399            }
3400            (FontFamilyKind::Generic(retained), FontFamilyKind::Generic(source))
3401                if retained == source => {}
3402            _ => {
3403                return Err(FontError::Arithmetic(
3404                    "prepared font stack materialization mismatch",
3405                ));
3406            }
3407        }
3408    }
3409    Ok(())
3410}
3411
3412fn scalar_presence_map() -> Result<Vec<u64>, FontError> {
3413    let mut presence = Vec::new();
3414    try_reserve_exact(
3415        &mut presence,
3416        SCALAR_MAP_WORDS,
3417        "Unicode scalar presence map",
3418    )?;
3419    presence.resize(SCALAR_MAP_WORDS, 0_u64);
3420    Ok(presence)
3421}
3422
3423fn apply_host_generics(database: &mut Database, generics: &HostGenericNames) {
3424    if let Some(name) = &generics.serif {
3425        database.set_serif_family(name);
3426    }
3427    if let Some(name) = &generics.sans_serif {
3428        database.set_sans_serif_family(name);
3429    }
3430    if let Some(name) = &generics.cursive {
3431        database.set_cursive_family(name);
3432    }
3433    if let Some(name) = &generics.fantasy {
3434        database.set_fantasy_family(name);
3435    }
3436    if let Some(name) = &generics.monospace {
3437        database.set_monospace_family(name);
3438    }
3439}
3440
3441#[cfg(all(
3442    unix,
3443    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3444))]
3445#[derive(Default)]
3446struct BoundedFontConfig {
3447    dirs: Vec<fontconfig_parser::DirData>,
3448    aliases: Vec<fontconfig_parser::Alias>,
3449    files: Vec<PathBuf>,
3450}
3451
3452#[cfg(all(
3453    unix,
3454    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3455))]
3456enum FontConfigTask {
3457    Parts {
3458        config_path: PathBuf,
3459        parts: std::vec::IntoIter<FontConfigDirective>,
3460    },
3461    Merge {
3462        path: PathBuf,
3463    },
3464    Include(PathBuf),
3465}
3466
3467#[cfg(all(
3468    unix,
3469    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3470))]
3471enum FontConfigRead {
3472    Loaded {
3473        parts: Vec<FontConfigDirective>,
3474        complete: bool,
3475    },
3476    Ignored,
3477}
3478
3479#[cfg(all(
3480    unix,
3481    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3482))]
3483enum FontConfigDirective {
3484    Alias(fontconfig_parser::Alias),
3485    Dir(fontconfig_parser::Dir),
3486    Include(fontconfig_parser::Include),
3487    ResetDirs,
3488}
3489
3490#[cfg(all(
3491    unix,
3492    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3493))]
3494fn merge_fontconfig_root(
3495    config: &mut BoundedFontConfig,
3496    config_path: &Path,
3497    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3498) -> Result<bool, FontError> {
3499    let FontConfigRead::Loaded { parts, complete } =
3500        read_bounded_fontconfig(config, config_path, false, prepared_stage.as_deref_mut())?
3501    else {
3502        return Ok(false);
3503    };
3504
3505    let mut tasks = Vec::new();
3506    reserve_prepared_or_local(
3507        &mut tasks,
3508        1,
3509        "fontconfig traversal",
3510        prepared_stage.as_deref_mut(),
3511    )?;
3512    tasks.push(FontConfigTask::Parts {
3513        config_path: config_path.to_path_buf(),
3514        parts: parts.into_iter(),
3515    });
3516
3517    while let Some(task) = tasks.pop() {
3518        match task {
3519            FontConfigTask::Parts {
3520                config_path,
3521                mut parts,
3522            } => {
3523                let Some(part) = parts.next() else { continue };
3524                reserve_prepared_or_local(
3525                    &mut tasks,
3526                    1,
3527                    "fontconfig traversal",
3528                    prepared_stage.as_deref_mut(),
3529                )?;
3530                tasks.push(FontConfigTask::Parts {
3531                    config_path: config_path.clone(),
3532                    parts,
3533                });
3534                match part {
3535                    FontConfigDirective::Alias(alias) => {
3536                        reserve_prepared_or_local(
3537                            &mut config.aliases,
3538                            1,
3539                            "fontconfig aliases",
3540                            prepared_stage.as_deref_mut(),
3541                        )?;
3542                        config.aliases.push(alias);
3543                    }
3544                    FontConfigDirective::Dir(dir) => {
3545                        reserve_prepared_or_local(
3546                            &mut config.dirs,
3547                            1,
3548                            "fontconfig directories",
3549                            prepared_stage.as_deref_mut(),
3550                        )?;
3551                        config.dirs.push(fontconfig_parser::DirData {
3552                            path: dir.calculate_path(&config_path),
3553                            salt: dir.salt,
3554                        });
3555                    }
3556                    FontConfigDirective::Include(include) => {
3557                        reserve_prepared_or_local(
3558                            &mut tasks,
3559                            1,
3560                            "fontconfig traversal",
3561                            prepared_stage.as_deref_mut(),
3562                        )?;
3563                        tasks.push(FontConfigTask::Include(
3564                            include.calculate_path(&config_path),
3565                        ));
3566                    }
3567                    FontConfigDirective::ResetDirs => config.dirs.clear(),
3568                }
3569            }
3570            FontConfigTask::Merge { path } => {
3571                // Upstream ignores included syntax failures, but keeps their valid prefix.
3572                if let FontConfigRead::Loaded { parts, .. } =
3573                    read_bounded_fontconfig(config, &path, true, prepared_stage.as_deref_mut())?
3574                {
3575                    reserve_prepared_or_local(
3576                        &mut tasks,
3577                        1,
3578                        "fontconfig traversal",
3579                        prepared_stage.as_deref_mut(),
3580                    )?;
3581                    tasks.push(FontConfigTask::Parts {
3582                        config_path: path,
3583                        parts: parts.into_iter(),
3584                    });
3585                }
3586            }
3587            FontConfigTask::Include(path) => {
3588                push_bounded_fontconfig_include(&mut tasks, &path, prepared_stage.as_deref_mut())?;
3589            }
3590        }
3591    }
3592    Ok(complete)
3593}
3594
3595#[cfg(all(
3596    unix,
3597    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3598))]
3599fn read_bounded_fontconfig(
3600    config: &mut BoundedFontConfig,
3601    config_path: &Path,
3602    must_exist: bool,
3603    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3604) -> Result<FontConfigRead, FontError> {
3605    let canonical_path = match fs::canonicalize(config_path) {
3606        Ok(path) => path,
3607        Err(source) if !must_exist && source.kind() == std::io::ErrorKind::NotFound => {
3608            return Ok(FontConfigRead::Ignored);
3609        }
3610        Err(source) => {
3611            return Err(FontError::Io {
3612                operation: "canonicalize fontconfig file",
3613                path: config_path.to_path_buf(),
3614                source,
3615            });
3616        }
3617    };
3618    for path in &config.files {
3619        if path == &canonical_path {
3620            return Ok(FontConfigRead::Loaded {
3621                parts: Vec::new(),
3622                complete: true,
3623            });
3624        }
3625    }
3626    reserve_prepared_or_local(
3627        &mut config.files,
3628        1,
3629        "fontconfig files",
3630        prepared_stage.as_deref_mut(),
3631    )?;
3632    config.files.push(canonical_path.clone());
3633    let mut file = File::open(&canonical_path).map_err(|source| FontError::Io {
3634        operation: "open fontconfig file",
3635        path: canonical_path.clone(),
3636        source,
3637    })?;
3638    let metadata_before = file.metadata().map_err(|source| FontError::Io {
3639        operation: "inspect fontconfig file",
3640        path: canonical_path.clone(),
3641        source,
3642    })?;
3643    if !metadata_before.is_file() {
3644        return Err(FontError::ChangedFile(canonical_path));
3645    }
3646    let length = metadata_before.len();
3647    let modified_before = metadata_before.modified().ok();
3648    let length =
3649        usize::try_from(length).map_err(|_| FontError::Arithmetic("fontconfig file length"))?;
3650
3651    let mut source = String::new();
3652    reserve_string_prepared_or_local(
3653        &mut source,
3654        length,
3655        "fontconfig source bytes",
3656        prepared_stage.as_deref_mut(),
3657    )?;
3658    let read = file
3659        .by_ref()
3660        .take(u64::try_from(length).map_err(|_| FontError::Arithmetic("fontconfig file length"))?)
3661        .read_to_string(&mut source)
3662        .map_err(|source| FontError::Io {
3663            operation: "read fontconfig file",
3664            path: canonical_path.clone(),
3665            source,
3666        })?;
3667    let metadata_after = file.metadata().map_err(|source| FontError::Io {
3668        operation: "reinspect fontconfig file",
3669        path: canonical_path.clone(),
3670        source,
3671    })?;
3672    if read != length
3673        || metadata_after.len()
3674            != u64::try_from(length).map_err(|_| FontError::Arithmetic("fontconfig file length"))?
3675        || modified_before.is_some_and(|modified| {
3676            metadata_after
3677                .modified()
3678                .map_or(true, |current| current != modified)
3679        })
3680    {
3681        return Err(FontError::ChangedFile(canonical_path));
3682    }
3683
3684    drop(file);
3685    match parse_bounded_fontconfig(&source, config_path, prepared_stage) {
3686        Ok((parts, complete)) => Ok(FontConfigRead::Loaded { parts, complete }),
3687        Err(FontError::ParseFontConfig { .. }) => Ok(FontConfigRead::Ignored),
3688        Err(error) => Err(error),
3689    }
3690}
3691
3692#[cfg(all(
3693    unix,
3694    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3695))]
3696fn parse_bounded_fontconfig(
3697    source: &str,
3698    config_path: &Path,
3699    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3700) -> Result<(Vec<FontConfigDirective>, bool), FontError> {
3701    if source.contains("<!ENTITY") {
3702        return Err(fontconfig_parse_error(
3703            config_path,
3704            "internal entities are not admitted",
3705        ));
3706    }
3707    let markup = u64::try_from(source.bytes().filter(|byte| *byte == b'<').count())
3708        .map_err(|_| FontError::Arithmetic("fontconfig XML node capacity"))?;
3709    let node_capacity = markup
3710        .checked_mul(2)
3711        .and_then(|capacity| capacity.checked_add(1))
3712        .ok_or(FontError::Arithmetic("fontconfig XML node capacity"))?;
3713    let nodes_limit = u32::try_from(node_capacity)
3714        .map_err(|_| FontError::Arithmetic("fontconfig XML node capacity"))?;
3715    let document = roxmltree::Document::parse_with_options(
3716        source,
3717        roxmltree::ParsingOptions {
3718            allow_dtd: true,
3719            nodes_limit,
3720        },
3721    )
3722    .map_err(|error| fontconfig_parse_error(config_path, error.to_string()))?;
3723    let root = document.root_element();
3724    if root.tag_name().name() != "fontconfig" {
3725        return Err(fontconfig_parse_error(
3726            config_path,
3727            "missing fontconfig root element",
3728        ));
3729    }
3730    let directive_count = root
3731        .children()
3732        .filter(|child| {
3733            child.is_element()
3734                && matches!(
3735                    child.tag_name().name(),
3736                    "alias" | "dir" | "include" | "reset-dirs"
3737                )
3738        })
3739        .count();
3740    let mut directives = Vec::new();
3741    reserve_prepared_or_local(
3742        &mut directives,
3743        directive_count,
3744        "fontconfig directives",
3745        prepared_stage.as_deref_mut(),
3746    )?;
3747    for child in root.children().filter(roxmltree::Node::is_element) {
3748        let directive = match child.tag_name().name() {
3749            "alias" => parse_fontconfig_alias(child, config_path, prepared_stage.as_deref_mut())
3750                .map(FontConfigDirective::Alias)
3751                .map(Some),
3752            "dir" => parse_fontconfig_dir(child, config_path, prepared_stage.as_deref_mut())
3753                .map(FontConfigDirective::Dir)
3754                .map(Some),
3755            "include" => {
3756                parse_fontconfig_include(child, config_path, prepared_stage.as_deref_mut())
3757                    .map(FontConfigDirective::Include)
3758                    .map(Some)
3759            }
3760            "reset-dirs" => Ok(Some(FontConfigDirective::ResetDirs)),
3761            _ => Ok(None),
3762        };
3763        match directive {
3764            Ok(Some(directive)) => directives.push(directive),
3765            Ok(None) => {}
3766            Err(FontError::ParseFontConfig { .. }) => return Ok((directives, false)),
3767            Err(error) => return Err(error),
3768        }
3769    }
3770    Ok((directives, true))
3771}
3772
3773#[cfg(all(
3774    unix,
3775    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3776))]
3777fn parse_fontconfig_alias(
3778    node: roxmltree::Node<'_, '_>,
3779    config_path: &Path,
3780    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3781) -> Result<fontconfig_parser::Alias, FontError> {
3782    let mut alias = fontconfig_parser::Alias::default();
3783    for child in node.children().filter(roxmltree::Node::is_element) {
3784        match child.tag_name().name() {
3785            "family" => {
3786                alias.alias = copy_fontconfig_string(
3787                    fontconfig_node_text(child, config_path)?,
3788                    "fontconfig alias family",
3789                    prepared_stage.as_deref_mut(),
3790                )?;
3791            }
3792            "prefer" => {
3793                copy_fontconfig_families(child, &mut alias.prefer, prepared_stage.as_deref_mut())?;
3794            }
3795            "accept" => {
3796                copy_fontconfig_families(child, &mut alias.accept, prepared_stage.as_deref_mut())?;
3797            }
3798            "default" => {
3799                copy_fontconfig_families(child, &mut alias.default, prepared_stage.as_deref_mut())?;
3800            }
3801            _ => {}
3802        }
3803    }
3804    Ok(alias)
3805}
3806
3807#[cfg(all(
3808    unix,
3809    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3810))]
3811fn copy_fontconfig_families(
3812    node: roxmltree::Node<'_, '_>,
3813    destination: &mut Vec<String>,
3814    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3815) -> Result<(), FontError> {
3816    let count = node
3817        .children()
3818        .filter(|child| child.is_element() && child.tag_name().name() == "family")
3819        .count();
3820    reserve_prepared_or_local(
3821        destination,
3822        count,
3823        "fontconfig alias preferences",
3824        prepared_stage.as_deref_mut(),
3825    )?;
3826    for family in node
3827        .children()
3828        .filter(|child| child.is_element() && child.tag_name().name() == "family")
3829    {
3830        let Some(text) = family.text() else { continue };
3831        destination.push(copy_fontconfig_string(
3832            text,
3833            "fontconfig alias preference",
3834            prepared_stage.as_deref_mut(),
3835        )?);
3836    }
3837    Ok(())
3838}
3839
3840#[cfg(all(
3841    unix,
3842    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3843))]
3844fn parse_fontconfig_dir(
3845    node: roxmltree::Node<'_, '_>,
3846    config_path: &Path,
3847    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3848) -> Result<fontconfig_parser::Dir, FontError> {
3849    let mut dir = fontconfig_parser::Dir::default();
3850    if let Some(prefix) = node.attribute("prefix") {
3851        dir.prefix = prefix.parse().map_err(|error: fontconfig_parser::Error| {
3852            fontconfig_parse_error(config_path, error.to_string())
3853        })?;
3854    }
3855    if let Some(salt) = node.attribute("salt") {
3856        dir.salt = copy_fontconfig_string(
3857            salt,
3858            "fontconfig directory salt",
3859            prepared_stage.as_deref_mut(),
3860        )?;
3861    }
3862    dir.path = copy_fontconfig_string(
3863        fontconfig_node_text(node, config_path)?,
3864        "fontconfig directory path",
3865        prepared_stage,
3866    )?;
3867    Ok(dir)
3868}
3869
3870#[cfg(all(
3871    unix,
3872    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3873))]
3874fn parse_fontconfig_include(
3875    node: roxmltree::Node<'_, '_>,
3876    config_path: &Path,
3877    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3878) -> Result<fontconfig_parser::Include, FontError> {
3879    let mut include = fontconfig_parser::Include::default();
3880    if let Some(prefix) = node.attribute("prefix") {
3881        include.prefix = prefix.parse().map_err(|error: fontconfig_parser::Error| {
3882            fontconfig_parse_error(config_path, error.to_string())
3883        })?;
3884    }
3885    include.ignore_missing = node.attribute("ignore_missing") == Some("yes");
3886    include.path = copy_fontconfig_string(
3887        fontconfig_node_text(node, config_path)?,
3888        "fontconfig include path",
3889        prepared_stage,
3890    )?;
3891    Ok(include)
3892}
3893
3894#[cfg(all(
3895    unix,
3896    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3897))]
3898fn fontconfig_node_text<'a>(
3899    node: roxmltree::Node<'a, '_>,
3900    config_path: &Path,
3901) -> Result<&'a str, FontError> {
3902    node.text()
3903        .ok_or_else(|| fontconfig_parse_error(config_path, "missing directive text"))
3904}
3905
3906#[cfg(all(
3907    unix,
3908    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3909))]
3910fn copy_fontconfig_string(
3911    source: &str,
3912    resource: &'static str,
3913    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3914) -> Result<String, FontError> {
3915    let mut retained = String::new();
3916    reserve_string_prepared_or_local(&mut retained, source.len(), resource, prepared_stage)?;
3917    retained.push_str(source);
3918    Ok(retained)
3919}
3920
3921#[cfg(all(
3922    unix,
3923    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3924))]
3925fn fontconfig_parse_error(config_path: &Path, reason: impl Into<String>) -> FontError {
3926    FontError::ParseFontConfig {
3927        path: config_path.to_path_buf(),
3928        reason: reason.into(),
3929    }
3930}
3931
3932#[cfg(all(
3933    unix,
3934    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
3935))]
3936fn push_bounded_fontconfig_include(
3937    tasks: &mut Vec<FontConfigTask>,
3938    include_path: &Path,
3939    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
3940) -> Result<(), FontError> {
3941    let metadata = match fs::metadata(include_path) {
3942        Ok(metadata) => metadata,
3943        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
3944        Err(source) => {
3945            return Err(FontError::Io {
3946                operation: "inspect fontconfig include",
3947                path: include_path.to_path_buf(),
3948                source,
3949            });
3950        }
3951    };
3952    if metadata.is_file() {
3953        reserve_prepared_or_local(tasks, 1, "fontconfig traversal", prepared_stage)?;
3954        tasks.push(FontConfigTask::Merge {
3955            path: include_path.to_path_buf(),
3956        });
3957        return Ok(());
3958    }
3959    if !metadata.is_dir() {
3960        return Ok(());
3961    }
3962    let entries = fs::read_dir(include_path).map_err(|source| FontError::Io {
3963        operation: "read fontconfig include directory",
3964        path: include_path.to_path_buf(),
3965        source,
3966    })?;
3967    let mut paths = Vec::new();
3968    for entry in entries {
3969        let entry = entry.map_err(|source| FontError::Io {
3970            operation: "read fontconfig include entry",
3971            path: include_path.to_path_buf(),
3972            source,
3973        })?;
3974        let file_type = entry.file_type().map_err(|source| FontError::Io {
3975            operation: "inspect fontconfig include entry",
3976            path: entry.path(),
3977            source,
3978        })?;
3979        if !file_type.is_file() && !file_type.is_symlink() {
3980            continue;
3981        }
3982        reserve_prepared_or_local(
3983            &mut paths,
3984            1,
3985            "fontconfig include entries",
3986            prepared_stage.as_deref_mut(),
3987        )?;
3988        paths.push(entry.path());
3989    }
3990    paths.sort_unstable_by(|left, right| native_path_cmp(left, right));
3991    reserve_prepared_or_local(tasks, paths.len(), "fontconfig traversal", prepared_stage)?;
3992    for path in paths.into_iter().rev() {
3993        tasks.push(FontConfigTask::Merge { path });
3994    }
3995    Ok(())
3996}
3997
3998#[cfg(target_os = "windows")]
3999fn platform_sources(
4000    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4001) -> Result<HostSources, FontError> {
4002    let mut paths = Vec::new();
4003    if let Some(system_root) = std::env::var_os("SYSTEMROOT") {
4004        paths.push(PathBuf::from(system_root).join("Fonts"));
4005    } else {
4006        paths.push(PathBuf::from(r"C:\Windows\Fonts\"));
4007    }
4008    if let Some(home) = std::env::var_os("USERPROFILE") {
4009        let home = PathBuf::from(home);
4010        paths.push(home.join(r"AppData\Local\Microsoft\Windows\Fonts"));
4011        paths.push(home.join(r"AppData\Roaming\Microsoft\Windows\Fonts"));
4012    }
4013    Ok(HostSources {
4014        roots: ordinal_roots(paths, prepared_stage)?,
4015        generics: HostGenericNames::default(),
4016    })
4017}
4018
4019#[cfg(target_os = "macos")]
4020fn platform_sources(
4021    _prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4022) -> Result<HostSources, FontError> {
4023    let mut roots = vec![
4024        SourceRoot {
4025            ordinal: 0,
4026            path: PathBuf::from("/Library/Fonts"),
4027            entry_prefix: None,
4028        },
4029        SourceRoot {
4030            ordinal: 1,
4031            path: PathBuf::from("/System/Library/Fonts"),
4032            entry_prefix: None,
4033        },
4034        SourceRoot {
4035            ordinal: 2,
4036            path: PathBuf::from("/System/Library/AssetsV2"),
4037            entry_prefix: Some("com_apple_MobileAsset_Font"),
4038        },
4039        SourceRoot {
4040            ordinal: 3,
4041            path: PathBuf::from("/Network/Library/Fonts"),
4042            entry_prefix: None,
4043        },
4044    ];
4045    if let Some(home) = std::env::var_os("HOME") {
4046        roots.push(SourceRoot {
4047            ordinal: 4,
4048            path: PathBuf::from(home).join("Library/Fonts"),
4049            entry_prefix: None,
4050        });
4051    }
4052    Ok(HostSources {
4053        roots,
4054        generics: HostGenericNames::default(),
4055    })
4056}
4057
4058#[cfg(target_os = "redox")]
4059fn platform_sources(
4060    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4061) -> Result<HostSources, FontError> {
4062    Ok(HostSources {
4063        roots: ordinal_roots(vec![PathBuf::from("/ui/fonts")], prepared_stage)?,
4064        generics: HostGenericNames::default(),
4065    })
4066}
4067
4068#[cfg(all(
4069    unix,
4070    not(any(target_os = "macos", target_os = "android", target_os = "redox"))
4071))]
4072fn platform_sources(
4073    mut prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4074) -> Result<HostSources, FontError> {
4075    let home = std::env::var("HOME").ok();
4076    let mut config = BoundedFontConfig::default();
4077    if let Ok(config_file) = std::env::var("FONTCONFIG_FILE") {
4078        merge_fontconfig_root(
4079            &mut config,
4080            Path::new(&config_file),
4081            prepared_stage.as_deref_mut(),
4082        )?;
4083    } else {
4084        let xdg_config_home = std::env::var("XDG_CONFIG_HOME")
4085            .ok()
4086            .map(PathBuf::from)
4087            .or_else(|| home.as_ref().map(|home| Path::new(home).join(".config")));
4088        let read_global = if let Some(path) = xdg_config_home {
4089            !merge_fontconfig_root(
4090                &mut config,
4091                &path.join("fontconfig/fonts.conf"),
4092                prepared_stage.as_deref_mut(),
4093            )?
4094        } else {
4095            true
4096        };
4097        if read_global {
4098            merge_fontconfig_root(
4099                &mut config,
4100                Path::new("/etc/fonts/local.conf"),
4101                prepared_stage.as_deref_mut(),
4102            )?;
4103        }
4104        merge_fontconfig_root(
4105            &mut config,
4106            Path::new("/etc/fonts/fonts.conf"),
4107            prepared_stage.as_deref_mut(),
4108        )?;
4109    }
4110
4111    let mut generics = HostGenericNames::default();
4112    for alias in &config.aliases {
4113        let name = alias
4114            .prefer
4115            .first()
4116            .or_else(|| alias.accept.first())
4117            .or_else(|| alias.default.first())
4118            .cloned();
4119        let Some(name) = name else { continue };
4120        match alias.alias.to_lowercase().as_str() {
4121            "serif" => generics.serif = Some(name),
4122            "sans-serif" | "sans serif" => generics.sans_serif = Some(name),
4123            "monospace" => generics.monospace = Some(name),
4124            "cursive" => generics.cursive = Some(name),
4125            "fantasy" => generics.fantasy = Some(name),
4126            _ => {}
4127        }
4128    }
4129
4130    let paths = if config.dirs.is_empty() {
4131        let mut paths = vec![
4132            PathBuf::from("/usr/share/fonts/"),
4133            PathBuf::from("/usr/local/share/fonts/"),
4134        ];
4135        if let Some(home) = home {
4136            paths.push(Path::new(&home).join(".fonts"));
4137            paths.push(Path::new(&home).join(".local/share/fonts"));
4138        }
4139        paths
4140    } else {
4141        let path_count = config
4142            .dirs
4143            .iter()
4144            .filter(|directory| !directory.path.starts_with("~") || home.is_some())
4145            .count();
4146        let mut paths = Vec::new();
4147        reserve_prepared_or_local(
4148            &mut paths,
4149            path_count,
4150            "fontconfig font roots",
4151            prepared_stage.as_deref_mut(),
4152        )?;
4153        for directory in config.dirs {
4154            if directory.path.starts_with("~") {
4155                let Some(home) = &home else { continue };
4156                paths.push(
4157                    Path::new(home).join(
4158                        directory
4159                            .path
4160                            .strip_prefix("~")
4161                            .expect("tilde-prefixed font path has a tilde component"),
4162                    ),
4163                );
4164            } else {
4165                paths.push(directory.path);
4166            }
4167        }
4168        paths
4169    };
4170    Ok(HostSources {
4171        roots: ordinal_roots(paths, prepared_stage)?,
4172        generics,
4173    })
4174}
4175
4176#[cfg(not(any(
4177    target_os = "windows",
4178    target_os = "macos",
4179    target_os = "redox",
4180    all(unix, not(target_os = "android"))
4181)))]
4182fn platform_sources(
4183    _prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4184) -> Result<HostSources, FontError> {
4185    Ok(HostSources {
4186        roots: Vec::new(),
4187        generics: HostGenericNames::default(),
4188    })
4189}
4190
4191fn ordinal_roots(
4192    paths: Vec<PathBuf>,
4193    prepared_stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
4194) -> Result<Vec<SourceRoot>, FontError> {
4195    let mut roots = Vec::new();
4196    reserve_prepared_or_local(
4197        &mut roots,
4198        paths.len(),
4199        "canonical font source roots",
4200        prepared_stage,
4201    )?;
4202    for (ordinal, path) in paths.into_iter().enumerate() {
4203        roots.push(SourceRoot {
4204            ordinal: u32::try_from(ordinal)
4205                .map_err(|_| FontError::Arithmetic("canonical font source root ordinal"))?,
4206            path,
4207            entry_prefix: None,
4208        });
4209    }
4210    Ok(roots)
4211}
4212
4213#[cfg(test)]
4214mod tests {
4215    use super::*;
4216
4217    mod admission;
4218    mod loading;
4219
4220    struct Outline(usize);
4221    impl ttf_parser::OutlineBuilder for Outline {
4222        fn move_to(&mut self, _: f32, _: f32) {
4223            self.0 += 1;
4224        }
4225        fn line_to(&mut self, _: f32, _: f32) {
4226            self.0 += 1;
4227        }
4228        fn quad_to(&mut self, _: f32, _: f32, _: f32, _: f32) {
4229            self.0 += 1;
4230        }
4231        fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, _: f32, _: f32) {
4232            self.0 += 1;
4233        }
4234        fn close(&mut self) {
4235            self.0 += 1;
4236        }
4237    }
4238
4239    #[test]
4240    fn poisoned_environment_returns_synchronization_without_discarding_fonts() {
4241        let environment = PreparedFontEnvironment::synthetic();
4242        let operation = environment.operation().unwrap();
4243        let file_bytes = Arc::clone(&environment.core.read().unwrap().fonts.files[0].bytes);
4244        let poisoned = environment.clone();
4245        let panic = std::thread::spawn(move || {
4246            let _guard = poisoned.core.write().unwrap();
4247            panic!("intentional writer panic to test a subsequent call's boundary");
4248        })
4249        .join();
4250        assert!(panic.is_err());
4251        assert!(matches!(
4252            environment.operation(),
4253            Err(FontError::Synchronization)
4254        ));
4255        assert!(matches!(
4256            environment.admit_text(test_sans_stack(), RequestedWeight::Normal, "A", None),
4257            Err(FontError::Synchronization)
4258        ));
4259        assert!(matches!(
4260            operation.seal_fonts(),
4261            Err(FontError::Synchronization)
4262        ));
4263        let core = environment.core.read().unwrap_err().into_inner();
4264        let fonts = &core.fonts;
4265        assert!(Arc::ptr_eq(&file_bytes, &fonts.files[0].bytes));
4266        assert_eq!(fonts.faces.len(), 1);
4267        assert!(fonts
4268            .issues
4269            .iter()
4270            .all(|issue| !matches!(issue.reason, super::admission::ScanReason::Parser { .. })));
4271    }
4272
4273    #[test]
4274    fn retained_face_lookups_require_the_exact_identity() {
4275        let environment = PreparedFontEnvironment::synthetic_faces(&[
4276            ("First", &['A']),
4277            ("Middle", &['A']),
4278            ("Last", &['A']),
4279        ]);
4280        for target in [0, 2, 3] {
4281            let identity = if target == 3 {
4282                FaceIdentity {
4283                    sha256: [0; 32],
4284                    face_index: 0,
4285                }
4286            } else {
4287                environment.core.read().unwrap().fonts.faces[target].identity
4288            };
4289            for route in 0..3 {
4290                let mut outline = Outline(0);
4291                let result = match route {
4292                    0 => environment
4293                        .shape_run(
4294                            identity,
4295                            "A",
4296                            ShapingDirection::LeftToRight,
4297                            rustybuzz::script::LATIN,
4298                        )
4299                        .map(|_| ()),
4300                    1 => environment.face_metrics(identity).map(|_| ()),
4301                    _ => environment
4302                        .outline_glyph(identity, 1, &mut outline)
4303                        .map(|_| ()),
4304                };
4305                if target == 3 {
4306                    assert!(matches!(
4307                        result,
4308                        Err(FontError::Shape {
4309                            reason: "identity is not retained",
4310                            ..
4311                        } | FontError::Outline {
4312                            reason: "identity is not retained",
4313                            ..
4314                        })
4315                    ));
4316                } else {
4317                    result.unwrap();
4318                    if route == 2 {
4319                        assert!(outline.0 > 0);
4320                    }
4321                }
4322            }
4323        }
4324    }
4325
4326    #[test]
4327    fn zero_descent_is_not_an_invalid_face_or_permission_to_reselect() {
4328        let valid = build_test_font_with_coverage("Valid Metrics", &['A']);
4329        let mut invalid = build_test_font_with_coverage("Invalid Metrics", &['A', 'B']);
4330        let os2 = ttf_parser::RawFace::parse(&invalid, 0)
4331            .unwrap()
4332            .table_records
4333            .into_iter()
4334            .find(|record| record.tag == ttf_parser::Tag::from_bytes(b"OS/2"))
4335            .unwrap();
4336        // A zero descent is meaningful, not a request for hhea/win replacement.
4337        set_i16(&mut invalid, usize::try_from(os2.offset).unwrap() + 70, 0);
4338        let core = CanonicalFontCore::from_generated(
4339            vec![valid, invalid],
4340            &HostGenericNames::default(),
4341            FontPreparation::new(),
4342            scalar_presence_map(),
4343        )
4344        .unwrap();
4345        let valid = core.faces()[0].identity;
4346        let invalid = core.faces()[1].identity;
4347        let environment = PreparedFontEnvironment::for_core(core).unwrap();
4348        let stack = named_stack(&["Valid Metrics", "Invalid Metrics"]);
4349        let pair = environment
4350            .resolve_pair(0, &stack, RequestedWeight::Normal, &['A'])
4351            .unwrap();
4352        assert_eq!(pair.provenance.candidates, [valid, invalid]);
4353        assert_eq!(pair.primary, valid);
4354        assert_eq!(environment.face_metrics(valid).unwrap().descender, -200);
4355        environment
4356            .shape_run(
4357                valid,
4358                "A",
4359                ShapingDirection::LeftToRight,
4360                rustybuzz::script::LATIN,
4361            )
4362            .unwrap();
4363
4364        environment
4365            .admit_text(&stack, RequestedWeight::Normal, "B", None)
4366            .unwrap();
4367        let pair = environment
4368            .prepared_pair(&stack, RequestedWeight::Normal)
4369            .unwrap()
4370            .unwrap();
4371        assert_eq!(
4372            pair.selection_for_unit("B", 'B').unwrap(),
4373            ScalarFaceSelection::Face(invalid),
4374        );
4375        assert_eq!(environment.face_metrics(invalid).unwrap().descender, 0);
4376        assert_eq!(
4377            environment
4378                .shape_run(
4379                    invalid,
4380                    "B",
4381                    ShapingDirection::LeftToRight,
4382                    rustybuzz::script::LATIN,
4383                )
4384                .unwrap()
4385                .metrics
4386                .source,
4387            MetricSource::Typographic,
4388        );
4389        let mut outline = Outline(0);
4390        environment.outline_glyph(invalid, 1, &mut outline).unwrap();
4391        assert!(outline.0 > 0);
4392        let invalid_primary = named_stack(&["Invalid Metrics", "Valid Metrics"]);
4393        let pair = environment
4394            .resolve_pair(1, &invalid_primary, RequestedWeight::Normal, &[])
4395            .unwrap();
4396        assert_eq!(pair.primary, invalid);
4397        assert_eq!(environment.face_metrics(pair.primary).unwrap().descender, 0);
4398    }
4399
4400    #[test]
4401    fn literal_font_values_preserve_bytes_duplicates_and_css_semantics() {
4402        let discoveries = FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
4403        let named = FontFamily::named("A, B").unwrap();
4404        let stack = FontStack::new([
4405            named.clone(),
4406            FontFamily::named("sans-serif").unwrap(),
4407            named.clone(),
4408            FontFamily::generic(GenericFontFamily::SansSerif),
4409        ])
4410        .unwrap();
4411        assert_eq!(stack.families()[0].name(), Some("A, B"));
4412        assert_eq!(stack.families()[2], named);
4413        assert_eq!(stack.families()[1].generic_family(), None);
4414        assert_eq!(
4415            stack.families()[3].generic_family(),
4416            Some(GenericFontFamily::SansSerif)
4417        );
4418        assert_eq!(
4419            stack.css().unwrap(),
4420            "\"A, B\", \"sans-serif\", \"A, B\", sans-serif"
4421        );
4422        for name in [
4423            "serif",
4424            "MONOSPACE",
4425            "cursive",
4426            "fantasy",
4427            "system-ui",
4428            "ui-serif",
4429            "ui-sans-serif",
4430            "ui-monospace",
4431            "ui-rounded",
4432            "math",
4433            "fangsong",
4434            "inherit",
4435            "initial",
4436            "unset",
4437            "revert",
4438            "revert-layer",
4439            "default",
4440        ] {
4441            assert_eq!(named_stack(&[name]).css().unwrap(), format!("\"{name}\""));
4442        }
4443        assert_eq!(
4444            named_stack(&["A\"B\\C", "A  B", "16 Font", "A; B"])
4445                .css()
4446                .unwrap(),
4447            "\"A\\\"B\\\\C\", \"A  B\", \"16 Font\", \"A; B\""
4448        );
4449        assert_eq!(
4450            builtin_font_stack().css().unwrap(),
4451            "Noto Sans, Noto Sans CJK SC, DejaVu Sans, Liberation Sans, Arial, sans-serif"
4452        );
4453        assert_eq!(
4454            named_stack(&["-Font", "--Font", "-16 Font", "sans-serif Display", "emoji"])
4455                .css()
4456                .unwrap(),
4457            "-Font, --Font, \"-16 Font\", \"sans-serif Display\", \"emoji\""
4458        );
4459        assert_eq!(FONT_DISCOVERY_CALLS.with(std::cell::Cell::get), discoveries);
4460    }
4461
4462    #[test]
4463    fn registered_pairs_reuse_normalization_and_selection_after_final_sealing() {
4464        let environment = PreparedFontEnvironment::synthetic();
4465        let stack = named_stack(&["Test Sans"]);
4466        FONT_NORMALIZATION_CALLS.with(|calls| calls.set(0));
4467        FONT_PAIR_RESOLUTION_CALLS.with(|calls| calls.set(0));
4468        FONT_SELECTION_PROBES.with(|calls| calls.set(0));
4469        environment
4470            .prepare_pairs(
4471                [
4472                    FontPairPreparationRequest::new(
4473                        0,
4474                        &stack,
4475                        RequestedWeight::Normal,
4476                        &['A', ' ', '\n'],
4477                    ),
4478                    FontPairPreparationRequest::new(1, &stack, RequestedWeight::Bold, &['A']),
4479                ]
4480                .into_iter(),
4481                None,
4482            )
4483            .unwrap();
4484        environment.operation().unwrap().seal_fonts().unwrap();
4485        {
4486            let pair = environment
4487                .clone()
4488                .prepared_pair(&stack, RequestedWeight::Normal)
4489                .unwrap()
4490                .unwrap();
4491            assert_eq!(pair.selected_scalars.len(), 3);
4492        }
4493        FONT_NORMALIZATION_CALLS.with(|calls| assert_eq!(calls.get(), 1));
4494        FONT_PAIR_RESOLUTION_CALLS.with(|calls| assert_eq!(calls.get(), 2));
4495        FONT_SELECTION_PROBES.with(|calls| assert_eq!(calls.get(), 3));
4496        assert!(matches!(
4497            environment.resolve_pair(0, &stack, RequestedWeight::Normal, &['A']),
4498            Err(FontError::PreparedPairAfterSeal { .. })
4499        ));
4500    }
4501
4502    #[cfg(all(
4503        unix,
4504        not(any(target_os = "macos", target_os = "android", target_os = "redox"))
4505    ))]
4506    #[test]
4507    fn bounded_fontconfig_missing_optional_paths_but_not_admitted_io_are_ignored() {
4508        let root = tempfile::tempdir().unwrap();
4509        let path = root.path().join("absent.conf");
4510        let mut config = BoundedFontConfig::default();
4511        assert!(matches!(
4512            read_bounded_fontconfig(&mut config, &path, false, None),
4513            Ok(FontConfigRead::Ignored)
4514        ));
4515        assert!(matches!(
4516            read_bounded_fontconfig(&mut config, &path, true, None),
4517            Err(FontError::Io { .. })
4518        ));
4519        fs::write(&path, [0xff]).unwrap();
4520        assert!(matches!(
4521            merge_fontconfig_root(&mut config, &path, None),
4522            Err(FontError::Io { .. })
4523        ));
4524
4525        let includes = root.path().join("conf.d");
4526        fs::create_dir(&includes).unwrap();
4527        std::os::unix::fs::symlink(root.path().join("missing"), includes.join("broken.conf"))
4528            .unwrap();
4529        let parent = root.path().join("parent.conf");
4530        fs::write(
4531            &parent,
4532            "<fontconfig><include prefix=\"relative\">conf.d</include></fontconfig>",
4533        )
4534        .unwrap();
4535        assert!(matches!(
4536            merge_fontconfig_root(&mut config, &parent, None),
4537            Err(FontError::Io { .. })
4538        ));
4539    }
4540
4541    #[test]
4542    fn discovery_closes_handle_on_observed_file_changes() {
4543        let root = tempfile::tempdir().unwrap();
4544        let path = root.path().join("a.ttf");
4545        fs::write(root.path().join("b.ttf"), b"unopened").unwrap();
4546        let roots = ordinal_roots(vec![root.path().to_path_buf()], None).unwrap();
4547        for hook in [
4548            (|path: &Path| fs::write(path, b"x").unwrap()) as fn(&Path),
4549            (|path: &Path| fs::write(path, b"longer than admitted").unwrap()) as fn(&Path),
4550        ] {
4551            fs::write(&path, b"original").unwrap();
4552            DISCOVERY_HANDLES.with(|state| state.set([0; 3]));
4553            DISCOVERY_AFTER_ADMISSION.with(|state| state.set(Some(hook)));
4554            assert!(matches!(discover_indexed_files(&roots, None),
4555                Err(FontError::ChangedFile(changed)) if changed == fs::canonicalize(&path).unwrap()));
4556            DISCOVERY_HANDLES.with(|state| assert_eq!(state.get(), [0, 1, 1]));
4557        }
4558    }
4559
4560    #[cfg(all(
4561        unix,
4562        not(any(target_os = "macos", target_os = "android", target_os = "redox"))
4563    ))]
4564    #[test]
4565    fn bounded_fontconfig_parser_capacity_and_entity_rejection_are_explicit() {
4566        let path = Path::new("fixture.conf");
4567        let source = "<fontconfig><dir salt=\"s\">/fonts</dir></fontconfig>";
4568        let (parts, complete) = parse_bounded_fontconfig(source, path, None).unwrap();
4569        assert!(complete);
4570        assert_eq!(parts.len(), 1);
4571        assert!(matches!(
4572            parse_bounded_fontconfig(
4573                "<!DOCTYPE fontconfig [<!ENTITY path '/fonts'>]><fontconfig><dir>&path;</dir></fontconfig>",
4574                path,
4575                None
4576            ),
4577            Err(FontError::ParseFontConfig { .. })
4578        ));
4579    }
4580
4581    #[test]
4582    fn canonical_candidate_order_retains_least_occurrence_per_identity() {
4583        let identity_a = identity(1, 0);
4584        let identity_b = identity(2, 0);
4585        let identity_c = identity(2, 1);
4586        let mut candidates = vec![
4587            candidate(identity_a, 1, 0),
4588            candidate(identity_c, 0, 0),
4589            candidate(identity_b, 0, 0),
4590            candidate(identity_a, 0, 20),
4591            candidate(identity_a, 0, 10),
4592        ];
4593
4594        canonicalize_candidate_occurrences(&mut candidates);
4595        assert_eq!(
4596            candidates,
4597            [
4598                candidate(identity_b, 0, 0),
4599                candidate(identity_c, 0, 0),
4600                candidate(identity_a, 0, 10),
4601            ]
4602        );
4603    }
4604
4605    #[test]
4606    fn missing_glyph_is_explicit_and_mandatory_controls_are_not_probed() {
4607        let candidates = [candidate(identity(1, 0), 0, 0)];
4608
4609        let mut presence = scalar_presence_map();
4610        let error = select_scalar_faces(4, &candidates, &['x'], &mut presence, |_, _| Ok(false))
4611            .unwrap_err();
4612        assert!(matches!(
4613            error,
4614            FontError::MissingGlyph {
4615                pair_ordinal: 4,
4616                scalar: 0x78
4617            }
4618        ));
4619
4620        let controls = [
4621            '\n', '\r', '\u{000B}', '\u{000C}', '\u{0085}', '\u{2028}', '\u{2029}',
4622        ];
4623
4624        let mut presence = scalar_presence_map();
4625        let selected = select_scalar_faces(0, &candidates, &controls, &mut presence, |_, _| {
4626            panic!("mandatory line-break controls must not be probed")
4627        })
4628        .unwrap();
4629        assert!(selected.iter().all(|selected| matches!(
4630            selected.selection,
4631            ScalarFaceSelection::NonRenderingMandatoryBreak
4632        )));
4633    }
4634
4635    #[test]
4636    fn sealed_environment_rejects_every_late_pair_resolution_route() {
4637        let environment = PreparedFontEnvironment::synthetic();
4638        let stack = named_stack(&["Test Sans"]);
4639        environment.reserve_prepared_pairs(1, None).unwrap();
4640        environment
4641            .prepare_pair(0, &stack, RequestedWeight::Normal, &['A'], None)
4642            .unwrap();
4643        environment.operation().unwrap().seal_fonts().unwrap();
4644
4645        assert!(matches!(
4646            environment.resolve_pair(1, &stack, RequestedWeight::Normal, &['A']),
4647            Err(FontError::PreparedPairAfterSeal { pair_ordinal: 1 })
4648        ));
4649        let counts = planning_counts();
4650        assert_eq!(
4651            environment
4652                .admit_text(&stack, RequestedWeight::Normal, "A", None)
4653                .unwrap(),
4654            0
4655        );
4656        assert!(matches!(
4657            environment.admit_text(&stack, RequestedWeight::Normal, "B", None),
4658            Err(FontError::PreparedPairAfterSeal { pair_ordinal: 0 })
4659        ));
4660        assert!(matches!(
4661            environment.admit_text(&stack, RequestedWeight::Bold, "A", None),
4662            Err(FontError::PreparedPairAfterSeal { pair_ordinal: 1 })
4663        ));
4664        assert!(matches!(
4665            environment.operation().unwrap().seal_fonts(),
4666            Err(FontError::OperationSealed)
4667        ));
4668        assert_eq!(planning_counts(), counts);
4669        assert!(matches!(
4670            environment.prepare_pairs(
4671                std::iter::once(FontPairPreparationRequest::new(
4672                    1,
4673                    &stack,
4674                    RequestedWeight::Bold,
4675                    &['A'],
4676                )),
4677                None,
4678            ),
4679            Err(FontError::PreparedPairAfterSeal { pair_ordinal: 1 })
4680        ));
4681    }
4682
4683    fn identity(byte: u8, face_index: u32) -> FaceIdentity {
4684        FaceIdentity {
4685            sha256: [byte; 32],
4686            face_index,
4687        }
4688    }
4689
4690    fn scalar_presence_map() -> Vec<u64> {
4691        let mut presence = Vec::new();
4692        presence.try_reserve_exact(SCALAR_MAP_WORDS).unwrap();
4693        presence.resize(SCALAR_MAP_WORDS, 0);
4694        presence
4695    }
4696
4697    fn candidate(
4698        identity: FaceIdentity,
4699        stack_entry_index: u32,
4700        weight_distance: u16,
4701    ) -> CandidateFace {
4702        CandidateFace {
4703            occurrence: CandidateOccurrence {
4704                stack_entry_index,
4705                style_distance: 0,
4706                stretch_distance: 0,
4707                weight_distance,
4708                identity,
4709            },
4710            face_ordinal: 0,
4711        }
4712    }
4713
4714    pub(super) fn generated_core() -> CanonicalFontCore {
4715        CanonicalFontCore::from_generated(
4716            vec![build_test_font()],
4717            &HostGenericNames::default(),
4718            FontPreparation::new(),
4719            scalar_presence_map(),
4720        )
4721        .unwrap()
4722    }
4723
4724    #[test]
4725    fn retained_units_prefer_complete_faces_without_changing_scalar_or_primary_selection() {
4726        let files = [
4727            ("Base", vec!['A']),
4728            ("Complete", vec!['A', '\u{0301}']),
4729            ("Mark", vec!['\u{0301}']),
4730        ]
4731        .into_iter()
4732        .map(|(family, coverage)| build_test_font_with_coverage(family, &coverage))
4733        .collect();
4734        let environment = PreparedFontEnvironment::for_core(
4735            CanonicalFontCore::from_generated(
4736                files,
4737                &HostGenericNames::default(),
4738                FontPreparation::new(),
4739                scalar_presence_map(),
4740            )
4741            .unwrap(),
4742        )
4743        .unwrap();
4744        let complete = named_stack(&["Base", "Complete"]);
4745        let split = named_stack(&["Base", "Mark"]);
4746        environment
4747            .prepare_pairs(
4748                [
4749                    FontPairPreparationRequest::new(
4750                        0,
4751                        &complete,
4752                        RequestedWeight::Normal,
4753                        &['A', '\u{0301}', '\u{200D}', '\u{FE0F}'],
4754                    ),
4755                    FontPairPreparationRequest::new(
4756                        1,
4757                        &split,
4758                        RequestedWeight::Normal,
4759                        &['A', '\u{0301}'],
4760                    ),
4761                ]
4762                .into_iter(),
4763                None,
4764            )
4765            .unwrap();
4766        for ordinal in 0..2 {
4767            environment
4768                .prepare_source_units(ordinal, "A A\u{0301}", None)
4769                .unwrap();
4770        }
4771        environment.operation().unwrap().seal_fonts().unwrap();
4772        let pair = environment
4773            .prepared_pair(&complete, RequestedWeight::Normal)
4774            .unwrap()
4775            .unwrap();
4776        assert_eq!(
4777            pair.selection_for_unit("A", 'A').unwrap(),
4778            ScalarFaceSelection::Face(pair.primary)
4779        );
4780        let unit_face = pair.provenance.candidates[1];
4781        for scalar in ['A', '\u{0301}'] {
4782            assert_eq!(
4783                pair.selection_for_unit("A\u{0301}", scalar).unwrap(),
4784                ScalarFaceSelection::Face(unit_face)
4785            );
4786        }
4787        assert!(matches!(
4788            pair.selection_for_unit("A\u{0301}\u{0301}", 'A'),
4789            Err(FontError::UnknownUnit { .. })
4790        ));
4791        assert!(matches!(
4792            environment.prepare_source_units(0, "A\u{0301}", None),
4793            Err(FontError::PreparedPairAfterSeal { .. })
4794        ));
4795        let split_pair = environment
4796            .prepared_pair(&split, RequestedWeight::Normal)
4797            .unwrap()
4798            .unwrap();
4799        assert_eq!(
4800            split_pair.selection_for_unit("A\u{0301}", 'A').unwrap(),
4801            ScalarFaceSelection::Face(split_pair.primary)
4802        );
4803        assert_eq!(
4804            split_pair
4805                .selection_for_unit("A\u{0301}", '\u{0301}')
4806                .unwrap(),
4807            ScalarFaceSelection::Face(split_pair.provenance.candidates[1])
4808        );
4809        environment
4810            .shape_run(
4811                unit_face,
4812                "A\u{0301}",
4813                ShapingDirection::LeftToRight,
4814                rustybuzz::script::LATIN,
4815            )
4816            .unwrap();
4817    }
4818
4819    #[test]
4820    fn materialized_collection_can_include_rejected_faces_without_retaining_the_operation() {
4821        let core = CanonicalFontCore::from_generated(
4822            vec![build_test_font(), vec![0; 16]],
4823            &HostGenericNames::default(),
4824            FontPreparation::new(),
4825            scalar_presence_map(),
4826        )
4827        .unwrap();
4828        assert_eq!(core.fonts.faces.len(), 1);
4829        let file_storage = core.fonts.files.as_ptr();
4830        let environment = PreparedFontEnvironment::for_core(core).unwrap();
4831        let alive = environment.liveness_probe();
4832        let operation = environment.operation().unwrap().liveness_probe();
4833        environment.operation().unwrap().seal_fonts().unwrap();
4834        let registry = SealedTextVerifier::new(&environment)
4835            .retain_fonts()
4836            .unwrap();
4837        assert!(Arc::ptr_eq(
4838            &registry,
4839            &environment.core.read().unwrap().fonts
4840        ));
4841        assert_eq!(
4842            registry.files.len(),
4843            2,
4844            "keep the complete collection, including files with no admitted faces"
4845        );
4846        assert_eq!(registry.files.as_ptr(), file_storage);
4847        drop(environment);
4848        assert!(!alive() && !operation());
4849        assert_eq!(registry.files[1].bytes.as_slice(), &[0; 16]);
4850    }
4851
4852    fn build_test_font() -> Vec<u8> {
4853        build_test_font_with_coverage("Test Sans", &[' ', 'A', '\u{05D0}'])
4854    }
4855
4856    #[allow(clippy::too_many_lines)]
4857    pub(super) fn build_test_font_with_coverage(family_name: &str, coverage: &[char]) -> Vec<u8> {
4858        let family = utf16_be(family_name);
4859        let postscript = utf16_be("TestSans-Regular");
4860        let mut name = Vec::new();
4861        push_u16(&mut name, 0);
4862        push_u16(&mut name, 3);
4863        push_u16(&mut name, 42);
4864        let mut offset = 0_u16;
4865        for (name_id, value) in [(1_u16, &family), (16_u16, &family), (6_u16, &postscript)] {
4866            push_u16(&mut name, 3);
4867            push_u16(&mut name, 1);
4868            push_u16(&mut name, 0x0409);
4869            push_u16(&mut name, name_id);
4870            push_u16(&mut name, u16::try_from(value.len()).unwrap());
4871            push_u16(&mut name, offset);
4872            offset += u16::try_from(value.len()).unwrap();
4873        }
4874        name.extend_from_slice(&family);
4875        name.extend_from_slice(&family);
4876        name.extend_from_slice(&postscript);
4877
4878        let mut cmap = Vec::new();
4879        push_u16(&mut cmap, 0);
4880        push_u16(&mut cmap, 1);
4881        push_u16(&mut cmap, 3);
4882        push_u16(&mut cmap, 10);
4883        push_u32(&mut cmap, 12);
4884        push_u16(&mut cmap, 12);
4885        push_u16(&mut cmap, 0);
4886        push_u32(&mut cmap, u32::try_from(16 + coverage.len() * 12).unwrap());
4887        push_u32(&mut cmap, 0);
4888        push_u32(&mut cmap, u32::try_from(coverage.len()).unwrap());
4889        for scalar in coverage {
4890            push_u32(&mut cmap, *scalar as u32);
4891            push_u32(&mut cmap, *scalar as u32);
4892            push_u32(&mut cmap, if *scalar == ' ' { 2 } else { 1 });
4893        }
4894
4895        let mut head = vec![0_u8; 54];
4896        set_u32(&mut head, 0, 0x0001_0000);
4897        set_u32(&mut head, 12, 0x5F0F_3CF5);
4898        set_u16(&mut head, 18, 1000);
4899        set_i16(&mut head, 36, 0);
4900        set_i16(&mut head, 38, 0);
4901        set_i16(&mut head, 40, 500);
4902        set_i16(&mut head, 42, 700);
4903        set_i16(&mut head, 50, 0);
4904
4905        let mut hhea = vec![0_u8; 36];
4906        set_u32(&mut hhea, 0, 0x0001_0000);
4907        set_i16(&mut hhea, 4, 800);
4908        set_i16(&mut hhea, 6, -200);
4909        set_u16(&mut hhea, 10, 600);
4910        set_u16(&mut hhea, 34, 3);
4911
4912        let mut maxp = vec![0_u8; 32];
4913        set_u32(&mut maxp, 0, 0x0001_0000);
4914        set_u16(&mut maxp, 4, 3);
4915
4916        let mut os2 = vec![0_u8; 78];
4917        set_u16(&mut os2, 0, 0);
4918        set_u16(&mut os2, 4, 400);
4919        set_u16(&mut os2, 6, 5);
4920        set_u16(&mut os2, 62, 0x0040);
4921        set_u16(&mut os2, 64, 0x0020);
4922        set_u16(&mut os2, 66, 0x0041);
4923        set_i16(&mut os2, 68, 800);
4924        set_i16(&mut os2, 70, -200);
4925        set_u16(&mut os2, 74, 800);
4926        set_u16(&mut os2, 76, 200);
4927
4928        let hmtx = vec![0x01, 0xF4, 0, 0, 0x02, 0x58, 0, 0, 0, 0xFA, 0, 0];
4929        let loca = vec![0, 0, 0, 0, 0, 17, 0, 17];
4930        let mut glyf = vec![0_u8; 34];
4931        set_i16(&mut glyf, 0, 1);
4932        set_i16(&mut glyf, 2, 0);
4933        set_i16(&mut glyf, 4, 0);
4934        set_i16(&mut glyf, 6, 500);
4935        set_i16(&mut glyf, 8, 700);
4936        set_u16(&mut glyf, 10, 3);
4937        set_u16(&mut glyf, 12, 0);
4938        glyf[14..18].fill(1);
4939        for (offset, value) in [(18, 0), (20, 500), (22, 0), (24, -500)] {
4940            set_i16(&mut glyf, offset, value);
4941        }
4942        for (offset, value) in [(26, 0), (28, 0), (30, 700), (32, 0)] {
4943            set_i16(&mut glyf, offset, value);
4944        }
4945
4946        build_sfnt(vec![
4947            (*b"OS/2", os2),
4948            (*b"cmap", cmap),
4949            (*b"glyf", glyf),
4950            (*b"head", head),
4951            (*b"hhea", hhea),
4952            (*b"hmtx", hmtx),
4953            (*b"loca", loca),
4954            (*b"maxp", maxp),
4955            (*b"name", name),
4956        ])
4957    }
4958
4959    fn build_sfnt(mut tables: Vec<([u8; 4], Vec<u8>)>) -> Vec<u8> {
4960        tables.sort_by_key(|(tag, _)| *tag);
4961        let directory_len = 12 + tables.len() * 16;
4962        let mut offset = directory_len;
4963        let mut records = Vec::new();
4964        for (tag, data) in &tables {
4965            records.push((*tag, offset, data.len()));
4966            offset += (data.len() + 3) & !3;
4967        }
4968        let mut font = Vec::with_capacity(offset);
4969        push_u32(&mut font, 0x0001_0000);
4970        push_u16(&mut font, u16::try_from(tables.len()).unwrap());
4971        push_u16(&mut font, 0);
4972        push_u16(&mut font, 0);
4973        push_u16(&mut font, 0);
4974        for (tag, offset, length) in &records {
4975            font.extend_from_slice(tag);
4976            push_u32(&mut font, 0);
4977            push_u32(&mut font, u32::try_from(*offset).unwrap());
4978            push_u32(&mut font, u32::try_from(*length).unwrap());
4979        }
4980        for (_, data) in tables {
4981            font.extend_from_slice(&data);
4982            while font.len() % 4 != 0 {
4983                font.push(0);
4984            }
4985        }
4986        font
4987    }
4988
4989    fn utf16_be(value: &str) -> Vec<u8> {
4990        value.encode_utf16().flat_map(u16::to_be_bytes).collect()
4991    }
4992
4993    fn push_u16(bytes: &mut Vec<u8>, value: u16) {
4994        bytes.extend_from_slice(&value.to_be_bytes());
4995    }
4996
4997    fn push_u32(bytes: &mut Vec<u8>, value: u32) {
4998        bytes.extend_from_slice(&value.to_be_bytes());
4999    }
5000
5001    fn set_u16(bytes: &mut [u8], offset: usize, value: u16) {
5002        bytes[offset..offset + 2].copy_from_slice(&value.to_be_bytes());
5003    }
5004
5005    fn set_i16(bytes: &mut [u8], offset: usize, value: i16) {
5006        bytes[offset..offset + 2].copy_from_slice(&value.to_be_bytes());
5007    }
5008
5009    fn set_u32(bytes: &mut [u8], offset: usize, value: u32) {
5010        bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes());
5011    }
5012}