lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Operation-local family discovery and support reports, using the renderer's
//! own source index, host generic resolver and admitted faces.

use super::*;
use std::collections::BTreeMap;

/// Explicit scope of a font support query.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FontScope {
    /// Check these preferences, in the supplied order.
    Selected(Vec<FontFamily>),
    /// Check every discovered selectable literal family.
    All,
}

impl From<FontFamily> for FontScope {
    fn from(family: FontFamily) -> Self {
        Self::Selected(vec![family])
    }
}

impl From<&[FontFamily]> for FontScope {
    fn from(families: &[FontFamily]) -> Self {
        Self::Selected(families.to_vec())
    }
}

impl From<Vec<FontFamily>> for FontScope {
    fn from(families: Vec<FontFamily>) -> Self {
        Self::Selected(families)
    }
}

impl<const N: usize> From<&[FontFamily; N]> for FontScope {
    fn from(families: &[FontFamily; N]) -> Self {
        Self::from(families.as_slice())
    }
}

impl TryFrom<&str> for FontScope {
    type Error = crate::Error;

    fn try_from(selection: &str) -> crate::Result<Self> {
        FontFamily::parse_selection(selection).map(Self::from)
    }
}

impl TryFrom<String> for FontScope {
    type Error = crate::Error;

    fn try_from(selection: String) -> crate::Result<Self> {
        Self::try_from(selection.as_str())
    }
}

impl TryFrom<&[&str]> for FontScope {
    type Error = crate::Error;

    fn try_from(selections: &[&str]) -> crate::Result<Self> {
        let families = selections
            .iter()
            .map(|selection| FontFamily::parse_selection(selection))
            .collect::<crate::Result<Vec<_>>>()?;
        Ok(Self::Selected(families))
    }
}

impl<const N: usize> TryFrom<&[&str; N]> for FontScope {
    type Error = crate::Error;

    fn try_from(selections: &[&str; N]) -> crate::Result<Self> {
        Self::try_from(selections.as_slice())
    }
}

impl TryFrom<&[String]> for FontScope {
    type Error = crate::Error;

    fn try_from(selections: &[String]) -> crate::Result<Self> {
        let families = selections
            .iter()
            .map(|selection| FontFamily::parse_selection(selection))
            .collect::<crate::Result<Vec<_>>>()?;
        Ok(Self::Selected(families))
    }
}

/// Evidence about a requested family's discovery in the current search scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontDiscovery {
    /// At least one actual matching family name was found.
    Found,
    /// No matching family was found in the completed search.
    NotFound,
    /// Source evidence does not settle whether this family was found.
    Undetermined,
}

impl FontDiscovery {
    /// The portable name of this discovery result.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Found => "found",
            Self::NotFound => "not_found",
            Self::Undetermined => "undetermined",
        }
    }
}

/// Support summary of the confirmed logical variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontSupport {
    /// All confirmed variants have an admitted candidate.
    Full,
    /// Different confirmed variants have different support outcomes.
    Partial,
    /// Confirmed variants exist, but all are unavailable.
    None,
    /// No valid variant support check was possible.
    NotChecked,
}

impl FontSupport {
    /// The portable name of this support result.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Partial => "partial",
            Self::None => "none",
            Self::NotChecked => "not_checked",
        }
    }
}

/// Actual native style of one logical font variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FontStyle {
    /// Upright style.
    Normal,
    /// Oblique style.
    Oblique,
    /// Italic style.
    Italic,
}

impl FontStyle {
    /// The portable name of this native variant style.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Oblique => "oblique",
            Self::Italic => "italic",
        }
    }
}

