Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(fonts): extract system font matching crate

ldm009257c15cf85
diff --git a/Cargo.lock b/Cargo.lock
index 6a4004c3b..c43e3cfbd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2644,14 +2644,13 @@ dependencies = [
"euclid",
"kurbo",
"moli-image",
- "parking_lot",
+ "moli-system-fonts",
"parley",
"stylo",
"stylo_taffy",
"taffy",
"thiserror",
"wuff",
- "yeslogic-fontconfig-sys",
]
[[package]]
@@ -3091,6 +3090,15 @@ dependencies = [
"svgtypes",
]
+[[package]]
+name = "moli-system-fonts"
+version = "0.1.0"
+dependencies = [
+ "fontique",
+ "parking_lot",
+ "yeslogic-fontconfig-sys",
+]
+
[[package]]
name = "moli-test-support"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index e85d68515..fc22a5c65 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -51,6 +51,7 @@ members = [
"moli-structured-clone",
"moli-stylesheet-blocking",
"moli-svg",
+ "moli-system-fonts",
"moli-test-support",
"moli-url",
"moli-url-policy",
diff --git a/moli-layout/Cargo.toml b/moli-layout/Cargo.toml
index 266028a76..6a3bfec64 100644
--- a/moli-layout/Cargo.toml
+++ b/moli-layout/Cargo.toml
@@ -2,22 +2,19 @@
name = "moli-layout"
version = "0.1.0"
edition = "2024"
-license = "(MIT OR Apache-2.0) AND BSD-3-Clause"
+license.workspace = true
[dependencies]
euclid = "=0.22.14"
kurbo = "=0.13.1"
moli-image = { path = "../moli-image" }
+moli-system-fonts = { path = "../moli-system-fonts" }
parley = "=0.11.1"
-parking_lot = "0.12"
stylo = "0.20"
stylo_taffy = { git = "https://github.com/DioxusLabs/blitz", rev = "5081c65811a4396f5a99b2e0aca542a4a4a6606f", default-features = false, features = ["std", "block", "flexbox", "grid", "floats"] }
taffy = { version = "=0.13.0", default-features = false, features = ["std", "block_layout", "flexbox", "grid", "float_layout", "content_size", "calc", "detailed_layout_info"] }
thiserror = "2.0.17"
wuff = "=0.2.5"
-[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
-yeslogic-fontconfig-sys = "=6.0.1"
-
[lints]
workspace = true
diff --git a/moli-layout/LICENSE-Skia-BSD-3-Clause b/moli-layout/LICENSE-Skia-BSD-3-Clause
deleted file mode 100644
index 21425b598..000000000
--- a/moli-layout/LICENSE-Skia-BSD-3-Clause
+++ /dev/null
@@ -1,35 +0,0 @@
-The metric-compatible font family table in src/system_fonts/matching.rs is
-adapted from Skia's src/ports/SkFontConfigInterface_direct.cpp.
-Copyright 2009-2015 Google Inc.
-
-Skia license:
-
-Copyright (c) 2011 Google Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the
- distribution.
-
- * Neither the name of the copyright holder nor the names of its
- contributors may be used to endorse or promote products derived
- from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index 11b3b16de..34384938c 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -34,7 +34,6 @@ mod source;
mod stacking;
mod style;
mod stylo_to_parley;
-mod system_fonts;
mod table;
mod taffy_tree;
mod text;
diff --git a/moli-layout/src/system_fonts.rs b/moli-layout/src/system_fonts.rs
deleted file mode 100644
index 776a22746..000000000
--- a/moli-layout/src/system_fonts.rs
+++ /dev/null
@@ -1,377 +0,0 @@
-// SPDX-License-Identifier: MIT OR Apache-2.0
-
-use std::{borrow::Cow, collections::HashMap};
-
-use parley::{FontFamily, FontFamilyName, TextStyle, fontique::Collection};
-
-use crate::stylo_to_parley::TextBrush;
-
-#[cfg(any(test, target_os = "linux", target_os = "freebsd"))]
-mod matching;
-
-pub(crate) struct SystemFontFamilyResolver {
- system_families: HashMap<String, String>,
- substitutions: HashMap<String, Option<String>>,
- #[cfg(test)]
- family_lookup_count: usize,
-}
-
-impl SystemFontFamilyResolver {
- pub(crate) fn new(collection: &mut Collection) -> Self {
- let system_families = collection
- .family_names()
- .map(|name| (normalized_family_name(name), name.to_owned()))
- .collect();
- Self {
- system_families,
- substitutions: HashMap::new(),
- #[cfg(test)]
- family_lookup_count: 0,
- }
- }
-
- pub(crate) fn resolve_text_style(
- &mut self,
- collection: &mut Collection,
- style: &mut TextStyle<'static, 'static, TextBrush>,
- ) {
- match &mut style.font_family {
- FontFamily::Single(family) => self.resolve_family(collection, family),
- FontFamily::List(families) => {
- for family in Cow::to_mut(families) {
- self.resolve_family(collection, family);
- }
- }
- FontFamily::Source(_) => {}
- }
- }
-
- fn resolve_family(
- &mut self,
- collection: &mut Collection,
- family: &mut FontFamilyName<'static>,
- ) {
- let FontFamilyName::Named(name) = family else {
- return;
- };
- let key = normalized_family_name(name);
- if let Some(cached) = self.substitutions.get(&key) {
- if let Some(substitute) = cached {
- *name = Cow::Owned(substitute.clone());
- }
- return;
- }
- #[cfg(test)]
- {
- self.family_lookup_count = self.family_lookup_count.saturating_add(1);
- }
- if collection.family_id(name).is_some() {
- self.substitutions.insert(key, None);
- return;
- }
- let Some(substitute) = self.resolve_missing_family(name) else {
- return;
- };
- *name = Cow::Owned(substitute);
- }
-
- fn resolve_missing_family(&mut self, family: &str) -> Option<String> {
- let key = normalized_family_name(family);
- if let Some(cached) = self.substitutions.get(&key) {
- return cached.clone();
- }
- let substitution = platform::match_family(family, &self.system_families);
- self.substitutions.insert(key, substitution.clone());
- substitution
- }
-}
-
-fn normalized_family_name(name: &str) -> String {
- name.chars().flat_map(char::to_lowercase).collect()
-}
-
-#[cfg(any(target_os = "linux", target_os = "freebsd"))]
-mod platform {
- use std::{
- collections::HashMap,
- ffi::{CStr, CString},
- ptr::NonNull,
- };
-
- use fontconfig_sys::{
- FcConfig, FcConfigSubstitute, FcDefaultSubstitute, FcFontSet, FcFontSetDestroy, FcFontSort,
- FcInit, FcMatchPattern, FcPattern, FcPatternAddBool, FcPatternAddString, FcPatternCreate,
- FcPatternDestroy, FcPatternGetString, FcResultMatch,
- constants::{FC_FAMILY, FC_SCALABLE},
- };
- use parking_lot::Mutex;
-
- use super::{matching::accepts_substitution, normalized_family_name};
-
- static FONTCONFIG_LOCK: Mutex<()> = Mutex::new(());
-
- struct Pattern(NonNull<FcPattern>);
-
- impl Drop for Pattern {
- fn drop(&mut self) {
- unsafe { FcPatternDestroy(self.0.as_ptr()) };
- }
- }
-
- struct FontSet(NonNull<FcFontSet>);
-
- impl Drop for FontSet {
- fn drop(&mut self) {
- unsafe { FcFontSetDestroy(self.0.as_ptr()) };
- }
- }
-
- pub(super) fn match_family(
- family: &str,
- available_families: &HashMap<String, String>,
- ) -> Option<String> {
- if family.len() > 2048 {
- return None;
- }
- let _guard = FONTCONFIG_LOCK.lock();
- let requested = CString::new(family).ok()?;
- unsafe {
- if FcInit() == 0 {
- return None;
- }
- let pattern = Pattern(NonNull::new(FcPatternCreate())?);
- if FcPatternAddString(
- pattern.0.as_ptr(),
- FC_FAMILY.as_ptr(),
- requested.as_ptr().cast(),
- ) == 0
- {
- return None;
- }
- if FcPatternAddBool(pattern.0.as_ptr(), FC_SCALABLE.as_ptr(), 1) == 0 {
- return None;
- }
- if FcConfigSubstitute(std::ptr::null_mut(), pattern.0.as_ptr(), FcMatchPattern) == 0 {
- return None;
- }
- FcDefaultSubstitute(pattern.0.as_ptr());
-
- match_pattern(std::ptr::null_mut(), family, &pattern, available_families)
- }
- }
-
- // The config (or global config for null) must outlive the query. Taking a
- // configured pattern keeps native substitution separate from accepting the
- // resulting best match; tests can supply an isolated application font set.
- unsafe fn match_pattern(
- config: *mut FcConfig,
- family: &str,
- pattern: &Pattern,
- available_families: &HashMap<String, String>,
- ) -> Option<String> {
- unsafe {
- let configured = family_names(pattern.0.as_ptr()).into_iter().next()?;
- let mut result = FcResultMatch;
- let matches = FontSet(NonNull::new(FcFontSort(
- config,
- pattern.0.as_ptr(),
- 0,
- std::ptr::null_mut(),
- &mut result,
- ))?);
- let font_set = matches.0.as_ref();
- for index in 0..font_set.nfont {
- let names = family_names(*font_set.fonts.add(index as usize));
- let Some(available) = names
- .iter()
- .find_map(|name| available_families.get(&normalized_family_name(name)))
- else {
- continue;
- };
- // Fontconfig always finds a best-effort font. Like Chromium's
- // SkFontConfigInterfaceDirect, reject an unrelated first match
- // so the next CSS family can be tried instead. Do not search
- // later matches for an arbitrary acceptable alias.
- return names
- .iter()
- .any(|name| accepts_substitution(family, &configured, name))
- .then(|| available.clone());
- }
- None
- }
- }
-
- // The caller retains the owning Pattern or FontSet for the entire read.
- unsafe fn family_names(pattern: *mut FcPattern) -> Vec<String> {
- let mut families = Vec::new();
- for index in 0..255 {
- let mut value = std::ptr::null_mut();
- if unsafe { FcPatternGetString(pattern, FC_FAMILY.as_ptr(), index, &mut value) }
- != FcResultMatch
- || value.is_null()
- {
- break;
- }
- families.push(
- unsafe { CStr::from_ptr(value.cast()) }
- .to_string_lossy()
- .into_owned(),
- );
- }
- families
- }
-
- #[cfg(test)]
- mod tests {
- use super::*;
- use fontconfig_sys::{FcConfigAppFontAddFile, FcConfigCreate, FcConfigDestroy};
-
- struct Config(NonNull<FcConfig>);
-
- impl Drop for Config {
- fn drop(&mut self) {
- unsafe { FcConfigDestroy(self.0.as_ptr()) };
- }
- }
-
- #[test]
- fn native_font_match_rejects_appended_alias_but_accepts_configured_rename() {
- let _guard = FONTCONFIG_LOCK.lock();
- unsafe {
- assert_ne!(FcInit(), 0);
- let config = Config(NonNull::new(FcConfigCreate()).expect("fontconfig config"));
- let file = CString::new(concat!(
- env!("CARGO_MANIFEST_DIR"),
- "/tests/fixtures/moli-ahem.ttf"
- ))
- .unwrap();
- assert_ne!(
- FcConfigAppFontAddFile(config.0.as_ptr(), file.as_ptr().cast()),
- 0
- );
- let families = HashMap::from([("moli ahem".to_owned(), "Moli Ahem".to_owned())]);
-
- for (requested, configured, expected) in [
- ("Missing Font", ["Missing Font", "Moli Ahem"], None),
- (
- "Renamed Font",
- ["Moli Ahem", "Renamed Font"],
- Some("Moli Ahem"),
- ),
- (
- "Moli Ahem",
- ["Different Override", "Moli Ahem"],
- Some("Moli Ahem"),
- ),
- ] {
- let pattern = Pattern(NonNull::new(FcPatternCreate()).expect("font pattern"));
- for name in configured {
- let name = CString::new(name).unwrap();
- assert_ne!(
- FcPatternAddString(
- pattern.0.as_ptr(),
- FC_FAMILY.as_ptr(),
- name.as_ptr().cast()
- ),
- 0
- );
- }
- FcDefaultSubstitute(pattern.0.as_ptr());
- assert_eq!(
- match_pattern(config.0.as_ptr(), requested, &pattern, &families).as_deref(),
- expected,
- "native best-match acceptance for {requested}"
- );
- }
- }
- }
- }
-}
-
-#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
-mod platform {
- pub(super) fn match_family(
- _family: &str,
- _available_families: &std::collections::HashMap<String, String>,
- ) -> Option<String> {
- None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn successful_family_lookup_is_cached() {
- let mut collection = Collection::new(parley::fontique::CollectionOptions {
- shared: false,
- system_fonts: true,
- });
- let family = collection
- .family_names()
- .next()
- .expect("the system font collection should expose at least one family")
- .to_owned();
- let mut resolver = SystemFontFamilyResolver::new(&mut collection);
-
- for _ in 0..2 {
- let mut style = TextStyle {
- font_family: FontFamily::Single(FontFamilyName::Named(Cow::Owned(family.clone()))),
- ..TextStyle::default()
- };
- resolver.resolve_text_style(&mut collection, &mut style);
- }
-
- assert_eq!(
- resolver.family_lookup_count, 1,
- "a known family must not rebuild Fontique's normalized lookup key"
- );
- }
-
- #[test]
- fn missing_family_lookup_is_cached_without_replacing_the_css_fallback() {
- let mut collection = Collection::new(parley::fontique::CollectionOptions {
- shared: false,
- system_fonts: true,
- });
- let mut resolver = SystemFontFamilyResolver::new(&mut collection);
- let family = "__moli_missing_font_family_cache_3bb2__";
- for _ in 0..2 {
- let mut style = TextStyle {
- font_family: FontFamily::Single(FontFamilyName::Named(Cow::Borrowed(family))),
- ..TextStyle::default()
- };
- resolver.resolve_text_style(&mut collection, &mut style);
- assert!(matches!(
- style.font_family,
- FontFamily::Single(FontFamilyName::Named(name)) if name == family
- ));
- }
- assert_eq!(resolver.family_lookup_count, 1);
- }
-
- #[cfg(any(target_os = "linux", target_os = "freebsd"))]
- #[test]
- fn fontconfig_aliases_do_not_convert_an_unknown_family_to_default_sans() {
- let mut collection = Collection::new(parley::fontique::CollectionOptions {
- shared: false,
- system_fonts: true,
- });
- let mut resolver = SystemFontFamilyResolver::new(&mut collection);
- assert_eq!(
- resolver.resolve_missing_family("__moli_another_missing_family_92a6__"),
- None
- );
-
- if resolver
- .system_families
- .contains_key(&normalized_family_name("Liberation Sans"))
- {
- assert_eq!(
- resolver.resolve_missing_family("Arial").as_deref(),
- Some("Liberation Sans")
- );
- }
- }
-}
diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rs
index ca3669068..c12304b4b 100644
--- a/moli-layout/src/text.rs
+++ b/moli-layout/src/text.rs
@@ -11,6 +11,7 @@ use std::{
sync::Arc,
};
+use moli_system_fonts::SystemFontFamilyResolver;
use parley::{
FontContext, FontFamily, FontFamilyName, LayoutContext, TextStyle,
fontique::{
@@ -21,7 +22,6 @@ use parley::{
use thiserror::Error;
use crate::stylo_to_parley::TextBrush;
-use crate::system_fonts::SystemFontFamilyResolver;
pub(crate) struct ParleyDocumentServices {
pub(crate) font_context: FontContext,
@@ -133,7 +133,23 @@ impl ParleyDocumentServices {
self.resolve_segmented_web_font_families(style, character);
if let Some(resolver) = self.system_font_family_resolver.as_mut() {
- resolver.resolve_text_style(&mut self.font_context.collection, style);
+ let mut resolve_family = |family: &mut FontFamilyName<'static>| {
+ if let FontFamilyName::Named(name) = family
+ && let Some(substitute) =
+ resolver.substitute_family(&mut self.font_context.collection, name)
+ {
+ *name = Cow::Owned(substitute);
+ }
+ };
+ match &mut style.font_family {
+ FontFamily::Single(family) => resolve_family(family),
+ FontFamily::List(families) => {
+ for family in Cow::to_mut(families) {
+ resolve_family(family);
+ }
+ }
+ FontFamily::Source(_) => {}
+ }
}
let resolved = style.font_family.clone().into_owned();
match character {
@@ -965,6 +981,34 @@ mod tests {
assert_eq!(parley.font_family_resolution_miss_count, 1);
}
+ #[test]
+ fn system_family_substitution_preserves_css_fallback_order() {
+ let mut parley = build_parley_services(SystemFontPolicy::Disabled, &BTreeMap::new());
+ parley.system_font_family_resolver = Some(SystemFontFamilyResolver::new(
+ &mut parley.font_context.collection,
+ ));
+ assert!(register_font(
+ &mut parley.font_context,
+ &RegisteredWebFont {
+ face: WebFontFace::new("Moli Ahem"),
+ sfnt_bytes: Arc::from(TEST_TTF),
+ },
+ ));
+ let families = FontFamily::List(Cow::Owned(vec![
+ FontFamilyName::Named(Cow::Borrowed("__moli_missing_css_family_order_3d16__")),
+ FontFamilyName::Named(Cow::Borrowed("Moli Ahem")),
+ FontFamilyName::Generic(parley::fontique::GenericFamily::Serif),
+ ]));
+ let mut style = TextStyle {
+ font_family: families.clone(),
+ ..TextStyle::default()
+ };
+
+ parley.resolve_font_families(&mut style, None);
+
+ assert_eq!(style.font_family, families);
+ }
+
#[test]
fn font_collection_rebuild_discards_resolution_and_metrics_caches() {
let mut services =
diff --git a/moli-system-fonts/Cargo.toml b/moli-system-fonts/Cargo.toml
new file mode 100644
index 000000000..778b2e891
--- /dev/null
+++ b/moli-system-fonts/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "moli-system-fonts"
+version = "0.1.0"
+edition = "2024"
+license = "(MIT OR Apache-2.0) AND BSD-3-Clause"
+
+[dependencies]
+fontique = "=0.11.1"
+
+[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
+parking_lot = "0.12"
+yeslogic-fontconfig-sys = "=6.0.1"
+
+[lints]
+workspace = true
diff --git a/moli-system-fonts/src/fontconfig.rs b/moli-system-fonts/src/fontconfig.rs
new file mode 100644
index 000000000..de0526f8d
--- /dev/null
+++ b/moli-system-fonts/src/fontconfig.rs
@@ -0,0 +1,196 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+
+use std::{
+ collections::HashMap,
+ ffi::{CStr, CString},
+ ptr::NonNull,
+};
+
+use fontconfig_sys::{
+ FcConfig, FcConfigSubstitute, FcDefaultSubstitute, FcFontSet, FcFontSetDestroy, FcFontSort,
+ FcInit, FcMatchPattern, FcPattern, FcPatternAddBool, FcPatternAddString, FcPatternCreate,
+ FcPatternDestroy, FcPatternGetString, FcResultMatch,
+ constants::{FC_FAMILY, FC_SCALABLE},
+};
+use parking_lot::Mutex;
+
+use super::{matching::accepts_substitution, normalized_family_name};
+
+static FONTCONFIG_LOCK: Mutex<()> = Mutex::new(());
+
+struct Pattern(NonNull<FcPattern>);
+
+impl Drop for Pattern {
+ fn drop(&mut self) {
+ unsafe { FcPatternDestroy(self.0.as_ptr()) };
+ }
+}
+
+struct FontSet(NonNull<FcFontSet>);
+
+impl Drop for FontSet {
+ fn drop(&mut self) {
+ unsafe { FcFontSetDestroy(self.0.as_ptr()) };
+ }
+}
+
+pub(super) fn match_family(
+ family: &str,
+ available_families: &HashMap<String, String>,
+) -> Option<String> {
+ if family.len() > 2048 {
+ return None;
+ }
+ let _guard = FONTCONFIG_LOCK.lock();
+ let requested = CString::new(family).ok()?;
+ unsafe {
+ if FcInit() == 0 {
+ return None;
+ }
+ let pattern = Pattern(NonNull::new(FcPatternCreate())?);
+ if FcPatternAddString(
+ pattern.0.as_ptr(),
+ FC_FAMILY.as_ptr(),
+ requested.as_ptr().cast(),
+ ) == 0
+ {
+ return None;
+ }
+ if FcPatternAddBool(pattern.0.as_ptr(), FC_SCALABLE.as_ptr(), 1) == 0 {
+ return None;
+ }
+ if FcConfigSubstitute(std::ptr::null_mut(), pattern.0.as_ptr(), FcMatchPattern) == 0 {
+ return None;
+ }
+ FcDefaultSubstitute(pattern.0.as_ptr());
+
+ match_pattern(std::ptr::null_mut(), family, &pattern, available_families)
+ }
+}
+
+// The config (or global config for null) must outlive the query. Taking a
+// configured pattern keeps native substitution separate from accepting the
+// resulting best match; tests can supply an isolated application font set.
+unsafe fn match_pattern(
+ config: *mut FcConfig,
+ family: &str,
+ pattern: &Pattern,
+ available_families: &HashMap<String, String>,
+) -> Option<String> {
+ unsafe {
+ let configured = family_names(pattern.0.as_ptr()).into_iter().next()?;
+ let mut result = FcResultMatch;
+ let matches = FontSet(NonNull::new(FcFontSort(
+ config,
+ pattern.0.as_ptr(),
+ 0,
+ std::ptr::null_mut(),
+ &mut result,
+ ))?);
+ let font_set = matches.0.as_ref();
+ for index in 0..font_set.nfont {
+ let names = family_names(*font_set.fonts.add(index as usize));
+ let Some(available) = names
+ .iter()
+ .find_map(|name| available_families.get(&normalized_family_name(name)))
+ else {
+ continue;
+ };
+ // Fontconfig always finds a best-effort font. Like Chromium's
+ // SkFontConfigInterfaceDirect, reject an unrelated first match
+ // so the next CSS family can be tried instead. Do not search
+ // later matches for an arbitrary acceptable alias.
+ return names
+ .iter()
+ .any(|name| accepts_substitution(family, &configured, name))
+ .then(|| available.clone());
+ }
+ None
+ }
+}
+
+// The caller retains the owning Pattern or FontSet for the entire read.
+unsafe fn family_names(pattern: *mut FcPattern) -> Vec<String> {
+ let mut families = Vec::new();
+ for index in 0..255 {
+ let mut value = std::ptr::null_mut();
+ if unsafe { FcPatternGetString(pattern, FC_FAMILY.as_ptr(), index, &mut value) }
+ != FcResultMatch
+ || value.is_null()
+ {
+ break;
+ }
+ families.push(
+ unsafe { CStr::from_ptr(value.cast()) }
+ .to_string_lossy()
+ .into_owned(),
+ );
+ }
+ families
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use fontconfig_sys::{FcConfigAppFontAddFile, FcConfigCreate, FcConfigDestroy};
+
+ struct Config(NonNull<FcConfig>);
+
+ impl Drop for Config {
+ fn drop(&mut self) {
+ unsafe { FcConfigDestroy(self.0.as_ptr()) };
+ }
+ }
+
+ #[test]
+ fn native_font_match_rejects_appended_alias_but_accepts_configured_rename() {
+ let _guard = FONTCONFIG_LOCK.lock();
+ unsafe {
+ assert_ne!(FcInit(), 0);
+ let config = Config(NonNull::new(FcConfigCreate()).expect("fontconfig config"));
+ let file = CString::new(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/moli-ahem.ttf"
+ ))
+ .unwrap();
+ assert_ne!(
+ FcConfigAppFontAddFile(config.0.as_ptr(), file.as_ptr().cast()),
+ 0
+ );
+ let families = HashMap::from([("moli ahem".to_owned(), "Moli Ahem".to_owned())]);
+
+ for (requested, configured, expected) in [
+ ("Missing Font", ["Missing Font", "Moli Ahem"], None),
+ (
+ "Renamed Font",
+ ["Moli Ahem", "Renamed Font"],
+ Some("Moli Ahem"),
+ ),
+ (
+ "Moli Ahem",
+ ["Different Override", "Moli Ahem"],
+ Some("Moli Ahem"),
+ ),
+ ] {
+ let pattern = Pattern(NonNull::new(FcPatternCreate()).expect("font pattern"));
+ for name in configured {
+ let name = CString::new(name).unwrap();
+ assert_ne!(
+ FcPatternAddString(
+ pattern.0.as_ptr(),
+ FC_FAMILY.as_ptr(),
+ name.as_ptr().cast()
+ ),
+ 0
+ );
+ }
+ FcDefaultSubstitute(pattern.0.as_ptr());
+ assert_eq!(
+ match_pattern(config.0.as_ptr(), requested, &pattern, &families).as_deref(),
+ expected,
+ "native best-match acceptance for {requested}"
+ );
+ }
+ }
+ }
+}
diff --git a/moli-system-fonts/src/lib.rs b/moli-system-fonts/src/lib.rs
new file mode 100644
index 000000000..3b387ea92
--- /dev/null
+++ b/moli-system-fonts/src/lib.rs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+
+//! Browser-compatible system font family substitutions for Fontique collections.
+//!
+//! Native matching supplies candidates; the matching policy accepts only exact
+//! names, configured renames, and known metric-compatible replacements. An
+//! unrelated best-effort match leaves the requested name unchanged so the caller
+//! can try the next CSS family. Font list ordering, downloadable fonts, shaping,
+//! and glyph fallback remain with the caller.
+
+use std::collections::HashMap;
+
+use fontique::Collection;
+
+#[cfg(any(test, target_os = "linux", target_os = "freebsd"))]
+mod matching;
+
+#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+#[path = "fontconfig.rs"]
+mod platform;
+
+/// Caches named-family substitutions for one font collection.
+///
+/// Create the resolver before registering downloadable fonts: the initial
+/// snapshot limits native candidates to system families. Existing collection
+/// families take precedence over platform substitutions. Recreate the resolver
+/// when rebuilding the collection or changing fonts after a cached lookup.
+pub struct SystemFontFamilyResolver {
+ system_families: HashMap<String, String>,
+ substitutions: HashMap<String, Option<String>>,
+ #[cfg(test)]
+ family_lookup_count: usize,
+}
+
+impl SystemFontFamilyResolver {
+ /// Snapshots the collection's system family names without performing matching.
+ pub fn new(collection: &mut Collection) -> Self {
+ let system_families = collection
+ .family_names()
+ .map(|name| (normalized_family_name(name), name.to_owned()))
+ .collect();
+ Self {
+ system_families,
+ substitutions: HashMap::new(),
+ #[cfg(test)]
+ family_lookup_count: 0,
+ }
+ }
+
+ /// Returns an accepted replacement for a named CSS family.
+ ///
+ /// `None` means to preserve the requested name: either the collection already
+ /// knows it, or no acceptable replacement exists. This does not establish
+ /// whether a family is installed. Generic CSS families bypass this method.
+ /// Both replacements and unchanged results are cached case-insensitively.
+ pub fn substitute_family(
+ &mut self,
+ collection: &mut Collection,
+ family: &str,
+ ) -> Option<String> {
+ let key = normalized_family_name(family);
+ if let Some(cached) = self.substitutions.get(&key) {
+ return cached.clone();
+ }
+ #[cfg(test)]
+ {
+ self.family_lookup_count = self.family_lookup_count.saturating_add(1);
+ }
+ if collection.family_id(family).is_some() {
+ self.substitutions.insert(key, None);
+ return None;
+ }
+ self.resolve_missing_family(family)
+ }
+
+ fn resolve_missing_family(&mut self, family: &str) -> Option<String> {
+ let key = normalized_family_name(family);
+ if let Some(cached) = self.substitutions.get(&key) {
+ return cached.clone();
+ }
+ let substitution = platform::match_family(family, &self.system_families);
+ self.substitutions.insert(key, substitution.clone());
+ substitution
+ }
+}
+
+fn normalized_family_name(name: &str) -> String {
+ name.chars().flat_map(char::to_lowercase).collect()
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
+mod platform {
+ pub(super) fn match_family(
+ _family: &str,
+ _available_families: &std::collections::HashMap<String, String>,
+ ) -> Option<String> {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn successful_family_lookup_is_cached() {
+ let mut collection = Collection::new(fontique::CollectionOptions {
+ shared: false,
+ system_fonts: true,
+ });
+ let family = collection
+ .family_names()
+ .next()
+ .expect("the system font collection should expose at least one family")
+ .to_owned();
+ let mut resolver = SystemFontFamilyResolver::new(&mut collection);
+
+ for _ in 0..2 {
+ assert_eq!(resolver.substitute_family(&mut collection, &family), None);
+ }
+
+ assert_eq!(
+ resolver.family_lookup_count, 1,
+ "a known family must not rebuild Fontique's normalized lookup key"
+ );
+ }
+
+ #[test]
+ fn missing_family_lookup_is_cached_without_replacing_the_css_fallback() {
+ let mut collection = Collection::new(fontique::CollectionOptions {
+ shared: false,
+ system_fonts: true,
+ });
+ let mut resolver = SystemFontFamilyResolver::new(&mut collection);
+ let family = "__moli_missing_font_family_cache_3bb2__";
+ for _ in 0..2 {
+ assert_eq!(resolver.substitute_family(&mut collection, family), None);
+ }
+ assert_eq!(resolver.family_lookup_count, 1);
+ }
+
+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]
+ #[test]
+ fn fontconfig_aliases_do_not_convert_an_unknown_family_to_default_sans() {
+ let mut collection = Collection::new(fontique::CollectionOptions {
+ shared: false,
+ system_fonts: true,
+ });
+ let mut resolver = SystemFontFamilyResolver::new(&mut collection);
+ assert_eq!(
+ resolver.resolve_missing_family("__moli_another_missing_family_92a6__"),
+ None
+ );
+
+ if resolver
+ .system_families
+ .contains_key(&normalized_family_name("Liberation Sans"))
+ {
+ assert_eq!(
+ resolver.resolve_missing_family("Arial").as_deref(),
+ Some("Liberation Sans")
+ );
+ }
+ }
+}
diff --git a/moli-layout/src/system_fonts/matching.rs b/moli-system-fonts/src/matching.rs
similarity index 74%
rename from moli-layout/src/system_fonts/matching.rs
rename to moli-system-fonts/src/matching.rs
index 51bc74b24..e3ee5bc5d 100644
--- a/moli-layout/src/system_fonts/matching.rs
+++ b/moli-system-fonts/src/matching.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: (MIT OR Apache-2.0) AND BSD-3-Clause
// Metric compatibility data adapted from Skia, Copyright 2009-2015 Google Inc.
-// See ../../LICENSE-Skia-BSD-3-Clause for the retained third-party notice.
+// Skia's BSD-3-Clause notice is retained at the end of this module.
// Chromium's Linux FCI path distinguishes metric-compatible replacements from
// Fontconfig's best-effort fallbacks. See SkFontConfigInterface_direct.cpp,
@@ -156,3 +156,37 @@ mod tests {
}
}
}
+
+/*
+Skia license:
+
+Copyright (c) 2011 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
diff --git a/moli-system-fonts/tests/fixtures/README.md b/moli-system-fonts/tests/fixtures/README.md
new file mode 100644
index 000000000..48ed14627
--- /dev/null
+++ b/moli-system-fonts/tests/fixtures/README.md
@@ -0,0 +1,9 @@
+# System font matching fixture
+
+`moli-ahem.ttf` is the project's generated Latin test font, licensed under
+MIT OR Apache-2.0. The native matching test registers it in an isolated
+Fontconfig configuration so the candidate does not depend on installed fonts.
+
+Regenerate it and the layout fixtures from the repository root with
+`uv run scripts/generate-layout-test-font.py`. The script writes the same TTF
+to both crates; tests in this crate do not read files from `moli-layout`.
diff --git a/moli-system-fonts/tests/fixtures/moli-ahem.ttf b/moli-system-fonts/tests/fixtures/moli-ahem.ttf
new file mode 100644
index 000000000..20245e400
Binary files /dev/null and b/moli-system-fonts/tests/fixtures/moli-ahem.ttf differ
diff --git a/scripts/generate-layout-test-font.py b/scripts/generate-layout-test-font.py
index 4f27340ab..95a62b2da 100644
--- a/scripts/generate-layout-test-font.py
+++ b/scripts/generate-layout-test-font.py
@@ -5,7 +5,7 @@
# "fonttools==4.59.0",
# ]
# ///
-"""Generate the deterministic fixed fonts used by Phase 3 layout tests."""
+"""Generate deterministic fonts for layout and system font matching tests."""
import hashlib
import os
@@ -20,6 +20,7 @@ from fontTools.ttLib import TTFont
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / "moli-layout" / "tests" / "fixtures"
TTF_PATH = FIXTURES / "moli-ahem.ttf"
+SYSTEM_FONT_TTF_PATH = ROOT / "moli-system-fonts" / "tests" / "fixtures" / "moli-ahem.ttf"
HEBREW_EMOJI_PATH = FIXTURES / "moli-hebrew-emoji.ttf"
CJK_PATH = FIXTURES / "moli-cjk.ttf"
DEJAVU_SOURCE = Path(
@@ -142,6 +143,8 @@ def main() -> None:
verify_source(DEJAVU_SOURCE, DEJAVU_SOURCE_SHA256)
verify_source(DROID_CJK_SOURCE, DROID_CJK_SOURCE_SHA256)
build_ttf()
+ SYSTEM_FONT_TTF_PATH.parent.mkdir(parents=True, exist_ok=True)
+ SYSTEM_FONT_TTF_PATH.write_bytes(TTF_PATH.read_bytes())
convert("woff")
convert("woff2")
subset_font(DEJAVU_SOURCE, HEBREW_EMOJI_PATH, [0x20, 0x05D0, 0x05D1, 0x1F600])