Files
vectorcraft/crates/text/src/fontdb.rs
BFlat 6f37bd839c VectorCraft on the craft UI framework (#8800)
VectorCraft's UI moves onto the shared craft UI framework in storytold/craft-libs (`next`; the framework side is storytold/craft-libs#2809), as PhotoCraft's did. The app keeps its engine, document model, file formats, commands and automation; its windows, panels, bars, dialogs and canvas are now built and driven by the framework: shell, docking and panels, hosted dialogs, keyboard, focus, IME and pointer routing, and theme tokens.

About 264,000 lines of VectorCraft's own egui UI code are removed and about 154,000 added. craft-libs is pinned at bf62d509f (in `next`), the egui fork at f5025284.

Tests that drove the old UI were rewritten against the port where only their premise changed, with their assertions kept. The UI tests still failing at merge, and their follow-ups, are listed in the pull request.
2026-11-24 08:25:24 +07:00

379 lines
17 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Font database: bundled OFL fonts, user fonts, the installed system fonts (cataloged once, loaded
//! on demand), outline cache.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use kurbo::BezPath;
use skrifa::instance::{Location, LocationRef, Size};
use skrifa::outline::OutlinePen;
use skrifa::raw::FileRef;
use skrifa::string::StringId;
use skrifa::{GlyphId, MetadataProvider, Tag};
use crate::GlyphImage;
use crate::colr::ColourContent;
use vectorcraft_doc::color::Color;
mod added;
mod alternates;
mod build;
mod cache;
mod composite;
mod db;
mod dirs;
mod face;
mod glyph_pen;
mod gsub;
mod lookup;
mod names;
mod scan;
mod stylistic_sets;
mod traits;
mod wanted;
#[cfg(test)]
pub(crate) use added::recently_added_of;
pub use added::{RECENTLY_ADDED_WITHIN, RecentlyAdded};
pub use alternates::GlyphAlternate;
pub(crate) use alternates::listed;
pub use build::style_weight;
#[cfg(test)]
use cache::GlyphCache;
use cache::{CanonicalNames, GlyphColours, GlyphImages};
pub use composite::{CompositeCoverage, LentCompositeFonts};
use craft::font_catalog::Catalog;
#[cfg(test)]
pub(crate) use dirs::sfnt_of;
pub use dirs::{
PlatformFontFiles, app_font_dir, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, system_font_dirs,
user_font_dirs,
};
use face::Instances;
#[cfg(test)]
pub(crate) use face::MAX_LIVE_INSTANCES;
pub(crate) use face::PathAlignHeights;
pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat};
pub(crate) use glyph_pen::FlipPen;
pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind};
#[cfg(not(target_arch = "wasm32"))]
use names::SysFallback;
#[cfg(test)]
pub use names::THAI_FAMILIES;
#[cfg(test)]
use names::{native_family_name, norm, pick_native_label};
#[cfg(all(not(target_arch = "wasm32"), test))]
pub(crate) use scan::file_face_names_within;
#[cfg(test)]
use scan::{MAX_FACES, enumerate_faces};
pub use scan::{is_font_file, is_suitcase};
pub use stylistic_sets::StylisticSet;
#[cfg(test)]
use traits::{Alias, FaceKeys, face_names};
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, is_generic_family};
#[cfg(test)]
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
pub use wanted::{WantedFont, WantedFonts};
/// Weak indexes of live file-font resources, by content hash (collisions checked by bytes) and id.
#[derive(Default)]
pub(super) struct FileFaces {
pub(super) by_key: HashMap<String, Vec<std::sync::Weak<FontFace>>>,
pub(super) by_id: HashMap<u32, std::sync::Weak<FontFace>>,
/// Only each admitted face's own byte allocation, never an unbounded list of alias owners.
pub(super) by_blob: HashMap<usize, std::sync::Weak<FontFace>>,
}
/// How many live fonts files carried the database admits at most (each shares its document's bytes).
pub const MAX_FILE_FACES: usize = 4096;
/// Process-wide font database.
pub struct FontDb {
faces: RwLock<Vec<Arc<FontFace>>>,
outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>,
/// [`FontDb::glyph_image`]'s answers per (face, glyph), misses too.
images: Mutex<GlyphImages>,
colours: Mutex<GlyphColours>,
/// The installed fonts: the system font scan's faces, found by any of their names
/// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find
/// never depends on what ran before them.
catalog: Arc<Catalog>,
/// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces,
/// so no family name, font menu, fallback or PostScript name lookup finds them.
pub(super) file_faces: RwLock<FileFaces>,
/// Keeps [`FontDb::canonical`]'s answers for names other than the loaded and installed
/// families until fonts are added or rescanned.
canonical_cache: Mutex<CanonicalNames>,
/// Families (lowercased) whose installed files were all loaded to find other versions of their
/// faces (see [`FontDb::versions`]); a rescan forgets them.
#[cfg(not(target_arch = "wasm32"))]
version_scanned: RwLock<std::collections::HashSet<String>>,
/// [`FontDb::family_list`] with the catalog's family list it was built from, built on demand
/// and dropped when fonts are added or rescanned.
family_cache: Mutex<Option<MenuFamilies>>,
menu_cache: Mutex<Option<MenuFamilies>>,
generation: AtomicU64,
/// This database's [`FontDb::id`].
id: u64,
/// System fallback state: characters no system font covers.
#[cfg(not(target_arch = "wasm32"))]
sys: Mutex<SysFallback>,
/// Faces instanced at the axis settings of type's Variable Font sliders ([`FontDb::instance`]).
instances: Mutex<Instances>,
/// Composite fonts (Type › Composite Fonts…) by lowercased name ([`FontDb::set_composite_font`]):
/// type naming one as its family is set in its parts' fonts. A thread's guards can lend others
/// in their place ([`FontDb::lend_composite_fonts`]).
composites: RwLock<HashMap<String, Arc<vectorcraft_doc::CompositeFont>>>,
/// The lookups of the custom character sets of the composite fonts held or lent, each built
/// when first used.
custom_classes: Mutex<composite::CustomClasses>,
}
static NEXT_ID: AtomicU32 = AtomicU32::new(1);
const OUTLINE_CACHE_MAX: usize = 50_000;
/// The most glyph images [`FontDb::glyph_image`] keeps (each a PNG of some 10–60 KB).
const IMAGE_CACHE_MAX: usize = 4_096;
/// The most PNG bytes it keeps: a font can make each one up to [`crate::bitmap::MAX_PNG_BYTES`].
const IMAGE_CACHE_BYTES: usize = 64 << 20;
/// How many answers [`FontDb::canonical`] keeps at most. When it has kept that many, it clears
/// them before it keeps the next one.
const CANONICAL_CACHE_MAX: usize = 4_096;
/// A family list with the list it was built from: [`FontDb::family_list`] with the catalog's
/// families, [`FontDb::menu_family_list`] with [`FontDb::family_list`].
type MenuFamilies = (Arc<[String]>, Arc<[String]>);
#[cfg(test)]
mod alias_tests {
use super::*;
/// A one-table font holding a name table from (platform, language, name id, string) records:
/// Windows Unicode (UTF-16) or Mac Roman (ASCII here).
fn name_font(records: &[(u16, u16, u16, &str)]) -> Vec<u8> {
let (mut head, mut strings) = (vec![], vec![]);
let n = records.len() as u16;
for v in [0, n, 6 + 12 * n] {
head.extend_from_slice(&v.to_be_bytes());
}
for &(platform, lang, id, s) in records {
let bytes: Vec<u8> = if platform == 3 { s.encode_utf16().flat_map(u16::to_be_bytes).collect() } else { s.as_bytes().to_vec() };
let encoding = if platform == 3 { 1 } else { 0 };
for v in [platform, encoding, lang, id, bytes.len() as u16, strings.len() as u16] {
head.extend_from_slice(&v.to_be_bytes());
}
strings.extend(bytes);
}
head.extend(strings);
let mut font = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0];
font.extend_from_slice(b"name");
for v in [0u32, 28, head.len() as u32] {
font.extend_from_slice(&v.to_be_bytes());
}
font.extend(head);
font
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_file_search_for_uncovered_characters_stops_at_its_budget() {
let db = FontDb::with_font_dirs(vec![]);
// The first search scans the font folders, which starts the count again.
db.system_fallback('\u{E001}');
db.sys.lock().unwrap().file_searches = names::MAX_FILE_SEARCHES;
assert!(!db.system_fallback('\u{E000}'));
let sys = db.sys.lock().unwrap();
assert_eq!(sys.file_searches, names::MAX_FILE_SEARCHES);
assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss");
}
#[test]
fn a_collection_lists_at_most_max_faces() {
let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]);
let n = 1000u32;
let base = 12 + 4 * n;
let table = u32::from_be_bytes(font[20..24].try_into().unwrap()) + base;
font[20..24].copy_from_slice(&table.to_be_bytes());
let mut ttc = b"ttcf".to_vec();
for v in [0x0001_0000, n] {
ttc.extend_from_slice(&u32::to_be_bytes(v));
}
for _ in 0..n {
ttc.extend_from_slice(&base.to_be_bytes());
}
ttc.extend(font);
let faces = enumerate_faces(&ttc);
assert!(!faces.is_empty());
assert!(faces.len() <= MAX_FACES as usize, "{} faces", faces.len());
}
fn keys(records: &[(u16, u16, u16, &str)]) -> (String, String, FaceKeys) {
let font = name_font(records);
let f = skrifa::FontRef::new(&font).unwrap();
let (family, style) = face_names(&f).unwrap();
let k = FaceKeys::of(&f, &family, &style);
(family, style, k)
}
const EN: u16 = 0x0409;
const JA: u16 = 0x0411;
/// Laid out like the name table of Hiragino Sans W3.
const HIRAGINO_W3: &[(u16, u16, u16, &str)] = &[
(1, 0, 1, "Hiragino Sans"),
(1, 0, 2, "W3"),
(3, EN, 1, "Hiragino Sans W3"),
(3, EN, 2, "Regular"),
(3, JA, 1, "ヒラギノ角ゴシック W3"),
(3, JA, 2, "Regular"),
(3, EN, 6, "HiraginoSans-W3"),
(3, EN, 16, "Hiragino Sans"),
(3, JA, 16, "ヒラギノ角ゴシック"),
(3, EN, 17, "W3"),
(3, JA, 17, "W3"),
];
#[test]
fn a_face_answers_to_its_names_in_every_language() {
let (family, style, k) = keys(HIRAGINO_W3);
assert_eq!((family.as_str(), style.as_str()), ("Hiragino Sans", "W3"));
let aliases = Alias::of(&family, &style, &k);
let find = |name: &str| aliases.iter().filter(|(n, _)| *n == norm(name)).map(|(_, a)| a.clone()).collect::<Vec<_>>();
assert!(find("ヒラギノ 角ゴシック").iter().any(|a| a.family == "Hiragino Sans" && a.style.is_none()), "a family name in Japanese");
let legacy = find("Hiragino Sans W3");
assert!(legacy.iter().any(|a| a.style.as_deref() == Some("W3") && a.paired.as_deref() == Some("regular")), "{legacy:?}");
assert!(!legacy.iter().any(|a| a.paired.as_deref() == Some("w3")), "Mac family + Windows style is no pair");
assert!(find("HiraginoSans-W3").iter().any(|a| a.style.as_deref() == Some("W3") && a.paired.is_none()), "the PostScript name");
}
/// #394 Preferences › Type › Show Font Names in English: pick the non-English name-table label.
#[test]
fn pick_native_label_prefers_a_non_english_name_record() {
assert_eq!(
pick_native_label("Hiragino Sans", &[(Some("en".into()), "Hiragino Sans".into()), (Some("ja".into()), "ヒラギノ角ゴシック".into())])
.as_deref(),
Some("ヒラギノ角ゴシック")
);
assert!(pick_native_label("Source Sans 3", &[(Some("en".into()), "Source Sans 3".into())]).is_none());
let font = name_font(HIRAGINO_W3);
let f = skrifa::FontRef::new(&font).unwrap();
let (family, _) = face_names(&f).unwrap();
assert_eq!(family, "Hiragino Sans");
assert_eq!(native_family_name(&f, &family).as_deref(), Some("ヒラギノ角ゴシック"));
}
#[test]
fn without_typographic_names_the_legacy_ones_are_the_familys() {
let (family, style, k) = keys(&[(3, EN, 1, "Example Serif"), (3, EN, 2, "Bold Italic"), (3, JA, 1, "例セリフ"), (3, JA, 2, "太字斜体")]);
assert_eq!((family.as_str(), style.as_str()), ("Example Serif", "Bold Italic"));
assert!(k.families.contains(&norm("例セリフ")) && k.styles.contains(&norm("太字斜体")) && k.legacy.is_empty());
}
#[test]
fn resolve_says_how_a_font_matched() {
let db = FontDb::with_font_dirs(vec![]);
let m = |f: &str, s: &str| db.resolve(f, s).map(|(face, m)| (face.family.clone(), face.style.clone(), m)).unwrap();
assert_eq!(m("Source Sans 3", "Semibold"), ("Source Sans 3".into(), "Semibold".into(), FontMatch::Exact));
assert_eq!(m("Source Sans 3", "Black").2, FontMatch::Style);
assert_eq!(m("No Such Family", "Regular"), (FALLBACK_FAMILY.into(), "Regular".into(), FontMatch::Missing));
// A PostScript name names its face, whatever style is asked for (text opened from a PDF).
assert_eq!(m("SourceSans3-Semibold", "Regular"), ("Source Sans 3".into(), "Semibold".into(), FontMatch::Exact));
let semi = db.find_postscript("sourcesans3-semibold").unwrap();
assert_eq!(semi.style, "Semibold");
assert!(db.find_postscript("NoSuchFont-Regular").is_none());
assert!(db.has_family("SourceSans3-Regular"));
}
/// A PDF names a font by PostScript name; when it isn't installed the importer splits the name
/// (`Honoka-Mincho` → Honoka, Mincho). Once a font of that PostScript name is installed, under
/// a family name of its own (ほのか明朝), the split pair finds it.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_family_and_style_split_from_a_postscript_name_find_its_face() {
// An installed face whose family name shares nothing with its PostScript name: Source
// Sans 3 Semibold as the family Honoka Gothic, its PostScript name HonokaMinch-Semibold
// (each name as long as the one it replaces, in the name table's UTF-16 and ASCII records).
let mut data = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Semibold.ttf")).unwrap();
for (from, to) in [("Source Sans 3", "Honoka Gothic"), ("SourceSans3", "HonokaMinch")] {
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(utf16(from), utf16(to)), (from.as_bytes().to_vec(), to.as_bytes().to_vec())] {
let mut i = 0;
while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) {
data[i + at..i + at + to.len()].copy_from_slice(&to);
i += at + to.len();
}
}
}
let dir = std::env::temp_dir().join(format!("vc-fontdb-{}-split-postscript", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("HonokaGothic-Semibold.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir.clone()]);
// A PDF names it HonokaMinch-Semibold; an importer without the font split the name.
let m = db.resolve("HonokaMinch", "Semibold").map(|(face, m)| (face.family.clone(), face.style.clone(), m)).unwrap();
assert_eq!(m, ("Honoka Gothic".into(), "Semibold".into(), FontMatch::Exact));
// Unknown names still fall back.
assert_eq!(db.resolve("HonokaMinch", "Gothic").unwrap().1, FontMatch::Missing);
let _ = std::fs::remove_dir_all(dir);
}
/// The database keeps at most [`CANONICAL_CACHE_MAX`] answers, and names asked for past that
/// many still get the same answers.
#[test]
fn the_answers_kept_for_names_are_capped() {
let db = FontDb::with_font_dirs(vec![]);
for i in 0..=CANONICAL_CACHE_MAX {
let name = format!("No Such Family {i}");
assert_eq!(db.canonical(&name, "Regular"), (name.clone(), "Regular".into()));
}
assert!(db.canonical_cache.lock().unwrap().len() <= CANONICAL_CACHE_MAX);
assert_eq!(db.canonical("SourceSans3-Semibold", "Regular"), ("Source Sans 3".into(), "Semibold".into()));
}
}
#[cfg(test)]
mod race_tests {
use super::*;
#[test]
fn a_family_loaded_by_another_thread_meanwhile_is_still_found() {
// Two threads ask for the same installed family at once: each must get it, not the
// fallback (the second one's load finds every face already added).
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts");
let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir])));
// Only the catalog knows Inter (the bundled faces are dropped).
db.faces.write().unwrap().retain(|f| f.family != "Inter");
let threads: Vec<_> = (0..8).map(|_| std::thread::spawn(move || db.face("Inter", "Regular").map(|f| f.family.clone()))).collect();
for t in threads {
assert_eq!(t.join().unwrap().as_deref(), Some("Inter"));
}
}
}
#[cfg(test)]
mod image_cache_tests {
use super::*;
#[test]
fn the_glyph_image_cache_keeps_its_bytes_within_its_budget() {
// Images as large as a font may make them: no test font has enough of those to fill the
// budget, so they're made here.
let image = || {
let blob = vectorcraft_doc::ImageBlob::png(vec![0; crate::bitmap::MAX_PNG_BYTES]);
Some(Arc::new(GlyphImage { blob, width: 1, height: 1, xf: kurbo::Affine::IDENTITY }))
};
let mut cache = GlyphCache::default();
for gid in 0..20 {
cache.keep((1, gid), image());
assert!(cache.bytes <= IMAGE_CACHE_BYTES, "{} bytes after {} images", cache.bytes, gid + 1);
}
// The same glyph again, as when two threads look it up at once, counts once.
cache.keep((1, 19), image());
assert_eq!(cache.bytes, cache.kept.values().flatten().map(|i: &Arc<GlyphImage>| i.blob.bytes.len()).sum::<usize>());
// A glyph without an image costs nothing, and is still kept.
cache.keep((1, 99), None);
assert!(cache.kept.contains_key(&(1, 99)));
}
}