Skip to main content

lichtung_plot/font/canonical/
query.rs

1//! Operation-local family discovery and support reports, using the renderer's
2//! own source index, host generic resolver and admitted faces.
3
4use super::*;
5use std::collections::BTreeMap;
6
7/// Explicit scope of a font support query.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum FontScope {
10    /// Check these preferences, in the supplied order.
11    Selected(Vec<FontFamily>),
12    /// Check every discovered selectable literal family.
13    All,
14}
15
16impl From<FontFamily> for FontScope {
17    fn from(family: FontFamily) -> Self {
18        Self::Selected(vec![family])
19    }
20}
21
22impl From<&[FontFamily]> for FontScope {
23    fn from(families: &[FontFamily]) -> Self {
24        Self::Selected(families.to_vec())
25    }
26}
27
28impl From<Vec<FontFamily>> for FontScope {
29    fn from(families: Vec<FontFamily>) -> Self {
30        Self::Selected(families)
31    }
32}
33
34impl<const N: usize> From<&[FontFamily; N]> for FontScope {
35    fn from(families: &[FontFamily; N]) -> Self {
36        Self::from(families.as_slice())
37    }
38}
39
40impl TryFrom<&str> for FontScope {
41    type Error = crate::Error;
42
43    fn try_from(selection: &str) -> crate::Result<Self> {
44        FontFamily::parse_selection(selection).map(Self::from)
45    }
46}
47
48impl TryFrom<String> for FontScope {
49    type Error = crate::Error;
50
51    fn try_from(selection: String) -> crate::Result<Self> {
52        Self::try_from(selection.as_str())
53    }
54}
55
56impl TryFrom<&[&str]> for FontScope {
57    type Error = crate::Error;
58
59    fn try_from(selections: &[&str]) -> crate::Result<Self> {
60        let families = selections
61            .iter()
62            .map(|selection| FontFamily::parse_selection(selection))
63            .collect::<crate::Result<Vec<_>>>()?;
64        Ok(Self::Selected(families))
65    }
66}
67
68impl<const N: usize> TryFrom<&[&str; N]> for FontScope {
69    type Error = crate::Error;
70
71    fn try_from(selections: &[&str; N]) -> crate::Result<Self> {
72        Self::try_from(selections.as_slice())
73    }
74}
75
76impl TryFrom<&[String]> for FontScope {
77    type Error = crate::Error;
78
79    fn try_from(selections: &[String]) -> crate::Result<Self> {
80        let families = selections
81            .iter()
82            .map(|selection| FontFamily::parse_selection(selection))
83            .collect::<crate::Result<Vec<_>>>()?;
84        Ok(Self::Selected(families))
85    }
86}
87
88/// Evidence about a requested family's discovery in the current search scope.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum FontDiscovery {
91    /// At least one actual matching family name was found.
92    Found,
93    /// No matching family was found in the completed search.
94    NotFound,
95    /// Source evidence does not settle whether this family was found.
96    Undetermined,
97}
98
99/// Support summary of the confirmed logical variants.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum FontSupport {
102    /// All confirmed variants have an admitted candidate.
103    Full,
104    /// Different confirmed variants have different support outcomes.
105    Partial,
106    /// Confirmed variants exist, but all are unavailable.
107    None,
108    /// No valid variant support check was possible.
109    NotChecked,
110}
111
112/// Actual native style of one logical font variant.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
114pub enum FontStyle {
115    /// Upright style.
116    Normal,
117    /// Oblique style.
118    Oblique,
119    /// Italic style.
120    Italic,
121}
122
123impl From<Style> for FontStyle {
124    fn from(style: Style) -> Self {
125        match style {
126            Style::Normal => Self::Normal,
127            Style::Oblique => Self::Oblique,
128            Style::Italic => Self::Italic,
129        }
130    }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
134pub(super) struct VariantKey {
135    style: FontStyle,
136    weight: u16,
137    width: u16,
138}
139
140impl VariantKey {
141    pub(super) fn new(style: Style, weight: u16, width: Stretch) -> Self {
142        Self {
143            style: style.into(),
144            weight,
145            width: width.to_number(),
146        }
147    }
148
149    fn of(face: &FaceMetadata) -> Self {
150        Self::new(face.style, face.weight, face.stretch)
151    }
152}
153
154/// Result of checking a single confirmed logical variant, independent of
155/// how many source files provide that same variant.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct FontVariantReport {
158    /// Original style.
159    pub style: FontStyle,
160    /// Original numeric weight class.
161    pub weight: u16,
162    /// Original width class (1 through 9).
163    pub width: u16,
164    /// Display subfamily name, if known.
165    pub name: Option<String>,
166    /// An actual candidate of this exact variant is available.
167    pub supported: bool,
168    /// Actual reason if this variant is unavailable.
169    pub reason: Option<String>,
170}
171
172/// An actual problem with one file or one known face in a collection.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct FontSourceIssue {
175    /// Original native source path.
176    pub path: PathBuf,
177    /// Actual collection index, when known.
178    pub face_index: Option<u32>,
179    /// English source failure reason.
180    pub reason: String,
181}
182
183/// The complete discovery and support result of one requested family.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct FontFamilyReport {
186    /// Original selection, including a generic preference or quoted literal.
187    pub requested: String,
188    /// Copyable actual family selection, when discovered.
189    pub family: Option<String>,
190    /// Current discovery evidence.
191    pub discovery: FontDiscovery,
192    /// Support of actual confirmed variants.
193    pub support: FontSupport,
194    /// Actual logical variants, each listed once.
195    pub variants: Vec<FontVariantReport>,
196    /// Failed sources, including those with unknown variant identity.
197    pub source_issues: Vec<FontSourceIssue>,
198    /// Explanation when discovery or the support check is incomplete.
199    pub reason: Option<String>,
200}
201
202fn catalog(include_variants: bool) -> Result<CanonicalFontCore, FontError> {
203    let sources = platform_sources(None)?;
204    let files = discover_indexed_files_for(&sources.roots, None, include_variants)?;
205    CanonicalFontCore::from_index(
206        files,
207        &sources.generics,
208        FontPreparation::new(),
209        scalar_presence_map()?,
210    )
211}
212
213pub(super) fn families(core: &CanonicalFontCore) -> crate::Result<BTreeMap<String, FontFamily>> {
214    let mut names = BTreeMap::new();
215    for file in &core.index {
216        crate::operation::checkpoint()?;
217        for name in file.faces.iter().flat_map(|face| &face.names) {
218            crate::operation::work(1)?;
219            if let Ok(family) = FontFamily::named(&name.value) {
220                names.entry(name.folded.clone()).or_insert(family);
221            }
222        }
223    }
224    Ok(names)
225}
226
227/// List the actual selectable literal families discovered on the current host.
228/// This performs discovery only, without glyph probes or font admission.
229pub fn font_families() -> crate::Result<Vec<String>> {
230    font_families_with_operation(&crate::operation::OperationOptions::default())
231}
232
233/// Discover actual font families using this call's operation options.
234pub fn font_families_with_operation(
235    options: &crate::operation::OperationOptions,
236) -> crate::Result<Vec<String>> {
237    crate::operation::run(options, || {
238        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
239        let families = font_families_in_operation()?;
240        crate::operation::checkpoint()?;
241        Ok(families)
242    })
243}
244
245fn font_families_in_operation() -> crate::Result<Vec<String>> {
246    let core = catalog(false).map_err(crate::Error::from)?;
247    if let Some(reason) = core
248        .index
249        .iter()
250        .find_map(|file| file.failure.as_ref().map(|failure| &failure.reason))
251    {
252        // A list has no source-issue channel for an incomplete discovery.
253        return Err(crate::Error::Render(reason.clone().into()));
254    }
255    crate::data::source::collect_source(
256        families(&core)?
257            .into_values()
258            .map(|family| Ok(family.selection())),
259    )
260}
261
262/// Check explicitly selected families, or all discovered literal families,
263/// using the same discovery, generic resolution and source admission as rendering.
264/// This does not perform layout, shaping probes or trial rendering.
265pub fn check_fonts<S>(scope: S) -> crate::Result<Vec<FontFamilyReport>>
266where
267    S: TryInto<FontScope>,
268    S::Error: Into<crate::Error>,
269{
270    check_fonts_with_operation(scope, &crate::operation::OperationOptions::default())
271}
272
273/// Check font support using this call's operation options.
274pub fn check_fonts_with_operation<S>(
275    scope: S,
276    options: &crate::operation::OperationOptions,
277) -> crate::Result<Vec<FontFamilyReport>>
278where
279    S: TryInto<FontScope>,
280    S::Error: Into<crate::Error>,
281{
282    // Convert an external scope before entering the operation.
283    let scope = scope.try_into().map_err(Into::into)?;
284    crate::operation::run(options, || {
285        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
286        let reports = check_fonts_in_operation(scope)?;
287        crate::operation::checkpoint()?;
288        Ok(reports)
289    })
290}
291
292fn check_fonts_in_operation(scope: FontScope) -> crate::Result<Vec<FontFamilyReport>> {
293    if matches!(&scope, FontScope::Selected(families) if families.is_empty()) {
294        return Err(crate::Error::Data(
295            "font check requires at least one selected family".into(),
296        ));
297    }
298    let mut core = catalog(true).map_err(crate::Error::from)?;
299    check_catalog(&mut core, scope)
300}
301
302pub(super) fn check_catalog(
303    core: &mut CanonicalFontCore,
304    scope: FontScope,
305) -> crate::Result<Vec<FontFamilyReport>> {
306    let names = families(core)?;
307    let selected = match scope {
308        FontScope::Selected(families) => families,
309        FontScope::All => {
310            if names.is_empty() {
311                if let Some(reason) = core
312                    .index
313                    .iter()
314                    .find_map(|file| file.failure.as_ref().map(|failure| &failure.reason))
315                {
316                    return Err(crate::Error::Render(reason.clone().into()));
317                }
318            }
319            names.values().cloned().collect()
320        }
321    };
322
323    let mut resolved = Vec::new();
324    for family in &selected {
325        crate::operation::checkpoint()?;
326        crate::operation::work(1)?;
327        let stack = FontStack::new([family.clone()])?;
328        let mut name = Vec::new();
329        resolve_stack_names_into(
330            &core.database,
331            &stack,
332            &mut name,
333            &mut core.preparation,
334            None,
335        )
336        .map_err(crate::Error::from)?;
337        resolved.push(name.pop().ok_or_else(|| {
338            crate::Error::Render("font resolution returned no family identity".into())
339        })?);
340    }
341    core.materialize_matching(&resolved, None)
342        .map_err(crate::Error::from)?;
343    selected
344        .iter()
345        .zip(&resolved)
346        .map(|(request, name)| {
347            crate::operation::checkpoint()?;
348            family_report(core, request, name, names.get(name)).map_err(crate::Error::from)
349        })
350        .collect()
351}
352
353#[derive(Default)]
354struct VariantEvidence {
355    name: Option<String>,
356    supported: bool,
357    failures: Vec<String>,
358}
359
360fn matching(face: &index::IndexedFace, name: &str) -> bool {
361    face.names
362        .iter()
363        .any(|occurrence| occurrence.folded == name)
364}
365
366fn issue(path: &Path, face_index: Option<u32>, reason: String) -> FontSourceIssue {
367    FontSourceIssue {
368        path: path.to_path_buf(),
369        face_index,
370        reason,
371    }
372}
373
374fn subfamily_name(file: &RetainedFontFile, index: u32) -> Result<Option<String>, FontError> {
375    let face =
376        ttf_parser::Face::parse(&file.bytes, index).map_err(|error| FontError::ParseFace {
377            path: file.canonical_path.clone(),
378            index,
379            reason: error.to_string(),
380        })?;
381    parsed_subfamily_name(&face)
382}
383
384fn parsed_subfamily_name(face: &ttf_parser::Face<'_>) -> Result<Option<String>, FontError> {
385    for name_id in [
386        ttf_parser::name_id::TYPOGRAPHIC_SUBFAMILY,
387        ttf_parser::name_id::SUBFAMILY,
388    ] {
389        for name in face.names() {
390            if name.name_id == name_id {
391                if let Some(value) = admission::decode_name(&name)? {
392                    if !value.is_empty() {
393                        return Ok(Some(value));
394                    }
395                }
396            }
397        }
398    }
399    Ok(None)
400}
401
402fn scan_reason(reason: admission::ScanReason) -> String {
403    match reason {
404        admission::ScanReason::TruncatedCollection => {
405            "truncated font collection offset array".into()
406        }
407        admission::ScanReason::Parser {
408            error,
409            head,
410            apple_bitmap_tables,
411        } => {
412            format!("font parser rejected face: {error}; head table: {head:?}; Apple bitmap tables: {apple_bitmap_tables}")
413        }
414        admission::ScanReason::UnsupportedImageOnly => {
415            "image-only face has no declared vector outline".into()
416        }
417        admission::ScanReason::MissingFamily => "face has no readable native family name".into(),
418    }
419}
420
421fn add_variant(
422    core: &CanonicalFontCore,
423    file: &index::IndexedFontFile,
424    indexed: &index::IndexedFace,
425    variants: &mut BTreeMap<VariantKey, VariantEvidence>,
426    issues: &mut Vec<FontSourceIssue>,
427) -> Result<(), FontError> {
428    let retained = core
429        .fonts
430        .files
431        .iter()
432        .enumerate()
433        .find(|(_, retained)| retained.canonical_path == file.path);
434    if let Some((ordinal, retained)) = retained {
435        if let Some(face) =
436            core.fonts.faces.iter().find(|face| {
437                face.file_ordinal == ordinal && face.identity.face_index == indexed.index
438            })
439        {
440            let key = VariantKey::of(face);
441            let variant = variants.entry(key).or_default();
442            if let Some(indexed_key) = indexed.variant {
443                if indexed_key != key {
444                    return Err(FontError::Arithmetic(
445                        "font variant index/admission mismatch",
446                    ));
447                }
448            }
449            if let Err(error) = face.metrics.validate(face.identity) {
450                let reason = error.to_string();
451                variant.failures.push(reason.clone());
452                issues.push(issue(&file.path, Some(indexed.index), reason));
453            } else {
454                variant.supported = true;
455                if variant.name.is_none() {
456                    variant.name = subfamily_name(retained, indexed.index)?;
457                }
458            }
459            return Ok(());
460        }
461        let failure = core
462            .fonts
463            .issues
464            .iter()
465            .find(|issue| issue.file_ordinal == ordinal && issue.face_index == Some(indexed.index))
466            .ok_or(FontError::Arithmetic(
467                "unadmitted font face has no rejection reason",
468            ))?;
469        if let Ok(parsed) = ttf_parser::Face::parse(&retained.bytes, indexed.index) {
470            let key = VariantKey::new(
471                admission::canonical_style(
472                    parsed.style(),
473                    parsed
474                        .raw_face()
475                        .table(ttf_parser::Tag::from_bytes(b"post")),
476                ),
477                parsed.weight().to_number(),
478                parsed.width(),
479            );
480            let variant = variants.entry(key).or_default();
481            variant.failures.push(scan_reason(failure.reason));
482            if variant.name.is_none() {
483                variant.name = parsed_subfamily_name(&parsed)?;
484            }
485        } else if let Some(key) = indexed.variant {
486            variants
487                .entry(key)
488                .or_default()
489                .failures
490                .push(scan_reason(failure.reason));
491        }
492    } else if let Some(failure) = &file.failure {
493        if let Some(key) = indexed.variant {
494            variants
495                .entry(key)
496                .or_default()
497                .failures
498                .push(failure.reason.clone());
499        }
500    } else {
501        return Err(FontError::Arithmetic(
502            "matching font source was not inspected",
503        ));
504    }
505    Ok(())
506}
507
508fn family_report(
509    core: &CanonicalFontCore,
510    request: &FontFamily,
511    name: &str,
512    family: Option<&FontFamily>,
513) -> Result<FontFamilyReport, FontError> {
514    let mut variants = BTreeMap::new();
515    let mut source_issues = Vec::new();
516    let mut uncertain = name.is_empty();
517    for file in &core.index {
518        let matched = file.faces.iter().any(|face| matching(face, name));
519        if let Some(failure) = &file.failure {
520            if matched || (family.is_none() && failure.incomplete_index) {
521                uncertain |= failure.incomplete_index;
522                source_issues.push(issue(
523                    &file.path,
524                    failure.face_index,
525                    failure.reason.clone(),
526                ));
527            }
528        }
529        for (index, reason) in &file.issues {
530            // An unaddressable face does not establish a family or variant.
531            uncertain = true;
532            // Once materialized, the admission diagnostic is more specific.
533            if !file.is_materialized() && (matched || family.is_none()) {
534                source_issues.push(issue(&file.path, *index, (*reason).to_owned()));
535            }
536        }
537        if matched {
538            for face in file.faces.iter().filter(|face| matching(face, name)) {
539                add_variant(core, file, face, &mut variants, &mut source_issues)?;
540            }
541        }
542    }
543    for entry in &core.fonts.issues {
544        let file = &core.fonts.files[entry.file_ordinal];
545        let indexed = core
546            .index
547            .iter()
548            .find(|indexed| indexed.path == file.canonical_path)
549            .ok_or(FontError::Arithmetic("font issue has no index record"))?;
550        let known = entry
551            .face_index
552            .and_then(|index| indexed.faces.iter().find(|face| face.index == index));
553        let relevant = known.map_or_else(
554            || family.is_none() || indexed.faces.iter().any(|face| matching(face, name)),
555            |face| matching(face, name),
556        );
557        if relevant {
558            source_issues.push(issue(
559                &file.canonical_path,
560                entry.face_index,
561                scan_reason(entry.reason),
562            ));
563        }
564    }
565
566    let discovery = if family.is_some() {
567        FontDiscovery::Found
568    } else if uncertain {
569        FontDiscovery::Undetermined
570    } else {
571        FontDiscovery::NotFound
572    };
573    let variants = variants
574        .into_iter()
575        .map(|(key, evidence)| FontVariantReport {
576            style: key.style,
577            weight: key.weight,
578            width: key.width,
579            name: evidence.name,
580            supported: evidence.supported,
581            reason: (!evidence.supported).then(|| evidence.failures.join("; ")),
582        })
583        .collect::<Vec<_>>();
584    let support = if variants.is_empty() {
585        FontSupport::NotChecked
586    } else if variants.iter().all(|variant| variant.supported) {
587        FontSupport::Full
588    } else if variants.iter().any(|variant| variant.supported) {
589        FontSupport::Partial
590    } else {
591        FontSupport::None
592    };
593    let reason = match discovery {
594        FontDiscovery::NotFound => {
595            Some("family was not found in the current search scope".to_owned())
596        }
597        FontDiscovery::Undetermined => {
598            Some("incomplete source evidence prevents confirming family discovery".to_owned())
599        }
600        FontDiscovery::Found if variants.is_empty() => {
601            Some("no logical variant identity could be confirmed".to_owned())
602        }
603        FontDiscovery::Found => None,
604    };
605    Ok(FontFamilyReport {
606        requested: request.selection(),
607        family: family.map(FontFamily::selection),
608        discovery,
609        support,
610        variants,
611        source_issues,
612        reason,
613    })
614}