font-catalog: generic_family names the installed sans-serif, serif, monospace or system-ui family

Catalog::generic_family(Generic) returns the installed family to draw
with when a caller has no family name, or the one it has is not
installed. With the system feature it takes the first family the
platform's font service lists for the generic family that the catalog
has (fontconfig's configured aliases on Linux and FreeBSD). Otherwise it
takes the first installed family of a fixed list for the catalog's
platform, then of the other platforms' lists. SystemUi tries the
platform's sans-serif families before the other platforms' lists. Names
are looked up as resolve() looks them up, so a legacy family name finds
its family, and added faces count.

The fonts example prints the four answers.
This commit is contained in:
dotCooCoo committed 2026-11-20 11:27:57 -08:00
1 parent a20dfd1623
commit d38fa97402
7 files changed
+193 -2

No files matched your search

+1
View File
@@ -54,6 +54,7 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family
- `family(name)` and `resolve(name, style)` accept any name of a family: its own name ignoring ASCII case, its names in other languages and its legacy names ignoring case and anything but letters and digits. `resolve` also accepts a legacy family with its legacy style (`Roboto Light` / `Regular`), a full name, and a PostScript name.
- Within a family, `resolve` matches the style by name (any of its names). Otherwise it picks the nearest weight, with italic differing counting as 1000, then the nearest width. It returns `Match::Exact` or `Match::NearestStyle`, so the app decides about substitutes.
- `by_postscript_name(name)`.
- `generic_family(Generic::SansSerif)` (also `Serif`, `Monospace` and `SystemUi`) names the installed family to use when a document names no family or one that is not installed. With the `system` feature it takes the first family the font service lists for it that the catalog has (fontconfig's configured aliases on Linux and FreeBSD). Otherwise, or when the catalog has none of those, it takes the first installed family of a fixed list for the catalog's platform (`Arial` for sans-serif on Windows, `Helvetica` on macOS, `DejaVu Sans` on Linux), then of the other platforms' lists. `SystemUi` tries the platform's sans-serif families before the other platforms' lists. It returns `None` when none of them is installed.
## Loading and threads
+4 -1
View File
@@ -8,7 +8,7 @@
use std::time::{Duration, Instant};
use craft_font_catalog::{Catalog, font_dirs, font_store_dir};
use craft_font_catalog::{Catalog, Generic, font_dirs, font_store_dir};
fn main() {
let catalog = Catalog::global();
@@ -18,6 +18,9 @@ fn main() {
let faces = catalog.faces();
println!("{} families, {} faces, first scan {:?}", families.len(), faces.len(), start.elapsed());
println!("font store: {:?}", font_store_dir(catalog.env()));
for generic in Generic::ALL {
println!("{}: {:?}", generic.css_name(), catalog.generic_family(generic));
}
for dir in font_dirs(catalog.env()).iter().filter(|d| d.is_dir()) {
println!("folder: {}", dir.display());
}
+5
View File
@@ -382,6 +382,11 @@ impl Catalog {
self.config.read().unwrap_or_else(PoisonError::into_inner)
}
/// Whether scans ask the platform's font service ([`Catalog::with_font_service`]).
pub(crate) fn uses_font_service(&self) -> bool {
self.read_config().font_service
}
/// The environment the catalog was made for.
pub fn env(&self) -> &FontEnv {
&self.env
+124
View File
@@ -0,0 +1,124 @@
//! Generic families: the installed family to use for sans-serif, serif, monospace or interface
//! text when a caller has no family name, or the name it has is not installed.
use crate::{Catalog, Os};
/// A generic family ([`Catalog::generic_family`]), as CSS names them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Generic {
/// `sans-serif`.
SansSerif,
/// `serif`.
Serif,
/// `monospace`.
Monospace,
/// `system-ui`: the face the platform draws its own interface with.
SystemUi,
}
impl Generic {
/// Every generic family.
pub const ALL: [Generic; 4] = [Generic::SansSerif, Generic::Serif, Generic::Monospace, Generic::SystemUi];
/// The CSS keyword (`sans-serif`, `serif`, `monospace`, `system-ui`).
pub fn css_name(self) -> &'static str {
match self {
Generic::SansSerif => "sans-serif",
Generic::Serif => "serif",
Generic::Monospace => "monospace",
Generic::SystemUi => "system-ui",
}
}
}
/// The platforms in the order their lists are tried after the catalog's own.
const OSES: [Os; 4] = [Os::Windows, Os::MacOs, Os::Unix, Os::Haiku];
/// The families tried for `generic` on `os`, most likely first.
fn names(generic: Generic, os: Os) -> &'static [&'static str] {
match (generic, os) {
(Generic::SansSerif, Os::Windows) => &["Arial", "Segoe UI", "Tahoma", "Verdana"],
(Generic::SansSerif, Os::MacOs) => &["Helvetica", "Helvetica Neue", "Arial"],
(Generic::SansSerif, Os::Unix) => &["DejaVu Sans", "Noto Sans", "Liberation Sans", "Cantarell", "Ubuntu", "FreeSans"],
(Generic::SansSerif, Os::Haiku) => &["Noto Sans", "DejaVu Sans"],
(Generic::Serif, Os::Windows) => &["Times New Roman", "Cambria", "Georgia"],
(Generic::Serif, Os::MacOs) => &["Times", "Times New Roman", "New York"],
(Generic::Serif, Os::Unix) => &["DejaVu Serif", "Noto Serif", "Liberation Serif", "FreeSerif"],
(Generic::Serif, Os::Haiku) => &["Noto Serif", "DejaVu Serif"],
(Generic::Monospace, Os::Windows) => &["Consolas", "Cascadia Mono", "Courier New"],
(Generic::Monospace, Os::MacOs) => &["Menlo", "SF Mono", "Monaco", "Courier", "Courier New"],
(Generic::Monospace, Os::Unix) => &["DejaVu Sans Mono", "Noto Sans Mono", "Liberation Mono", "FreeMono"],
(Generic::Monospace, Os::Haiku) => &["Noto Sans Mono", "DejaVu Sans Mono"],
(Generic::SystemUi, Os::Windows) => &["Segoe UI", "Tahoma"],
(Generic::SystemUi, Os::MacOs) => &[".SF NS", "SF Pro", "SF Pro Text", "Helvetica Neue", "Lucida Grande"],
(Generic::SystemUi, Os::Unix) => &["Cantarell", "Ubuntu", "Noto Sans", "DejaVu Sans"],
(Generic::SystemUi, Os::Haiku) => &["Noto Sans"],
(_, Os::None) => &[],
}
}
/// The names [`Catalog::generic_family`] tries, in order: the font service's (`service`) and the
/// list for `os`, then the other platforms' lists. For [`Generic::SystemUi`], the font service's
/// and `os`'s sans-serif names (`sans_service`) come before the other platforms' lists, and their
/// sans-serif lists come last.
fn candidates<'a>(generic: Generic, os: Os, service: &'a [String], sans_service: &'a [String]) -> Vec<&'a str> {
let others = |generic: Generic| OSES.into_iter().filter(move |o| *o != os).flat_map(move |o| names(generic, o).iter().copied());
let mut out: Vec<&str> = service.iter().map(String::as_str).chain(names(generic, os).iter().copied()).collect();
if generic == Generic::SystemUi {
out.extend(sans_service.iter().map(String::as_str).chain(names(Generic::SansSerif, os).iter().copied()));
out.extend(others(generic).chain(others(Generic::SansSerif)));
} else {
out.extend(others(generic));
}
out
}
impl Catalog {
/// The installed family for `generic`, as the catalog names it.
///
/// With the font service on ([`Catalog::with_font_service`]), the families the platform's
/// service lists for `generic` come first (fontconfig's configured aliases on Linux and
/// FreeBSD, fixed names on macOS and Windows). A fixed list for the catalog's platform
/// ([`crate::FontEnv::os`]) follows, then the other platforms' lists. [`Generic::SystemUi`]
/// tries the service's and the platform's sans-serif families before the other platforms'
/// lists. The first of these names that [`Catalog::resolve`] finds wins, so a legacy family
/// name finds its family. Faces added with [`Catalog::add_bytes`] or [`Catalog::add_file`]
/// count as installed. Returns `None` when none of the names is installed. Pass the family
/// to [`Catalog::resolve`] for a face in a style.
pub fn generic_family(&self, generic: Generic) -> Option<String> {
let service = |generic| if self.uses_font_service() { crate::system::generic_family_names(generic) } else { Vec::new() };
let (own, sans) = (service(generic), if generic == Generic::SystemUi { service(Generic::SansSerif) } else { Vec::new() });
candidates(generic, self.env().os, &own, &sans).into_iter().find_map(|name| self.resolve(name, "").map(|(face, _)| face.family))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn candidates_put_the_service_first_then_this_platform_then_the_others() {
let service = ["Configured Sans".to_string()];
let tried = candidates(Generic::SansSerif, Os::Unix, &service, &[]);
assert_eq!(&tried[..3], ["Configured Sans", "DejaVu Sans", "Noto Sans"]);
let windows = tried.iter().position(|n| *n == "Arial");
let mac = tried.iter().position(|n| *n == "Helvetica");
assert!(windows.is_some() && mac.is_some() && windows < mac, "the other platforms' lists follow in a fixed order");
let ui = candidates(Generic::SystemUi, Os::Windows, &[], &service);
assert_eq!(&ui[..4], ["Segoe UI", "Tahoma", "Configured Sans", "Arial"], "this platform's sans-serif names follow its system-ui names");
let (cantarell, dejavu) = (ui.iter().position(|n| *n == "Cantarell"), ui.iter().rposition(|n| *n == "DejaVu Sans"));
assert!(cantarell < dejavu, "the other platforms' system-ui names come before their sans-serif names");
assert!(candidates(Generic::Serif, Os::None, &[], &[]).contains(&"Times New Roman"));
}
#[test]
fn every_generic_has_names_on_every_platform_with_font_folders() {
for generic in Generic::ALL {
for os in OSES {
assert!(!names(generic, os).is_empty(), "{generic:?} on {os:?}");
}
assert!(names(generic, Os::None).is_empty());
}
assert_eq!(Generic::ALL.map(Generic::css_name), ["sans-serif", "serif", "monospace", "system-ui"]);
}
}
+2
View File
@@ -26,6 +26,7 @@ mod env;
mod face_data;
mod fallback;
mod fontconfig;
mod generic;
mod ligature;
mod line_break;
mod outline;
@@ -46,6 +47,7 @@ pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs};
pub use face_data::FaceData;
pub use fallback::{cluster_face, drawable_characters};
pub use fontconfig::fontconfig_dirs;
pub use generic::Generic;
pub use ligature::ligature_caret_stops;
pub use line_break::settle_line_break;
pub use outline::{FontOutline, GlyphPen, OutlineError};
+24 -1
View File
@@ -13,7 +13,7 @@ mod imp {
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
use fontique::{Collection, CollectionOptions, SourceKind};
use fontique::{Collection, CollectionOptions, GenericFamily, SourceKind};
use crate::{FontEnv, font_store_dir};
@@ -160,6 +160,19 @@ mod imp {
})
}
pub fn generic_family_names(generic: crate::Generic) -> Vec<String> {
let generic = match generic {
crate::Generic::SansSerif => GenericFamily::SansSerif,
crate::Generic::Serif => GenericFamily::Serif,
crate::Generic::Monospace => GenericFamily::Monospace,
crate::Generic::SystemUi => GenericFamily::SystemUi,
};
with(false, |s| {
let ids: Vec<_> = s.collection.generic_families(generic).collect();
ids.into_iter().filter_map(|id| s.collection.family_name(id).map(str::to_owned)).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -241,6 +254,10 @@ mod imp {
pub fn font_files(_refresh: bool) -> Vec<PathBuf> {
Vec::new()
}
pub fn generic_family_names(_generic: crate::Generic) -> Vec<String> {
Vec::new()
}
}
#[cfg(all(feature = "system", not(target_arch = "wasm32")))]
@@ -269,3 +286,9 @@ pub fn refresh() {
pub(crate) fn font_files(refresh: bool) -> Vec<std::path::PathBuf> {
imp::font_files(refresh)
}
/// The families the platform's font service lists for `generic`, most preferred first; none
/// without the `system` feature.
pub(crate) fn generic_family_names(generic: crate::Generic) -> Vec<String> {
imp::generic_family_names(generic)
}
+33
View File
@@ -445,6 +445,39 @@ fn added_fonts_come_first_and_respect_the_limits() {
assert!(matches!(cat.load(&bold), Err(FontFileError::Gone)));
}
#[test]
fn generic_families_follow_the_platforms_list_then_the_others() {
let root = temp("generic");
let dir = root.join("listed");
write(&dir.join("Arial.ttf"), font(&spec("Arial", "Regular", 400)));
write(&dir.join("NotoSans.ttf"), font(&spec("Noto Sans", "Regular", 400)));
write(&dir.join("Mono.ttf"), font(&spec("DEJAVU SANS MONO", "Regular", 400)));
write(&dir.join("Times.ttf"), font(&Spec { legacy: Some(("Times New Roman", "Regular")), ..spec("Times New Roman Pro", "Regular", 400) }));
write(&dir.join("DejaVuSans.ttf"), font(&Spec { outlines: false, ..spec("DejaVu Sans", "Regular", 400) }));
let catalog = |os: Os| {
let listed = dir.clone();
Catalog::new(FontEnv { os, ..linux_env(&root) }).with_font_service(false).with_lister(Arc::new(move || vec![listed.clone()]))
};
// Linux: DejaVu Sans has no outlines, so Noto Sans; the family's own spelling comes back.
let linux = catalog(Os::Unix);
assert_eq!(linux.generic_family(Generic::SansSerif).as_deref(), Some("Noto Sans"));
assert_eq!(linux.generic_family(Generic::Monospace).as_deref(), Some("DEJAVU SANS MONO"));
// A legacy family name finds its family.
assert_eq!(linux.generic_family(Generic::Serif).as_deref(), Some("Times New Roman Pro"));
assert_eq!(linux.generic_family(Generic::SystemUi).as_deref(), Some("Noto Sans"));
// Windows tries Arial before the Linux names.
let windows = catalog(Os::Windows);
assert_eq!(windows.generic_family(Generic::SansSerif).as_deref(), Some("Arial"));
// Nothing of macOS's system-ui list: sans-serif's answer.
assert_eq!(catalog(Os::MacOs).generic_family(Generic::SystemUi).as_deref(), Some("Arial"));
// An added face counts; with nothing installed there is no answer.
let empty = Catalog::new(linux_env(&root.join("empty"))).with_font_service(false);
assert_eq!(empty.generic_family(Generic::Monospace), None);
empty.add_bytes(font(&spec("Liberation Mono", "Regular", 400)), Source::Document, &Limits::default()).unwrap();
assert_eq!(empty.generic_family(Generic::Monospace).as_deref(), Some("Liberation Mono"));
assert_eq!(empty.generic_family(Generic::Serif), None);
}
#[test]
fn the_scan_reads_only_what_it_may() {
let root = temp("bounded");