Skip to content

armgit / moli

Public Imported from GitHub
0

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

perf(fonts): reuse payloads and incrementally register faces

ldm0b5c2605ea937
diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rs
index 9809cb06f..af3a86e8c 100644
--- a/moli-layout/src/text.rs
+++ b/moli-layout/src/text.rs
@@ -69,8 +69,9 @@ fn font_selection_capabilities(attributes: Attributes) -> WebFontCapabilities {
#[derive(Clone, Debug)]
struct SegmentedWebFontFace {
+ source_slot: String,
internal_family_name: String,
- source_order: usize,
+ source_priority: (bool, usize),
unicode_ranges: Vec<WebFontUnicodeRange>,
}
@@ -297,7 +298,10 @@ impl ParleyDocumentServices {
})
.flat_map(|group| &group.faces)
.collect::<Vec<_>>();
- faces.sort_by_key(|face| face.source_order);
+ faces.sort_by(|first, second| {
+ (first.source_priority, first.source_slot.as_str())
+ .cmp(&(second.source_priority, second.source_slot.as_str()))
+ });
let default_uses_latin_metrics =
character.is_none() && faces.iter().any(|face| face.contains('x'));
resolved.extend(
@@ -719,10 +723,10 @@ pub enum WebFontRegistrationError {
UnsupportedPayload,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug)]
struct RegisteredWebFont {
face: WebFontFace,
- sfnt_bytes: Arc<[u8]>,
+ sfnt_bytes: Blob<u8>,
stylesheet: bool,
}
@@ -845,6 +849,24 @@ impl DocumentLayoutServices {
.map(|(slot, _)| slot.clone())
.collect::<Vec<_>>();
if current == previous {
+ // Unloaded members can shift indices without changing the current
+ // registered order. Future incremental arrivals use the new indices.
+ if let Some(parley) = self.parley.as_mut() {
+ for family in parley.web_font_families.values_mut() {
+ for group in &mut family.groups {
+ for face in &mut group.faces {
+ face.source_priority = self
+ .web_font_order
+ .get(&face.source_slot)
+ .copied()
+ .unwrap_or((
+ !self.web_fonts[&face.source_slot].stylesheet,
+ usize::MAX,
+ ));
+ }
+ }
+ }
+ }
return false;
}
if self.parley.is_some() {
@@ -870,23 +892,44 @@ impl DocumentLayoutServices {
return Err(WebFontRegistrationError::EmptySlot);
}
registration.face.validate()?;
- let sfnt_bytes = decode_web_font_bytes(&registration.bytes)?;
- validate_registered_font(&registration.face, Arc::clone(&sfnt_bytes))?;
+ let sfnt_bytes = decode_web_font_bytes(registration.bytes)?;
let font = RegisteredWebFont {
face: registration.face,
sfnt_bytes,
stylesheet: registration.stylesheet,
};
let outcome = match self.web_fonts.get(&registration.slot) {
- Some(current) if current == &font => WebFontRegistrationOutcome::Unchanged,
+ Some(current)
+ if current.face == font.face
+ && current.stylesheet == font.stylesheet
+ && current.sfnt_bytes.as_ref() == font.sfnt_bytes.as_ref() =>
+ {
+ WebFontRegistrationOutcome::Unchanged
+ }
Some(_) => WebFontRegistrationOutcome::Replaced,
None => WebFontRegistrationOutcome::Added,
};
if outcome == WebFontRegistrationOutcome::Unchanged {
return Ok(outcome);
}
+ // Fontique's successful registration is the validation for an added
+ // face. Keep it in the live collection instead of trial-registering in
+ // a throwaway collection and then rebuilding every existing family.
+ if outcome == WebFontRegistrationOutcome::Added
+ && let Some(parley) = self.parley.as_mut()
+ {
+ validate_sfnt_table_bounds(font.sfnt_bytes.as_ref())?;
+ parley.register_web_font(&registration.slot, &font, &self.web_font_order)?;
+ self.web_fonts.insert(registration.slot, font);
+ parley.invalidate_font_selection();
+ return Ok(outcome);
+ }
+ validate_registered_font(&font.face, font.sfnt_bytes.clone())?;
self.web_fonts.insert(registration.slot, font);
if self.parley.is_some() {
+ // Replacement still needs a rebuild: Fontique can unregister by
+ // family/attributes, not by our exact source slot. Removing that
+ // match would also remove other unicode-range faces sharing it.
self.parley = Some(Box::new(build_parley_services(
self.system_font_policy,
&self.web_fonts,
@@ -1011,18 +1054,39 @@ fn build_parley_services(
let system_font_family_resolver = system_font_policy
.is_enabled()
.then(|| SystemFontFamilyResolver::new(&mut collection));
- let mut font_context = FontContext {
+ let font_context = FontContext {
collection,
source_cache: Default::default(),
};
- let mut web_font_families = BTreeMap::<String, SegmentedWebFontFamily>::new();
- for (source_order, (_, font)) in ordered_web_fonts(web_fonts, web_font_order)
- .into_iter()
- .enumerate()
- {
- let data: Arc<dyn AsRef<[u8]> + Send + Sync> = Arc::new(Arc::clone(&font.sfnt_bytes));
- let blob = Blob::new(data);
- let selector_fonts = font_context.collection.register_fonts(
+ let mut services = ParleyDocumentServices {
+ font_context,
+ layout_context: LayoutContext::new(),
+ system_font_family_resolver,
+ web_font_families: BTreeMap::new(),
+ font_family_resolution_plans: Vec::new(),
+ inline_font_metrics_cache: Vec::new(),
+ #[cfg(test)]
+ font_family_resolution_miss_count: 0,
+ };
+ for (slot, font) in ordered_web_fonts(web_fonts, web_font_order) {
+ services
+ .register_web_font(slot, font, web_font_order)
+ .expect("retained web fonts passed Fontique registration");
+ }
+ services
+}
+
+impl ParleyDocumentServices {
+ /// Initial population and incremental arrivals use the owner's selection
+ /// order. Stable resource identity never determines FontFaceSet priority.
+ fn register_web_font(
+ &mut self,
+ slot: &str,
+ font: &RegisteredWebFont,
+ 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
@@ -1030,25 +1094,30 @@ fn build_parley_services(
),
);
if selector_fonts.is_empty() {
- continue;
+ return Err(WebFontRegistrationError::UnsupportedPayload);
}
- let internal_family_name = format!("\0moli-web-font:{source_order}");
- if font_context
- .collection
- .register_fonts(
- blob.clone(),
- Some(
- font.face
- .fontique_override_for_family(&internal_family_name),
- ),
- )
- .is_empty()
- {
- continue;
- }
+ // 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}");
+ let internal_fonts = self.font_context.collection.register_fonts(
+ blob.clone(),
+ Some(
+ font.face
+ .fontique_override_for_family(&internal_family_name),
+ ),
+ );
+ assert!(
+ !internal_fonts.is_empty(),
+ "the same font with a nonempty alias must register"
+ );
- let family = web_font_families
+ let source_priority = web_font_order
+ .get(slot)
+ .copied()
+ .unwrap_or((!font.stylesheet, usize::MAX));
+ let family = self
+ .web_font_families
.entry(normalized_web_font_family_name(font.face.family_name()))
.or_default();
for (_, fonts) in selector_fonts {
@@ -1073,58 +1142,45 @@ fn build_parley_services(
index
});
let group = &mut family.groups[group_index];
- if !group
- .faces
- .iter()
- .any(|face| face.internal_family_name == internal_family_name)
- {
- group.faces.push(SegmentedWebFontFace {
- internal_family_name: internal_family_name.clone(),
- source_order,
- unicode_ranges: font.face.unicode_ranges.clone(),
- });
+ if let Err(index) = group.faces.binary_search_by(|face| {
+ (face.source_priority, face.source_slot.as_str()).cmp(&(source_priority, slot))
+ }) {
+ group.faces.insert(
+ index,
+ SegmentedWebFontFace {
+ source_slot: slot.to_owned(),
+ source_priority,
+ internal_family_name: internal_family_name.clone(),
+ unicode_ranges: font.face.unicode_ranges.clone(),
+ },
+ );
}
}
}
+ Ok(())
}
- ParleyDocumentServices {
- font_context,
- layout_context: LayoutContext::new(),
- system_font_family_resolver,
- web_font_families,
- font_family_resolution_plans: Vec::new(),
- inline_font_metrics_cache: Vec::new(),
- #[cfg(test)]
- font_family_resolution_miss_count: 0,
- }
-}
-fn register_font(font_context: &mut FontContext, font: &RegisteredWebFont) -> bool {
- let data: Arc<dyn AsRef<[u8]> + Send + Sync> = Arc::new(Arc::clone(&font.sfnt_bytes));
- !font_context
- .collection
- .register_fonts(
- Blob::new(data),
- Some(
- font.face
- .fontique_override_for_family(font.face.family_name()),
- ),
- )
- .is_empty()
+ fn invalidate_font_selection(&mut self) {
+ self.font_family_resolution_plans.clear();
+ self.inline_font_metrics_cache.clear();
+ // A family which previously needed a platform substitution may now
+ // have its own downloaded face. Keep the platform inventory, but do
+ // not let the old substitution bypass that face.
+ if let Some(resolver) = self.system_font_family_resolver.as_mut() {
+ resolver.invalidate_substitutions();
+ }
+ }
}
fn normalized_web_font_family_name(name: &str) -> String {
name.chars().flat_map(char::to_lowercase).collect()
}
-fn validate_registered_font(
- face: &WebFontFace,
- sfnt_bytes: Arc<[u8]>,
-) -> Result<(), WebFontRegistrationError> {
+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
// before accepting either a single SFNT font or a font collection.
- let file = read_fonts::FileRef::new(&sfnt_bytes)
+ let file = read_fonts::FileRef::new(sfnt_bytes)
.map_err(|_| WebFontRegistrationError::UnsupportedPayload)?;
for font in file.fonts() {
let font = font.map_err(|_| WebFontRegistrationError::UnsupportedPayload)?;
@@ -1138,39 +1194,44 @@ fn validate_registered_font(
}
}
}
- let mut font_context = FontContext {
- collection: Collection::new(CollectionOptions {
- shared: false,
- system_fonts: false,
- }),
- source_cache: Default::default(),
- };
- let font = RegisteredWebFont {
- face: face.clone(),
- sfnt_bytes,
- stylesheet: false,
- };
- register_font(&mut font_context, &font)
- .then_some(())
- .ok_or(WebFontRegistrationError::UnsupportedPayload)
+ Ok(())
}
-/// Validate font bytes without registering them in a document's layout.
-pub fn validate_web_font_bytes(bytes: &[u8]) -> Result<(), WebFontRegistrationError> {
- validate_registered_font(&WebFontFace::new("FontFace"), decode_web_font_bytes(bytes)?)
+fn validate_registered_font(
+ face: &WebFontFace,
+ sfnt_bytes: Blob<u8>,
+) -> Result<(), WebFontRegistrationError> {
+ validate_sfnt_table_bounds(sfnt_bytes.as_ref())?;
+ let mut collection = Collection::new(CollectionOptions {
+ shared: false,
+ system_fonts: false,
+ });
+ (!collection
+ .register_fonts(
+ sfnt_bytes,
+ Some(face.fontique_override_for_family(face.family_name())),
+ )
+ .is_empty())
+ .then_some(())
+ .ok_or(WebFontRegistrationError::UnsupportedPayload)
}
-fn decode_web_font_bytes(bytes: &[u8]) -> Result<Arc<[u8]>, WebFontRegistrationError> {
+fn decode_web_font_bytes<'a>(
+ bytes: impl Into<Cow<'a, [u8]>>,
+) -> Result<Blob<u8>, WebFontRegistrationError> {
+ let bytes = bytes.into();
let decoded = match bytes.get(..4) {
- Some(b"wOFF") => wuff::decompress_woff1(bytes)
+ Some(b"wOFF") => wuff::decompress_woff1(&bytes)
.map_err(|_| WebFontRegistrationError::DecodeFailed { format: "WOFF" })?,
Some(b"wOF2") => {
- wuff::decompress_woff2_with_custom_brotli(bytes, &mut decompress_woff2_brotli)
+ wuff::decompress_woff2_with_custom_brotli(&bytes, &mut decompress_woff2_brotli)
.map_err(|_| WebFontRegistrationError::DecodeFailed { format: "WOFF2" })?
}
- _ => bytes.to_vec(),
+ _ => bytes.into_owned(),
};
- Ok(Arc::from(decoded))
+ // Own the Vec, not an Arc<[u8]> made by copying it. An owned SFNT response
+ // moves here unchanged; WOFF decoders likewise donate their output buffer.
+ Ok(Blob::new(Arc::new(decoded)))
}
fn decompress_woff2_brotli(
@@ -1187,10 +1248,31 @@ fn decompress_woff2_brotli(
Ok(output)
}
+/// Validates a downloadable font payload without retaining it in a document.
+///
+/// `FontFace` BufferSource and data-URL inputs must use the same decoder and
+/// OpenType registration checks as stylesheet-backed fonts. A MIME or magic
+/// byte sniff alone accepts truncated WOFF/WOFF2 payloads that can never be
+/// shaped.
+/// Owned inputs transfer their buffer without a payload copy. Borrowed inputs
+/// remain supported for callers which need to retain the original bytes.
+pub fn validate_web_font_bytes<'a>(
+ bytes: impl Into<Cow<'a, [u8]>>,
+) -> Result<(), WebFontRegistrationError> {
+ let face = WebFontFace::new("__moli-font-validation__");
+ let sfnt_bytes = decode_web_font_bytes(bytes)?;
+ validate_registered_font(&face, sfnt_bytes)
+}
+
+#[cfg(test)]
+mod benchmarks;
+
#[cfg(test)]
mod tests {
use super::*;
+ mod registration;
+
const TEST_TTF: &[u8] = include_bytes!("../tests/fixtures/moli-ahem.ttf");
const TEST_CJK_TTF: &[u8] = include_bytes!("../tests/fixtures/moli-cjk.ttf");
const TEST_WOFF: &[u8] = include_bytes!("../tests/fixtures/moli-ahem.woff");
@@ -1299,14 +1381,12 @@ mod tests {
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),
- stylesheet: false,
- },
- ));
+ let face = WebFontFace::new("Moli Ahem");
+ let registered = parley.font_context.collection.register_fonts(
+ decode_web_font_bytes(TEST_TTF).unwrap(),
+ Some(face.fontique_override_for_family(face.family_name())),
+ );
+ assert!(!registered.is_empty());
let families = FontFamily::List(Cow::Owned(vec![
FontFamilyName::Named(Cow::Borrowed("__moli_missing_css_family_order_3d16__")),
FontFamilyName::Named(Cow::Borrowed("Moli Ahem")),
@@ -1323,9 +1403,10 @@ mod tests {
}
#[test]
- fn font_collection_rebuild_discards_resolution_and_metrics_caches() {
+ fn font_registration_discards_selection_caches_without_rebuilding_context() {
let mut services =
DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ let context_address = std::ptr::from_ref(&services.parley_mut().font_context);
{
let parley = services.parley_mut();
let mut style = TextStyle::default();
@@ -1345,7 +1426,8 @@ mod tests {
let parley = services.parley_mut();
assert!(parley.font_family_resolution_plans.is_empty());
assert!(parley.inline_font_metrics_cache.is_empty());
- assert_eq!(parley.font_family_resolution_miss_count, 0);
+ assert_eq!(parley.font_family_resolution_miss_count, 1);
+ assert_eq!(context_address, std::ptr::from_ref(&parley.font_context));
}
#[test]
@@ -1695,7 +1777,10 @@ mod tests {
for padding in 1..=3 {
let mut padded_font = TEST_WOFF2.to_vec();
padded_font[20..24].copy_from_slice(&(compressed_size + padding).to_be_bytes());
- assert_eq!(decode_web_font_bytes(&padded_font).unwrap(), expected);
+ assert_eq!(
+ decode_web_font_bytes(&padded_font).unwrap().as_ref(),
+ expected.as_ref()
+ );
}
}
diff --git a/moli-layout/src/text/benchmarks.rs b/moli-layout/src/text/benchmarks.rs
new file mode 100644
index 000000000..26b787ac8
--- /dev/null
+++ b/moli-layout/src/text/benchmarks.rs
@@ -0,0 +1,109 @@
+//! Opt-in, release-mode font-loading measurements. No wall-clock assertions.
+//!
+//! cargo test -p moli-layout --release --lib text::benchmarks::font_loading \
+//! -- --ignored --nocapture
+//! MOLI_FONT_BENCH_EXTRA may name one additional local font (read before timing).
+
+use std::{hint::black_box, time::Instant};
+
+use super::*;
+
+const SAMPLES: usize = 7;
+
+fn median_ms(mut sample: impl FnMut() -> f64) -> f64 {
+ // Warm code/data separately from the measured samples.
+ black_box(sample());
+ let mut samples: Vec<_> = (0..SAMPLES).map(|_| sample()).collect();
+ samples.sort_by(f64::total_cmp);
+ samples[SAMPLES / 2]
+}
+
+fn batch_registration(bytes: &[u8], count: usize, initialized: bool, unchanged: bool) -> f64 {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ if initialized {
+ black_box(services.parley_mut());
+ }
+ let registrations: Vec<_> = (0..count)
+ .map(|index| {
+ let index = if unchanged { 0 } else { index };
+ WebFontRegistration::new(
+ format!("slot-{index:04}"),
+ WebFontFace::new(format!("Family {index:04}")),
+ bytes.to_vec(),
+ )
+ })
+ .collect();
+ if unchanged {
+ services
+ .register_web_font(registrations[0].clone())
+ .unwrap();
+ }
+ // Payload copies, context initialization and destruction are not timed.
+ let start = Instant::now();
+ for registration in registrations {
+ black_box(services.register_web_font(black_box(registration)).unwrap());
+ }
+ let elapsed = start.elapsed().as_secs_f64() * 1000.0;
+ assert_eq!(services.web_font_count(), if unchanged { 1 } else { count });
+ black_box(&services);
+ elapsed
+}
+
+#[test]
+#[ignore = "opt-in release microbenchmark; not a correctness or CI timing gate"]
+fn font_loading() {
+ let mut fonts = vec![
+ (
+ "ahem-ttf".to_owned(),
+ include_bytes!("../../tests/fixtures/moli-ahem.ttf").to_vec(),
+ ),
+ (
+ "ahem-woff".to_owned(),
+ include_bytes!("../../tests/fixtures/moli-ahem.woff").to_vec(),
+ ),
+ (
+ "ahem-woff2".to_owned(),
+ include_bytes!("../../tests/fixtures/moli-ahem.woff2").to_vec(),
+ ),
+ ];
+ if let Some(path) = std::env::var_os("MOLI_FONT_BENCH_EXTRA") {
+ fonts.push((
+ path.to_string_lossy().into_owned(),
+ std::fs::read(path).unwrap(),
+ ));
+ }
+ println!("font,bytes,operation,count,median_ms");
+ for (name, bytes) in fonts {
+ let iterations = if bytes.len() > 1_000_000 { 8 } else { 128 };
+ for (operation, validate) in [("decode", false), ("validate", true)] {
+ let elapsed = median_ms(|| {
+ let start = Instant::now();
+ for _ in 0..iterations {
+ if validate {
+ validate_web_font_bytes(black_box(&bytes)).unwrap();
+ } else {
+ black_box(decode_web_font_bytes(black_box(&bytes)).unwrap());
+ }
+ }
+ start.elapsed().as_secs_f64() * 1000.0 / iterations as f64
+ });
+ println!("{name},{},{operation},1,{elapsed:.6}", bytes.len());
+ }
+ let counts: &[usize] = if bytes.len() > 1_000_000 {
+ &[1, 4, 8]
+ } else {
+ &[1, 16, 64, 128]
+ };
+ for &count in counts {
+ for (operation, initialized, unchanged) in [
+ ("register-lazy", false, false),
+ ("register-initialized", true, false),
+ ("register-unchanged", true, true),
+ ] {
+ let elapsed =
+ median_ms(|| batch_registration(&bytes, count, initialized, unchanged));
+ println!("{name},{},{operation},{count},{elapsed:.6}", bytes.len());
+ }
+ }
+ }
+}
diff --git a/moli-layout/src/text/font_source.rs b/moli-layout/src/text/font_source.rs
index 6ed9647e8..1f91f526b 100644
--- a/moli-layout/src/text/font_source.rs
+++ b/moli-layout/src/text/font_source.rs
@@ -10,7 +10,7 @@ use super::*;
/// One decoded, validated SFNT face, ready for document registration.
#[derive(Clone, Debug)]
pub struct FontFaceData {
- pub(super) bytes: Arc<[u8]>,
+ pub(super) bytes: Blob<u8>,
}
impl FontFaceData {
@@ -19,8 +19,8 @@ impl FontFaceData {
Self::from_index(bytes, 0)
}
- fn from_index(bytes: Arc<[u8]>, index: u32) -> Result<Self, WebFontRegistrationError> {
- let font = FontRef::from_index(&bytes, index)
+ fn from_index(bytes: Blob<u8>, index: u32) -> Result<Self, WebFontRegistrationError> {
+ let font = FontRef::from_index(bytes.as_ref(), index)
.map_err(|_| WebFontRegistrationError::UnsupportedPayload)?;
let bytes = if font.ttc_index().is_some() {
standalone_face(&font).ok_or(WebFontRegistrationError::UnsupportedPayload)?
@@ -32,13 +32,13 @@ impl FontFaceData {
}
pub fn bytes(&self) -> &[u8] {
- &self.bytes
+ self.bytes.as_ref()
}
}
// Fontique registers every member of a collection. Extract the selected local
// face first so a CSS alias cannot accidentally refer to another TTC member.
-fn standalone_face(font: &FontRef<'_>) -> Option<Arc<[u8]>> {
+fn standalone_face(font: &FontRef<'_>) -> Option<Blob<u8>> {
let directory = font.table_directory();
let mut records = directory.table_records().to_vec();
records.retain(|record| record.tag() != read_fonts::types::Tag::new(b"DSIG"));
@@ -79,7 +79,7 @@ fn standalone_face(font: &FontRef<'_>) -> Option<Arc<[u8]>> {
let head = head_offset?;
let adjustment = 0xb1b0_afba_u32.wrapping_sub(sfnt_checksum(&bytes));
bytes[head + 8..head + 12].copy_from_slice(&adjustment.to_be_bytes());
- Some(Arc::from(bytes))
+ Some(Blob::new(Arc::new(bytes)))
}
fn sfnt_checksum(bytes: &[u8]) -> u32 {
@@ -153,7 +153,7 @@ impl LocalFontSources {
}
let info = self.names.as_ref()?.get(&name.to_lowercase())?;
let data = info.load(Some(&mut self.cache))?;
- FontFaceData::from_index(Arc::from(data.as_ref()), info.index()).ok()
+ FontFaceData::from_index(data, info.index()).ok()
}
}
@@ -237,7 +237,8 @@ mod tests {
}
for (index, original) in fonts.iter().enumerate() {
let selected =
- FontFaceData::from_index(Arc::from(collection.as_slice()), index as u32).unwrap();
+ FontFaceData::from_index(Blob::new(Arc::new(collection.clone())), index as u32)
+ .unwrap();
let font = FontRef::new(selected.bytes()).unwrap();
assert!(font.ttc_index().is_none());
assert_eq!(
diff --git a/moli-layout/src/text/tests/registration.rs b/moli-layout/src/text/tests/registration.rs
new file mode 100644
index 000000000..5f889f41e
--- /dev/null
+++ b/moli-layout/src/text/tests/registration.rs
@@ -0,0 +1,374 @@
+use super::*;
+
+#[test]
+fn incremental_font_registration_retains_sfnt_table_bounds_validation() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services
+ .register_web_font(WebFontRegistration::new(
+ "stable",
+ WebFontFace::new("Stable"),
+ TEST_TTF.to_vec(),
+ ))
+ .unwrap();
+ services.parley_mut();
+
+ let mut bytes = TEST_TTF.to_vec();
+ let table_count = u16::from_be_bytes(bytes[4..6].try_into().unwrap()) as usize;
+ let record = (0..table_count)
+ .map(|index| 12 + index * 16)
+ .find(|offset| &bytes[*offset..*offset + 4] == b"post")
+ .expect("the fixture has an optional post table");
+ let outside = u32::try_from(bytes.len() + 1).unwrap();
+ bytes[record + 8..record + 12].copy_from_slice(&outside.to_be_bytes());
+ assert!(matches!(
+ services.register_web_font(WebFontRegistration::new(
+ "invalid",
+ WebFontFace::new("Rejected"),
+ bytes,
+ )),
+ Err(WebFontRegistrationError::UnsupportedPayload)
+ ));
+ assert_eq!(services.web_font_count(), 1);
+ assert!(
+ services
+ .parley_mut()
+ .font_context
+ .collection
+ .family_by_name("Rejected")
+ .is_none()
+ );
+}
+
+#[test]
+fn owned_sfnt_payload_is_retained_without_copying_its_buffer() {
+ // Spare capacity must not force a shrink/copy either.
+ let mut bytes = Vec::with_capacity(TEST_TTF.len() * 2);
+ bytes.extend_from_slice(TEST_TTF);
+ let original_buffer = bytes.as_ptr();
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services
+ .register_web_font(WebFontRegistration::new(
+ "owned",
+ WebFontFace::new("Owned"),
+ bytes,
+ ))
+ .unwrap();
+ let retained = &services.web_fonts["owned"].sfnt_bytes;
+ assert_eq!(retained.as_ref().as_ptr(), original_buffer);
+ let blob_id = retained.id();
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Owned", 400.0), 'R'),
+ TEST_TTF
+ );
+ let font = services
+ .parley_mut()
+ .font_context
+ .collection
+ .family_by_name("Owned")
+ .unwrap();
+ assert_eq!(font.fonts()[0].load(None).unwrap().id(), blob_id);
+}
+
+#[test]
+fn owned_and_borrowed_validation_have_the_same_acceptance() {
+ for bytes in [
+ TEST_TTF,
+ TEST_WOFF,
+ TEST_WOFF2,
+ TEST_CJK_TTF,
+ b"garbage",
+ b"wOFFbad",
+ b"wOF2bad",
+ b"",
+ ] {
+ assert_eq!(
+ validate_web_font_bytes(bytes),
+ validate_web_font_bytes(bytes.to_vec())
+ );
+ }
+}
+
+fn source_id(services: &mut ParleyDocumentServices, family: &str) -> parley::fontique::SourceId {
+ services
+ .font_context
+ .collection
+ .family_by_name(family)
+ .unwrap()
+ .fonts()[0]
+ .source()
+ .id
+}
+
+#[test]
+fn incremental_arrivals_do_not_reregister_old_fonts_or_replace_contexts() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services.parley_mut();
+ services
+ .register_web_font(registration("seed", "Seed", TEST_TTF))
+ .unwrap();
+ let context_address = std::ptr::from_ref(&services.parley_mut().font_context);
+ let layout_address = std::ptr::from_ref(&services.parley_mut().layout_context);
+ let original_source = source_id(services.parley_mut(), "Seed");
+ for index in (0..128).rev() {
+ let slot = format!("{index:03}");
+ let family = format!("Family {index}");
+ services
+ .register_web_font(registration(&slot, &family, TEST_TTF))
+ .unwrap();
+ let parley = services.parley_mut();
+ assert_eq!(
+ source_id(parley, "Seed"),
+ original_source,
+ "Fontique source must not be re-registered"
+ );
+ assert_eq!(context_address, std::ptr::from_ref(&parley.font_context));
+ assert_eq!(layout_address, std::ptr::from_ref(&parley.layout_context));
+ }
+ assert_eq!(services.web_font_count(), 129);
+}
+
+#[test]
+fn invalid_incremental_arrival_leaves_fonts_and_selection_caches_untouched() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services
+ .register_web_font(registration("seed", "Seed", TEST_TTF))
+ .unwrap();
+ let original_source = source_id(services.parley_mut(), "Seed");
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Seed", 625.0), 'R'),
+ TEST_TTF
+ );
+ let plan_count = services.parley_mut().font_family_resolution_plans.len();
+ for bytes in [b"garbage".as_slice(), b"wOF2bad", &TEST_TTF[..32]] {
+ assert!(
+ services
+ .register_web_font(registration("bad", "Invalid Arrival", bytes))
+ .is_err()
+ );
+ assert_eq!(services.web_font_count(), 1);
+ assert_eq!(source_id(services.parley_mut(), "Seed"), original_source);
+ assert_eq!(
+ services.parley_mut().font_family_resolution_plans.len(),
+ plan_count
+ );
+ assert!(!has_family(&mut services, "Invalid Arrival"));
+ }
+}
+
+#[test]
+fn arriving_font_invalidates_a_previously_cached_missing_font_and_metrics() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ let style = web_font_style("Arriving", 400.0);
+ services
+ .parley_mut()
+ .resolve_font_families(&mut style.clone(), Some('R'));
+ assert!(
+ services
+ .parley_mut()
+ .inline_font_metrics(&style, None)
+ .is_none()
+ );
+ services
+ .register_web_font(WebFontRegistration::new(
+ "arrival",
+ WebFontFace::new("Arriving"),
+ TEST_TTF.to_vec(),
+ ))
+ .unwrap();
+ assert_eq!(
+ shape_one_character(services.parley_mut(), style.clone(), 'R'),
+ TEST_TTF
+ );
+ assert!(
+ services
+ .parley_mut()
+ .inline_font_metrics(&style, None)
+ .is_some()
+ );
+}
+
+#[test]
+fn out_of_order_incremental_selection_matches_a_fresh_ordered_collection() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services.parley_mut();
+ services
+ .register_web_font(registration("unrelated", "Unrelated", TEST_TTF))
+ .unwrap();
+ let unrelated_source = source_id(services.parley_mut(), "Unrelated");
+ let context_address = std::ptr::from_ref(&services.parley_mut().font_context);
+ let faces = [
+ WebFontFace::new("Shared").with_weight(400.0),
+ WebFontFace::new("Shared").with_weight(700.0),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_style(WebFontStyle::Italic),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_style(WebFontStyle::Oblique(None)),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_style(WebFontStyle::Oblique(Some(14.0))),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_stretch(75.0),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_unicode_ranges([WebFontUnicodeRange::new(0x4e00, 0x9fff)]),
+ WebFontFace::new("Shared")
+ .with_weight(400.0)
+ .with_unicode_ranges([WebFontUnicodeRange::new(0, 0xff)]),
+ WebFontFace::new("Shared").with_css_descriptors("100 900", "normal", "normal"),
+ WebFontFace::new("Shared").with_css_descriptors("400", "75% 125%", "normal"),
+ WebFontFace::new("Shared").with_css_descriptors("400", "normal", "oblique 10deg 30deg"),
+ ];
+ for index in [4, 8, 3, 7, 2, 10, 6, 0, 9, 5, 1] {
+ services
+ .register_web_font(WebFontRegistration::new(
+ format!("slot-{index}"),
+ faces[index].clone(),
+ TEST_TTF.to_vec(),
+ ))
+ .unwrap();
+ assert_eq!(
+ source_id(services.parley_mut(), "Unrelated"),
+ unrelated_source
+ );
+ assert_eq!(
+ std::ptr::from_ref(&services.parley_mut().font_context),
+ context_address
+ );
+ let mut fresh = build_parley_services(
+ SystemFontPolicy::Disabled,
+ &services.web_fonts,
+ &services.web_font_order,
+ );
+ for weight in [100.0, 400.0, 500.0, 625.0, 700.0, 900.0] {
+ for font_style in [
+ FontStyle::Normal,
+ FontStyle::Italic,
+ FontStyle::Oblique(None),
+ FontStyle::Oblique(Some(14.0)),
+ FontStyle::Oblique(Some(-10.0)),
+ ] {
+ for width in [75.0, 100.0, 125.0] {
+ for character in [None, Some('R'), Some('中')] {
+ let mut incremental_style = web_font_style("Shared", weight);
+ incremental_style.font_style = font_style;
+ incremental_style.font_width = FontWidth::from_percentage(width);
+ let mut fresh_style = incremental_style.clone();
+ services
+ .parley_mut()
+ .resolve_font_families(&mut incremental_style, character);
+ fresh.resolve_font_families(&mut fresh_style, character);
+ assert_eq!(
+ incremental_style.font_family, fresh_style.font_family,
+ "after slot-{index}, weight={weight}, style={font_style:?}, width={width}, char={character:?}"
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn incremental_ranges_refresh_priorities_after_unloaded_members_are_removed() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ let narrow = include_bytes!("../../../tests/fixtures/moli-ahem-narrow.ttf");
+ let wide = include_bytes!("../../../tests/fixtures/moli-ahem-wide.ttf");
+ services.set_web_font_order(&[], &["unloaded".into(), "z-wide".into()]);
+ services
+ .register_web_font(WebFontRegistration::new(
+ "z-wide",
+ WebFontFace::new("Shifted").with_css_descriptors("100 900", "normal", "normal"),
+ wide.to_vec(),
+ ))
+ .unwrap();
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Shifted", 700.0), 'A'),
+ wide
+ );
+ let context_address = std::ptr::from_ref(&services.parley_mut().font_context);
+ assert!(!services.set_web_font_order(&[], &["z-wide".into(), "a-narrow".into()]));
+ services
+ .register_web_font(WebFontRegistration::new(
+ "a-narrow",
+ WebFontFace::new("Shifted").with_css_descriptors("500 800", "normal", "normal"),
+ narrow.to_vec(),
+ ))
+ .unwrap();
+ assert_eq!(
+ std::ptr::from_ref(&services.parley_mut().font_context),
+ context_address
+ );
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Shifted", 700.0), 'A'),
+ narrow
+ );
+}
+
+#[test]
+fn replacement_and_removal_preserve_other_same_capability_slots() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services.parley_mut();
+ for slot in ["a", "b"] {
+ services
+ .register_web_font(registration(slot, "Shared", TEST_TTF))
+ .unwrap();
+ }
+ services
+ .register_web_font(registration("a", "Replacement", TEST_CJK_TTF))
+ .unwrap();
+ assert!(has_family(&mut services, "Shared"));
+ assert!(has_family(&mut services, "Replacement"));
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Shared", 625.0), 'R'),
+ TEST_TTF
+ );
+ assert!(services.remove_web_font("a"));
+ assert!(!has_family(&mut services, "Replacement"));
+ assert_eq!(
+ shape_one_character(services.parley_mut(), web_font_style("Shared", 625.0), 'R'),
+ TEST_TTF
+ );
+ assert!(services.remove_web_font("b"));
+ assert!(!has_family(&mut services, "Shared"));
+}
+
+#[test]
+fn unchanged_bytes_still_replace_changed_stylesheet_scope() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services
+ .register_web_font(registration("same", "Same", TEST_TTF))
+ .unwrap();
+ for stylesheet in [true, false] {
+ let mut registration = registration("same", "Same", TEST_TTF);
+ if stylesheet {
+ registration = registration.with_stylesheet_scope();
+ }
+ assert_eq!(
+ services.register_web_font(registration),
+ Ok(WebFontRegistrationOutcome::Replaced)
+ );
+ services.with_active_stylesheet_fonts(
+ |_| false,
+ |selected| assert_eq!(selected.web_font_count(), usize::from(!stylesheet)),
+ );
+ }
+}
+
+#[test]
+fn unchanged_bytes_do_not_depend_on_blob_allocation_identity() {
+ let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
+ services
+ .register_web_font(registration("same", "Same", TEST_TTF))
+ .unwrap();
+ let source = source_id(services.parley_mut(), "Same");
+ for _ in 0..4 {
+ assert_eq!(
+ services.register_web_font(registration("same", "Same", TEST_TTF)),
+ Ok(WebFontRegistrationOutcome::Unchanged)
+ );
+ assert_eq!(source_id(services.parley_mut(), "Same"), source);
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
index 36d660e63..3e96b3fe4 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
@@ -1415,6 +1415,51 @@ fn css_owner_changes_prepare_font_projections_only_for_exposed_collections() {
assert_eq!(vm.eval("lazyStyle.remove(); [heldFonts.size, heldSheets.length, heldFonts === document.fonts].join('|')").unwrap(), "0|0|true");
}
+#[test]
+fn font_face_owned_binary_and_data_url_validation_accept_real_fonts() {
+ let mut vm = new_storage_test_vm("https://font-face-owned-validation.test/");
+ for bytes in [
+ include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../moli-layout/tests/fixtures/moli-ahem.ttf"
+ ))
+ .as_slice(),
+ include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../moli-layout/tests/fixtures/moli-ahem.woff2"
+ ))
+ .as_slice(),
+ ] {
+ let input = serde_json::to_string(bytes).unwrap();
+ vm.eval(&format!(
+ r#"
+(() => {{
+ const bytes = Uint8Array.from({input});
+ const url = 'data:application/octet-stream;base64,' + btoa(String.fromCharCode(...bytes));
+ const faces = [new FontFace('Binary', bytes), new FontFace('DataUrl', `url("${{url}}")`)];
+ globalThis.__ownedFontProbe = {{
+ status: faces.map(face => face.status),
+ promises: faces.map(face => face.load() === face.loaded),
+ settled: ['pending', 'pending'],
+ inputIntact: bytes.length === {length} && bytes[0] === {first}
+ }};
+ faces.forEach((face, index) => face.loaded.then(
+ () => {{ __ownedFontProbe.settled[index] = 'loaded'; }},
+ error => {{ __ownedFontProbe.settled[index] = error.name; }}
+ ));
+}})()
+"#,
+ length = bytes.len(),
+ first = bytes[0],
+ ))
+ .expect("owned font payloads should validate");
+ assert_eq!(
+ vm.eval("JSON.stringify(__ownedFontProbe)").unwrap(),
+ r#"{"status":["loaded","unloaded"],"promises":[true,true],"settled":["loaded","loaded"],"inputIntact":true}"#
+ );
+ }
+}
+
#[test]
fn font_face_rejects_malformed_string_and_magic_prefixed_payloads() {
let mut vm = new_storage_test_vm("https://font-face-payload-validation.test/");
diff --git a/moli-system-fonts/src/lib.rs b/moli-system-fonts/src/lib.rs
index 3b387ea92..08af9983b 100644
--- a/moli-system-fonts/src/lib.rs
+++ b/moli-system-fonts/src/lib.rs
@@ -24,7 +24,8 @@ mod platform;
/// 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.
+/// when rebuilding the collection; invalidate substitutions when adding fonts
+/// after a cached lookup.
pub struct SystemFontFamilyResolver {
system_families: HashMap<String, String>,
substitutions: HashMap<String, Option<String>>,
@@ -33,6 +34,11 @@ pub struct SystemFontFamilyResolver {
}
impl SystemFontFamilyResolver {
+ /// Clears cached matches after font arrival without rescanning system families.
+ pub fn invalidate_substitutions(&mut self) {
+ self.substitutions.clear();
+ }
+
/// Snapshots the collection's system family names without performing matching.
pub fn new(collection: &mut Collection) -> Self {
let system_families = collection
@@ -102,6 +108,22 @@ mod platform {
mod tests {
use super::*;
+ #[test]
+ fn font_arrival_clears_substitutions_but_preserves_the_platform_inventory() {
+ let mut resolver = SystemFontFamilyResolver {
+ system_families: HashMap::from([("fallback".to_owned(), "Fallback".to_owned())]),
+ substitutions: HashMap::from([
+ ("arriving".to_owned(), Some("Fallback".to_owned())),
+ ("missing".to_owned(), None),
+ ]),
+ family_lookup_count: 2,
+ };
+ resolver.invalidate_substitutions();
+ assert!(resolver.substitutions.is_empty());
+ assert_eq!(resolver.system_families["fallback"], "Fallback");
+ assert_eq!(resolver.family_lookup_count, 2);
+ }
+
#[test]
fn successful_family_lookup_is_cached() {
let mut collection = Collection::new(fontique::CollectionOptions {