mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 19:19:35 +00:00
Type: the font menu's Show Similar Fonts lists the families that look like a family first
A ≈ button on a family's row in the font menus orders the listed families by
how alike they look to it: that family first, then the families that set the
same script (Japanese, Thai or neither), then the others, each group nearest
first. The Recent Fonts section is left out while the list is ordered this
way. A ≈ chip under the filters names the family and clears the order, with
that family still highlighted; closing the menu clears it too.
The measure is VectorCraft's own. Each face records its OS/2 PANOSE digits,
weight and width classes, x-height, cap height and average character width,
and its post italic angle; a named instance of a variable font takes its wght
and slnt settings. The system font scan reads the head table and the post
table's header besides the tables it read before, so installed families are
compared by the same numbers without loading them. A family is compared by its
face nearest an upright Regular, a number either face does not give is left
out, and a family of another kind counts as further away.
text.similarFonts {family, limit?} returns the same order, with errors for a
missing or non-string family, a family that is not available or not listed in
the font menus, and a limit that is not a whole number from 1 to 100000.
This commit is contained in:
@@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet;
|
||||
use traits::Alias;
|
||||
#[cfg(test)]
|
||||
use traits::{FaceKeys, face_names};
|
||||
pub use traits::{FontClass, FontMatch, FontTraits};
|
||||
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits};
|
||||
#[cfg(test)]
|
||||
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
|
||||
pub use wanted::{WantedFont, WantedFonts};
|
||||
|
||||
@@ -8,7 +8,10 @@ pub(super) struct CatalogFamily {
|
||||
/// Non-English family name from the name table, when the scan found one.
|
||||
pub(super) native: Option<String>,
|
||||
pub(super) faces: Vec<CatalogFace>,
|
||||
/// The family's kind (from its first face found); variable when any face found is.
|
||||
/// The family's kind (from its first face found); variable when any face found is. Its
|
||||
/// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]).
|
||||
///
|
||||
/// [`regular_rank`]: super::traits::regular_rank
|
||||
pub(super) traits: Option<FontTraits>,
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file};
|
||||
#[cfg(test)]
|
||||
use super::traits::faces_published;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::traits::{Alias, FaceStyle};
|
||||
use super::traits::{Alias, FaceStyle, regular_rank};
|
||||
use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{ScanStamp, modified};
|
||||
@@ -430,6 +430,9 @@ impl FontDb {
|
||||
let entry = catalog.entry(family.to_ascii_lowercase()).or_default();
|
||||
let kind = entry.traits.get_or_insert(traits);
|
||||
kind.variable |= traits.variable;
|
||||
if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) {
|
||||
kind.likeness = traits.likeness;
|
||||
}
|
||||
if entry.name.is_empty() {
|
||||
entry.name = family;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS;
|
||||
use super::names::{norm, norm_chars, script_families};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::scan::{enumerate_faces, font_files};
|
||||
use super::traits::{Alias, FontMatch, FontTraits};
|
||||
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
|
||||
use super::{
|
||||
Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX,
|
||||
Ordering, Size,
|
||||
@@ -86,26 +86,77 @@ impl FontDb {
|
||||
/// loaded face, else from the system font scan. Variable when any of its faces, loaded or
|
||||
/// scanned, is: a family may install static files beside a variable one. Cheap: no font file
|
||||
/// is read, and a loaded family doesn't start the scan. A composite font takes its base font's.
|
||||
/// Its likeness is the one of its face nearest an upright Regular, loaded or scanned.
|
||||
pub fn family_traits(&self, family: &str) -> FontTraits {
|
||||
if let Some((base, _)) = self.composite_base(family) {
|
||||
return self.family_traits(&base);
|
||||
}
|
||||
let loaded = {
|
||||
let faces = self.read_faces();
|
||||
let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family));
|
||||
of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits })
|
||||
let mut found: Option<FontTraits> = None;
|
||||
for f in faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)) {
|
||||
match &mut found {
|
||||
None => found = Some(f.traits),
|
||||
Some(traits) => {
|
||||
traits.variable |= f.traits.variable;
|
||||
if regular_rank(&f.traits.likeness) < regular_rank(&traits.likeness) {
|
||||
traits.likeness = f.traits.likeness;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
};
|
||||
let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits);
|
||||
match loaded {
|
||||
None => scanned(&self.read_catalog()).unwrap_or_default(),
|
||||
Some(traits) if traits.variable => traits,
|
||||
Some(traits) => {
|
||||
let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable);
|
||||
FontTraits { variable, ..traits }
|
||||
Some(mut traits) => {
|
||||
// What the scan found so far, without starting it.
|
||||
if let Some(found) = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)) {
|
||||
traits.variable |= found.variable;
|
||||
if regular_rank(&found.likeness) < regular_rank(&traits.likeness) {
|
||||
traits.likeness = found.likeness;
|
||||
}
|
||||
}
|
||||
traits
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself
|
||||
/// first when listed, then the families that set the same script as it (Japanese, Thai or
|
||||
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
|
||||
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
|
||||
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
|
||||
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
|
||||
/// file, as `family_traits` does not.
|
||||
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
|
||||
let base = self.family_traits(family);
|
||||
let script = |t: &FontTraits| {
|
||||
if t.japanese {
|
||||
0
|
||||
} else if t.thai {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
};
|
||||
let mut keyed: Vec<(bool, f32, &String)> = families
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let traits = self.family_traits(f);
|
||||
let d = if f.eq_ignore_ascii_case(family) {
|
||||
-1.0
|
||||
} else {
|
||||
base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 }
|
||||
};
|
||||
(script(&traits) != script(&base), d, f)
|
||||
})
|
||||
.collect();
|
||||
keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
|
||||
keyed.into_iter().map(|(_, _, f)| f.clone()).collect()
|
||||
}
|
||||
|
||||
/// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how
|
||||
/// it matched. A composite font matches as its base font does ([`Self::composite_base`]).
|
||||
pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc<FontFace>, FontMatch)> {
|
||||
|
||||
@@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
use std::io::SeekFrom;
|
||||
/// The largest table read from a (possibly damaged) file.
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
/// The `post` table's header: version, italic angle, underline and fixed-pitch fields.
|
||||
const POST_HEADER: u32 = 32;
|
||||
let mut read = 0u64;
|
||||
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
|
||||
read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?;
|
||||
@@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
let mut table = |tag: &[u8; 4]| -> Option<Vec<u8>> {
|
||||
// A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing.
|
||||
let mut table_within = |tag: &[u8; 4], most: u32| -> Option<Vec<u8>> {
|
||||
let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most));
|
||||
if len > MAX_NAME_TABLE {
|
||||
return None;
|
||||
}
|
||||
read_at(offset.into(), len as usize)
|
||||
};
|
||||
let name = table(b"name")?;
|
||||
let name = table_within(b"name", u32::MAX)?;
|
||||
// A variable font's named instances are styles too.
|
||||
let fvar = table(b"fvar");
|
||||
let fvar = table_within(b"fvar", u32::MAX);
|
||||
// Its OS/2 table (the font's classification, for the menus' filters), when it has one.
|
||||
let os2 = table(b"OS/2");
|
||||
let os2 = table_within(b"OS/2", u32::MAX);
|
||||
// Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]):
|
||||
// the `head` table and the `post` table's 32-byte header, as a version 3 table (one
|
||||
// without glyph names).
|
||||
let head = table_within(b"head", u32::MAX);
|
||||
let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| {
|
||||
p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes());
|
||||
p
|
||||
});
|
||||
// A font holding just these tables, to read them as the font itself would.
|
||||
let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)];
|
||||
if let Some(fvar) = &fvar {
|
||||
tables.push((b"fvar", fvar));
|
||||
}
|
||||
if let Some(os2) = &os2 {
|
||||
tables.push((b"OS/2", os2));
|
||||
for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] {
|
||||
if let Some(data) = data {
|
||||
tables.push((tag, data.as_slice()));
|
||||
}
|
||||
}
|
||||
let font = sfnt_of(&tables)?;
|
||||
Some(face_styles(&skrifa::FontRef::new(&font).ok()?))
|
||||
|
||||
@@ -101,6 +101,111 @@ pub struct FontTraits {
|
||||
/// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of
|
||||
/// its faces has.
|
||||
pub variable: bool,
|
||||
/// What Show Similar Fonts compares; for a family, its face nearest an upright Regular.
|
||||
pub likeness: FontLikeness,
|
||||
}
|
||||
|
||||
/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]),
|
||||
/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads
|
||||
/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the
|
||||
/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to
|
||||
/// hold the value).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct FontLikeness {
|
||||
/// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit).
|
||||
pub panose: [u8; 10],
|
||||
/// The OS/2 weight class, at most 1000; a named instance's `wght` setting.
|
||||
pub weight: u16,
|
||||
/// The OS/2 width class, 1 to 9.
|
||||
pub width: u8,
|
||||
/// The OS/2 x-height and cap height in thousandths of the em.
|
||||
pub x_height: u16,
|
||||
pub cap_height: u16,
|
||||
/// The OS/2 average character width in thousandths of the em.
|
||||
pub avg_width: u16,
|
||||
/// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named
|
||||
/// instance's `slnt` setting.
|
||||
pub italic_angle: Option<i16>,
|
||||
/// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a
|
||||
/// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a
|
||||
/// family's face nearest an upright Regular.
|
||||
pub italic: bool,
|
||||
}
|
||||
|
||||
impl FontLikeness {
|
||||
/// From a face's tables, with a named instance's `variations` (its axis settings in user
|
||||
/// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2
|
||||
/// weight class, its `slnt` setting in place of the italic angle, and whether it is
|
||||
/// `italic`. The heights and the average width need the `head` table's units per em (16 to
|
||||
/// 16384).
|
||||
fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option<f32>, italic: Option<bool>) -> Self {
|
||||
use skrifa::raw::TableProvider;
|
||||
let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from);
|
||||
// Thousandths of the em, 0 for nothing (and for a value at or below 0).
|
||||
let per_mille = |v: i16| match em {
|
||||
Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16,
|
||||
_ => 0,
|
||||
};
|
||||
let mut likeness = Self::default();
|
||||
if let Ok(o) = font.os2() {
|
||||
for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) {
|
||||
*digit = *value;
|
||||
}
|
||||
likeness.weight = o.us_weight_class().min(1000);
|
||||
likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0);
|
||||
likeness.x_height = o.sx_height().map_or(0, per_mille);
|
||||
likeness.cap_height = o.s_cap_height().map_or(0, per_mille);
|
||||
likeness.avg_width = per_mille(o.x_avg_char_width());
|
||||
// fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags.
|
||||
likeness.italic = o.fs_selection().bits() & 0x0201 != 0;
|
||||
}
|
||||
if let Some(w) = weight.filter(|w| w.is_finite()) {
|
||||
likeness.weight = w.round().clamp(1.0, 1000.0) as u16;
|
||||
}
|
||||
let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16);
|
||||
likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") {
|
||||
Some((_, slant)) => angle(*slant),
|
||||
None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())),
|
||||
};
|
||||
likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0));
|
||||
likeness
|
||||
}
|
||||
|
||||
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
|
||||
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
|
||||
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
|
||||
/// 3 apart. The weights and scales are VectorCraft's own.
|
||||
pub fn distance(&self, other: &Self) -> f32 {
|
||||
let mut d = 0.0;
|
||||
let (kind, other_kind) = (self.panose[0], other.panose[0]);
|
||||
if kind > 1 && other_kind > 1 {
|
||||
if kind == other_kind {
|
||||
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
|
||||
if *a > 1 && *b > 1 {
|
||||
d += f32::from(a.abs_diff(*b)) * 0.15;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
d += 3.0;
|
||||
}
|
||||
}
|
||||
if self.weight != 0 && other.weight != 0 {
|
||||
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
|
||||
}
|
||||
if self.width != 0 && other.width != 0 {
|
||||
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
|
||||
}
|
||||
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
|
||||
{
|
||||
if a != 0 && b != 0 {
|
||||
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
|
||||
}
|
||||
}
|
||||
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
|
||||
d += f32::from(a.abs_diff(b)) / 50.0;
|
||||
}
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
impl FontTraits {
|
||||
@@ -216,10 +321,20 @@ impl FontTraits {
|
||||
FontClass::Other
|
||||
};
|
||||
let variable = (1..=MAX_AXES).contains(&font.axes().len());
|
||||
FontTraits { japanese, thai, class, variable }
|
||||
FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) }
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face
|
||||
/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a
|
||||
/// face that gives no weight last), then by the numbers themselves, so that the same faces give
|
||||
/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness
|
||||
/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded.
|
||||
pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) {
|
||||
let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) };
|
||||
(likeness.italic, off, *likeness)
|
||||
}
|
||||
|
||||
/// What a name other than a family's own one stands for ([`FontDb::canonical`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Alias {
|
||||
@@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
|
||||
let Some((family, style)) = face_names(f) else { return vec![] };
|
||||
let native_family = native_family_name(f, &family);
|
||||
let mut keys = FaceKeys::of(f, &family, &style);
|
||||
let traits = FontTraits::of(f, &keys);
|
||||
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
|
||||
for i in &mut instances {
|
||||
i.traits = traits;
|
||||
}
|
||||
let mut traits = FontTraits::of(f, &keys);
|
||||
// A variable font's default face renders at its `wght` default, whatever its name table and
|
||||
// OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular
|
||||
// at 400): weigh it so, and name it by its default instance when that is another weight.
|
||||
@@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec<FaceStyle> {
|
||||
.map(|a| a.default_value())
|
||||
.filter(|w| w.is_finite())
|
||||
.map(|w| w.clamp(1.0, 1000.0));
|
||||
// Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`).
|
||||
if f.axes().len() <= MAX_AXES {
|
||||
let defaults: Vec<Variation> = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect();
|
||||
traits.likeness = FontLikeness::of(f, &defaults, weight, None);
|
||||
}
|
||||
let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone());
|
||||
// Each named instance shares the face's kind; its likeness is measured at its own axis settings.
|
||||
// Without an `ital` or `slnt` axis, an instance of an italic face is italic too.
|
||||
for i in &mut instances {
|
||||
let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt");
|
||||
let italic = i.italic || (!slant_axis && traits.likeness.italic);
|
||||
i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits };
|
||||
}
|
||||
let style = renamed.unwrap_or(style);
|
||||
let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits };
|
||||
std::iter::once(face).chain(instances).collect()
|
||||
|
||||
@@ -41,10 +41,10 @@ pub use features::{
|
||||
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
|
||||
};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition,
|
||||
LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file,
|
||||
is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs,
|
||||
user_font_dirs,
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins,
|
||||
JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir,
|
||||
is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight,
|
||||
system_font_dirs, user_font_dirs,
|
||||
};
|
||||
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
|
||||
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
|
||||
|
||||
@@ -28,6 +28,7 @@ mod path_joins;
|
||||
mod ruby;
|
||||
mod scripts;
|
||||
mod shape_plans;
|
||||
mod similar;
|
||||
mod snap;
|
||||
mod svg_glyphs;
|
||||
mod sysfonts;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness
|
||||
//! from its face nearest an upright Regular, and families ordered by likeness.
|
||||
|
||||
use skrifa::raw::TableProvider;
|
||||
|
||||
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
|
||||
use crate::*;
|
||||
|
||||
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
|
||||
/// heights in their OS/2 tables.
|
||||
fn db() -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
for heights in [true, false] {
|
||||
assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1);
|
||||
}
|
||||
db
|
||||
}
|
||||
|
||||
fn names(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_face_is_compared_by_its_tables() {
|
||||
let db = db();
|
||||
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
|
||||
assert_eq!(regular.weight, 400);
|
||||
assert_eq!(regular.italic_angle, Some(0));
|
||||
assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}");
|
||||
assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}");
|
||||
// The OS/2 average character width, in thousandths of the em.
|
||||
let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled");
|
||||
let font = skrifa::FontRef::new(&bytes).expect("it parses");
|
||||
let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em());
|
||||
assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round());
|
||||
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
|
||||
assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}");
|
||||
assert!(italic.italic && !regular.italic);
|
||||
let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness;
|
||||
assert_eq!(bold.weight, 700);
|
||||
// The OS/2 heights, in thousandths of its 1,000-unit em.
|
||||
let heights = db.family_traits(HEIGHT_FAMILY).likeness;
|
||||
assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16));
|
||||
// Without them (a version 1 OS/2 table), the heights are left out.
|
||||
let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness;
|
||||
assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}");
|
||||
assert_eq!(heightless.avg_width, regular.avg_width);
|
||||
}
|
||||
|
||||
/// A variable font's named instance takes its `wght` setting as its weight; the default face its
|
||||
/// default weight.
|
||||
#[test]
|
||||
fn a_named_instance_is_weighed_by_its_axis_setting() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3);
|
||||
let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness;
|
||||
let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness;
|
||||
let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness;
|
||||
assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700));
|
||||
// The family is compared by its Regular face.
|
||||
assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular);
|
||||
}
|
||||
|
||||
/// A face without an italic angle is compared by the other numbers only.
|
||||
#[test]
|
||||
fn a_missing_italic_angle_is_left_out() {
|
||||
let db = db();
|
||||
let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness;
|
||||
assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0);
|
||||
assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0);
|
||||
}
|
||||
|
||||
/// A family is compared by its face nearest an upright Regular, not by the first one loaded.
|
||||
#[test]
|
||||
fn a_family_is_compared_by_its_regular_face() {
|
||||
let db = db();
|
||||
let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness;
|
||||
assert_eq!(db.family_traits("Source Sans 3").likeness, regular);
|
||||
assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn likeness_is_a_distance() {
|
||||
let db = db();
|
||||
let (sans, serif, mono) =
|
||||
(db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness);
|
||||
assert_eq!(sans.distance(&sans), 0.0);
|
||||
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
|
||||
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
|
||||
// A number a face does not give is left out, not counted as 0.
|
||||
let unknown = FontLikeness::default();
|
||||
assert_eq!(sans.distance(&unknown), 0.0);
|
||||
let lighter = FontLikeness { weight: 300, ..sans };
|
||||
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
|
||||
}
|
||||
|
||||
/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every
|
||||
/// other family, and the order never moves away from the family and back.
|
||||
#[test]
|
||||
fn families_are_ordered_by_likeness() {
|
||||
let db = db();
|
||||
let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
|
||||
let order = db.similar_families("Source Sans 3", &families);
|
||||
assert_eq!(order.len(), families.len());
|
||||
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
|
||||
let base = db.family_traits("Source Sans 3");
|
||||
let far = |f: &str| {
|
||||
let t = db.family_traits(f);
|
||||
base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 }
|
||||
};
|
||||
for pair in order[1..].windows(2) {
|
||||
assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}");
|
||||
}
|
||||
// Asked by another case, or for a family not in the list.
|
||||
assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3");
|
||||
let without = db.similar_families("Source Sans 3", &families[..4]);
|
||||
assert_eq!(without[0], HEIGHTLESS_FAMILY);
|
||||
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
|
||||
}
|
||||
@@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() {
|
||||
assert!(db.family_traits(FAMILY).variable);
|
||||
}
|
||||
|
||||
/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does,
|
||||
/// and a family's are its Regular face's whichever file is found first.
|
||||
#[test]
|
||||
fn the_scan_reads_a_familys_likeness_without_loading_it() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap();
|
||||
std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap();
|
||||
let scanned = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let likeness = scanned.family_traits(FAMILY).likeness;
|
||||
assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded");
|
||||
let loaded = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1);
|
||||
assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness);
|
||||
assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}");
|
||||
// With only the italic loaded, the scanned Regular face still gives the family's numbers.
|
||||
assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1);
|
||||
assert!(scanned.is_loaded(FAMILY));
|
||||
assert_eq!(scanned.family_traits(FAMILY).likeness, likeness);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_fonts_outside_the_font_folders_are_their_full_paths() {
|
||||
let dir = std::env::temp_dir().join("Fonts");
|
||||
@@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() {
|
||||
let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap();
|
||||
u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap()))
|
||||
};
|
||||
// What one face costs: its table directory and its name and OS/2 tables.
|
||||
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2");
|
||||
// What one face costs: its table directory, its name, OS/2 and head tables and the post table's header.
|
||||
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32;
|
||||
let n = 300;
|
||||
let base = 12 + 4 * n;
|
||||
let mut ttc = b"ttcf".to_vec();
|
||||
|
||||
Reference in New Issue
Block a user