impl From<Style> for FontStyle {
    fn from(style: Style) -> Self {
        match style {
            Style::Normal => Self::Normal,
            Style::Oblique => Self::Oblique,
            Style::Italic => Self::Italic,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct VariantKey {
    style: FontStyle,
    weight: u16,
    width: u16,
}

impl VariantKey {
    pub(super) fn new(style: Style, weight: u16, width: Stretch) -> Self {
        Self {
            style: style.into(),
            weight,
            width: width.to_number(),
        }
    }

    fn of(face: &FaceMetadata) -> Self {
        Self::new(face.style, face.weight, face.stretch)
    }
}

/// Result of checking a single confirmed logical variant, independent of
/// how many source files provide that same variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontVariantReport {
    /// Original style.
    pub style: FontStyle,
    /// Original numeric weight class.
    pub weight: u16,
    /// Original width class (1 through 9).
    pub width: u16,
    /// Display subfamily name, if known.
    pub name: Option<String>,
    /// An actual candidate of this exact variant is available.
    pub supported: bool,
    /// Actual reason if this variant is unavailable.
    pub reason: Option<String>,
}

/// An actual problem with one file or one known face in a collection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontSourceIssue {
    /// Original native source path.
    pub path: PathBuf,
    /// Actual collection index, when known.
    pub face_index: Option<u32>,
    /// English source failure reason.
    pub reason: String,
}

/// The complete discovery and support result of one requested family.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontFamilyReport {
    /// Original selection, including a generic preference or quoted literal.
    pub requested: String,
    /// Copyable actual family selection, when discovered.
    pub family: Option<String>,
    /// Current discovery evidence.
    pub discovery: FontDiscovery,
    /// Support of actual confirmed variants.
    pub support: FontSupport,
    /// Actual logical variants, each listed once.
    pub variants: Vec<FontVariantReport>,
    /// Failed sources, including those with unknown variant identity.
    pub source_issues: Vec<FontSourceIssue>,
    /// Explanation when discovery or the support check is incomplete.
    pub reason: Option<String>,
}

fn catalog(include_variants: bool) -> Result<CanonicalFontCore, FontError> {
    let sources = platform_sources(None)?;
    let files = discover_indexed_files_for(&sources.roots, None, include_variants)?;
    CanonicalFontCore::from_index(
        files,
        &sources.generics,
        FontPreparation::new(),
        scalar_presence_map()?,
    )
}

pub(super) fn families(core: &CanonicalFontCore) -> crate::Result<BTreeMap<String, FontFamily>> {
    let mut names = BTreeMap::new();
    for file in &core.index {
        crate::operation::checkpoint()?;
        for name in file.faces.iter().flat_map(|face| &face.names) {
            crate::operation::check()?;
            if let Ok(family) = FontFamily::named(&name.value) {
                names.entry(name.folded.clone()).or_insert(family);
            }
        }
    }
    Ok(names)
}

/// List the actual selectable literal families discovered on the current host.
/// This performs discovery only, without glyph probes or font admission.
pub fn font_families() -> crate::Result<Vec<String>> {
    font_families_with_operation(&crate::operation::OperationOptions::default())
}

/// Discover actual font families using this call's operation options.
pub fn font_families_with_operation(
    options: &crate::operation::OperationOptions,
) -> crate::Result<Vec<String>> {
    crate::operation::run(options, || {
        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
        let families = font_families_in_operation()?;
        crate::operation::checkpoint()?;
        Ok(families)
    })
}

fn font_families_in_operation() -> crate::Result<Vec<String>> {
    let core = catalog(false).map_err(crate::Error::from)?;
    if let Some(reason) = core
        .index
        .iter()
        .find_map(|file| file.failure.as_ref().map(|failure| &failure.reason))
    {
        // A list has no source-issue channel for an incomplete discovery.
        return Err(crate::Error::Render(reason.clone().into()));
    }
    crate::data::source::collect_source(
        families(&core)?
            .into_values()
            .map(|family| Ok(family.selection())),
    )
}

/// Check explicitly selected families, or all discovered literal families,
/// using the same discovery, generic resolution and source admission as rendering.
/// This does not perform layout, shaping probes or trial rendering.
pub fn check_fonts<S>(scope: S) -> crate::Result<Vec<FontFamilyReport>>
where
    S: TryInto<FontScope>,
    S::Error: Into<crate::Error>,
{
    check_fonts_with_operation(scope, &crate::operation::OperationOptions::default())
}

/// Check font support using this call's operation options.
pub fn check_fonts_with_operation<S>(
    scope: S,
    options: &crate::operation::OperationOptions,
) -> crate::Result<Vec<FontFamilyReport>>
where
    S: TryInto<FontScope>,
    S::Error: Into<crate::Error>,
{
    // Convert an external scope before entering the operation.
    let scope = scope.try_into().map_err(Into::into)?;
    crate::operation::run(options, || {
        crate::operation::phase(crate::errors::OperationPhase::Prepare)?;
        let reports = check_fonts_in_operation(scope)?;
        crate::operation::checkpoint()?;
        Ok(reports)
    })
}

fn check_fonts_in_operation(scope: FontScope) -> crate::Result<Vec<FontFamilyReport>> {
    if matches!(&scope, FontScope::Selected(families) if families.is_empty()) {
        return Err(crate::Error::Data(
            "font check requires at least one selected family".into(),
        ));
    }
    let mut core = catalog(true).map_err(crate::Error::from)?;
    check_catalog(&mut core, scope)
}

