From bbd4eddd45e96c766985c0097ac7f8cf34f11e8a Mon Sep 17 00:00:00 2001
From: mo <131036780+mbolling@users.noreply.github.com>
Date: Wed, 21 Oct 2026 12:05:48 -0400
Subject: [PATCH] Find installed fonts where fontconfig looks: XDG dirs,
fontconfig
entries, Flatpak host fonts
On Linux and the BSDs the font scan only walked /usr/share/fonts,
/usr/local/share/fonts, ~/.fonts and ~/.local/share/fonts. NixOS and Guix
keep every font package in its own store path and tell fontconfig about
them through entries (/etc/fonts/conf.d/00-nixos-cache.conf,
home-manager's ~/.config/fontconfig/conf.d) and $XDG_DATA_DIRS; a Flatpak
sandbox sees the host's fonts only under /run/host. On such systems the
scan found nothing, so CJK and Arabic characters in drawing text drew the
missing-glyph box although fonts with them were installed (#674).
A resolver in ttf/dirs.rs returns the directories fontconfig would use, in
priority order: $XDG_DATA_HOME/fonts and ~/.fonts, every $XDG_DATA_DIRS
entry + /fonts (plus /usr/share/fonts and /usr/local/share/fonts whether
listed or not), Flatpak's /run/host/{fonts,local-fonts,user-fonts}, then
the elements of $FONTCONFIG_FILE or /etc/fonts/fonts.conf, following
files and conf.d directories with fontconfig's documented prefix
rules (~, xdg, relative). It is a pure function of injected env and file
lookups, so its tests run the same everywhere, and bounded in files,
nesting, bytes, elements and directories; a hand-written scanner reads the
two element names rather than adding an XML dependency to the fonts crate.
The scan canonicalizes the directories so a symlinked profile is not
walked twice, and keeps its entry cap. macOS and Windows are unchanged.
installed_font_path() exposes the scan's stem map, for the interface to
find its fonts by file stem.
Co-Authored-By: Claude Fable 5.1
---
crates/fonts/src/ttf.rs | 31 ++-
crates/fonts/src/ttf/dirs.rs | 433 +++++++++++++++++++++++++++++++++++
2 files changed, 460 insertions(+), 4 deletions(-)
create mode 100644 crates/fonts/src/ttf/dirs.rs
diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs
index 62759c1b0..f393d399a 100644
--- a/crates/fonts/src/ttf.rs
+++ b/crates/fonts/src/ttf.rs
@@ -27,6 +27,9 @@ use skrifa::{FontRef, GlyphId, MetadataProvider};
use crate::{Run, Shaped};
+#[cfg(not(target_arch = "wasm32"))]
+mod dirs;
+
/// One face of a font file (a TrueType collection holds several).
#[derive(Clone)]
pub struct Face {
@@ -218,6 +221,8 @@ fn lock() -> MutexGuard<'static, Db> {
g
}
+/// Installed font files by lower-case stem, from the platform's font directories (on Linux and
+/// the BSDs, wherever fontconfig looks: [`dirs`]).
#[cfg(not(target_arch = "wasm32"))]
fn scan() -> HashMap {
let mut out = HashMap::new();
@@ -233,11 +238,19 @@ fn scan() -> HashMap {
dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));
}
} else {
- dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
- if let Some(h) = std::env::var_os("HOME") {
- dirs.push(PathBuf::from(&h).join(".fonts"));
- dirs.push(PathBuf::from(h).join(".local/share/fonts"));
+ // Where fontconfig looks: NixOS, Guix and Flatpak keep fonts outside /usr/share/fonts
+ // (#674). Later directories take precedence (the stack pops them first), so the
+ // resolver's priority order is reversed; symlinked directories resolve so none is
+ // walked twice.
+ let mut found: Vec = Vec::new();
+ for d in dirs::font_dirs(|k| std::env::var_os(k), dirs::read_config) {
+ if let Ok(c) = std::fs::canonicalize(&d)
+ && !found.contains(&c)
+ {
+ found.push(c);
+ }
}
+ dirs.extend(found.into_iter().rev());
}
let mut stack = dirs;
let mut seen = 0usize;
@@ -515,6 +528,16 @@ pub fn find(name: &str) -> Option {
r
}
+/// The installed font file with this stem (`DejaVuSans`, `NotoSansCJK-Regular`; case and an
+/// extension don't matter), wherever the system keeps its fonts. A font compiled in from
+/// craft-fonts is no file and gives `None`.
+pub fn installed_font_path(stem: &str) -> Option {
+ match lock().paths.get(&key(stem))? {
+ Source::File(p) => Some(p.clone()),
+ Source::Static(_) => None,
+ }
+}
+
struct Prefs {
alt: String,
fallback: Vec,
diff --git a/crates/fonts/src/ttf/dirs.rs b/crates/fonts/src/ttf/dirs.rs
new file mode 100644
index 000000000..7d362b0bd
--- /dev/null
+++ b/crates/fonts/src/ttf/dirs.rs
@@ -0,0 +1,433 @@
+//! Where installed fonts live on Linux and the BSDs, the way fontconfig finds them: the XDG base
+//! directories, the `` entries of fontconfig's configuration (NixOS and Guix keep each font
+//! package in its own store path, nowhere near `/usr/share/fonts`) and the host fonts a Flatpak
+//! sandbox mounts. Directories only: fontconfig's aliases and matching rules are not read.
+//!
+//! The resolver is a pure function of the environment and a configuration reader, so its tests
+//! run the same on every machine.
+
+use std::collections::HashSet;
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+
+/// Bounds on a configuration a package or a user may have made hostile: files read, ``
+/// nesting, bytes per file, elements per file, entries per path list, directories returned.
+const MAX_CONFIG_FILES: usize = 256;
+const MAX_INCLUDE_DEPTH: usize = 4;
+const MAX_CONFIG_BYTES: u64 = 1 << 20;
+const MAX_ELEMENTS: usize = 4096;
+const MAX_PATH_LIST: usize = 64;
+const MAX_DIRS: usize = 1024;
+
+/// Where Flatpak mounts the host's system, local and user font directories in a sandbox (it also
+/// lists them in `/run/host/font-dirs.xml`, which the runtime's `fonts.conf` includes).
+const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
+
+/// What an `` names: a configuration file's text, or the `[0-9]*.conf` files of a
+/// directory, sorted, as fontconfig reads them.
+pub(super) enum Include {
+ File(String),
+ Dir(Vec),
+}
+
+/// Font directories in priority order, without duplicates: the user's XDG font directories,
+/// `$XDG_DATA_DIRS/fonts` (`/usr/local/share/fonts` and `/usr/share/fonts` whether listed or
+/// not), Flatpak's host font mounts, then the `` entries of fontconfig's configuration
+/// (`$FONTCONFIG_FILE`, else `/etc/fonts/fonts.conf`, following its ``s). `env` reads an
+/// environment variable, `read` a configuration file or directory (`None` when missing).
+pub(super) fn font_dirs(env: impl Fn(&str) -> Option, read: impl Fn(&Path) -> Option) -> Vec {
+ let var = |k: &str| env(k).filter(|v| !v.is_empty());
+ let home = var("HOME").map(PathBuf::from);
+ let data_home = var("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".local/share")));
+ let config_home = var("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".config")));
+ let list = |k: &str, default: &str| -> Vec {
+ std::env::split_paths(&var(k).unwrap_or_else(|| default.into())).filter(|p| p.is_absolute()).take(MAX_PATH_LIST).collect()
+ };
+ let mut user: Vec = data_home.iter().map(|d| d.join("fonts")).chain(home.iter().map(|h| h.join(".fonts"))).collect();
+ user.extend(list("XDG_DATA_DIRS", "/usr/local/share:/usr/share").into_iter().map(|d| d.join("fonts")));
+ user.extend(["/usr/local/share/fonts", "/usr/share/fonts"].iter().chain(FLATPAK_FONT_DIRS).map(PathBuf::from));
+ let mut r = Resolver {
+ home,
+ data_home,
+ config_home,
+ config_path: list("FONTCONFIG_PATH", "/etc/fonts"),
+ read: &read,
+ out: Vec::new(),
+ visited: HashSet::new(),
+ };
+ for d in user {
+ r.add(d);
+ }
+ r.include(&var("FONTCONFIG_FILE").map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "/etc/fonts/fonts.conf".into()), None, 0);
+ r.out
+}
+
+struct Resolver<'a> {
+ home: Option,
+ data_home: Option,
+ config_home: Option,
+ /// Where a relative `` name is looked up: `$FONTCONFIG_PATH`, else `/etc/fonts`.
+ config_path: Vec,
+ read: &'a dyn Fn(&Path) -> Option,
+ out: Vec,
+ /// Configuration files and directories read: cycles and the file bound.
+ visited: HashSet,
+}
+
+impl Resolver<'_> {
+ fn add(&mut self, p: PathBuf) {
+ if p.is_absolute() && self.out.len() < MAX_DIRS && !self.out.contains(&p) {
+ self.out.push(p);
+ }
+ }
+
+ /// A path with a leading `~` meaning `$HOME`.
+ fn expand_home(&self, s: &str) -> Option {
+ match s.strip_prefix('~') {
+ Some(rest) => self.home.as_ref().map(|h| h.join(rest.trim_start_matches('/'))),
+ None => Some(PathBuf::from(s)),
+ }
+ }
+
+ /// Follow an `` (or the top-level file): an absolute name, or a relative one looked
+ /// up in the configuration path. `here` is the including file's directory.
+ fn include(&mut self, name: &str, here: Option<&Path>, depth: usize) {
+ match self.expand_home(name) {
+ Some(p) if p.is_absolute() => {
+ self.config(&p, depth);
+ }
+ Some(p) => {
+ let bases: Vec = if here.is_some() { here.map(Path::to_path_buf).into_iter().collect() } else { self.config_path.clone() };
+ for base in bases {
+ if self.config(&base.join(&p), depth) {
+ break;
+ }
+ }
+ }
+ None => {}
+ }
+ }
+
+ /// Read a configuration file (or every file of a directory) and its includes, nested at most
+ /// `MAX_INCLUDE_DEPTH` deep. True when something was read.
+ fn config(&mut self, file: &Path, depth: usize) -> bool {
+ if depth > MAX_INCLUDE_DEPTH || self.visited.len() >= MAX_CONFIG_FILES || !self.visited.insert(file.to_path_buf()) {
+ return false;
+ }
+ let xml = match (self.read)(file) {
+ Some(Include::File(xml)) => xml,
+ Some(Include::Dir(files)) => {
+ for f in files.iter().take(MAX_CONFIG_FILES) {
+ self.config(f, depth);
+ }
+ return true;
+ }
+ None => return false,
+ };
+ let here = file.parent().map(Path::to_path_buf);
+ for e in elements(&xml) {
+ match (e.name, e.prefix) {
+ ("dir", Some("xdg")) => {
+ if let Some(d) = self.data_home.as_ref().map(|d| d.join(&e.text)) {
+ self.add(d);
+ }
+ }
+ ("dir", Some("relative")) => {
+ if let Some(d) = here.as_ref().map(|h| h.join(&e.text)) {
+ self.add(d);
+ }
+ }
+ // "default", "cwd" or none: as written; a relative directory is skipped.
+ ("dir", _) => {
+ if let Some(d) = self.expand_home(&e.text) {
+ self.add(d);
+ }
+ }
+ ("include", Some("xdg")) => {
+ if let Some(f) = self.config_home.as_ref().map(|c| c.join(&e.text)) {
+ self.config(&f, depth + 1);
+ }
+ }
+ ("include", Some("relative")) => self.include(&e.text, here.as_deref(), depth + 1),
+ ("include", _) => self.include(&e.text, None, depth + 1),
+ _ => {}
+ }
+ }
+ true
+ }
+}
+
+struct Element<'a> {
+ name: &'a str,
+ prefix: Option<&'a str>,
+ text: String,
+}
+
+/// The `` and `` elements of a configuration file with text, in order; comments
+/// are skipped. A bounded scan over the text: fontconfig files are small and regular.
+fn elements(xml: &str) -> Vec> {
+ let mut out = Vec::new();
+ let mut rest = xml;
+ while let Some(i) = rest.find('<') {
+ let Some(tag) = rest.get(i + 1..) else { break };
+ if let Some(c) = tag.strip_prefix("!--") {
+ rest = c.find("-->").and_then(|j| c.get(j + 3..)).unwrap_or("");
+ continue;
+ }
+ let Some(end) = tag.find('>') else { break };
+ let (head, after) = (tag.get(..end).unwrap_or(""), tag.get(end + 1..).unwrap_or(""));
+ rest = after;
+ let mut words = head.split_whitespace();
+ let name = words.next().unwrap_or("");
+ if !matches!(name, "dir" | "include") {
+ continue;
+ }
+ let prefix = words.find_map(|w| w.strip_prefix("prefix=")).map(|v| v.trim_matches(['"', '\'']));
+ let text = unescape(after.split('<').next().unwrap_or("").trim());
+ if !text.is_empty() {
+ out.push(Element { name, prefix, text });
+ }
+ if out.len() >= MAX_ELEMENTS {
+ break;
+ }
+ }
+ out
+}
+
+fn unescape(s: &str) -> String {
+ if !s.contains('&') {
+ return s.to_string();
+ }
+ s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
+}
+
+/// Read a configuration file (skipped beyond `MAX_CONFIG_BYTES`) or list a directory's
+/// `[0-9]*.conf` files, sorted.
+pub(super) fn read_config(path: &Path) -> Option {
+ use std::io::Read as _;
+ if path.is_dir() {
+ let conf =
+ |p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf"));
+ let mut files: Vec = std::fs::read_dir(path).ok()?.flatten().map(|e| e.path()).filter(|p| conf(p)).take(MAX_CONFIG_FILES).collect();
+ files.sort();
+ return Some(Include::Dir(files));
+ }
+ let mut xml = String::new();
+ std::fs::File::open(path).ok()?.take(MAX_CONFIG_BYTES.saturating_add(1)).read_to_string(&mut xml).ok()?;
+ (xml.len() as u64 <= MAX_CONFIG_BYTES).then_some(Include::File(xml))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn env_of<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option + 'a {
+ move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
+ }
+
+ fn reader<'a>(files: &'a [(&str, &str)], dirs: &'a [(&str, &[&str])]) -> impl Fn(&Path) -> Option + 'a {
+ move |p| {
+ if let Some((_, xml)) = files.iter().find(|(n, _)| Path::new(n) == p) {
+ return Some(Include::File((*xml).to_string()));
+ }
+ dirs.iter().find(|(n, _)| Path::new(n) == p).map(|(_, fs)| Include::Dir(fs.iter().map(PathBuf::from).collect()))
+ }
+ }
+
+ fn paths(v: &[&str]) -> Vec {
+ v.iter().map(PathBuf::from).collect()
+ }
+
+ const XDG: &[&str] = &["/usr/local/share/fonts", "/usr/share/fonts", "/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
+
+ #[test]
+ fn xdg_defaults_without_variables() {
+ let d = font_dirs(env_of(&[("HOME", "/home/u")]), |_| None);
+ assert_eq!(d, paths(&[&["/home/u/.local/share/fonts", "/home/u/.fonts"], XDG].concat()));
+ assert_eq!(font_dirs(|_| None, |_| None), paths(XDG), "no HOME: system directories only");
+ }
+
+ #[test]
+ fn xdg_variables_name_the_font_dirs() {
+ let env = env_of(&[
+ ("HOME", "/home/u"),
+ ("XDG_DATA_HOME", "/data"),
+ ("XDG_DATA_DIRS", "/nix/profile/share:/run/current-system/sw/share:relative:/usr/share/:"),
+ ]);
+ let d = font_dirs(env, |_| None);
+ assert_eq!(
+ d.get(..6),
+ Some(
+ paths(&[
+ "/data/fonts",
+ "/home/u/.fonts",
+ "/nix/profile/share/fonts",
+ "/run/current-system/sw/share/fonts",
+ "/usr/share/fonts",
+ "/usr/local/share/fonts"
+ ])
+ .as_slice()
+ )
+ );
+ assert_eq!(d.len(), 9, "{d:?}");
+ }
+
+ #[test]
+ fn fontconfig_dirs_nixos_style() {
+ let files = [
+ (
+ "/etc/fonts/fonts.conf",
+ "\n\n\n\
+ \nfontconfig\n\
+ /etc/fonts/conf.d\nfonts\n\
+ /nix/store/aaa-dejavu-fonts-minimal-2.37\n\n",
+ ),
+ (
+ "/etc/fonts/conf.d/00-nixos-cache.conf",
+ "\n \n /nix/store/bbb-dejavu-fonts-2.37\n/nix/store/ccc-unifont-16.0.03\n\
+ \n /nix/store/ddd-fc-cache\n\n",
+ ),
+ (
+ "/etc/fonts/conf.d/50-user.conf",
+ "\nfontconfig/conf.d\n\n",
+ ),
+ (
+ "/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf",
+ "\n/nix/store/eee-home-manager-path/etc/fonts/conf.d\n\
+ /nix/store/eee-home-manager-path/share/fonts\n/etc/profiles/per-user/u/share/fonts\n\n",
+ ),
+ ];
+ let dirs: [(&str, &[&str]); 2] = [
+ ("/etc/fonts/conf.d", &["/etc/fonts/conf.d/00-nixos-cache.conf", "/etc/fonts/conf.d/50-user.conf"]),
+ ("/home/u/.config/fontconfig/conf.d", &["/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf"]),
+ ];
+ let d = font_dirs(env_of(&[("HOME", "/home/u"), ("XDG_DATA_DIRS", "/etc/profiles/per-user/u/share")]), reader(&files, &dirs));
+ let expect = [
+ "/home/u/.local/share/fonts",
+ "/home/u/.fonts",
+ "/etc/profiles/per-user/u/share/fonts",
+ "/usr/local/share/fonts",
+ "/usr/share/fonts",
+ "/run/host/fonts",
+ "/run/host/local-fonts",
+ "/run/host/user-fonts",
+ "/nix/store/bbb-dejavu-fonts-2.37",
+ "/nix/store/ccc-unifont-16.0.03",
+ "/nix/store/eee-home-manager-path/share/fonts",
+ "/nix/store/aaa-dejavu-fonts-minimal-2.37",
+ ];
+ assert_eq!(d, paths(&expect));
+ }
+
+ #[test]
+ fn fontconfig_dirs_debian_style() {
+ let files = [
+ (
+ "/etc/fonts/fonts.conf",
+ "\n/usr/share/fonts\n/usr/local/share/fonts\nfonts\n\
+ ~/.fonts\n/opt/fonts & more\nrelative/skipped\nalso/skipped\n\
+ conf.d\n\n",
+ ),
+ ("/etc/fonts/conf.d/51-local.conf", "local.conf"),
+ ("/etc/fonts/conf.d/52-site.conf", "../site/fonts.conf"),
+ ("/etc/fonts/local.conf", "/srv/fontsmore"),
+ ("/etc/fonts/conf.d/../site/fonts.conf", "/site/fonts"),
+ ];
+ let dirs: [(&str, &[&str]); 1] = [("/etc/fonts/conf.d", &["/etc/fonts/conf.d/51-local.conf", "/etc/fonts/conf.d/52-site.conf"])];
+ let d = font_dirs(env_of(&[("HOME", "/home/u")]), reader(&files, &dirs));
+ let tail: Vec = d.iter().skip(7).cloned().collect();
+ assert_eq!(tail, paths(&["/opt/fonts & more", "/srv/fonts", "/etc/fonts/more", "/site/fonts"]));
+ assert_eq!(d.len(), 11, "the directories already listed are not repeated: {d:?}");
+ }
+
+ #[test]
+ fn fontconfig_file_and_path_variables() {
+ let files = [("/cfg/custom.conf", "/custom/fonts")];
+ let env = env_of(&[("FONTCONFIG_FILE", "custom.conf"), ("FONTCONFIG_PATH", "/nowhere:/cfg")]);
+ let d = font_dirs(env, reader(&files, &[]));
+ assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
+ let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/custom.conf")]), reader(&files, &[]));
+ assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
+ assert_eq!(font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/missing.conf")]), reader(&files, &[])), paths(XDG));
+ }
+
+ #[test]
+ fn include_cycles_and_depth_are_bounded() {
+ let files = [
+ ("/etc/fonts/fonts.conf", "/d0/etc/fonts/b.conf"),
+ (
+ "/etc/fonts/b.conf",
+ "/d1/etc/fonts/fonts.conf/etc/fonts/b.conf",
+ ),
+ ];
+ let d = font_dirs(|_| None, reader(&files, &[]));
+ assert_eq!(d.iter().skip(XDG.len()).cloned().collect::>(), paths(&["/d0", "/d1"]));
+
+ let chain: Vec<(String, String)> = (0..10)
+ .map(|i| {
+ (format!("/etc/fonts/{i}.conf"), format!("/depth{i}/etc/fonts/{}.conf", i + 1))
+ })
+ .collect();
+ let read = |p: &Path| chain.iter().find(|(n, _)| Path::new(n) == p).map(|(_, xml)| Include::File(xml.clone()));
+ let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/etc/fonts/0.conf")]), read);
+ let depths: Vec<&PathBuf> = d.iter().skip(XDG.len()).collect();
+ assert_eq!(depths.len(), MAX_INCLUDE_DEPTH + 1, "{depths:?}");
+ assert_eq!(depths.last().map(|p| p.as_path()), Some(Path::new("/depth4")));
+ }
+
+ #[test]
+ fn many_files_are_bounded() {
+ let names: Vec = (0..1000).map(|i| format!("/etc/fonts/conf.d/{i:04}.conf")).collect();
+ let read = |p: &Path| {
+ if p == Path::new("/etc/fonts/fonts.conf") {
+ return Some(Include::File("/etc/fonts/conf.d".into()));
+ }
+ if p == Path::new("/etc/fonts/conf.d") {
+ return Some(Include::Dir(names.iter().map(PathBuf::from).collect()));
+ }
+ p.starts_with("/etc/fonts/conf.d").then(|| Include::File(format!("{}", p.display())))
+ };
+ let d = font_dirs(|_| None, read);
+ assert!(d.len() <= XDG.len() + MAX_CONFIG_FILES, "{}", d.len());
+ assert!(d.len() > XDG.len() + 200);
+ }
+
+ #[test]
+ fn elements_survive_odd_markup() {
+ let xml = "/unterminated/xr