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