pub(super) fn check_catalog(
    core: &mut CanonicalFontCore,
    scope: FontScope,
) -> crate::Result<Vec<FontFamilyReport>> {
    let names = families(core)?;
    let selected = match scope {
        FontScope::Selected(families) => families,
        FontScope::All => {
            if names.is_empty() {
                if let Some(reason) = core
                    .index
                    .iter()
                    .find_map(|file| file.failure.as_ref().map(|failure| &failure.reason))
                {
                    return Err(crate::Error::Render(reason.clone().into()));
                }
            }
            names.values().cloned().collect()
        }
    };

    let mut resolved = Vec::new();
    for family in &selected {
        crate::operation::checkpoint()?;
        let stack = FontStack::new([family.clone()])?;
        let mut name = Vec::new();
        resolve_stack_names_into(
            &core.database,
            &stack,
            &mut name,
            &mut core.preparation,
            None,
        )
        .map_err(crate::Error::from)?;
        resolved.push(name.pop().ok_or_else(|| {
            crate::Error::Render("font resolution returned no family identity".into())
        })?);
    }
    core.materialize_matching(&resolved, None)
        .map_err(crate::Error::from)?;
    selected
        .iter()
        .zip(&resolved)
        .map(|(request, name)| {
            crate::operation::checkpoint()?;
            family_report(core, request, name, names.get(name)).map_err(crate::Error::from)
        })
        .collect()
}

#[derive(Default)]
struct VariantEvidence {
    name: Option<String>,
    supported: bool,
    failures: Vec<String>,
}

fn matching(face: &index::IndexedFace, name: &str) -> bool {
    face.names
        .iter()
        .any(|occurrence| occurrence.folded == name)
}

fn issue(path: &Path, face_index: Option<u32>, reason: String) -> FontSourceIssue {
    FontSourceIssue {
        path: path.to_path_buf(),
        face_index,
        reason,
    }
}

fn subfamily_name(file: &RetainedFontFile, index: u32) -> Result<Option<String>, FontError> {
    let face =
        ttf_parser::Face::parse(&file.bytes, index).map_err(|error| FontError::ParseFace {
            path: file.canonical_path.clone(),
            index,
            reason: error.to_string(),
        })?;
    parsed_subfamily_name(&face)
}

fn parsed_subfamily_name(face: &ttf_parser::Face<'_>) -> Result<Option<String>, FontError> {
    for name_id in [
        ttf_parser::name_id::TYPOGRAPHIC_SUBFAMILY,
        ttf_parser::name_id::SUBFAMILY,
    ] {
        for name in face.names() {
            if name.name_id == name_id {
                if let Some(value) = admission::decode_name(&name)? {
                    if !value.is_empty() {
                        return Ok(Some(value));
                    }
                }
            }
        }
    }
    Ok(None)
}

fn scan_reason(reason: admission::ScanReason) -> String {
    match reason {
        admission::ScanReason::TruncatedCollection => {
            "truncated font collection offset array".into()
        }
        admission::ScanReason::Parser {
            error,
            head,
            apple_bitmap_tables,
        } => {
            format!("font parser rejected face: {error}; head table: {head:?}; Apple bitmap tables: {apple_bitmap_tables}")
        }
        admission::ScanReason::UnsupportedImageOnly => {
            "image-only face has no declared vector outline".into()
        }
        admission::ScanReason::MissingFamily => "face has no readable native family name".into(),
    }
}

fn add_variant(
    core: &CanonicalFontCore,
    file: &index::IndexedFontFile,
    indexed: &index::IndexedFace,
    variants: &mut BTreeMap<VariantKey, VariantEvidence>,
    issues: &mut Vec<FontSourceIssue>,
) -> Result<(), FontError> {
    let retained = core
        .fonts
        .files
        .iter()
        .enumerate()
        .find(|(_, retained)| retained.canonical_path == file.path);
    if let Some((ordinal, retained)) = retained {
        if let Some(face) =
            core.fonts.faces.iter().find(|face| {
                face.file_ordinal == ordinal && face.identity.face_index == indexed.index
            })
        {
            let key = VariantKey::of(face);
            let variant = variants.entry(key).or_default();
            if let Some(indexed_key) = indexed.variant {
                if indexed_key != key {
                    return Err(FontError::Arithmetic(
                        "font variant index/admission mismatch",
                    ));
                }
            }
            if let Err(error) = face.metrics.validate(face.identity) {
                let reason = error.to_string();
                variant.failures.push(reason.clone());
                issues.push(issue(&file.path, Some(indexed.index), reason));
            } else {
                variant.supported = true;
                if variant.name.is_none() {
                    variant.name = subfamily_name(retained, indexed.index)?;
                }
            }
            return Ok(());
        }
        let failure = core
            .fonts
            .issues
            .iter()
            .find(|issue| issue.file_ordinal == ordinal && issue.face_index == Some(indexed.index))
            .ok_or(FontError::Arithmetic(
                "unadmitted font face has no rejection reason",
            ))?;
        if let Ok(parsed) = ttf_parser::Face::parse(&retained.bytes, indexed.index) {
            let key = VariantKey::new(
                admission::canonical_style(
                    parsed.style(),
                    parsed
                        .raw_face()
                        .table(ttf_parser::Tag::from_bytes(b"post")),
                ),
                parsed.weight().to_number(),
                parsed.width(),
            );
            let variant = variants.entry(key).or_default();
            variant.failures.push(scan_reason(failure.reason));
            if variant.name.is_none() {
                variant.name = parsed_subfamily_name(&parsed)?;
            }
        } else if let Some(key) = indexed.variant {
            variants
                .entry(key)
                .or_default()
                .failures
                .push(scan_reason(failure.reason));
        }
    } else if let Some(failure) = &file.failure {
        if let Some(key) = indexed.variant {
            variants
                .entry(key)
                .or_default()
                .failures
                .push(failure.reason.clone());
        }
    } else {
        return Err(FontError::Arithmetic(
            "matching font source was not inspected",
        ));
    }
    Ok(())
}

