diff --git a/moli-css-parse/src/font_face.rs b/moli-css-parse/src/font_face.rs index 771ab297722..6eed2497797 100644 --- a/moli-css-parse/src/font_face.rs +++ b/moli-css-parse/src/font_face.rs @@ -1,7 +1,5 @@ use cssparser::{Parser, Token}; -use crate::unquote_css_string; - pub use style::moli_font_face::{CssFontFace, normalize_font_face_src, parse_font_faces}; #[derive(Clone, Debug, PartialEq, Eq)] @@ -204,24 +202,46 @@ pub fn font_load_query_is_valid(query: &str) -> bool { } pub fn font_load_query_family(query: &str) -> Option { - let trimmed = query.trim(); - if trimmed.is_empty() { - return None; - } - let mut quote = None; - let mut last_ws = None; - for (index, ch) in trimmed.char_indices() { - match ch { - '\'' | '"' if quote == Some(ch) => quote = None, - '\'' | '"' if quote.is_none() => quote = Some(ch), - _ if quote.is_none() && ch.is_whitespace() => last_ws = Some(index), - _ => {} - } - } - let family = last_ws - .map(|index| trimmed[index..].trim()) - .unwrap_or(trimmed); - Some(unquote_css_string(family)) + font_load_query_families(query) + .or_else(|| parse_font_family_list(query))? + .pop() +} + +/// Extract literal family names from a font shorthand. +/// Stylo expands the shorthand; CSS tokens decode quoted names and escapes. +/// Unquoted generic families do not identify a user-provided FontFace. +pub fn font_load_query_families(query: &str) -> Option> { + let mut block = crate::CssDeclarationBlock::default(); + let projection = block.set_property_with_projection("font", query, false); + let family_text = (projection.set_result != crate::CssSetResult::ParseError + && !projection.has_unresolved_value) + .then(|| block.property_value("font-family")) + .flatten()?; + parse_font_family_list(&family_text) +} + +fn parse_font_family_list(input: &str) -> Option> { + let mut parser = Parser::new(input); + let families = parser + .parse_comma_separated::<_, _, ()>(|input| { + if let Ok(name) = input.try_parse(|input| input.expect_string_cloned()) { + input.expect_exhausted()?; + return Ok(Some(name.to_string())); + } + let start = input.position(); + let mut parts = vec![input.expect_ident_cloned()?.to_string()]; + while !input.is_exhausted() { + parts.push(input.expect_ident_cloned()?.to_string()); + } + let named = crate::parse_font_face_descriptor_entry_with_stylo( + "font-family", + input.slice_from(start), + ) + .is_some(); + Ok(named.then(|| parts.join(" "))) + }) + .ok()?; + Some(families.into_iter().flatten().collect()) } fn is_css_wide_keyword(value: &str) -> bool { @@ -488,11 +508,30 @@ mod tests { )); assert_eq!( font_load_query_family(r#"italic small-caps bold 16px/2 "A B", serif"#).as_deref(), - Some("serif") + Some("A B") ); assert_eq!( font_load_query_family(r#""Standalone Family""#).as_deref(), Some("Standalone Family") ); + assert_eq!( + super::font_load_query_families( + r#"italic bold 16px/2 "A, B", Literal\ Family, "Literal\"Quote", serif"# + ), + Some(vec![ + "A, B".to_owned(), + "Literal Family".to_owned(), + "Literal\"Quote".to_owned(), + ]) + ); + assert_eq!( + super::font_load_query_families(r#"16px "sans-serif", sans-serif"#), + Some(vec!["sans-serif".to_owned()]) + ); + assert_eq!( + super::font_load_query_families(r#"16px "a\0 b""#), + Some(vec!["a\u{fffd}b".to_owned()]) + ); + assert_eq!(super::font_load_query_families("caption"), None); } } diff --git a/moli-css-parse/src/font_family.rs b/moli-css-parse/src/font_family.rs new file mode 100644 index 00000000000..28c8cb67967 --- /dev/null +++ b/moli-css-parse/src/font_family.rs @@ -0,0 +1,107 @@ +/// Whether a literal FontFace family needs CSS string serialization. +/// +/// Family names are literal names, so backslashes and quotes in the input +/// are not CSS syntax to parse or unescape. +pub fn font_family_name_needs_quotes(name: &[u16]) -> bool { + let ident = name.strip_prefix(&[b'-' as u16]).unwrap_or(name); + let name_start = |unit: u16| { + unit >= 0x80 + || unit == b'_' as u16 + || (b'a' as u16..=b'z' as u16).contains(&unit) + || (b'A' as u16..=b'Z' as u16).contains(&unit) + }; + if !ident.first().is_some_and(|unit| name_start(*unit)) + || !ident.iter().all(|unit| { + name_start(*unit) || *unit == b'-' as u16 || (b'0' as u16..=b'9' as u16).contains(unit) + }) + { + return true; + } + let text = String::from_utf16_lossy(name); + [ + "initial", + "inherit", + "unset", + "revert", + "revert-layer", + "default", + ] + .iter() + .any(|keyword| text.eq_ignore_ascii_case(keyword)) + || matches!( + text.as_str(), + "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui" | "math" + ) +} + +/// Serialize a literal FontFace family without interpreting it as CSS input. +pub fn serialize_font_family_name_utf16(name: &[u16]) -> Vec { + if !font_family_name_needs_quotes(name) { + return name.to_vec(); + } + let mut output = Vec::with_capacity(name.len() + 2); + output.push(b'"' as u16); + for character in char::decode_utf16(name.iter().copied()) { + // String serialization operates on code points. As in browser CSSOM, + // an unpaired surrogate has no code point and is escaped as zero. + // The native family identity remains the original UTF-16 string. + let character = character.unwrap_or('\0'); + match character { + '\0'..='\u{1f}' | '\u{7f}' => { + output.extend(format!("\\{:x} ", character as u32).encode_utf16()); + } + '"' | '\\' => { + output.push(b'\\' as u16); + output.push(character as u16); + } + _ => { + output.extend_from_slice(character.encode_utf16(&mut [0; 2])); + } + } + } + output.push(b'"' as u16); + output +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn literal_family_serialization_does_not_parse_css_escapes_or_lists() { + for (name, expected) in [ + ("Demo", "Demo"), + ("Demo Face", "\"Demo Face\""), + (" a b ", "\" a b \""), + ("sans-serif", "\"sans-serif\""), + ("INHERIT", "\"INHERIT\""), + ("A, B", "\"A, B\""), + ("A\\ B", "\"A\\\\ B\""), + ("\"A\"", "\"\\\"A\\\"\""), + ("--name", "\"--name\""), + ("a\0\nb", "\"a\\0 \\a b\""), + ("", "\"\""), + ("漢字", "漢字"), + ] { + assert_eq!( + serialize_font_family_name_utf16(&name.encode_utf16().collect::>()), + expected.encode_utf16().collect::>(), + "{name:?}" + ); + } + } + + #[test] + fn literal_family_identity_keeps_unpaired_surrogates() { + assert_eq!(serialize_font_family_name_utf16(&[0xd800]), [0xd800]); + assert_eq!(serialize_font_family_name_utf16(&[0xdc00]), [0xdc00]); + assert_eq!( + serialize_font_family_name_utf16(&[0xd83d, 0xde00]), + [0xd83d, 0xde00] + ); + assert_eq!( + serialize_font_family_name_utf16(&[0xd800, b' ' as u16]), + "\"\\0 \"".encode_utf16().collect::>() + ); + } +} diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs index 7b8fa80af91..d4806436598 100644 --- a/moli-css-parse/src/lib.rs +++ b/moli-css-parse/src/lib.rs @@ -6,6 +6,7 @@ mod color; mod declaration; mod font_face; +mod font_family; mod font_palette; mod font_selection; mod math; @@ -28,10 +29,11 @@ pub use declaration::{ }; pub use font_face::{ CssFontFace, CssFontFamily, CssFontShorthand, CssFontSource, font_family_name_key, - font_load_query_contains_css_wide_keyword, font_load_query_family, font_load_query_is_valid, + font_load_query_families, 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, }; +pub use font_family::{font_family_name_needs_quotes, serialize_font_family_name_utf16}; pub use font_palette::{ CssFontPaletteValuesProperty, parse_font_palette_values_property_with_stylo, }; diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index b4902e5a7db..2fe81d2526b 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -222,7 +222,7 @@ pub(crate) use crypto::{ crypto_key_clone_payload_from_object, crypto_key_object_from_clone_payload, }; pub(crate) use css_fontface_runtime::{ - new_font_face_set, rebuild_font_face_set_faces, settle_document_font_face_set_ready, + font_face_raw_family, mark_font_face_css_connected, new_font_face_set, rebuild_font_face_set_faces, settle_document_font_face_set_ready, }; pub(crate) use form_navigation::FormNavigationHistory; pub(crate) use history_mutation::update_history_for_document_open; diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs index 81db79244c8..e0ae3e09192 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs @@ -10,6 +10,7 @@ fn apply_pending_stylesheet_source_css_projections(scope: &mut v8::PinScope<'_, const FONT_FACE_SET_FACES_SLOT: &str = "__moliFontFaceSetFaces"; pub(super) const FONT_FACE_FAMILY_SLOT: &str = "__moliFontFaceFamily"; +pub(super) const FONT_FACE_FAMILY_CSS_TEXT_SLOT: &str = "__moliFontFaceFamilyCssText"; pub(super) const FONT_FACE_SOURCE_SLOT: &str = "__moliFontFaceSource"; pub(super) const FONT_FACE_STYLE_SLOT: &str = "__moliFontFaceStyle"; pub(super) const FONT_FACE_WEIGHT_SLOT: &str = "__moliFontFaceWeight"; @@ -51,6 +52,9 @@ pub(in crate::context_bootstrap) use events::{ pub(super) use font_face::{ font_face_constructor_callback, font_face_load_callback, install_font_face_template_accessors, }; +pub(crate) use font_face::{ + font_face_raw_family, mark_font_face_css_connected, +}; pub(super) use font_face_set::{ font_face_set_add_callback, font_face_set_check_callback, font_face_set_clear_callback, font_face_set_delete_callback, font_face_set_entries_callback, font_face_set_for_each_callback, diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs index 866540390d6..2e4c5ec63ba 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs @@ -1,7 +1,10 @@ use super::*; use crate::web_api_interfaces; use crate::{ - util::{callback_data_index_value, callback_data_item, get_private_value, set_private_value}, + util::{ + callback_data_index_value, callback_data_item, get_private_value, set_private_value, + v8_string_from_utf16_units, v8_string_to_u16_string, + }, webidl, }; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; @@ -13,7 +16,9 @@ use descriptors::{FONT_FACE_WRITABLE_ATTRIBUTES, parse_font_face_descriptors}; #[webapi(interface = web_api_interfaces::FontFace)] struct FontFaceObjectDeclaration<'s> { #[webapi(slot = FONT_FACE_FAMILY_SLOT)] - family: String, + family: webidl::DomString16, + #[webapi(slot = FONT_FACE_FAMILY_CSS_TEXT_SLOT)] + family_css_text: bool, #[webapi(slot = FONT_FACE_SOURCE_SLOT)] source: String, #[webapi(slot = FONT_FACE_STYLE_SLOT)] @@ -53,7 +58,7 @@ struct FontFaceObjectDeclaration<'s> { struct FontFacePrototypeAccessorsDeclaration { #[webapi( accessor_property, - getter = font_face_writable_attribute_getter_callback, + getter = font_face_family_getter_callback, setter = font_face_attribute_setter_callback, data = callback_data_index_value(scope, 0), enumerable @@ -182,8 +187,8 @@ struct FontFacePrototypeAccessorsDeclaration { #[derive(webidl::WebIdlArgs)] #[webidl(prefix = "FontFace")] struct FontFaceConstructorArgs<'s> { - #[webidl(required)] - family: String, + #[webidl(required, converter = "raw")] + family: webidl::DomString16, #[webidl(required, with = font_face_constructor_source_arg)] source: FontFaceConstructorSource<'s>, } @@ -201,6 +206,27 @@ pub(in crate::context_bootstrap) fn install_font_face_template_accessors<'s>( FontFacePrototypeAccessorsDeclaration::initialize_prototype_template(scope, prototype); } +fn font_face_family_getter_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'s, v8::Value>, +) { + let value = font_face_slot_value(scope, args.this(), FONT_FACE_FAMILY_SLOT) + .unwrap_or_else(|| v8::undefined(scope).into()); + if font_face_slot_value(scope, args.this(), FONT_FACE_FAMILY_CSS_TEXT_SLOT) + .is_some_and(|value| value.is_true()) + && let Ok(name) = v8::Local::::try_from(value) + { + let name = v8_string_to_u16_string(scope, name); + let serialized = moli_css_parse::serialize_font_family_name_utf16(name.as_slice()); + if let Some(value) = v8_string_from_utf16_units(scope, &serialized) { + rv.set(value.into()); + } + return; + } + rv.set(value); +} + fn font_face_writable_attribute_getter_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -318,6 +344,8 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>( size_adjust, ] = descriptors; let this = args.this(); + let family_css_text = matches!(&parsed.source, FontFaceConstructorSource::Css(_)) + && moli_css_parse::font_family_name_needs_quotes(&parsed.family.0); let (source, sources, binary) = match parsed.source { FontFaceConstructorSource::Css(source) => { let sources = moli_css_parse::parse_font_face_sources(&source).map(|sources| { @@ -348,6 +376,7 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>( }; FontFaceObjectDeclaration::new( parsed.family, + family_css_text, source, style, weight, @@ -444,3 +473,23 @@ fn set_font_face_slot_value<'s>( ) { set_private_value(scope, object, slot, value); } + +pub(crate) fn mark_font_face_css_connected<'s>( + scope: &mut v8::PinScope<'s, '_>, + face: v8::Local<'s, v8::Object>, +) { + let value = v8::Boolean::new(scope, false); + set_font_face_slot_value(scope, face, FONT_FACE_FAMILY_CSS_TEXT_SLOT, value.into()); +} + +pub(crate) fn font_face_raw_family<'s>( + scope: &mut v8::PinScope<'s, '_>, + face: v8::Local<'s, v8::Object>, +) -> Option { + let name = font_face_slot_value(scope, face, FONT_FACE_FAMILY_SLOT) + .and_then(|value| v8::Local::::try_from(value).ok())?; + let units = v8_string_to_u16_string(scope, name); + Some(moli_dom::native::DomStringValue::from_utf16( + units.as_slice(), + )) +} 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 4401d603e08..0995a5a5418 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 @@ -33,6 +33,11 @@ pub(super) fn font_face_set_matching_faces_array<'s>( let Ok(face_object) = v8::Local::::try_from(face) else { continue; }; + // CSS parsing replaces unpaired surrogates; such a literal FontFace + // name must not alias the replacement character in a parsed query. + if super::font_face::font_face_raw_family(scope, face_object)?.as_str().is_none() { + continue; + } let load = super::state::get(scope, face_object).expect("FontFace has native state"); let descriptor = load.borrow().descriptor().clone(); // Constructors and successful setters update this same typed descriptor diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs index fd881a12f24..74510c218e1 100644 --- a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs +++ b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs @@ -117,8 +117,9 @@ fn construct_font_face_from_parts<'s>( ); } } - ctor.new_instance(scope, &[family.into(), source.into(), descriptors.into()]) - .map(Into::into) + let face = ctor.new_instance(scope, &[family.into(), source.into(), descriptors.into()])?; + crate::context_bootstrap::mark_font_face_css_connected(scope, face); + Some(face.into()) } fn construct_font_face<'s>( @@ -145,12 +146,13 @@ fn collect_font_face_objects<'s>( values } -fn font_face_matches_descriptor( - scope: &mut v8::PinScope<'_, '_>, - face: v8::Local<'_, v8::Object>, +fn font_face_matches_descriptor<'s>( + scope: &mut v8::PinScope<'s, '_>, + face: v8::Local<'s, v8::Object>, descriptor: &StylesheetFontFaceDescriptor, ) -> bool { - object_string_property(scope, face, "family").as_deref() == Some(descriptor.family()) + crate::context_bootstrap::font_face_raw_family(scope, face) + .is_some_and(|family| family.as_str() == Some(descriptor.family())) && object_string_property(scope, face, "source").as_deref() == Some(descriptor.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 f341325d6e1..6f19071e990 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 @@ -1528,6 +1528,118 @@ async fn invalid_font_face_defers_loaded_rejection_until_promise_is_observed() { ); } +#[tokio::test] +async fn font_face_family_serialization_preserves_source_modes_and_utf16() { + let result = eval_font_loading_fixture( + "https://font-face-family.test/", + r#" +(async () => { + const frame = document.createElement('iframe'); + (document.body || document.documentElement).appendChild(frame); + const failures = []; + const check = (name, actual, expected) => { + if (actual !== expected) failures.push({name, actual, expected}); + }; + for (const [label, realm] of [['main', window], ['child', frame.contentWindow]]) { + for (const [name, expected] of [ + ['Simple', 'Simple'], + ['A B', '"A B"'], + [' a b ', '" a b "'], + ['sans-serif', '"sans-serif"'], + ['A, B', '"A, B"'], + ['A\\ B', '"A\\\\ B"'], + ['"A"', '"\\"A\\""'], + ['', '""'], + ['a\0b', '"a\\0 b"'], + ['\ud800', '\ud800'], + ['\udc00', '\udc00'], + ['🙂', '🙂'], + ]) { + const face = new realm.FontFace(name, 'url(unused)'); + check(label + ' construct ' + name, face.family, expected); + face.family = name; + check(label + ' assign ' + name, face.family, expected); + check(label + ' status ' + name, face.status, 'unloaded'); + } + const literal = new realm.FontFace('A B', 'url(unused)'); + literal.family = 'Simple'; + check(label + ' quoted to identifier', literal.family, 'Simple'); + literal.family = 'A, B'; + check(label + ' quoted to list literal', literal.family, '"A, B"'); + const identifier = new realm.FontFace('Simple', 'url(unused)'); + identifier.family = 'A, B'; + check(label + ' identifier source mode', identifier.family, 'A, B'); + const binary = new realm.FontFace('A B', new realm.Uint8Array([1, 2, 3])); + check(label + ' binary source mode', binary.family, 'A B'); + } + const style = document.createElement('style'); + style.textContent = '@font-face { font-family: "CSS A B"; src: url(unused); }'; + document.head.appendChild(style); + const connected = Array.from(document.fonts).find(face => face.family === 'CSS A B'); + check('CSS connected family', connected && connected.family, 'CSS A B'); + check('CSS connected identity', document.fonts.has(connected), true); + style.remove(); + return JSON.stringify(failures); +})() +"#, + ) + .await; + assert_eq!(result, "[]"); +} + +#[tokio::test] +async fn font_face_set_queries_use_native_literal_families() { + let result = eval_font_loading_fixture( + "https://font-face-native-family-query.test/", + r#" +(async () => { + const frame = document.createElement('iframe'); + (document.body || document.documentElement).appendChild(frame); + const failures = []; + const check = (name, condition) => { if (!condition) failures.push(name); }; + for (const [label, realm] of [['main', window], ['child', frame.contentWindow]]) { + const set = realm.document.fonts; + for (const name of ['Literal Family', 'sans-serif', 'Literal, Family', 'Literal"Quote', 'Literal\\Slash']) { + const face = new realm.FontFace(name, fontFixtureSource); + set.add(face); + let reads = 0; + Object.defineProperty(face, 'family', { + get() { ++reads; throw Error('author family getter'); } + }); + const query = '16px ' + JSON.stringify(name); + check(label + ' not loaded ' + name, set.check(query) === false); + const loaded = await set.load(query); + check(label + ' native match ' + name, loaded.length === 1 && loaded[0] === face); + check(label + ' loaded ' + name, set.check(query) === true); + check(label + ' no author code ' + name, reads === 0); + set.delete(face); + } + const first = new realm.FontFace('First Literal', fontFixtureSource); + const second = new realm.FontFace('Second Literal', fontFixtureSource); + set.add(second).add(first); + const loaded = await set.load('16px "First Literal", "Second Literal", serif'); + check(label + ' every named family', loaded.length === 2 && loaded[0] === first && loaded[1] === second); + const repeated = await set.load('16px "First Literal", "Second Literal", "First Literal"'); + check(label + ' repeated named family', repeated.length === 3 && repeated[0] === first && repeated[1] === second && repeated[2] === first); + set.delete(first); + set.delete(second); + const caption = new realm.FontFace('caption', fontFixtureSource); + set.add(caption); + check(label + ' system font is not a literal family', (await set.load('caption')).length === 0); + set.delete(caption); + const unpaired = new realm.FontFace('\ud800', fontFixtureSource); + set.add(unpaired); + check(label + ' distinct scalar identity', (await set.load('16px "\ufffd"')).length === 0); + set.delete(unpaired); + } + return JSON.stringify(failures); +})() +"#, + ) + .await; + assert_eq!(result, "[]"); +} + #[tokio::test] async fn font_face_string_sources_follow_load_state_and_connected_style_use() { let result = eval_font_loading_fixture(