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