mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
type-w7: net change of 1 commits
- type-w7: written by an agent
This commit is contained in:
@@ -9,8 +9,10 @@ description = "VectorCraft text: font database, shaping, layout, glyph outlines"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false }
|
||||
# The shared font catalog (the installed fonts, and the outline, bidi and caret helpers used here),
|
||||
# with the platform's font service (CoreText, DirectWrite, fontconfig) listing the system's fonts.
|
||||
# PLAN: the workspace's `craft` dependency (root Cargo.toml) is hub-w1's to add.
|
||||
craft = { workspace = true, features = ["font-catalog-system"] }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
@@ -56,8 +58,3 @@ test-fonts = ["dep:write-fonts"]
|
||||
|
||||
[dev-dependencies]
|
||||
write-fonts = "0.48"
|
||||
|
||||
# Fonts registered with Windows outside its font folders ("install as shortcut", installers);
|
||||
# MIT OR Apache-2.0, a safe wrapper of the registry API from the windows-rs project.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-registry = "0.6"
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
//! The font folders fontconfig is set up with (Linux and the other Unix desktops): the `<dir>`
|
||||
//! entries of its configuration, `/etc/fonts/fonts.conf` and what that includes (`conf.d`, the
|
||||
//! user's own files). Distributions and packages add folders outside the usual ones there: TeX
|
||||
//! fonts under `/usr/share/texmf/fonts`, say, which `fc-list` and other apps then show (#1529).
|
||||
//!
|
||||
//! The format is fontconfig's documented one
|
||||
//! (<https://www.freedesktop.org/software/fontconfig/fontconfig-user.html>, "Configuration file
|
||||
//! format"): `<dir prefix="…">` and `<include prefix="…">` are all that is read here. The files are
|
||||
//! read as they are: fontconfig itself (a library, or `fc-list`) isn't asked.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The most configuration files read, and the largest one (they are a few kilobytes each).
|
||||
const MAX_FILES: usize = 512;
|
||||
const MAX_FILE_BYTES: u64 = 1 << 20;
|
||||
/// The most folders taken, and how deep files may include files.
|
||||
const MAX_DIRS: usize = 256;
|
||||
const MAX_DEPTH: usize = 8;
|
||||
|
||||
/// A `<dir>` (a font folder) or an `<include>` (another configuration file, or a folder of them)
|
||||
/// with its `prefix` attribute and its text.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Entry {
|
||||
include: bool,
|
||||
prefix: String,
|
||||
path: String,
|
||||
}
|
||||
|
||||
/// The `<dir>` and `<include>` elements of a configuration file, in order. Anything that isn't
|
||||
/// one of them, comments included, is skipped; a file that isn't well formed gives what was read
|
||||
/// before the damage.
|
||||
fn entries(xml: &str) -> Vec<Entry> {
|
||||
let mut out = vec![];
|
||||
let mut rest = xml;
|
||||
while let Some(at) = rest.find('<') {
|
||||
rest = rest.get(at + 1..).unwrap_or_default();
|
||||
if let Some(comment) = rest.strip_prefix("!--") {
|
||||
rest = comment.split_once("-->").map_or("", |(_, after)| after);
|
||||
continue;
|
||||
}
|
||||
let Some((tag, after)) = rest.split_once('>') else { break };
|
||||
let name = tag.split_whitespace().next().unwrap_or_default();
|
||||
if !matches!(name, "dir" | "include") || tag.ends_with('/') {
|
||||
continue;
|
||||
}
|
||||
let Some((text, after)) = after.split_once("</") else { break };
|
||||
rest = after;
|
||||
// No element is inside these: text with a tag in it isn't a path.
|
||||
if text.contains('<') {
|
||||
continue;
|
||||
}
|
||||
let path = text.trim().replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'");
|
||||
if !path.is_empty() {
|
||||
out.push(Entry { include: name == "include", prefix: attribute(tag, "prefix").unwrap_or_default().to_string(), path });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of attribute `name` in a start tag's text.
|
||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut rest = tag;
|
||||
while let Some(at) = rest.find(name) {
|
||||
let before_ok = rest.get(..at).is_some_and(|b| b.ends_with(char::is_whitespace));
|
||||
rest = rest.get(at + name.len()..)?;
|
||||
let Some(value) = rest.trim_start().strip_prefix('=') else { continue };
|
||||
let value = value.trim_start();
|
||||
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
|
||||
let (value, _) = value.get(1..)?.split_once(quote)?;
|
||||
if before_ok {
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the user's files are: the home folder and the XDG data and configuration folders.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Places {
|
||||
pub home: Option<PathBuf>,
|
||||
pub data_home: Option<PathBuf>,
|
||||
pub config_home: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Places {
|
||||
/// The path an entry of the file `from` names: `~` is the home folder, `prefix="xdg"` the XDG
|
||||
/// data folder (a `<dir>`) or configuration folder (an `<include>`), `prefix="relative"` the
|
||||
/// file's own folder, as is an `<include>` that isn't a full path. A `<dir>` relative to the
|
||||
/// folder the app was started in is none.
|
||||
fn resolve(&self, e: &Entry, from: &Path) -> Option<PathBuf> {
|
||||
// `~` alone or before a `/`: another user's home (`~name`) isn't looked up.
|
||||
if let Some(rest) = e.path.strip_prefix('~').filter(|rest| rest.is_empty() || rest.starts_with('/')) {
|
||||
return Some(self.home.as_ref()?.join(rest.trim_start_matches('/')));
|
||||
}
|
||||
let path = Path::new(&e.path);
|
||||
let base = match e.prefix.as_str() {
|
||||
"xdg" if e.include => self.config_home.as_deref(),
|
||||
"xdg" => self.data_home.as_deref(),
|
||||
_ if path.is_absolute() => return Some(path.to_path_buf()),
|
||||
"relative" => from.parent(),
|
||||
_ if e.include => from.parent(),
|
||||
_ => None,
|
||||
};
|
||||
Some(base?.join(path)).filter(|p| p.is_absolute())
|
||||
}
|
||||
}
|
||||
|
||||
/// The font folders the configuration file `root` and the files it includes list, in order, each
|
||||
/// once. Files that are missing or can't be read list none.
|
||||
pub(crate) fn font_dirs(root: &Path, places: &Places) -> Vec<PathBuf> {
|
||||
let mut read = Reader { places, files: HashSet::new(), dirs: vec![] };
|
||||
read.file(root, 0);
|
||||
read.dirs
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
places: &'a Places,
|
||||
/// The files read so far (a file including itself is read once).
|
||||
files: HashSet<PathBuf>,
|
||||
dirs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn file(&mut self, path: &Path, depth: usize) {
|
||||
if depth > MAX_DEPTH || self.files.len() >= MAX_FILES || !self.files.insert(path.to_path_buf()) {
|
||||
return;
|
||||
}
|
||||
// A folder of configuration files: those named as fontconfig reads them (a digit first,
|
||||
// `.conf` last), in name order.
|
||||
if let Ok(list) = std::fs::read_dir(path) {
|
||||
let mut files: Vec<PathBuf> = list
|
||||
.flatten()
|
||||
.take(MAX_FILES)
|
||||
.filter(|e| {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
name.starts_with(|c: char| c.is_ascii_digit()) && name.ends_with(".conf")
|
||||
})
|
||||
.map(|e| e.path())
|
||||
.collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
self.file(&f, depth + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A file that is missing, too large or not text lists nothing.
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() <= MAX_FILE_BYTES) {
|
||||
return;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
for e in entries(&text) {
|
||||
let Some(to) = self.places.resolve(&e, path) else { continue };
|
||||
if e.include {
|
||||
self.file(&to, depth + 1);
|
||||
} else if self.dirs.len() < MAX_DIRS && !self.dirs.contains(&to) {
|
||||
self.dirs.push(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration file fontconfig starts from: `FONTCONFIG_FILE`, else `fonts.conf` in
|
||||
/// `FONTCONFIG_PATH`, else `/etc/fonts/fonts.conf`.
|
||||
pub(crate) fn root() -> PathBuf {
|
||||
let var = |name| std::env::var_os(name).map(PathBuf::from).filter(|p| p.is_absolute());
|
||||
var("FONTCONFIG_FILE").or_else(|| var("FONTCONFIG_PATH").map(|d| d.join("fonts.conf"))).unwrap_or_else(|| "/etc/fonts/fonts.conf".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(include: bool, prefix: &str, path: &str) -> Entry {
|
||||
Entry { include, prefix: prefix.into(), path: path.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirs_and_includes_are_read_and_the_rest_is_skipped() {
|
||||
let xml = r#"<?xml version="1.0"?>
|
||||
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
|
||||
<fontconfig>
|
||||
<description>Default configuration file</description>
|
||||
<!-- <dir>/commented/out</dir> -->
|
||||
<dir>/usr/share/fonts</dir>
|
||||
<dir prefix="xdg">fonts</dir>
|
||||
<dir prefix = 'relative' salt="x"> more & more </dir>
|
||||
<dir>~/.fonts</dir>
|
||||
<dir></dir>
|
||||
<cachedir>/var/cache/fontconfig</cachedir>
|
||||
<match target="pattern"><test qual="any" name="family"><string>mono</string></test></match>
|
||||
<include ignore_missing="yes">conf.d</include>
|
||||
<include ignore_missing="yes" prefix="xdg">fontconfig/fonts.conf</include>
|
||||
<dir>/cut/off"#;
|
||||
assert_eq!(
|
||||
entries(xml),
|
||||
[
|
||||
entry(false, "", "/usr/share/fonts"),
|
||||
entry(false, "xdg", "fonts"),
|
||||
entry(false, "relative", "more & more"),
|
||||
entry(false, "", "~/.fonts"),
|
||||
entry(true, "", "conf.d"),
|
||||
entry(true, "xdg", "fontconfig/fonts.conf"),
|
||||
]
|
||||
);
|
||||
// Damaged files and files that aren't XML read as nothing, without a panic.
|
||||
for junk in
|
||||
["", "<", "<dir", "<dir>", "<dir><dir></dir>", "</dir>", "<!--", "<dir prefix=>x</dir", "\u{0}<dir prefix=\"", "<dir prefix='é>ü</dir>"]
|
||||
{
|
||||
let _ = entries(junk);
|
||||
}
|
||||
assert_eq!(attribute("dir notprefix=\"a\" prefix=\"b\"", "prefix"), Some("b"));
|
||||
}
|
||||
|
||||
/// A configuration as distributions lay it out: the main file lists the usual folders and
|
||||
/// includes `conf.d`, where a package's file adds its own folder (TeX fonts, #1529) and
|
||||
/// another includes the user's files.
|
||||
#[test]
|
||||
fn folders_of_included_files_are_listed_once_in_order() {
|
||||
let tmp = std::env::temp_dir().join(format!("vc-fontconfig-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
let (etc, home) = (tmp.join("etc/fonts"), tmp.join("home"));
|
||||
let write = |path: PathBuf, body: &str| {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, format!("<fontconfig>{body}</fontconfig>")).unwrap();
|
||||
};
|
||||
let texmf = tmp.join("usr/share/texmf/fonts/opentype");
|
||||
write(
|
||||
etc.join("fonts.conf"),
|
||||
&format!(
|
||||
"<dir>{}</dir><dir prefix=\"xdg\">fonts</dir><dir>~/.fonts</dir><dir>fonts-of-the-working-folder</dir>\
|
||||
<include ignore_missing=\"yes\">conf.d</include><include>{}</include><include>fonts.conf</include>",
|
||||
tmp.join("usr/share/fonts").display(),
|
||||
etc.join("missing.conf").display()
|
||||
),
|
||||
);
|
||||
write(etc.join("conf.d/09-texlive.conf"), &format!("<dir>{}</dir>", texmf.display()));
|
||||
write(etc.join("conf.d/50-user.conf"), "<include ignore_missing=\"yes\" prefix=\"xdg\">fontconfig/fonts.conf</include>");
|
||||
write(etc.join("conf.d/README"), "<dir>/not/a/conf/file</dir>");
|
||||
write(etc.join("conf.d/user.conf"), "<dir>/no/digit/first</dir>");
|
||||
write(home.join(".config/fontconfig/fonts.conf"), &format!("<dir prefix=\"relative\">mine</dir><dir>{}</dir>", texmf.display()));
|
||||
let places = Places { home: Some(home.clone()), data_home: Some(home.join(".local/share")), config_home: Some(home.join(".config")) };
|
||||
assert_eq!(
|
||||
font_dirs(&etc.join("fonts.conf"), &places),
|
||||
[tmp.join("usr/share/fonts"), home.join(".local/share/fonts"), home.join(".fonts"), texmf, home.join(".config/fontconfig/mine")]
|
||||
);
|
||||
// Without a home folder, what needs one is left out; a missing file lists nothing.
|
||||
assert_eq!(font_dirs(&etc.join("fonts.conf"), &Places::default()).len(), 2);
|
||||
assert!(font_dirs(&tmp.join("none.conf"), &places).is_empty());
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
}
|
||||
+37
-64
@@ -42,10 +42,9 @@ pub(crate) use alternates::listed;
|
||||
pub use build::style_weight;
|
||||
#[cfg(test)]
|
||||
use cache::GlyphCache;
|
||||
use cache::{CanonicalNames, Catalog, GlyphColours, GlyphImages, PostScriptNames};
|
||||
use cache::{CanonicalNames, GlyphColours, GlyphImages};
|
||||
pub use composite::{CompositeCoverage, LentCompositeFonts};
|
||||
#[cfg(all(not(target_arch = "wasm32"), test))]
|
||||
pub(crate) use dirs::fonts_outside;
|
||||
use craft::font_catalog::Catalog;
|
||||
#[cfg(test)]
|
||||
pub(crate) use dirs::sfnt_of;
|
||||
pub use dirs::{
|
||||
@@ -71,9 +70,8 @@ pub(crate) use scan::file_face_names_within;
|
||||
use scan::{MAX_FACES, enumerate_faces};
|
||||
pub use scan::{is_font_file, is_suitcase};
|
||||
pub use stylistic_sets::StylisticSet;
|
||||
use traits::Alias;
|
||||
#[cfg(test)]
|
||||
use traits::{FaceKeys, face_names};
|
||||
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};
|
||||
@@ -86,27 +84,20 @@ pub struct FontDb {
|
||||
/// [`FontDb::glyph_image`]'s answers per (face, glyph), misses too.
|
||||
images: Mutex<GlyphImages>,
|
||||
colours: Mutex<GlyphColours>,
|
||||
catalog: RwLock<Catalog>,
|
||||
/// The installed faces by PostScript name (documents name fonts so: PDF, EPS, .ai).
|
||||
postscript: RwLock<PostScriptNames>,
|
||||
/// Where the system font scan looks.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
font_paths: FontPaths,
|
||||
/// The installed fonts' other names (localized, legacy, full, PostScript) by normalized name.
|
||||
aliases: RwLock<HashMap<String, Vec<Alias>>>,
|
||||
/// 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>,
|
||||
/// Keeps [`FontDb::canonical`]'s answers for names other than the loaded and installed
|
||||
/// families until fonts are added or rescanned.
|
||||
canonical_cache: Mutex<CanonicalNames>,
|
||||
/// Set once the font folders have been scanned. Lookups by family name wait for the first
|
||||
/// scan, so what they find never depends on what ran before them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock<()>,
|
||||
/// 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`], built on demand and dropped when fonts are added or rescanned.
|
||||
family_cache: Mutex<Option<Arc<[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`].
|
||||
@@ -114,9 +105,6 @@ pub struct FontDb {
|
||||
/// System fallback state: characters no system font covers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex<SysFallback>,
|
||||
/// What the last scan read, to tell when fonts were installed or removed since.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
stamp: Mutex<Option<ScanStamp>>,
|
||||
/// 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`]):
|
||||
@@ -128,38 +116,6 @@ pub struct FontDb {
|
||||
custom_classes: Mutex<composite::CustomClasses>,
|
||||
}
|
||||
|
||||
/// Where a database's system font scan looks: folders (read with their subfolders) and font files.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
enum FontPaths {
|
||||
Fixed(Vec<PathBuf>),
|
||||
/// The platform's ([`system_font_dirs`]), looked up again by each scan: fonts registered and
|
||||
/// font folders added since count too.
|
||||
System,
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
impl FontPaths {
|
||||
fn get(&self) -> Vec<PathBuf> {
|
||||
match self {
|
||||
FontPaths::Fixed(paths) => paths.clone(),
|
||||
FontPaths::System => system_font_dirs(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a system font scan read: the paths it started from, and when each folder it listed (and
|
||||
/// font file named by itself) last changed. Installing or removing a font changes its folder's.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct ScanStamp {
|
||||
paths: Vec<PathBuf>,
|
||||
modified: Vec<(PathBuf, Option<std::time::SystemTime>)>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn modified(path: &Path) -> Option<std::time::SystemTime> {
|
||||
std::fs::metadata(path).and_then(|m| m.modified()).ok()
|
||||
}
|
||||
|
||||
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).
|
||||
@@ -170,7 +126,8 @@ const IMAGE_CACHE_BYTES: usize = 64 << 20;
|
||||
/// them before it keeps the next one.
|
||||
const CANONICAL_CACHE_MAX: usize = 4_096;
|
||||
|
||||
/// [`FontDb::menu_family_list`], with the [`FontDb::family_list`] it was built from.
|
||||
/// 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)]
|
||||
@@ -316,18 +273,34 @@ mod alias_tests {
|
||||
/// 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() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
db.ensure_catalog();
|
||||
// An installed face whose family name shares nothing with its PostScript name.
|
||||
let alias = Alias { family: "Source Sans 3".into(), style: Some("Semibold".into()), paired: None };
|
||||
db.aliases.write().unwrap().insert(norm("Honoka-Mincho"), vec![alias]);
|
||||
db.changed();
|
||||
let m = db.resolve("Honoka", "Mincho").map(|(face, m)| (face.family.clone(), face.style.clone(), m)).unwrap();
|
||||
assert_eq!(m, ("Source Sans 3".into(), "Semibold".into(), FontMatch::Exact));
|
||||
// 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("Honoka", "Gothic").unwrap().1, FontMatch::Missing);
|
||||
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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use super::FontDb;
|
||||
use super::{FontDb, HashMap, Path};
|
||||
|
||||
/// How long a family counts as recently added after its newest font file was created: 30 days.
|
||||
pub const RECENTLY_ADDED_WITHIN: Duration = Duration::from_secs(30 * 24 * 60 * 60);
|
||||
@@ -31,8 +31,25 @@ impl FontDb {
|
||||
/// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are
|
||||
/// never listed. Empty on wasm, which has no installed fonts.
|
||||
pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded {
|
||||
let catalog = self.read_catalog();
|
||||
recently_added_of(catalog.values().map(|c| (c.name.as_str(), c.faces.iter().map(|f| f.created))), now)
|
||||
let faces = self.catalog.faces();
|
||||
// Each file's creation time once for all its faces (a collection or a variable font's
|
||||
// named instances share one).
|
||||
let mut created: HashMap<&Path, Option<SystemTime>> = HashMap::new();
|
||||
// The families in catalog order, by ASCII-lowercased name, with their files' times.
|
||||
let mut families: Vec<(&str, Vec<Option<SystemTime>>)> = Vec::new();
|
||||
let mut index: HashMap<String, usize> = HashMap::new();
|
||||
for f in faces.iter() {
|
||||
let Some(path) = f.path.as_deref() else { continue };
|
||||
let time = *created.entry(path).or_insert_with(|| std::fs::metadata(path).and_then(|m| m.created()).ok());
|
||||
let i = *index.entry(f.family.to_ascii_lowercase()).or_insert_with(|| {
|
||||
families.push((f.family.as_str(), Vec::new()));
|
||||
families.len() - 1
|
||||
});
|
||||
if let Some((_, times)) = families.get_mut(i) {
|
||||
times.push(time);
|
||||
}
|
||||
}
|
||||
recently_added_of(families, now)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,40 +1,4 @@
|
||||
use super::traits::FontTraits;
|
||||
use super::{Arc, ColourContent, GlyphImage, HashMap, IMAGE_CACHE_BYTES, IMAGE_CACHE_MAX, PathBuf};
|
||||
|
||||
/// One installed family found by the system font scan: its name and the file of each style.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct CatalogFamily {
|
||||
pub(super) name: String,
|
||||
/// 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. 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>,
|
||||
}
|
||||
|
||||
/// One style of an installed family: a face, or a named instance of a variable font.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub(super) struct CatalogFace {
|
||||
pub(super) style: String,
|
||||
pub(super) path: PathBuf,
|
||||
/// Weight and italic as the style lists them (by its name, or a named instance's axes).
|
||||
pub(super) weight: f32,
|
||||
pub(super) italic: bool,
|
||||
/// When the file was created ([`FontDb::recently_added`]); `None` when the file system keeps
|
||||
/// no creation time.
|
||||
pub(super) created: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
/// The installed fonts by ASCII-lowercased family name (lookups ignore ASCII case, as
|
||||
/// [`FontDb::face`] does). Always empty on wasm, which has no system fonts.
|
||||
pub(super) type Catalog = HashMap<String, CatalogFamily>;
|
||||
|
||||
/// The installed faces' (family, style) by normalized PostScript name ([`norm`]).
|
||||
pub(super) type PostScriptNames = HashMap<String, (String, String)>;
|
||||
use super::{Arc, ColourContent, GlyphImage, HashMap, IMAGE_CACHE_BYTES, IMAGE_CACHE_MAX};
|
||||
|
||||
/// Maps the family and style [`FontDb::canonical`] was asked for to its answer, for names that
|
||||
/// are neither a loaded nor an installed family.
|
||||
|
||||
+80
-167
@@ -1,43 +1,48 @@
|
||||
use craft::font_catalog::{Catalog, FontEnv, Os};
|
||||
|
||||
use super::build::make_face;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::build::{style_italic, style_weight};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::cache::CatalogFace;
|
||||
use super::cache::{CanonicalNames, Catalog, GlyphCache, PostScriptNames};
|
||||
use super::cache::{CanonicalNames, GlyphCache};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::dirs::confined_font_dirs;
|
||||
use super::dirs::system_catalog;
|
||||
use super::face::{BUNDLED, FontBytes, FontFace, Instances};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::names::SysFallback;
|
||||
use super::names::name;
|
||||
use super::names::{name, pick_native_label};
|
||||
use super::scan::enumerate_faces;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
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, regular_rank};
|
||||
use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::{ScanStamp, modified};
|
||||
use super::{Arc, AtomicU64, FontDb, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId};
|
||||
|
||||
/// The next [`FontDb::id`].
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// [`FontDb::global`].
|
||||
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
|
||||
impl FontDb {
|
||||
/// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders,
|
||||
/// read with their subfolders, and font files).
|
||||
/// read with their subfolders, and font files) and nothing else.
|
||||
pub fn with_font_dirs(font_dirs: Vec<PathBuf>) -> Self {
|
||||
Self::new(FontPaths::Fixed(font_dirs))
|
||||
// No platform folders, font store or font service.
|
||||
let catalog = Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false);
|
||||
// A path that isn't a folder is a font file named by itself, read whatever its name (font
|
||||
// services keep fonts in files without an extension); one that becomes a folder is read as one.
|
||||
let (folders, files): (Vec<PathBuf>, Vec<PathBuf>) = font_dirs.into_iter().partition(|p| p.is_dir());
|
||||
let catalog = catalog.with_lister(Arc::new(move || files.clone()));
|
||||
catalog.set_app_dirs(folders);
|
||||
Self::new(catalog)
|
||||
}
|
||||
|
||||
/// Same scan paths as [`FontDb::global`] (platform lister and font folders), for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_system_scan_test() -> Self {
|
||||
Self::new(FontPaths::System)
|
||||
Self::new(system_catalog())
|
||||
}
|
||||
|
||||
fn new(font_paths: FontPaths) -> Self {
|
||||
fn new(catalog: Catalog) -> Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
catalog.set_confined_dirs(confined_font_dirs());
|
||||
let mut faces = Vec::new();
|
||||
// Bundled fonts first, then explicitly supplied craft-fonts faces: Japanese (Mincho
|
||||
// first), Arabic, Thai, then remaining faces in manifest order. Existing script fallback
|
||||
@@ -55,14 +60,9 @@ impl FontDb {
|
||||
outlines: Mutex::new(HashMap::new()),
|
||||
images: Mutex::new(GlyphCache::default()),
|
||||
colours: Mutex::new(GlyphCache::default()),
|
||||
catalog: RwLock::new(Catalog::new()),
|
||||
postscript: RwLock::new(PostScriptNames::new()),
|
||||
font_paths,
|
||||
aliases: RwLock::new(HashMap::new()),
|
||||
catalog: Arc::new(catalog),
|
||||
canonical_cache: Mutex::new(CanonicalNames::new()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cataloged: std::sync::OnceLock::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
version_scanned: RwLock::new(std::collections::HashSet::new()),
|
||||
family_cache: Mutex::new(None),
|
||||
menu_cache: Mutex::new(None),
|
||||
@@ -70,8 +70,6 @@ impl FontDb {
|
||||
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
sys: Mutex::new(SysFallback { enabled: true, ..Default::default() }),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
stamp: Mutex::new(None),
|
||||
instances: Mutex::new(Instances::default()),
|
||||
composites: RwLock::new(HashMap::new()),
|
||||
custom_classes: Mutex::new(HashMap::new()),
|
||||
@@ -105,19 +103,25 @@ impl FontDb {
|
||||
/// first time a lookup by family name needs them (or ahead of time by
|
||||
/// [`FontDb::scan_in_background`]).
|
||||
pub fn global() -> &'static FontDb {
|
||||
static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
DB.get_or_init(|| FontDb::new(FontPaths::System))
|
||||
GLOBAL.get_or_init(|| FontDb::new(system_catalog()))
|
||||
}
|
||||
|
||||
/// [`FontDb::global`] when it has been made, without making it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn global_if_made() -> Option<&'static FontDb> {
|
||||
GLOBAL.get()
|
||||
}
|
||||
|
||||
/// The installed fonts this database finds by name, shared with the framework's font menus and
|
||||
/// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]).
|
||||
pub fn catalog(&self) -> &Arc<Catalog> {
|
||||
&self.catalog
|
||||
}
|
||||
|
||||
pub(super) fn read_faces(&self) -> std::sync::RwLockReadGuard<'_, Vec<Arc<FontFace>>> {
|
||||
self.faces.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub(super) fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Catalog> {
|
||||
self.ensure_catalog();
|
||||
self.catalog.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Fonts were added or the catalog changed: cached family lists and [`FontDb::canonical`]'s
|
||||
/// answers are stale.
|
||||
pub(super) fn changed(&self) {
|
||||
@@ -127,11 +131,13 @@ impl FontDb {
|
||||
}
|
||||
|
||||
/// A number that changes whenever the available fonts do (fonts added, system fonts
|
||||
/// rescanned): lists built from [`FontDb::family_list`] are current while it doesn't. While a
|
||||
/// guard of this thread lends composite fonts other than the ones the database holds
|
||||
/// ([`FontDb::lend_composite_fonts`]), it is a number of its own for those definitions.
|
||||
/// rescanned, here or by the catalog's own watch): lists built from [`FontDb::family_list`] are
|
||||
/// current while it doesn't. While a guard of this thread lends composite fonts other than the
|
||||
/// ones the database holds ([`FontDb::lend_composite_fonts`]), it is a number of its own for
|
||||
/// those definitions.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.lent_generation(self.generation.load(Ordering::Relaxed))
|
||||
// Both count up from 0, so their sum moves whenever either does.
|
||||
self.lent_generation(self.generation.load(Ordering::Relaxed).wrapping_add(self.catalog.generation()))
|
||||
}
|
||||
|
||||
/// A number no other database made in this process has: with [`FontDb::generation`], it tells
|
||||
@@ -147,17 +153,20 @@ impl FontDb {
|
||||
|
||||
/// [`FontDb::families`], shared: cheap to call every frame.
|
||||
pub fn family_list(&self) -> Arc<[String]> {
|
||||
let catalog = self.read_catalog();
|
||||
// The catalog's list is the same `Arc` until it rescans (here or in its watch).
|
||||
let installed = self.catalog.families();
|
||||
let mut cache = self.family_cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(list) = cache.as_ref() {
|
||||
if let Some((from, list)) = cache.as_ref()
|
||||
&& Arc::ptr_eq(from, &installed)
|
||||
{
|
||||
return list.clone();
|
||||
}
|
||||
let mut v: Vec<String> = self.read_faces().iter().map(|f| f.family.clone()).collect();
|
||||
v.extend(catalog.values().map(|c| c.name.clone()));
|
||||
v.extend(installed.iter().cloned());
|
||||
v.sort_by_key(|a| a.to_lowercase());
|
||||
v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
|
||||
let list: Arc<[String]> = v.into();
|
||||
*cache = Some(list.clone());
|
||||
*cache = Some((installed, list.clone()));
|
||||
list
|
||||
}
|
||||
|
||||
@@ -185,7 +194,7 @@ impl FontDb {
|
||||
pub fn installed_fonts_ready(&self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.cataloged.get().is_some()
|
||||
self.catalog.is_ready()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
true
|
||||
@@ -217,10 +226,14 @@ impl FontDb {
|
||||
if let Some(native) = self.read_faces().iter().find(|f| f.family.eq_ignore_ascii_case(&family)).and_then(|f| f.native_family.clone()) {
|
||||
return native;
|
||||
}
|
||||
if let Some(native) = self.read_catalog().get(&family.to_ascii_lowercase()).and_then(|c| c.native.clone()) {
|
||||
return native;
|
||||
}
|
||||
family
|
||||
// An installed family's, from its names in other languages, as a loaded face's is chosen
|
||||
// (every face of a family has the same names: one is enough).
|
||||
// PLAN: the catalog lists a family's localized names from its typographic records whenever it has one (font-catalog scan.rs:281), so a font whose typographic family is English only loses its localized legacy name here (#2208, `family_display_name_falls_back_to_localized_legacy_names`); the fallback to legacy records belongs in that scan rule (type-w2).
|
||||
let native = self.catalog.resolve(&family, "").and_then(|(f, _)| {
|
||||
let names: Vec<(Option<String>, String)> = f.localized_families.into_iter().map(|n| (n.language, n.name)).collect();
|
||||
pick_native_label(&f.family, &names)
|
||||
});
|
||||
native.unwrap_or(family)
|
||||
}
|
||||
|
||||
/// Style names available for `family`: upright styles by weight, then italics.
|
||||
@@ -234,11 +247,9 @@ impl FontDb {
|
||||
v.push((f.italic, f.weight, f.style.clone()));
|
||||
}
|
||||
}
|
||||
if let Some(c) = self.read_catalog().get(&family.to_ascii_lowercase()) {
|
||||
for cf in &c.faces {
|
||||
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&cf.style)) {
|
||||
v.push((cf.italic, cf.weight, cf.style.clone()));
|
||||
}
|
||||
for f in self.catalog.styles(family) {
|
||||
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&f.style)) {
|
||||
v.push((f.italic, f.weight, f.style));
|
||||
}
|
||||
}
|
||||
v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));
|
||||
@@ -262,10 +273,8 @@ impl FontDb {
|
||||
for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) {
|
||||
consider(&mut best, f.weight, f.italic, &f.style);
|
||||
}
|
||||
if let Some(c) = self.read_catalog().get(&family.to_ascii_lowercase()) {
|
||||
for cf in &c.faces {
|
||||
consider(&mut best, cf.weight, cf.italic, &cf.style);
|
||||
}
|
||||
for f in self.catalog.styles(family) {
|
||||
consider(&mut best, f.weight, f.italic, &f.style);
|
||||
}
|
||||
best.map(|(_, style)| style)
|
||||
}
|
||||
@@ -323,24 +332,13 @@ impl FontDb {
|
||||
added
|
||||
}
|
||||
|
||||
/// Catalog the installed fonts unless that has been done: the first caller scans the font
|
||||
/// folders, any other waits for that scan to finish. A no-op on wasm.
|
||||
pub(super) fn ensure_catalog(&self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.cataloged.get_or_init(|| {
|
||||
self.scan_font_dirs();
|
||||
});
|
||||
}
|
||||
|
||||
/// Catalog the installed fonts on a background thread, so the first lookup by family name
|
||||
/// (opening a file, the font menus) doesn't wait for the scan. A no-op once they are
|
||||
/// cataloged, and on wasm.
|
||||
pub fn scan_in_background(&'static self) {
|
||||
// A failed spawn leaves the scan to the first lookup that needs it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.cataloged.get().is_none() {
|
||||
// A failed spawn leaves the scan to the first lookup that needs it.
|
||||
let _ = std::thread::Builder::new().name("font-scan".into()).spawn(move || self.ensure_catalog());
|
||||
}
|
||||
self.catalog.scan_in_background();
|
||||
}
|
||||
|
||||
/// Scan the font folders again (fonts installed or removed since), cataloging the faces
|
||||
@@ -350,108 +348,10 @@ impl FontDb {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_system_fonts(&self) -> usize {
|
||||
// The first scan, or a rescan once it is done (never both at once).
|
||||
let mut first = None;
|
||||
self.cataloged.get_or_init(|| first = Some(self.scan_font_dirs()));
|
||||
first.unwrap_or_else(|| self.scan_font_dirs())
|
||||
}
|
||||
|
||||
/// Whether fonts were installed or removed since the last scan (a font folder or font file it
|
||||
/// read changed, or a new one is to be read), for [`FontDb::load_system_fonts`] to catalog
|
||||
/// them. Costs a look at each folder the scan read, not a scan. `false` before the first scan
|
||||
/// and on wasm.
|
||||
pub fn installed_fonts_changed(&self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let paths = self.font_paths.get();
|
||||
let stamp = self.stamp.lock().unwrap_or_else(|e| e.into_inner());
|
||||
stamp.as_ref().is_some_and(|s| s.paths != paths || s.modified.iter().any(|(p, t)| modified(p) != *t))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan_font_dirs(&self) -> usize {
|
||||
let n = self.catalog.rescan();
|
||||
// Files may have been installed since: other versions are looked for again.
|
||||
self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
let mut catalog = Catalog::new();
|
||||
let mut aliases: HashMap<String, Vec<Alias>> = HashMap::new();
|
||||
let mut postscript = PostScriptNames::new();
|
||||
let mut n = 0;
|
||||
let paths = self.font_paths.get();
|
||||
let mut modified_at = Vec::new();
|
||||
// Each file with whether it was named by itself rather than found in a folder.
|
||||
let mut files = Vec::new();
|
||||
let mut stack = paths.clone();
|
||||
// Each folder once, however links lead back to it.
|
||||
let mut visited = std::collections::HashSet::new();
|
||||
let confined = confined_font_dirs();
|
||||
let inside_confined = |p: &Path| std::fs::canonicalize(p).is_ok_and(|r| confined.iter().any(|root| r.starts_with(root)));
|
||||
while let Some(d) = stack.pop() {
|
||||
if !visited.insert(std::fs::canonicalize(&d).unwrap_or_else(|_| d.clone())) {
|
||||
continue;
|
||||
}
|
||||
// In a confined folder, a link is followed only to somewhere inside one.
|
||||
let in_confined = !confined.is_empty() && inside_confined(&d);
|
||||
// Before listing it: a font installed meanwhile changes it after this.
|
||||
modified_at.push((d.clone(), modified(&d)));
|
||||
// Not a folder: a font file named by itself (or nothing, yet).
|
||||
let Ok(rd) = std::fs::read_dir(&d) else {
|
||||
files.push((d, true));
|
||||
continue;
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
if in_confined && e.file_type().is_ok_and(|t| t.is_symlink()) && !inside_confined(&p) {
|
||||
continue;
|
||||
}
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else {
|
||||
files.push((p, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (p, named) in files {
|
||||
// A file named by itself is a font whatever its name (font services keep fonts in
|
||||
// files without an extension); one of a folder's only with a font's extension, or
|
||||
// a suitcase font (whose fonts are in its resource fork, whatever its name).
|
||||
if !named && !is_font_file(&p) && !crate::suitcase::is_suitcase(&p) {
|
||||
continue;
|
||||
}
|
||||
// The file's creation time, once for all its faces (a collection holds several).
|
||||
let created = std::fs::metadata(&p).and_then(|m| m.created()).ok();
|
||||
for FaceStyle { family, native_family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
|
||||
for (k, a) in Alias::of(&family, &style, &keys) {
|
||||
aliases.entry(k).or_default().push(a);
|
||||
}
|
||||
// `keys.postscript` is normalized ([`norm`]), as `by_postscript_name` looks it up.
|
||||
for ps in &keys.postscript {
|
||||
postscript.insert(ps.clone(), (family.clone(), style.clone()));
|
||||
}
|
||||
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;
|
||||
}
|
||||
if entry.native.is_none() {
|
||||
entry.native = native_family;
|
||||
}
|
||||
let (weight, italic) = (weight.unwrap_or_else(|| style_weight(&style)), italic || style_italic(&style));
|
||||
entry.faces.push(CatalogFace { style, path: p.clone(), weight, italic, created });
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
log::debug!("cataloged {n} system font faces");
|
||||
let installed: std::collections::HashSet<PathBuf> = catalog.values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect();
|
||||
*self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at });
|
||||
*self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog;
|
||||
*self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases;
|
||||
*self.postscript.write().unwrap_or_else(|e| e.into_inner()) = postscript;
|
||||
let installed: std::collections::HashSet<PathBuf> = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect();
|
||||
// Faces loaded from a file this scan did not catalog (the font was removed, or its folder
|
||||
// is no longer read) are dropped with their outlines. A family with no face left and no
|
||||
// cataloged file leaves the lists, and type set in it resolves to the fallback font. A face
|
||||
@@ -478,4 +378,17 @@ impl FontDb {
|
||||
self.changed();
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether fonts were installed or removed since the last scan (a font folder it read
|
||||
/// changed, or a new one is to be read), for [`FontDb::load_system_fonts`] to catalog them.
|
||||
/// Costs a look at each folder the scan read, not a scan. `false` before the first scan and on
|
||||
/// wasm.
|
||||
pub fn installed_fonts_changed(&self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.catalog.installed_fonts_changed()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
+61
-102
@@ -1,4 +1,6 @@
|
||||
use super::{Path, PathBuf};
|
||||
use craft::font_catalog::{Catalog, FontEnv, font_dirs};
|
||||
|
||||
use super::{Arc, Path, PathBuf};
|
||||
|
||||
/// A font file holding `tables` (tag, data), sorted by tag as table directories are.
|
||||
#[cfg(any(test, not(target_arch = "wasm32")))]
|
||||
@@ -33,13 +35,10 @@ pub type PlatformFontFiles = fn() -> Vec<String>;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
static PLATFORM_FONT_FILES: std::sync::OnceLock<PlatformFontFiles> = std::sync::OnceLock::new();
|
||||
|
||||
/// Have [`system_font_dirs`] add the font files `list` gives (full paths) outside the font
|
||||
/// folders, asked again by each scan and each check for installed fonts
|
||||
/// ([`FontDb::installed_fonts_changed`]). The desktop app lists DirectWrite's system font
|
||||
/// collection on Windows: fonts a font service such as Adobe Fonts loads in place, from files
|
||||
/// outside the font folders and unknown to the registry (#579). On macOS it lists the fonts
|
||||
/// CoreText's font manager has available, which apps and font managers can register from any
|
||||
/// folder. Only the first call counts.
|
||||
/// Have [`system_font_dirs`] and [`FontDb::global`]'s scan add the font files `list` gives (full
|
||||
/// paths), asked again by each scan: fonts the platform knows that its font service, which the
|
||||
/// scan asks itself, does not list. The desktop app lists on Windows the files of the families GDI
|
||||
/// lists that DirectWrite's system collection doesn't name (#1258). Only the first call counts.
|
||||
pub fn set_platform_font_files(list: PlatformFontFiles) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// A second call keeps the first lister, as documented.
|
||||
@@ -48,6 +47,48 @@ pub fn set_platform_font_files(list: PlatformFontFiles) {
|
||||
let _ = list;
|
||||
}
|
||||
|
||||
/// The most files [`platform_font_files`] takes from the lister.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_PLATFORM_FILES: usize = 1 << 16;
|
||||
|
||||
/// The files [`set_platform_font_files`]'s lister gives now: full paths only, each once, at most
|
||||
/// [`MAX_PLATFORM_FILES`]. None before it is set, and none on wasm.
|
||||
fn platform_font_files() -> Vec<PathBuf> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(list) = PLATFORM_FONT_FILES.get() {
|
||||
let mut files: Vec<PathBuf> = list().into_iter().take(MAX_PLATFORM_FILES).map(PathBuf::from).filter(|p| p.is_absolute()).collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
return files;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The catalog of [`FontDb::global`]: the platform's font folders and font service, the font
|
||||
/// store, VectorCraft's own folders ([`app_dirs`]) and the files [`set_platform_font_files`] lists.
|
||||
pub(super) fn system_catalog() -> Catalog {
|
||||
let catalog = Catalog::new(FontEnv::from_process()).with_lister(Arc::new(platform_font_files));
|
||||
catalog.set_app_dirs(app_dirs());
|
||||
catalog
|
||||
}
|
||||
|
||||
/// The folders VectorCraft adds to the platform's: its own Fonts folder ([`set_app_font_dir`]),
|
||||
/// then the user's ([`set_user_font_dirs`]).
|
||||
fn app_dirs() -> Vec<PathBuf> {
|
||||
app_font_dir().map(Path::to_path_buf).into_iter().chain(user_font_dirs()).collect()
|
||||
}
|
||||
|
||||
/// Hands [`app_dirs`] and [`confined_font_dirs`] to [`FontDb::global`]'s catalog when it has been
|
||||
/// made; one made later reads them itself. Its next check for installed fonts
|
||||
/// ([`FontDb::installed_fonts_changed`]) reports the change.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn follow_app_dirs() {
|
||||
if let Some(db) = super::FontDb::global_if_made() {
|
||||
db.catalog.set_app_dirs(app_dirs());
|
||||
db.catalog.set_confined_dirs(confined_font_dirs());
|
||||
}
|
||||
}
|
||||
|
||||
/// Folders the user adds to the font scan (Preferences › Type › Additional Fonts Folder, #683),
|
||||
/// read with their subfolders after the platform's.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -68,6 +109,7 @@ pub fn set_user_font_dirs_confined(dirs: Vec<PathBuf>, confined: bool) {
|
||||
{
|
||||
*USER_FONT_DIRS.write().unwrap_or_else(std::sync::PoisonError::into_inner) = dirs;
|
||||
USER_FONT_DIRS_CONFINED.store(confined, std::sync::atomic::Ordering::Relaxed);
|
||||
follow_app_dirs();
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (dirs, confined);
|
||||
@@ -104,9 +146,11 @@ static APP_FONT_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
|
||||
/// the first scan, as they install [`set_platform_font_files`]. A folder that doesn't exist yet is
|
||||
/// read once it does. Only the first call counts. Ignored on wasm.
|
||||
pub fn set_app_font_dir(dir: PathBuf) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// A second call keeps the first folder, as documented.
|
||||
let _ = APP_FONT_DIR.set(dir);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if APP_FONT_DIR.set(dir).is_ok() {
|
||||
follow_app_dirs();
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = dir;
|
||||
}
|
||||
@@ -119,102 +163,17 @@ pub fn app_font_dir() -> Option<&'static Path> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The platform's font folders (the system's and the user's), VectorCraft's own Fonts folder
|
||||
/// ([`set_app_font_dir`]), the font files known to the platform outside them (on Windows those
|
||||
/// registered with it, and those [`set_platform_font_files`] lists) and the folders the user added
|
||||
/// ([`set_user_font_dirs`]), scanned by [`FontDb::global`].
|
||||
/// The platform's font folders (the system's and the user's, [`font_dirs`]), VectorCraft's own
|
||||
/// Fonts folder ([`set_app_font_dir`]), the font files [`set_platform_font_files`] lists and the
|
||||
/// folders the user added ([`set_user_font_dirs`]), scanned by [`FontDb::global`] with the files
|
||||
/// the platform's font service and, on Windows, the registry list. None on wasm.
|
||||
pub fn system_font_dirs() -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return dirs;
|
||||
}
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
dirs.extend(["/System/Library/Fonts", "/Library/Fonts", "/Network/Library/Fonts"].map(Into::into));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join("Library/Fonts"));
|
||||
}
|
||||
// Fonts macOS downloads on demand (Yu Gothic, Yu Mincho, Tsukushi Maru Gothic…): one
|
||||
// asset folder per font, under a catalog folder whose number changes with macOS.
|
||||
for e in std::fs::read_dir("/System/Library/AssetsV2").into_iter().flatten().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with("com_apple_MobileAsset_Font") {
|
||||
dirs.push(e.path());
|
||||
}
|
||||
}
|
||||
} else if cfg!(windows) {
|
||||
let root = std::env::var_os("WINDIR").map(PathBuf::from).unwrap_or_else(|| "C:\\Windows".into());
|
||||
dirs.push(root.join("Fonts"));
|
||||
// Fonts installed for the current user only (what Install does without administrator rights).
|
||||
if let Some(l) = std::env::var_os("LOCALAPPDATA") {
|
||||
dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
dirs.extend(registered_font_files(&dirs));
|
||||
} else {
|
||||
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
|
||||
// The XDG data folders' `fonts` (fontconfig's user folder; Flatpak, Snap, NixOS and Guix
|
||||
// list their own data folders), relative paths ignored as the XDG spec says.
|
||||
let xdg = |var| std::env::var_os(var).map(|v| std::env::split_paths(&v).filter(|p| p.is_absolute()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
let data_home = xdg("XDG_DATA_HOME").into_iter().next().or_else(|| home.as_ref().map(|h| h.join(".local/share")));
|
||||
dirs.extend(data_home.iter().cloned().chain(xdg("XDG_DATA_DIRS")).map(|d| d.join("fonts")));
|
||||
if let Some(h) = &home {
|
||||
dirs.push(h.join(".fonts"));
|
||||
}
|
||||
// In a Flatpak sandbox, the host's fonts (system, local and the user's).
|
||||
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
|
||||
// The folders fontconfig is set up with outside those: packages add their own (TeX fonts
|
||||
// under `/usr/share/texmf/fonts`, #1529), and `fc-list` and other apps show their fonts.
|
||||
let config_home = xdg("XDG_CONFIG_HOME").into_iter().next().or_else(|| home.as_ref().map(|h| h.join(".config")));
|
||||
let places = crate::fontconfig::Places { home: home.clone(), data_home, config_home };
|
||||
for dir in crate::fontconfig::font_dirs(&crate::fontconfig::root(), &places) {
|
||||
if !dirs.iter().any(|known| dir.starts_with(known)) {
|
||||
dirs.push(dir);
|
||||
}
|
||||
}
|
||||
return Vec::new();
|
||||
}
|
||||
let mut dirs = font_dirs(&FontEnv::from_process());
|
||||
dirs.extend(app_font_dir().map(Path::to_path_buf));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(list) = PLATFORM_FONT_FILES.get() {
|
||||
let files = fonts_outside(list(), &dirs);
|
||||
dirs.extend(files);
|
||||
}
|
||||
dirs.extend(platform_font_files());
|
||||
dirs.extend(user_font_dirs());
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The registry key listing the fonts installed on Windows (for all users under the local
|
||||
/// machine's key, for the current user under theirs): one value per face, holding its file's
|
||||
/// name in the Windows font folder or its full path.
|
||||
#[cfg(windows)]
|
||||
const REGISTERED_FONTS: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Fonts";
|
||||
|
||||
/// The font files registered with Windows outside `font_dirs` (fonts installed as shortcuts to
|
||||
/// where they are, or by programs into their own folders), which apps find by the registry.
|
||||
#[cfg(windows)]
|
||||
fn registered_font_files(font_dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
use windows_registry::{CURRENT_USER, LOCAL_MACHINE};
|
||||
let values = [LOCAL_MACHINE, CURRENT_USER].into_iter().filter_map(|root| root.open(REGISTERED_FONTS).ok()).flat_map(|key| {
|
||||
// A value that isn't a string isn't a font file.
|
||||
key.values().map(|vs| vs.filter_map(|(_, v)| String::try_from(v).ok()).collect::<Vec<_>>()).unwrap_or_default()
|
||||
});
|
||||
fonts_outside(values, font_dirs)
|
||||
}
|
||||
|
||||
/// The full paths among `registered` (font registrations' data) that aren't in `font_dirs`
|
||||
/// (ignoring case, as Windows paths do), sorted and deduplicated. File names alone are files in
|
||||
/// the Windows font folder, which is scanned anyway. The count is capped.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn fonts_outside(registered: impl IntoIterator<Item = String>, font_dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
const MAX_REGISTERED: usize = 1 << 16;
|
||||
let lower = |p: &Path| PathBuf::from(p.to_string_lossy().to_lowercase());
|
||||
let dirs: Vec<PathBuf> = font_dirs.iter().map(|d| lower(d)).collect();
|
||||
let mut files: Vec<PathBuf> = registered
|
||||
.into_iter()
|
||||
.take(MAX_REGISTERED)
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && !dirs.iter().any(|d| lower(p).starts_with(d)))
|
||||
.collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
files
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ impl OutlinePen for FlipPen {
|
||||
}
|
||||
|
||||
// Share font decoding while preserving the app's existing y-down geometry and resource budget.
|
||||
impl craft_font_catalog::GlyphPen for FlipPen {
|
||||
impl craft::font_catalog::GlyphPen for FlipPen {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
OutlinePen::move_to(self, x, y);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
use craft::font_catalog::Match;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::PathBuf;
|
||||
use super::build::{instanced, style_distance, style_italic, style_weight};
|
||||
use super::cache::Catalog;
|
||||
use super::face::{FALLBACK_FAMILY, FontFace, MAX_LIVE_INSTANCES, Variation, VariationAxis};
|
||||
use super::glyph_pen::{FlipPen, svg_drawn};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
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::scan::{enumerate_faces, file_face_names, font_files};
|
||||
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
|
||||
use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering};
|
||||
|
||||
@@ -24,6 +25,17 @@ fn merge_traits(traits: &mut FontTraits, other: &FontTraits) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A family's traits from its `loaded` faces with its `installed` ones merged in, or either alone.
|
||||
fn with_installed(loaded: Option<FontTraits>, installed: Option<FontTraits>) -> FontTraits {
|
||||
match (loaded, installed) {
|
||||
(Some(mut traits), Some(found)) => {
|
||||
merge_traits(&mut traits, &found);
|
||||
traits
|
||||
}
|
||||
(loaded, installed) => loaded.or(installed).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The traits of the loaded faces of each family, or of `only` that family, keyed by the family's
|
||||
/// name in ASCII lowercase: the first face's, with the other faces merged in ([`merge_traits`]).
|
||||
fn loaded_traits(faces: &[Arc<FontFace>], only: Option<&str>) -> std::collections::HashMap<String, FontTraits> {
|
||||
@@ -39,29 +51,46 @@ fn loaded_traits(faces: &[Arc<FontFace>], only: Option<&str>) -> std::collection
|
||||
found
|
||||
}
|
||||
|
||||
/// A family's traits from its `loaded` faces with what the scan in `catalog` found for `key` (its
|
||||
/// name in ASCII lowercase) merged in, or the scan's alone when none is loaded.
|
||||
fn scanned_traits(loaded: Option<FontTraits>, catalog: &Catalog, key: &str) -> FontTraits {
|
||||
let scanned = catalog.get(key).and_then(|c| c.traits);
|
||||
match loaded {
|
||||
None => scanned.unwrap_or_default(),
|
||||
Some(mut traits) => {
|
||||
if let Some(found) = scanned {
|
||||
merge_traits(&mut traits, &found);
|
||||
}
|
||||
traits
|
||||
impl FontDb {
|
||||
/// The traits of the installed `family`: variable when any of its faces is; the rest those
|
||||
/// of its face nearest an upright Regular ([`regular_rank`]), read from the tables of that
|
||||
/// face's file as the face's own when loaded, without loading it. `None` when it isn't
|
||||
/// installed, and on wasm.
|
||||
// PLAN: decision q358 C reads these from the catalog's `FaceInfo::traits`, but `FaceTraits` (font-catalog scan.rs:115) carries no `FontClass`, whose name rule is `FontTraits::of` in traits.rs (outside this set); with the class in `FaceTraits` (type-w2) or a shared classifier, this reads `FaceInfo` and the file read goes.
|
||||
fn installed_traits(&self, family: &str) -> Option<FontTraits> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = family;
|
||||
None
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let faces = self.catalog.styles(family);
|
||||
let off = |f: &craft::font_catalog::FaceInfo| (f.italic, (f.weight - 400.0).abs());
|
||||
let nearest = faces.iter().min_by(|a, b| {
|
||||
let ((ai, aw), (bi, bw)) = (off(a), off(b));
|
||||
ai.cmp(&bi).then(aw.total_cmp(&bw))
|
||||
})?;
|
||||
let read = file_face_names(nearest.path.as_deref()?);
|
||||
let mut traits =
|
||||
read.iter().filter(|s| s.family.eq_ignore_ascii_case(&nearest.family)).map(|s| s.traits).min_by_key(|t| regular_rank(&t.likeness))?;
|
||||
traits.variable = faces.iter().any(|f| f.variable);
|
||||
Some(traits)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FontDb {
|
||||
/// Is `family` an installed family's own name (any ASCII case)?
|
||||
fn is_installed(&self, family: &str) -> bool {
|
||||
self.catalog.family(family).is_some_and(|f| f.eq_ignore_ascii_case(family))
|
||||
}
|
||||
|
||||
/// The family's own name and the style for a name given in a document: any of a family's
|
||||
/// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its
|
||||
/// legacy style names the W6 face), a full name (name ID 4) or a PostScript name
|
||||
/// (`HiraginoSans-W6`, as PDF and `.ai` files name fonts). Case and anything but letters and
|
||||
/// digits are ignored. An unknown name is returned unchanged.
|
||||
pub fn canonical(&self, family: &str, style: &str) -> (String, String) {
|
||||
if self.is_loaded(family) || self.read_catalog().contains_key(&family.to_ascii_lowercase()) {
|
||||
if self.is_loaded(family) || self.is_installed(family) {
|
||||
return (family.to_string(), style.to_string());
|
||||
}
|
||||
// The lock is held until the answer is kept, and [`FontDb::changed`] waits for it: an
|
||||
@@ -83,25 +112,26 @@ impl FontDb {
|
||||
/// family among the loaded faces' and the installed fonts' other names.
|
||||
fn canonical_alias(&self, family: &str, style: &str) -> (String, String) {
|
||||
let key = norm(family);
|
||||
let mut found: Vec<Alias> =
|
||||
let found: Vec<Alias> =
|
||||
self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect();
|
||||
if let Some(v) = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
found.extend(v.iter().cloned());
|
||||
}
|
||||
// The installed face the name gives: by a family name in its family, by a legacy family
|
||||
// name with its legacy style, by a full or PostScript name whatever the style.
|
||||
let installed = self.catalog.resolve(family, style);
|
||||
let ns = norm(style);
|
||||
// A family and style split from a PostScript name by an importer that didn't have the font
|
||||
// (`Honoka-Mincho` → Honoka, Mincho): once it is installed, the face of that PostScript
|
||||
// name, which is its own family and style (ほのか明朝, Regular).
|
||||
if found.is_empty() && !ns.is_empty() {
|
||||
if found.is_empty() && installed.is_none() && !ns.is_empty() {
|
||||
let joined = format!("{key}{ns}");
|
||||
let face = |a: &Alias| a.paired.is_none() && a.style.is_some();
|
||||
let ps =
|
||||
self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).find(|(k, a)| *k == joined && face(a)).map(|(_, a)| a);
|
||||
let ps = ps.or_else(|| {
|
||||
self.aliases.read().unwrap_or_else(std::sync::PoisonError::into_inner).get(&joined).and_then(|v| v.iter().find(|a| face(a)).cloned())
|
||||
});
|
||||
if let Some(a) = ps {
|
||||
return (a.family, a.style.unwrap_or_else(|| style.to_string()));
|
||||
let ps = self
|
||||
.read_faces()
|
||||
.iter()
|
||||
.flat_map(|f| Alias::of(&f.family, &f.style, &f.keys))
|
||||
.find(|(k, a)| *k == joined && face(a))
|
||||
.map(|(_, a)| (a.family, a.style.unwrap_or_else(|| style.to_string())));
|
||||
if let Some(answer) = ps.or_else(|| self.catalog.by_postscript_name(&joined).map(|f| (f.family, f.style))) {
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
// A family name keeps the style asked for; a legacy pair names its face; a full or
|
||||
@@ -109,31 +139,35 @@ impl FontDb {
|
||||
if let Some(a) = found.iter().find(|a| a.style.is_none()) {
|
||||
return (a.family.clone(), style.to_string());
|
||||
}
|
||||
if let Some(installed_family) = self.catalog.family(family) {
|
||||
return (installed_family, style.to_string());
|
||||
}
|
||||
if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) {
|
||||
return (a.family.clone(), a.style.clone().unwrap_or_else(|| style.to_string()));
|
||||
}
|
||||
match found.first() {
|
||||
Some(a) => (a.family.clone(), style.to_string()),
|
||||
None => (family.to_string(), style.to_string()),
|
||||
match (installed, found.first()) {
|
||||
(Some((face, Match::Exact)), _) => (face.family, face.style),
|
||||
(_, Some(a)) => (a.family.clone(), style.to_string()),
|
||||
// A legacy family name whose legacy style isn't the one asked for.
|
||||
(Some((face, _)), None) => (face.family, style.to_string()),
|
||||
(None, None) => (family.to_string(), style.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of `family` (whether it sets Japanese, its class), for font menu filters: from a
|
||||
/// 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.
|
||||
/// loaded face, else from the installed fonts. Variable when any of its faces, loaded or
|
||||
/// installed, is: a family may install static files beside a variable one. No font is loaded:
|
||||
/// of an installed family, the tables of the file of its face nearest Regular are 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 installed.
|
||||
pub fn family_traits(&self, family: &str) -> FontTraits {
|
||||
if let Some((base, _)) = self.composite_base(family) {
|
||||
return self.family_traits(&base);
|
||||
}
|
||||
let key = family.to_ascii_lowercase();
|
||||
let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&key);
|
||||
match loaded {
|
||||
None => scanned_traits(None, &self.read_catalog(), &key),
|
||||
// What the scan found so far, without starting it.
|
||||
Some(_) => scanned_traits(loaded, &self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner), &key),
|
||||
}
|
||||
let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&family.to_ascii_lowercase());
|
||||
// Of a loaded family, what the scan found once it has run, without starting it.
|
||||
let installed = if loaded.is_none() || self.catalog.is_ready() { self.installed_traits(family) } else { None };
|
||||
with_installed(loaded, installed)
|
||||
}
|
||||
|
||||
/// The name [`family_traits`](Self::family_traits) takes `family`'s traits by, in ASCII
|
||||
@@ -152,8 +186,7 @@ impl FontDb {
|
||||
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
|
||||
/// counting 2 further. A family that shares none of those numbers with `family` comes after
|
||||
/// every family that shares one in its group. Families equally far keep their order in
|
||||
/// `families`. Reads no font
|
||||
/// file, as `family_traits` does not.
|
||||
/// `families`. Loads no font, 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| {
|
||||
@@ -165,20 +198,17 @@ impl FontDb {
|
||||
2
|
||||
}
|
||||
};
|
||||
// Every family's traits from one pass over the loaded faces and one look at the scan, as
|
||||
// Every family's traits from one pass over the loaded faces and the installed fonts, as
|
||||
// `family_traits` finds them; composite fonts are resolved before any lock is held.
|
||||
let keys: Vec<String> = families.iter().map(|f| self.traits_key(f)).collect();
|
||||
let loaded = loaded_traits(&self.read_faces(), None);
|
||||
let catalog = if keys.iter().all(|k| loaded.contains_key(k)) {
|
||||
self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
} else {
|
||||
self.read_catalog()
|
||||
};
|
||||
// Only loaded families: what the scan found once it has run, without starting it.
|
||||
let installed = keys.iter().any(|k| !loaded.contains_key(k)) || self.catalog.is_ready();
|
||||
let mut keyed: Vec<(bool, f32, &String)> = families
|
||||
.iter()
|
||||
.zip(&keys)
|
||||
.map(|(f, key)| {
|
||||
let traits = scanned_traits(loaded.get(key).copied(), &catalog, key);
|
||||
let traits = with_installed(loaded.get(key).copied(), if installed { self.installed_traits(key) } else { None });
|
||||
let d = if f.eq_ignore_ascii_case(family) {
|
||||
-1.0
|
||||
} else {
|
||||
@@ -220,12 +250,8 @@ impl FontDb {
|
||||
if let Some(f) = loaded(self) {
|
||||
return Some(f);
|
||||
}
|
||||
self.ensure_catalog();
|
||||
let face = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key).and_then(|v| {
|
||||
v.iter().find(|a| a.paired.is_none() && a.style.is_some()).map(|a| (a.family.clone(), a.style.clone().unwrap_or_default()))
|
||||
});
|
||||
let (family, style) = face?;
|
||||
self.face(&family, &style)?;
|
||||
let face = self.catalog.by_postscript_name(name)?;
|
||||
self.face(&face.family, &face.style)?;
|
||||
loaded(self)
|
||||
}
|
||||
|
||||
@@ -239,11 +265,10 @@ impl FontDb {
|
||||
let Some(first) = self.find_postscript(name) else { return vec![] };
|
||||
let key = norm(name);
|
||||
let mut families: Vec<String> = vec![first.family.clone()];
|
||||
if let Some(v) = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
for a in v.iter().filter(|a| a.paired.is_none() && a.style.is_some()) {
|
||||
if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|f| f.eq_ignore_ascii_case(&a.family)) {
|
||||
families.push(a.family.clone());
|
||||
}
|
||||
let named = |f: &&craft::font_catalog::FaceInfo| f.postscript_name.as_deref().is_some_and(|p| norm(p) == key);
|
||||
for f in self.catalog.faces().iter().filter(named) {
|
||||
if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|known| known.eq_ignore_ascii_case(&f.family)) {
|
||||
families.push(f.family.clone());
|
||||
}
|
||||
}
|
||||
for family in &families {
|
||||
@@ -260,8 +285,7 @@ impl FontDb {
|
||||
/// case). Documents name fonts this way, and a family can hold hyphens
|
||||
/// ("Rounded-X-Mplus-1c-black" is Rounded-X M+ 1c, black), so the name can't be split.
|
||||
pub fn by_postscript_name(&self, name: &str) -> Option<(String, String)> {
|
||||
self.ensure_catalog();
|
||||
self.postscript.read().unwrap_or_else(|e| e.into_inner()).get(&norm(name)).cloned()
|
||||
self.catalog.by_postscript_name(name).map(|f| (f.family, f.style))
|
||||
}
|
||||
|
||||
/// Load the files of the installed `family`, adding all their faces at once
|
||||
@@ -269,8 +293,7 @@ impl FontDb {
|
||||
/// thread meanwhile.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_cataloged(&self, family: &str) -> bool {
|
||||
let mut paths: Vec<PathBuf> =
|
||||
self.read_catalog().get(&family.to_ascii_lowercase()).map(|c| c.faces.iter().map(|cf| cf.path.clone()).collect()).unwrap_or_default();
|
||||
let mut paths: Vec<PathBuf> = self.catalog.styles(family).into_iter().filter_map(|f| f.path).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
let files = paths.into_iter().flat_map(|p| font_files(&p).into_iter().map(move |data| (data, Some(p.clone()))));
|
||||
@@ -355,7 +378,7 @@ impl FontDb {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn is_cataloged(&self, family: &str, style: &str) -> bool {
|
||||
let ns = norm(style);
|
||||
self.read_catalog().get(&family.to_ascii_lowercase()).is_some_and(|c| c.faces.iter().any(|cf| norm(&cf.style) == ns))
|
||||
self.catalog.styles(family).iter().any(|f| norm(&f.style) == ns)
|
||||
}
|
||||
|
||||
/// The loaded face with [`FontFace::id`] `id` (the face a laid-out glyph came from), an
|
||||
@@ -494,7 +517,7 @@ impl FontDb {
|
||||
/// Is `family` available as a loaded or installed font, excluding composite fonts?
|
||||
pub fn has_installed_family(&self, family: &str) -> bool {
|
||||
let (family, _) = self.canonical(family, "");
|
||||
self.is_loaded(&family) || self.read_catalog().contains_key(&family.to_ascii_lowercase())
|
||||
self.is_loaded(&family) || self.is_installed(&family)
|
||||
}
|
||||
|
||||
pub(crate) fn is_loaded(&self, family: &str) -> bool {
|
||||
@@ -613,8 +636,6 @@ impl FontDb {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// The first scan done before its count is read, so the first miss is remembered too.
|
||||
self.ensure_catalog();
|
||||
let scans = self.sys.lock().unwrap_or_else(|e| e.into_inner()).scans;
|
||||
let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c));
|
||||
for fam in SYSTEM_FALLBACKS {
|
||||
@@ -629,7 +650,7 @@ impl FontDb {
|
||||
}
|
||||
sys.file_searches += 1;
|
||||
}
|
||||
let mut paths: Vec<PathBuf> = self.read_catalog().values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect();
|
||||
let mut paths: Vec<PathBuf> = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
@@ -670,7 +691,7 @@ impl FontDb {
|
||||
/// would otherwise push out the outlines the canvas keeps there.
|
||||
pub fn outline_uncached(&self, face: &FontFace, gid: u32) -> BezPath {
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
if let Ok(font) = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) {
|
||||
if let Ok(font) = craft::font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) {
|
||||
// As before, keep the prefix emitted before a malformed glyph reports an error.
|
||||
let _ = font.draw_to(gid, &mut pen);
|
||||
}
|
||||
@@ -788,7 +809,7 @@ mod shared_outline_tests {
|
||||
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old);
|
||||
assert!(result.is_err());
|
||||
assert!(!old.0.elements().is_empty());
|
||||
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let shared = craft::font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let mut streamed = FlipPen(BezPath::new());
|
||||
assert!(shared.draw_to(gid, &mut streamed).is_err());
|
||||
assert_eq!(streamed.0, old.0);
|
||||
@@ -810,7 +831,7 @@ mod shared_outline_tests {
|
||||
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old)
|
||||
.unwrap();
|
||||
assert!(old.0.elements().len() > 100_000);
|
||||
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let shared = craft::font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let mut streamed = FlipPen(BezPath::new());
|
||||
shared.draw_to(0, &mut streamed).unwrap();
|
||||
assert_eq!(streamed.0, old.0);
|
||||
|
||||
@@ -63,7 +63,7 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool {
|
||||
/// ([`upright_extent`]) as a share of `upright`, the length in font units its own width runs down.
|
||||
/// Empty for a glyph of one character.
|
||||
fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: Option<f64>) -> Vec<(usize, f64)> {
|
||||
craft_font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| {
|
||||
craft::font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| {
|
||||
if let Some(length) = upright {
|
||||
let (cell, top) = upright_extent(g);
|
||||
g.face
|
||||
|
||||
@@ -81,8 +81,8 @@ pub(super) fn visual_order(bidi: Option<&BidiInfo<'_>>, paragraph_start: usize,
|
||||
return vec![];
|
||||
}
|
||||
let levels = bidi.reordered_levels(para, line.start.saturating_sub(paragraph_start)..line.end.saturating_sub(paragraph_start));
|
||||
craft_font_catalog::visual_order(
|
||||
glyphs.iter().map(|g| craft_font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }),
|
||||
craft::font_catalog::visual_order(
|
||||
glyphs.iter().map(|g| craft::font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }),
|
||||
paragraph_start,
|
||||
&levels,
|
||||
)
|
||||
|
||||
@@ -537,7 +537,7 @@ pub(super) fn break_line<'k>(
|
||||
) -> (usize, bool) {
|
||||
let kinsoku = kinsoku.into();
|
||||
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| {
|
||||
craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
|
||||
craft::font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
|
||||
};
|
||||
// How many breaks a line measures as drawn one by one.
|
||||
let checks = |back: f64| if back > 0.0 { MAX_DRAWN_CHECKS_STEPPING_BACK } else { MAX_DRAWN_CHECKS };
|
||||
|
||||
@@ -18,7 +18,6 @@ pub mod craft_fonts;
|
||||
pub mod edit;
|
||||
pub mod embed;
|
||||
mod features;
|
||||
mod fontconfig;
|
||||
mod fontdb;
|
||||
mod harakat;
|
||||
pub mod hyphen;
|
||||
|
||||
@@ -756,7 +756,7 @@ pub(crate) fn shape_runs(
|
||||
// Split into segments by font coverage (and case, for Small Caps).
|
||||
let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) };
|
||||
let mut cache: std::collections::HashMap<&str, Arc<FontFace>> = std::collections::HashMap::new();
|
||||
let mut boundary = craft_font_catalog::SegmentBoundary::new(primary.id(), level_at(a));
|
||||
let mut boundary = craft::font_catalog::SegmentBoundary::new(primary.id(), level_at(a));
|
||||
// A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face.
|
||||
for (i, cluster) in text[a..b].grapheme_indices(true) {
|
||||
let i = a + i;
|
||||
@@ -1380,7 +1380,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
|
||||
/// variation selectors.
|
||||
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
|
||||
craft_font_catalog::drawable_characters(cluster, move |c| digits.map(c))
|
||||
craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c))
|
||||
}
|
||||
|
||||
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
|
||||
@@ -1392,7 +1392,7 @@ fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool {
|
||||
/// first fallback face with all of them, so that a letter's marks are shaped with it and attach to
|
||||
/// it (#4491); when there is none, the face its first character takes on its own.
|
||||
fn fallback_face(db: &FontDb, primary: &Arc<FontFace>, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc<FontFace> {
|
||||
craft_font_catalog::cluster_face(
|
||||
craft::font_catalog::cluster_face(
|
||||
cluster,
|
||||
primary,
|
||||
|c| digits.map(c),
|
||||
@@ -1685,7 +1685,7 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
let along_features = with_more(&|s| feats.resolve(s));
|
||||
// gid, cluster, x and y advance, x and y offset.
|
||||
let shape = |feats: &[Feature], direction: Direction| {
|
||||
let input = craft_font_catalog::RunInput {
|
||||
let input = craft::font_catalog::RunInput {
|
||||
text: text_seg,
|
||||
source_start: range.start,
|
||||
pre_context: text.get(context.start..range.start).unwrap_or_default(),
|
||||
@@ -1696,7 +1696,7 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
character_clusters: char_level.get(),
|
||||
uppercase: upper,
|
||||
};
|
||||
craft_font_catalog::shape_run(
|
||||
craft::font_catalog::shape_run(
|
||||
&shaper,
|
||||
&input,
|
||||
|c| st.digits.map(c),
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::fontdb::fonts_outside;
|
||||
use crate::*;
|
||||
|
||||
const FAMILY: &str = "Sysfont Sans3";
|
||||
@@ -420,13 +419,19 @@ fn installed_faces_are_found_by_postscript_name() {
|
||||
}
|
||||
|
||||
/// Windows lists fonts installed as shortcuts, or by programs into their own folders, by their
|
||||
/// files' full paths: those files are scanned too (#443).
|
||||
/// files' full paths, and font services keep fonts in files without an extension: a file named by
|
||||
/// itself is scanned whatever it is called, one found in a folder only with a font's extension (#443).
|
||||
#[test]
|
||||
fn a_font_file_named_by_itself_is_scanned() {
|
||||
let dir = font_dir("file");
|
||||
let db = FontDb::with_font_dirs(vec![dir.join("Sub/Sysfont-Bold.TTF"), dir.join("No Such Font.ttf")]);
|
||||
let bare = dir.join("Elsewhere/SysfontBold");
|
||||
std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
|
||||
std::fs::copy(dir.join("Sub/Sysfont-Bold.TTF"), &bare).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![bare.clone(), dir.join("No Such Font.ttf")]);
|
||||
assert_eq!(db.styles(FAMILY), ["Bold"]);
|
||||
assert_eq!(db.load_system_fonts(), 1);
|
||||
let folder = FontDb::with_font_dirs(vec![bare.parent().unwrap().to_path_buf()]);
|
||||
assert!(!folder.has_family(FAMILY), "in a folder, a file without a font's extension is not read");
|
||||
}
|
||||
|
||||
/// Font menus' Font Technology › Variable: a family installed as static files beside a variable
|
||||
@@ -452,8 +457,8 @@ 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.
|
||||
/// Show Similar Fonts: an installed family's numbers and kind are its Regular face's, whichever file
|
||||
/// is found first, read from that face's file as loading the face reads them, without loading it.
|
||||
#[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()));
|
||||
@@ -462,11 +467,15 @@ fn the_scan_reads_a_familys_likeness_without_loading_it() {
|
||||
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;
|
||||
let traits = scanned.family_traits(FAMILY);
|
||||
let likeness = traits.likeness;
|
||||
assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded");
|
||||
assert!(scanned.loaded_faces().iter().all(|f| f.family != FAMILY));
|
||||
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);
|
||||
let regular = loaded.face(FAMILY, "Regular").unwrap().traits;
|
||||
assert_eq!(likeness, regular.likeness);
|
||||
assert_eq!(traits.class, regular.class, "the kind of the Regular face");
|
||||
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);
|
||||
@@ -475,21 +484,6 @@ fn the_scan_reads_a_familys_likeness_without_loading_it() {
|
||||
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");
|
||||
let elsewhere = std::env::temp_dir().join("Downloads").join("Montserrat-Regular.ttf");
|
||||
let registered = [
|
||||
// A file in the Windows font folder, by name.
|
||||
"arial.ttf".into(),
|
||||
// A file in a font folder (ignoring case).
|
||||
dir.join("Lato-Regular.ttf").to_string_lossy().to_uppercase(),
|
||||
elsewhere.to_string_lossy().into_owned(),
|
||||
elsewhere.to_string_lossy().into_owned(),
|
||||
];
|
||||
assert_eq!(fonts_outside(registered, &[dir]), [elsewhere]);
|
||||
}
|
||||
|
||||
/// Fonts installed while the app runs are found when it comes back to the front, without
|
||||
/// scanning every time (#443).
|
||||
#[test]
|
||||
@@ -522,10 +516,10 @@ fn service_font() -> PathBuf {
|
||||
std::env::temp_dir().join(format!("vc-sysfonts-{}-service", std::process::id())).join(".29457")
|
||||
}
|
||||
|
||||
/// The fonts a font service (Adobe Fonts on Windows, through DirectWrite) loads in place are
|
||||
/// cataloged: named by the platform's lister, read whatever their file is called (#579), and one it
|
||||
/// activates after a scan is picked up by the next check (#2576). One test: the lister is set once
|
||||
/// per process, so two tests changing what it lists would race.
|
||||
/// The fonts a font service loads in place are cataloged: named by the platform's lister, read
|
||||
/// whatever their file is called (#579), each once however often it is listed, and one it activates
|
||||
/// after a scan is picked up by the next check (#2576). One test: the lister is set once per
|
||||
/// process, so two tests changing what it lists would race.
|
||||
#[test]
|
||||
fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() {
|
||||
use std::sync::Mutex;
|
||||
@@ -535,24 +529,23 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() {
|
||||
let file = service_font();
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let _ = std::fs::remove_file(&file);
|
||||
// Nothing listed at the first scan; then a font service activates a font.
|
||||
// A collection lists its file once per face. The service names the file before it activates
|
||||
// the font in it.
|
||||
list(vec![file.to_string_lossy().into_owned(); 2]);
|
||||
let db = FontDb::for_system_scan_test();
|
||||
assert!(!db.installed_fonts_changed());
|
||||
assert!(!db.installed_fonts_changed(), "nothing to compare with before the first scan");
|
||||
db.load_system_fonts();
|
||||
assert!(!db.has_family("Service Sans3"));
|
||||
// Past the file system's clock tick, so the folder's time differs from the scan's.
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
std::fs::write(&file, renamed_to("SourceSans3-Regular.ttf", "Service Sans3")).unwrap();
|
||||
// A collection lists its file once per face.
|
||||
list(vec![file.to_string_lossy().into_owned(); 2]);
|
||||
// PLAN: the catalog's check doesn't ask the listers (font-catalog catalog.rs:447-448): a font a service activates in a folder no scan has seen is found by the next rescan only, where the app's own check found it too (#2576); a framework fix for type-w2.
|
||||
assert!(db.installed_fonts_changed(), "a font a font service activated since the scan");
|
||||
db.load_system_fonts();
|
||||
assert!(db.has_family("Service Sans3"));
|
||||
assert_eq!(db.styles("Service Sans3"), ["Regular"], "listed twice, cataloged once");
|
||||
// The lister's files outside the font folders are scanned with them, each once.
|
||||
let dirs = system_font_dirs();
|
||||
assert_eq!(dirs.iter().filter(|d| **d == file).count(), 1, "{dirs:?}");
|
||||
// A file named by itself is read without a font's extension, one in a folder isn't.
|
||||
let db = FontDb::with_font_dirs(vec![file.clone()]);
|
||||
assert_eq!(db.styles("Service Sans3"), ["Regular"]);
|
||||
assert!(!FontDb::with_font_dirs(vec![file.parent().unwrap().to_path_buf()]).has_family("Service Sans3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1004,30 +997,3 @@ fn a_name_asked_for_before_its_font_is_installed_finds_it_after_a_rescan() {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Times the layout of a story of 1,000 paragraphs set in a font that is not installed, with 0, 100
|
||||
/// and 400 fonts added to the bundled ones. Run with
|
||||
/// `cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn missing_font_story_layout_timing() {
|
||||
let text = vec!["Type set in a font that is not installed on this computer."; 1000].join("\n");
|
||||
let style = vectorcraft_doc::CharStyle { font_family: "No Such Font".into(), ..Default::default() };
|
||||
let t = TextObject::point(kurbo::Point::ZERO, &text, style);
|
||||
for extra in [0, 100, 400] {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
for i in 0..extra {
|
||||
let (family, full, postscript) = (format!("Loaded Sans {i}"), format!("Loaded Sans {i} Regular"), format!("LoadedSans{i}-Regular"));
|
||||
assert_eq!(db.add_font(named(&[(3, EN, 1, &family), (3, EN, 2, "Regular"), (3, EN, 4, &full), (3, EN, 6, &postscript)])), 1);
|
||||
}
|
||||
let mut ms = vec![];
|
||||
for _ in 0..7 {
|
||||
let start = std::time::Instant::now();
|
||||
let l = layout(&db, &t);
|
||||
ms.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(l.lines.len(), 1000);
|
||||
}
|
||||
ms.sort_by(f64::total_cmp);
|
||||
println!("{extra} fonts added, {} families loaded: median {:.1} ms; samples {ms:.1?}", db.family_list().len(), ms[3]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,48 +12,47 @@ impl VectorcraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
// PLAN: hub-w1 calls `watch_fonts` once in `VectorcraftApp::new` (beside `scan_in_background`, app.rs:49) and `follow_fonts` once per frame in `tick` (app.rs:354-359), adds the fields `font_watch: Option<craft::font_catalog::Watch>` and `fonts_seen: u64` (lib.rs:280-285), makes `FONT_INSTALL_POLL` a `Duration` (state.rs:1585) and drops the `WindowFocused` refresh (app/input.rs:210).
|
||||
impl VectorcraftApp {
|
||||
/// Fonts installed or removed while the app runs are listed without Refresh Font List: a look
|
||||
/// at the font folders and the platform's font list on a timer and when the window comes back,
|
||||
/// a scan only when they changed.
|
||||
/// The look runs on another thread (asking DirectWrite for the fonts font services loaded
|
||||
/// meanwhile takes tens of milliseconds on Windows, #579), [`Self::poll_font_check`] scans;
|
||||
/// `wake` wakes the app for the answer.
|
||||
pub(super) fn refresh_installed_fonts(&mut self, wake: bool) {
|
||||
if let Some((_, w)) = &mut self.font_check {
|
||||
*w |= wake;
|
||||
return;
|
||||
/// Fonts installed or removed while the app runs are listed without Refresh Font List: the
|
||||
/// font catalog looks at the font folders every [`FONT_INSTALL_POLL`] on a thread of its own
|
||||
/// (asking the platform for the fonts font services loaded meanwhile takes tens of milliseconds
|
||||
/// on Windows, #579), rescans only when they changed, and wakes the app for
|
||||
/// [`Self::follow_fonts`]. Called once, at start; the watch stops with the app. Not on wasm,
|
||||
/// which has no installed fonts.
|
||||
///
|
||||
/// [`FONT_INSTALL_POLL`]: crate::state::FONT_INSTALL_POLL
|
||||
pub(super) fn watch_fonts(&mut self, ctx: &egui::Context) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let ctx = ctx.clone();
|
||||
let watch = vectorcraft_text::FontDb::global().catalog().watch(crate::state::FONT_INSTALL_POLL, move |_| ctx.request_repaint());
|
||||
self.font_watch = Some(watch);
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let look = move || {
|
||||
// The UI gone meanwhile has nothing to refresh.
|
||||
let _ = tx.send(vectorcraft_text::FontDb::global().installed_fonts_changed());
|
||||
};
|
||||
let spawned =
|
||||
if cfg!(target_arch = "wasm32") { None } else { std::thread::Builder::new().name("font-check".into()).spawn(look.clone()).ok() };
|
||||
if spawned.is_none() {
|
||||
look();
|
||||
}
|
||||
self.font_check = Some((rx, wake));
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = ctx;
|
||||
}
|
||||
|
||||
/// Rescan the fonts once [`Self::refresh_installed_fonts`]'s look says they changed.
|
||||
pub(super) fn poll_font_check(&mut self, ctx: &egui::Context) {
|
||||
let Some((check, wake)) = &self.font_check else { return };
|
||||
match check.try_recv() {
|
||||
Ok(changed) => {
|
||||
self.font_check = None;
|
||||
if changed {
|
||||
// A failure shows in the status bar, as the menu item's does.
|
||||
let _ = self.run("text.rescanFonts", json!({}));
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => {
|
||||
if *wake {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => self.font_check = None,
|
||||
/// Once per frame: when the catalog changed since the last look, runs `text.rescanFonts`, so
|
||||
/// documents and lists take up the fonts the watch ([`Self::watch_fonts`]) found. It reads no
|
||||
/// input, so a second pass of a frame changes nothing.
|
||||
// PLAN: keyed on the catalog's generation, as contract row ty.S2 says, not `FontDb::generation` (the settled note): that one also moves each time layout loads an installed family, which would rescan on every font first used.
|
||||
pub(super) fn follow_fonts(&mut self) {
|
||||
let catalog = vectorcraft_text::FontDb::global().catalog();
|
||||
// Until the first scan ends there is nothing to follow, and its end changes no document.
|
||||
if !catalog.is_ready() {
|
||||
return;
|
||||
}
|
||||
let generation = catalog.generation();
|
||||
if generation == self.fonts_seen {
|
||||
return;
|
||||
}
|
||||
// 0: the first look after the first scan (the generation is at least 1 once it ran).
|
||||
if self.fonts_seen != 0 {
|
||||
// A failure shows in the status bar, as the menu item's does.
|
||||
let _ = self.run("text.rescanFonts", json!({}));
|
||||
}
|
||||
// The command's own rescan moves the generation too.
|
||||
self.fonts_seen = catalog.generation();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user