fn family_report(
    core: &CanonicalFontCore,
    request: &FontFamily,
    name: &str,
    family: Option<&FontFamily>,
) -> Result<FontFamilyReport, FontError> {
    let mut variants = BTreeMap::new();
    let mut source_issues = Vec::new();
    let mut uncertain = name.is_empty();
    for file in &core.index {
        let matched = file.faces.iter().any(|face| matching(face, name));
        if let Some(failure) = &file.failure {
            if matched || (family.is_none() && failure.incomplete_index) {
                uncertain |= failure.incomplete_index;
                source_issues.push(issue(
                    &file.path,
                    failure.face_index,
                    failure.reason.clone(),
                ));
            }
        }
        for (index, reason) in &file.issues {
            // An unaddressable face does not establish a family or variant.
            uncertain = true;
            // Once materialized, the admission diagnostic is more specific.
            if !file.is_materialized() && (matched || family.is_none()) {
                source_issues.push(issue(&file.path, *index, (*reason).to_owned()));
            }
        }
        if matched {
            for face in file.faces.iter().filter(|face| matching(face, name)) {
                add_variant(core, file, face, &mut variants, &mut source_issues)?;
            }
        }
    }
    for entry in &core.fonts.issues {
        let file = &core.fonts.files[entry.file_ordinal];
        let indexed = core
            .index
            .iter()
            .find(|indexed| indexed.path == file.canonical_path)
            .ok_or(FontError::Arithmetic("font issue has no index record"))?;
        let known = entry
            .face_index
            .and_then(|index| indexed.faces.iter().find(|face| face.index == index));
        let relevant = known.map_or_else(
            || family.is_none() || indexed.faces.iter().any(|face| matching(face, name)),
            |face| matching(face, name),
        );
        if relevant {
            source_issues.push(issue(
                &file.canonical_path,
                entry.face_index,
                scan_reason(entry.reason),
            ));
        }
    }

    let discovery = if family.is_some() {
        FontDiscovery::Found
    } else if uncertain {
        FontDiscovery::Undetermined
    } else {
        FontDiscovery::NotFound
    };
    let variants = variants
        .into_iter()
        .map(|(key, evidence)| FontVariantReport {
            style: key.style,
            weight: key.weight,
            width: key.width,
            name: evidence.name,
            supported: evidence.supported,
            reason: (!evidence.supported).then(|| evidence.failures.join("; ")),
        })
        .collect::<Vec<_>>();
    let support = if variants.is_empty() {
        FontSupport::NotChecked
    } else if variants.iter().all(|variant| variant.supported) {
        FontSupport::Full
    } else if variants.iter().any(|variant| variant.supported) {
        FontSupport::Partial
    } else {
        FontSupport::None
    };
    let reason = match discovery {
        FontDiscovery::NotFound => {
            Some("family was not found in the current search scope".to_owned())
        }
        FontDiscovery::Undetermined => {
            Some("incomplete source evidence prevents confirming family discovery".to_owned())
        }
        FontDiscovery::Found if variants.is_empty() => {
            Some("no logical variant identity could be confirmed".to_owned())
        }
        FontDiscovery::Found => None,
    };
    Ok(FontFamilyReport {
        requested: request.selection(),
        family: family.map(FontFamily::selection),
        discovery,
        support,
        variants,
        source_issues,
        reason,
    })
}