use super::*;
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FontScope {
Selected(Vec<FontFamily>),
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))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontDiscovery {
Found,
NotFound,
Undetermined,
}
impl FontDiscovery {
pub const fn as_str(self) -> &'static str {
match self {
Self::Found => "found",
Self::NotFound => "not_found",
Self::Undetermined => "undetermined",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontSupport {
Full,
Partial,
None,
NotChecked,
}
impl FontSupport {
pub const fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::Partial => "partial",
Self::None => "none",
Self::NotChecked => "not_checked",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FontStyle {
Normal,
Oblique,
Italic,
}
impl FontStyle {
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)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontVariantReport {
pub style: FontStyle,
pub weight: u16,
pub width: u16,
pub name: Option<String>,
pub supported: bool,
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontSourceIssue {
pub path: PathBuf,
pub face_index: Option<u32>,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontFamilyReport {
pub requested: String,
pub family: Option<String>,
pub discovery: FontDiscovery,
pub support: FontSupport,
pub variants: Vec<FontVariantReport>,
pub source_issues: Vec<FontSourceIssue>,
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)
}
pub fn font_families() -> crate::Result<Vec<String>> {
font_families_with_operation(&crate::operation::OperationOptions::default())
}
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))
{
return Err(crate::Error::Render(reason.clone().into()));
}
crate::data::source::collect_source(
families(&core)?
.into_values()
.map(|family| Ok(family.selection())),
)
}
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())
}
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>,
{
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 {
uncertain = true;
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,
})
}