Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(fonts): share Chromium-compatible Unicode family matching

ldm05953bd1622f1
diff --git a/Cargo.lock b/Cargo.lock
index 1f6485a1f..2e3c0ee55 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2812,6 +2812,7 @@ dependencies = [
"cssparser",
"stylo",
"stylo_traits",
+ "unicode-case-mapping",
"url",
]
@@ -6200,6 +6201,12 @@ version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+[[package]]
+name = "unicode-case-mapping"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e9026503b74f3207a4c04e6bf4ea735daa8edf6c0bbfa044cae597bb947a9db"
+
[[package]]
name = "unicode-id-start"
version = "1.4.0"
diff --git a/moli-css-parse/Cargo.toml b/moli-css-parse/Cargo.toml
index d818aac9d..97cbcc28a 100644
--- a/moli-css-parse/Cargo.toml
+++ b/moli-css-parse/Cargo.toml
@@ -5,6 +5,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
+unicode-case-mapping = "1.0"
cssparser = "0.38"
stylo = "0.22"
style_traits = { package = "stylo_traits", version = "0.22" }
diff --git a/moli-css-parse/src/font_face.rs b/moli-css-parse/src/font_face.rs
index c494c07bf..771ab2977 100644
--- a/moli-css-parse/src/font_face.rs
+++ b/moli-css-parse/src/font_face.rs
@@ -79,6 +79,26 @@ pub enum CssFontFamily {
Generic(style::values::computed::font::GenericFontFamily),
}
+/// A CSS font-family lookup key matching Blink's case-folding hash: Unicode
+/// simple folding of UTF-16 code units, without normalization or locale tailoring.
+/// This is separate from platform local() full-name lookup.
+pub fn font_family_name_key(name: &str) -> String {
+ if name.is_ascii() {
+ return name.to_ascii_lowercase();
+ }
+ name.chars()
+ .map(|character| {
+ // Blink hashes each UTF-16 code unit; surrogate pairs do not fold.
+ if character.len_utf16() == 2 {
+ return character;
+ }
+ unicode_case_mapping::case_folded(character)
+ .and_then(|folded| char::from_u32(folded.get()))
+ .unwrap_or(character)
+ })
+ .collect()
+}
+
#[derive(Clone, Debug)]
pub struct CssFontShorthand {
pub family_css: String,
@@ -213,6 +233,38 @@ fn is_css_wide_keyword(value: &str) -> bool {
#[cfg(test)]
mod tests {
+ #[test]
+ fn font_name_keys_follow_chromium_case_folding_without_expansion_or_normalization() {
+ use super::font_family_name_key;
+ for (a, b) in [
+ ("Äpfel", "äpfel"),
+ ("Σπίτι", "σπίτι"),
+ ("ΟΣ", "ος"),
+ ("K", "k"),
+ ("ẞ", "ß"),
+ ("µ", "Μ"),
+ ] {
+ assert_eq!(
+ font_family_name_key(a),
+ font_family_name_key(b),
+ "{a} / {b}"
+ );
+ }
+ for (a, b) in [
+ ("Straße", "STRASSE"),
+ ("Å", "A\u{030a}"),
+ ("İ", "i"),
+ ("İ", "i\u{0307}"),
+ ("𐐀", "𐐨"),
+ ] {
+ assert_ne!(
+ font_family_name_key(a),
+ font_family_name_key(b),
+ "{a} / {b}"
+ );
+ }
+ }
+
#[test]
fn font_sources_preserve_local_names_and_supported_url_fallback_order() {
use super::*;
diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs
index d1bf9546e..bf6bdccc9 100644
--- a/moli-css-parse/src/lib.rs
+++ b/moli-css-parse/src/lib.rs
@@ -21,7 +21,7 @@ pub use color::{
};
pub use declaration::{CssDeclaration, DeclarationParseOptions, parse_declaration_list};
pub use font_face::{
- CssFontFace, CssFontFamily, CssFontShorthand, CssFontSource,
+ CssFontFace, CssFontFamily, CssFontShorthand, CssFontSource, font_family_name_key,
font_load_query_contains_css_wide_keyword, font_load_query_family, font_load_query_is_valid,
legacy_variations_font_format, normalize_font_face_src, parse_font_face_sources,
parse_font_faces, parse_font_shorthand,
diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rs
index af3a86e8c..7bf82bd21 100644
--- a/moli-layout/src/text.rs
+++ b/moli-layout/src/text.rs
@@ -11,7 +11,9 @@ use std::{
sync::Arc,
};
-use moli_css_parse::{FontSelectionCapabilities as WebFontCapabilities, FontSelectionRange};
+use moli_css_parse::{
+ FontSelectionCapabilities as WebFontCapabilities, FontSelectionRange, font_family_name_key,
+};
use moli_system_fonts::SystemFontFamilyResolver;
use parley::{
FontContext, FontFamily, FontFamilyName, LayoutContext, TextStyle,
@@ -218,7 +220,7 @@ impl ParleyDocumentServices {
return false;
};
self.web_font_families
- .get(&normalized_web_font_family_name(name))
+ .get(&font_family_name_key(name))
.is_some_and(|family| {
family.groups.iter().any(|group| {
group
@@ -271,7 +273,7 @@ impl ParleyDocumentServices {
resolved.push(family);
continue;
};
- let family_key = normalized_web_font_family_name(name);
+ let family_key = font_family_name_key(name);
if !self.web_font_families.contains_key(&family_key) {
resolved.push(family);
continue;
@@ -1086,17 +1088,6 @@ impl ParleyDocumentServices {
web_font_order: &BTreeMap<String, (bool, usize)>,
) -> Result<(), WebFontRegistrationError> {
let blob = font.sfnt_bytes.clone();
- let selector_fonts = self.font_context.collection.register_fonts(
- blob.clone(),
- Some(
- font.face
- .fontique_override_for_family(font.face.family_name()),
- ),
- );
- if selector_fonts.is_empty() {
- return Err(WebFontRegistrationError::UnsupportedPayload);
- }
-
// Unlike an enumerated index, a stable slot never renames existing
// families when an earlier-sorting resource finishes later.
let internal_family_name = format!("\0moli-web-font:{slot}");
@@ -1107,10 +1098,12 @@ impl ParleyDocumentServices {
.fontique_override_for_family(&internal_family_name),
),
);
- assert!(
- !internal_fonts.is_empty(),
- "the same font with a nonempty alias must register"
- );
+ if internal_fonts.is_empty() {
+ return Err(WebFontRegistrationError::UnsupportedPayload);
+ }
+ // CSS matching belongs to the document registry below. Registering a
+ // second, public family alias would let Fontique's broader name matching
+ // bypass a rejected CSS family and select that face during fallback.
let source_priority = web_font_order
.get(slot)
@@ -1118,9 +1111,9 @@ impl ParleyDocumentServices {
.unwrap_or((!font.stylesheet, usize::MAX));
let family = self
.web_font_families
- .entry(normalized_web_font_family_name(font.face.family_name()))
+ .entry(font_family_name_key(font.face.family_name()))
.or_default();
- for (_, fonts) in selector_fonts {
+ for (_, fonts) in internal_fonts {
for selector_font in fonts {
let capabilities = font.face.capabilities.unwrap_or_else(|| {
font_selection_capabilities(Attributes::new(
@@ -1172,10 +1165,6 @@ impl ParleyDocumentServices {
}
}
-fn normalized_web_font_family_name(name: &str) -> String {
- name.chars().flat_map(char::to_lowercase).collect()
-}
-
fn validate_sfnt_table_bounds(sfnt_bytes: &[u8]) -> Result<(), WebFontRegistrationError> {
// Fontique reads metadata lazily and can register a font whose unused
// tables extend past the supplied bytes. Validate every directory entry
@@ -1462,7 +1451,7 @@ mod tests {
TEST_TTF.to_vec(),
))
.unwrap();
- let style = TextStyle {
+ let mut style = TextStyle {
font_family: FontFamily::List(std::borrow::Cow::Owned(vec![
FontFamilyName::Named(std::borrow::Cow::Borrowed("Moli CJK")),
FontFamilyName::Named(std::borrow::Cow::Borrowed("Moli Latin")),
@@ -1470,6 +1459,7 @@ mod tests {
..TextStyle::default()
};
let parley = services.parley_mut();
+ parley.resolve_font_families(&mut style, None);
assert!(parley.inline_font_metrics(&style, None).is_none());
assert!(
@@ -1701,13 +1691,30 @@ mod tests {
)
}
+ fn resolved_registered_family_name(
+ parley: &mut ParleyDocumentServices,
+ family: &str,
+ ) -> Option<String> {
+ let mut style = TextStyle {
+ font_family: FontFamily::Single(FontFamilyName::Named(Cow::Owned(family.to_owned()))),
+ ..TextStyle::default()
+ };
+ parley.resolve_segmented_web_font_families(&mut style, None);
+ let FontFamily::List(families) = style.font_family else {
+ return None;
+ };
+ families.iter().find_map(|family| match family {
+ FontFamilyName::Named(name) => Some(name.to_string()),
+ _ => None,
+ })
+ }
+
fn has_family(services: &mut DocumentLayoutServices, family: &str) -> bool {
- services
- .parley_mut()
- .font_context
- .collection
- .family_id(family)
- .is_some()
+ let parley = services.parley_mut();
+ let Some(family) = resolved_registered_family_name(parley, family) else {
+ return false;
+ };
+ parley.font_context.collection.family_id(&family).is_some()
}
#[test]
diff --git a/moli-layout/src/text/tests/registration.rs b/moli-layout/src/text/tests/registration.rs
index 5f889f41e..68b7c79c3 100644
--- a/moli-layout/src/text/tests/registration.rs
+++ b/moli-layout/src/text/tests/registration.rs
@@ -60,11 +60,12 @@ fn owned_sfnt_payload_is_retained_without_copying_its_buffer() {
shape_one_character(services.parley_mut(), web_font_style("Owned", 400.0), 'R'),
TEST_TTF
);
- let font = services
- .parley_mut()
+ let parley = services.parley_mut();
+ let family = resolved_registered_family_name(parley, "Owned").unwrap();
+ let font = parley
.font_context
.collection
- .family_by_name("Owned")
+ .family_by_name(&family)
.unwrap();
assert_eq!(font.fonts()[0].load(None).unwrap().id(), blob_id);
}
@@ -89,10 +90,11 @@ fn owned_and_borrowed_validation_have_the_same_acceptance() {
}
fn source_id(services: &mut ParleyDocumentServices, family: &str) -> parley::fontique::SourceId {
+ let family = resolved_registered_family_name(services, family).unwrap();
services
.font_context
.collection
- .family_by_name(family)
+ .family_by_name(&family)
.unwrap()
.fonts()[0]
.source()
@@ -175,14 +177,19 @@ fn arriving_font_invalidates_a_previously_cached_missing_font_and_metrics() {
TEST_TTF.to_vec(),
))
.unwrap();
+ assert!(services.parley_mut().inline_font_metrics_cache.is_empty());
assert_eq!(
shape_one_character(services.parley_mut(), style.clone(), 'R'),
TEST_TTF
);
+ let mut resolved = style;
+ services
+ .parley_mut()
+ .resolve_font_families(&mut resolved, None);
assert!(
services
.parley_mut()
- .inline_font_metrics(&style, None)
+ .inline_font_metrics(&resolved, None)
.is_some()
);
}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
index 0616d0b79..178bf1a59 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
@@ -42,7 +42,9 @@ pub(super) fn font_face_set_matching_faces_array<'s>(
let ranges = super::loading::string_slot(scope, face_object, FONT_FACE_UNICODE_RANGE_SLOT);
candidates.push(Candidate {
face,
- family: moli_css_parse::unquote_css_string(&family),
+ family: moli_css_parse::font_family_name_key(&moli_css_parse::unquote_css_string(
+ &family,
+ )),
selection: selection::Selection::new(&weight, &stretch, &style),
ranges: crate::css_resource_urls::parse_font_unicode_ranges(&ranges)
.unwrap_or_default(),
@@ -54,9 +56,10 @@ pub(super) fn font_face_set_matching_faces_array<'s>(
let moli_css_parse::CssFontFamily::Named(family) = family else {
continue;
};
+ let family = moli_css_parse::font_family_name_key(&family);
let family_faces = candidates
.iter()
- .filter(|face| family.eq_ignore_ascii_case(&face.family))
+ .filter(|face| family == face.family)
.collect::<Vec<_>>();
let Some(best) = family_faces
.iter()
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
index 0cc62694b..83c48d732 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/matching.rs
@@ -259,3 +259,93 @@ fn font_query_generic_families_do_not_match_named_font_faces() {
assert_eq!(vm.eval("face.status").unwrap(), "error");
}
}
+
+#[test]
+fn font_query_matches_chromium_unicode_case_folding() {
+ for (family, query, matches) in [
+ ("Äpfel", "äpfel", true),
+ ("Σπίτι", "σπίτι", true),
+ ("ΟΣ", "ος", true),
+ ("K", "k", true),
+ ("ẞ", "ß", true),
+ ("µ", "Μ", true),
+ ("Straße", "STRASSE", false),
+ ("Å", "A\u{030a}", false),
+ ("İ", "i", false),
+ ("İ", "i\u{0307}", false),
+ ("𐐀", "𐐨", false),
+ ] {
+ let mut vm = new_storage_test_vm("https://unicode-font-family.test/");
+ vm.eval(&format!(
+ r#"
+ globalThis.face=new FontFace('{family}','url(data:font/ttf;base64,AA==)');
+ face.loaded.catch(()=>{{}});document.fonts.add(face);
+ globalThis.result=[];
+ "#
+ ))
+ .unwrap();
+ let font = format!("16px \"{query}\"");
+ assert_eq!(
+ vm.eval(&format!("document.fonts.check('{font}','A')"))
+ .unwrap(),
+ (!matches).to_string(),
+ "{family} / {query}"
+ );
+ vm.eval(&format!("document.fonts.load('{font}','A').then(faces=>result.push(faces.length),error=>result.push(error.name))")).unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(result)").unwrap(),
+ if matches {
+ r#"["NetworkError"]"#
+ } else {
+ "[0]"
+ },
+ "{family} / {query}"
+ );
+ assert_eq!(
+ vm.eval("face.status").unwrap(),
+ if matches { "error" } else { "unloaded" }
+ );
+ }
+}
+
+#[test]
+fn unicode_font_family_queries_and_layout_use_the_same_matching_key() {
+ let (narrow, wide) = super::selection_order::order_font_data();
+ for (family, query, matches) in [
+ ("Äpfel", "äpfel", true),
+ ("Σπίτι", "σπίτι", true),
+ ("ΟΣ", "ος", true),
+ ("K", "k", true),
+ ("ẞ", "ß", true),
+ ("µ", "Μ", true),
+ ("Straße", "STRASSE", false),
+ ("Å", "A\u{030a}", false),
+ ("İ", "i", false),
+ ("𐐀", "𐐨", false),
+ ] {
+ let mut vm = super::selection_order::order_vm();
+ vm.eval(&format!(
+ r#"
+ const bytes=data=>Uint8Array.from(atob(data),c=>c.charCodeAt(0));
+ globalThis.target=new FontFace('{family}',bytes('{wide}'));
+ document.fonts.add(target);
+ document.fonts.add(new FontFace('FallbackFixture',bytes('{narrow}')));
+ probe.style.fontFamily='"{query}", FallbackFixture';
+ globalThis.matches=false;
+ document.fonts.load('40px "{query}"','A').then(faces=>{{matches=faces[0]===target}});
+ "#
+ ))
+ .unwrap();
+ assert_eq!(
+ vm.eval("matches").unwrap(),
+ matches.to_string(),
+ "{family} / {query}"
+ );
+ assert_eq!(
+ vm.eval("String(probe.getBoundingClientRect().width)")
+ .unwrap(),
+ if matches { "160" } else { "80" },
+ "{family} / {query}"
+ );
+ }
+}