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