The headless browser for AI agents and web scraping
fix(render): render webfont icons and color emoji
SGavrl4f485571875d
diff --git a/crates/obscura-render/assets/FONT-PROVENANCE.md b/crates/obscura-render/assets/FONT-PROVENANCE.mdnew file mode 100644index 00000000..8dc536fa--- /dev/null+++ b/crates/obscura-render/assets/FONT-PROVENANCE.md@@ -0,0 +1,10 @@+# Bundled font provenance++## Noto Color Emoji++- File: `noto-color-emoji.ttf`+- Upstream: `googlefonts/noto-emoji`+- Version: 2.051 (Unicode 17.0)+- Commit: `8998f5dd683424a73e2314a8c1f1e359c19e8742`+- SHA-256: `72a635cb3d2f3524c51620cdde406b217204e8a6a06c6a096ff8ed4b5fd6e27b`+- License: SIL Open Font License 1.1, included in `LICENSE-NOTO-COLOR-EMOJI.txt`diff --git a/crates/obscura-render/assets/LICENSE-NOTO-COLOR-EMOJI.txt b/crates/obscura-render/assets/LICENSE-NOTO-COLOR-EMOJI.txtnew file mode 100644index 00000000..d952d62c--- /dev/null+++ b/crates/obscura-render/assets/LICENSE-NOTO-COLOR-EMOJI.txt@@ -0,0 +1,92 @@+This Font Software is licensed under the SIL Open Font License,+Version 1.1.++This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font+creation efforts of academic and linguistic communities, and to+provide a free and open framework in which fonts may be shared and+improved in partnership with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply to+any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software+components as distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to,+deleting, or substituting -- in part or in whole -- any of the+components of the Original Version, by changing formats or by porting+the Font Software to a new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed,+modify, redistribute, and sell modified and unmodified copies of the+Font Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components, in+Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the+corresponding Copyright Holder. This restriction only applies to the+primary font name as presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created using+the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/crates/obscura-render/assets/noto-color-emoji.ttf b/crates/obscura-render/assets/noto-color-emoji.ttfnew file mode 100644index 00000000..943741dfBinary files /dev/null and b/crates/obscura-render/assets/noto-color-emoji.ttf differdiff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 880f3f80..280130b7 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -4616,18 +4616,37 @@ fn layout_dom_once();grow_trailing_auto_cells(tree, &mut styles);+ let descendants = tree.descendants(tree.document());+ let needs_emoji_font = descendants.iter().any(|id| {+ tree.get_node(*id).is_some_and(|node| match &node.data {+ obscura_dom::tree::NodeData::Text { contents } => {+ crate::inline::text_may_need_emoji_font(contents)+ }+ _ => false,+ })+ }) || styles.values().any(|style| {+ style+ .before_content+ .as_deref()+ .is_some_and(crate::inline::text_may_need_emoji_font)+ || style+ .after_content+ .as_deref()+ .is_some_and(crate::inline::text_may_need_emoji_font)+ });+// The leaf context is the index of a cosmic-text inline formatting// context in `engine`; leaves without text carry no context.let mut taffy_tree: TaffyTree<usize> = crate::new_taffy_tree();let mut id_map: HashMap<taffy::NodeId, NodeId> = HashMap::new();let mut words: HashMap<taffy::NodeId, (NodeId, String)> = HashMap::new();- let mut engine = crate::inline::TextEngine::new_with_web_fonts(fonts);+ let mut engine =+ crate::inline::TextEngine::new_with_web_fonts_and_emoji(fonts, needs_emoji_font);let mut ifc_items = IfcRegistry::default();// The document node itself is not an element; lay out from the first// element descendant (the <html> root).- let root = tree- .descendants(tree.document())+ let root = descendants.into_iter().find(|id| tree.get_node(*id).map(|n| n.is_element()).unwrap_or(false));@@ -9471,7 +9490,7 @@ fn build_flex_grid_children(EffectiveGridChild::Generated { host, kind } => {let pseudo = effective_grid_child_style(effective_children[index], styles);if let Some((nodes, _)) = build_in_flow_pseudo(- host, kind, pseudo, taffy_tree, words, ifc_items,+ host, kind, pseudo, taffy_tree, words, engine, ifc_items,) {children.extend(nodes);}@@ -9774,7 +9793,14 @@ fn build_pseudo_content(style: &crate::LayoutStyle,taffy_tree: &mut TaffyTree<usize>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,+ ifc_items: &mut IfcRegistry,) -> Vec<taffy::NodeId> {+ let shaped = build_shaped_word_leaves(id, content, style, taffy_tree, words, engine, ifc_items);+ if !shaped.is_empty() {+ return shaped;+ }+let fsize = style.font_size.unwrap_or(16.0);let is_bold = crate::style::used_font_weight(style) >= 600;build_word_leaves(@@ -9834,6 +9860,7 @@ fn build_in_flow_pseudo(pseudo: Option<&crate::LayoutStyle>,taffy_tree: &mut TaffyTree<usize>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,ifc_items: &mut IfcRegistry,) -> Option<(Vec<taffy::NodeId>, bool)> {let pseudo = pseudo?;@@ -9844,7 +9871,8 @@ fn build_in_flow_pseudo(}let content = pseudo.before_content.as_deref();if !pseudo_requires_generated_box(pseudo, content) {- let leaves = build_pseudo_content(host, content?, pseudo, taffy_tree, words);+ let leaves =+ build_pseudo_content(host, content?, pseudo, taffy_tree, words, engine, ifc_items);return (!leaves.is_empty()).then_some((leaves, false));}@@ -9854,7 +9882,7 @@ fn build_in_flow_pseudo(// retaining that text as a measured leaf gives the otherwise-empty// generated table a spurious space glyph of intrinsic width..filter(|text| !text.is_empty() && !(pseudo.is_table_box && text.trim().is_empty()))- .map(|text| build_pseudo_content(host, text, pseudo, taffy_tree, words))+ .map(|text| build_pseudo_content(host, text, pseudo, taffy_tree, words, engine, ifc_items)).unwrap_or_default();let mut taffy_style = to_taffy_style(pseudo);// A block pseudo's outer participation is block-level, but its generated@@ -12536,6 +12564,7 @@ fn build(style.before_pseudo.as_deref(),taffy_tree,words,+ engine,ifc_items,) {before.append(&mut child_ids);@@ -12547,6 +12576,7 @@ fn build(style.after_pseudo.as_deref(),taffy_tree,words,+ engine,ifc_items,) {child_ids.append(&mut after);@@ -12797,6 +12827,7 @@ fn build_mixed_block(style.before_pseudo.as_deref(),taffy_tree,words,+ engine,ifc_items,);let after = build_in_flow_pseudo(@@ -12805,6 +12836,7 @@ fn build_mixed_block(style.after_pseudo.as_deref(),taffy_tree,words,+ engine,ifc_items,);let (before_leaves, before_block) = before.unwrap_or_else(|| (Vec::new(), false));@@ -13723,9 +13755,9 @@ fn build_children_with_native_float_band(}}}- if let Some((nodes, _)) =- build_in_flow_pseudo(parent_id, kind, pseudo, taffy_tree, words, ifc_items)- {+ if let Some((nodes, _)) = build_in_flow_pseudo(+ parent_id, kind, pseudo, taffy_tree, words, engine, ifc_items,+ ) {if let Some(style) = pseudo {for node in nodes {set_native_float_clear(taffy_tree, node, style, true);@@ -19517,6 +19549,44 @@ mod tests {);}+ #[test]+ fn generated_pseudo_content_shapes_with_the_loaded_webfont() {+ let tree = parse_html(+ r#"<style>+ html,body,p { margin:0 }+ #token::before {+ content:"WWWWiiii";+ font-family:Fixture, sans-serif;+ font-size:40px;+ line-height:50px+ }+ </style>+ <p id="token"></p>"#,+ );+ let token = tree.get_element_by_id("token").unwrap();+ let fallback = layout_dom(&tree, (500.0, 150.0));+ let loaded = layout_dom_with_web_fonts(+ &tree,+ (500.0, 150.0),+ &HashMap::new(),+ &[crate::inline::WebFont {+ data: include_bytes!("../assets/liberation-serif.ttf").to_vec(),+ family: Some("Fixture".to_string()),+ weight: Some((400, 400)),+ italic: Some(false),+ }],+ );++ assert!(+ loaded.word_ifc_items.contains_key(&token),+ "generated text must retain its webfont-shaped paint item"+ );+ assert_ne!(+ fallback.text_runs[&token][0].0.width, loaded.text_runs[&token][0].0.width,+ "the loaded face's advances must drive generated-content geometry"+ );+ }+#[test]fn positioned_pseudo_inherits_the_hosts_computed_font_metrics() {let tree = parse_html(diff --git a/crates/obscura-render/src/inline.rs b/crates/obscura-render/src/inline.rsindex 60896e15..150b434e 100644--- a/crates/obscura-render/src/inline.rs+++ b/crates/obscura-render/src/inline.rs@@ -45,6 +45,7 @@ static MONO_O: &[u8] = include_bytes!("../assets/liberation-mono-oblique.ttf");static MONO_BO: &[u8] = include_bytes!("../assets/liberation-mono-boldoblique.ttf");static SYSTEM_R: &[u8] = include_bytes!("../assets/dejavu-sans.ttf");static SYSTEM_B: &[u8] = include_bytes!("../assets/dejavu-sans-bold.ttf");+static EMOJI_R: &[u8] = include_bytes!("../assets/noto-color-emoji.ttf");#[cfg(test)]static FALLBACK: &[u8] = SYSTEM_R;@@ -53,6 +54,45 @@ const SERIF_FAMILY: &str = "Liberation Serif";const MONO_FAMILY: &str = "Liberation Mono";const SYSTEM_FAMILY: &str = "DejaVu Sans";+/// Whether text contains a code point that can request emoji presentation.+/// Keep the color face out of ordinary render passes: its bitmap table is+/// large, and loading it for every page would spend RSS and startup time even+/// when no emoji can be shaped.+pub(crate) fn text_may_need_emoji_font(text: &str) -> bool {+ text.chars().any(|ch| {+ matches!(+ ch,+ '\u{00A9}' | '\u{00AE}' | '\u{203C}' | '\u{2049}' | '\u{2122}' | '\u{2139}'+ | '\u{2194}'..='\u{2199}' | '\u{21A9}'..='\u{21AA}'+ | '\u{231A}'..='\u{231B}' | '\u{2328}' | '\u{23CF}'+ | '\u{23E9}'..='\u{23F3}' | '\u{23F8}'..='\u{23FA}' | '\u{24C2}'+ | '\u{25AA}'..='\u{25AB}' | '\u{25B6}' | '\u{25C0}'+ | '\u{25FB}'..='\u{25FE}' | '\u{2600}'..='\u{2604}' | '\u{2611}'+ | '\u{2614}'..='\u{2615}' | '\u{2618}' | '\u{261D}' | '\u{2620}'+ | '\u{2622}'..='\u{2623}' | '\u{2626}' | '\u{262A}'+ | '\u{262E}'..='\u{262F}' | '\u{2638}'..='\u{263A}' | '\u{2640}'+ | '\u{2642}' | '\u{2648}'..='\u{2653}' | '\u{265F}'..='\u{2660}'+ | '\u{2663}' | '\u{2665}'..='\u{2666}' | '\u{2668}' | '\u{267B}'+ | '\u{267E}'..='\u{267F}' | '\u{2692}'..='\u{2697}' | '\u{2699}'+ | '\u{269B}'..='\u{269C}' | '\u{26A0}'..='\u{26A1}' | '\u{26A7}'+ | '\u{26AA}'..='\u{26AB}' | '\u{26B0}'..='\u{26B1}'+ | '\u{26BD}'..='\u{26BE}' | '\u{26C4}'..='\u{26C5}' | '\u{26C8}'+ | '\u{26CE}'..='\u{26CF}' | '\u{26D1}' | '\u{26D3}'..='\u{26D4}'+ | '\u{26E9}'..='\u{26EA}' | '\u{26F0}'..='\u{26F5}'+ | '\u{26F7}'..='\u{26FA}' | '\u{26FD}' | '\u{2702}' | '\u{2705}'+ | '\u{2708}'..='\u{270D}' | '\u{270F}' | '\u{2712}' | '\u{2714}'+ | '\u{2716}' | '\u{271D}' | '\u{2721}' | '\u{2728}'+ | '\u{2733}'..='\u{2734}' | '\u{2744}' | '\u{2747}' | '\u{274C}'+ | '\u{274E}' | '\u{2753}'..='\u{2755}' | '\u{2757}'+ | '\u{2763}'..='\u{2764}' | '\u{2795}'..='\u{2797}' | '\u{27A1}'+ | '\u{27B0}' | '\u{27BF}' | '\u{2934}'..='\u{2935}'+ | '\u{2B05}'..='\u{2B07}' | '\u{2B1B}'..='\u{2B1C}' | '\u{2B50}'+ | '\u{2B55}' | '\u{3030}' | '\u{303D}' | '\u{3297}' | '\u{3299}'+ | '\u{FE0F}' | '\u{1F000}'..='\u{1FAFF}'+ )+ })+}+/// Map a CSS `font-family` list to a bundled face the way Chromium resolves the/// generic families on this host. Chromium's Linux `system-ui` resolves to/// DejaVu Sans, while `sans-serif`/Arial/Helvetica resolve to Liberation Sans.@@ -945,6 +985,10 @@ impl TextEngine {}pub(crate) fn new_with_web_fonts(fonts: &[WebFont]) -> Self {+ Self::new_with_web_fonts_and_emoji(fonts, false)+ }++ pub(crate) fn new_with_web_fonts_and_emoji(fonts: &[WebFont], load_emoji: bool) -> Self {// Build a database from embedded and page-provided faces. Never call// load_system_fonts: a host's font set would make layout differ// machine to machine and add a multi-millisecond startup scan.@@ -958,6 +1002,11 @@ impl TextEngine {declarations.push((id, None, None, None));}}+ if load_emoji {+ for id in db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(EMOJI_R))) {+ declarations.push((id, None, None, None));+ }+ }for font in fonts {for id in db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(font.data.clone(),@@ -4880,4 +4929,55 @@ gamma</div>"#,let flat = (0.0f32, vec![([7, 8, 9, 255], None)]);assert_eq!(sample_gradient(&flat, 3.0, 3.0, 20.0, 20.0), [7, 8, 9, 255]);}++ #[test]+ fn emoji_font_is_loaded_only_for_emoji_documents() {+ assert!(!text_may_need_emoji_font("Plain text and arrows ->"));+ assert!(text_may_need_emoji_font("Add ➕ or remove ➖"));+ assert!(text_may_need_emoji_font("Launch 🚀"));++ let plain = TextEngine::new_with_web_fonts_and_emoji(&[], false);+ assert!(!plain.loaded_families.contains_key("noto color emoji"));++ let mut engine = TextEngine::new_with_web_fonts_and_emoji(&[], true);+ let emoji_ids: std::collections::HashSet<_> = engine.loaded_families["noto color emoji"]+ .faces+ .iter()+ .filter_map(|face| face.font_id)+ .collect();+ let tree = obscura_dom::parse_html("<p id='copy'>➕ 😀 🚀</p>");+ let copy = tree.get_element_by_id("copy").unwrap();+ let style = LayoutStyle {+ display: Display::Block,+ font_size: Some(48.0),+ line_height: Some(crate::LineHeight::Px(64.0)),+ ..Default::default()+ };+ let item = engine+ .try_build(&tree, copy, &HashMap::from([(copy, style)]))+ .unwrap();+ engine.finalize(item, (0.0, 0.0), 300.0, None);+ let font_ids: std::collections::HashSet<_> = engine.items[item]+ .buffer+ .layout_runs()+ .flat_map(|run| run.glyphs.iter())+ .map(|glyph| glyph.font_id)+ .collect();+ assert!(+ !font_ids.is_disjoint(&emoji_ids),+ "emoji clusters must shape with the bundled color face"+ );+ let mut pixmap = tiny_skia::Pixmap::new(300, 80).unwrap();+ engine.paint_item(item, &mut pixmap, (0.0, 0.0));+ let colors: std::collections::HashSet<_> = pixmap+ .pixels()+ .iter()+ .filter(|pixel| pixel.alpha() != 0)+ .map(|pixel| (pixel.red(), pixel.green(), pixel.blue()))+ .collect();+ assert!(+ colors.len() > 20,+ "the bundled CBDT face must rasterize as color, not a monochrome mask"+ );+ }}diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex f95d66d6..6c169ef6 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -152,6 +152,10 @@ pub mod inline {#[derive(Default)]pub struct TextEngine;+ pub(crate) fn text_may_need_emoji_font(_text: &str) -> bool {+ false+ }+impl TextEngine {pub fn new() -> Self {TextEngine@@ -161,6 +165,10 @@ pub mod inline {TextEngine}+ pub(crate) fn new_with_web_fonts_and_emoji(_fonts: &[WebFont], _load_emoji: bool) -> Self {+ TextEngine+ }+pub fn register_replaced(&mut self,_width: f32,diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex da22b56a..3ac0eb72 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -4536,11 +4536,24 @@ fn paint_laid_dom_scrolled(}}- // `::before`/`::after` generated text (see `dom::build_pseudo_content`)- // has no DOM text node of its own; its word runs are registered under- // the host element's own id instead, so paint them here rather than- // through `paint_text_node` (which only runs for real text nodes).- if let Some(runs) = laid.text_runs.get(&nid) {+ // `::before`/`::after` generated text has no DOM text node of its own.+ // Its shaped word items are registered under the host element, so+ // paint them here. The static path remains for layout-only builds and+ // for a face that cosmic-text cannot decode.+ if let Some(items) = laid.word_ifc_items.get(&nid) {+ let offset = scroll_state.translation_for(laid, nid);+ for &item in items {+ laid.text_engine.paint_item_with_clip_mask_scaled_for_print(+ item,+ &mut pixmap,+ offset,+ clip,+ element_clip_mask,+ raster_scale,+ print_economy,+ );+ }+ } else if let Some(runs) = laid.text_runs.get(&nid) {let color = style.color.unwrap_or([0, 0, 0, 255]);let fsize = style.font_size.unwrap_or(16.0);let is_bold = crate::style::used_font_weight(style) >= 600;@@ -6854,6 +6867,13 @@ fn collect_web_fonts(cache: &mut RenderResourceCache,dynamic_fonts: &[DynamicFontFace],) -> Vec<crate::inline::WebFont> {+ struct FontRule {+ sources: Vec<(String, String)>,+ family: Option<String>,+ weight: Option<(u16, u16)>,+ italic: Option<bool>,+ }+let mut seen = std::collections::HashSet::new();let mut fonts = Vec::new();let mut rules = Vec::new();@@ -6874,16 +6894,20 @@ fn collect_web_fonts(if !font_face_covers_ascii(face) {continue;}- let Some(src) = font_face_urls(face).into_iter().next() else {+ let sources: Vec<_> = font_face_urls(face)+ .into_iter()+ .filter(|src| font_source_may_be_supported(src))+ .map(|src| (font_resource_key(&src, base_url), src))+ .collect();+ if sources.is_empty() {continue;- };- rules.push((- font_resource_key(&src, base_url),- src,- font_face_family(face),- font_face_weight(face),- font_face_italic(face),- ));+ }+ rules.push(FontRule {+ sources,+ family: font_face_family(face),+ weight: font_face_weight(face),+ italic: font_face_italic(face),+ });}}for face in dynamic_fonts {@@ -6894,16 +6918,20 @@ fn collect_web_fonts(if !font_face_covers_ascii(&descriptor_block) {continue;}- let Some(src) = font_face_urls(&descriptor_block).into_iter().next() else {+ let sources: Vec<_> = font_face_urls(&descriptor_block)+ .into_iter()+ .filter(|src| font_source_may_be_supported(src))+ .map(|src| (font_resource_key(&src, base_url), src))+ .collect();+ if sources.is_empty() {continue;- };- rules.push((- font_resource_key(&src, base_url),- src,- (!face.family.is_empty()).then(|| face.family.clone()),- font_face_weight(&descriptor_block),- font_face_italic(&descriptor_block),- ));+ }+ rules.push(FontRule {+ sources,+ family: (!face.family.is_empty()).then(|| face.family.clone()),+ weight: font_face_weight(&descriptor_block),+ italic: font_face_italic(&descriptor_block),+ });}// Critical web fonts are normally preloaded from the document with a URL@@ -6939,35 +6967,54 @@ fn collect_web_fonts(continue;}if let Some(decoded) = fetch_and_decode_font(src, base_url, cache) {- let metadata = rules.iter().find(|rule| rule.0 == key);+ let metadata = rules.iter().find(|rule| {+ rule.sources+ .iter()+ .any(|(source_key, _)| *source_key == key)+ });fonts.push(crate::inline::WebFont {data: decoded,- family: metadata.and_then(|rule| rule.2.clone()),- weight: metadata.and_then(|rule| rule.3),- italic: metadata.and_then(|rule| rule.4),+ family: metadata.and_then(|rule| rule.family.clone()),+ weight: metadata.and_then(|rule| rule.weight),+ italic: metadata.and_then(|rule| rule.italic),});}}- for (key, src, family, weight, italic) in rules {+ for rule in rules {if fonts.len() >= 16 {break;}- if !seen.insert(key) {- continue;- }- if let Some(decoded) = fetch_and_decode_font(&src, base_url, cache) {- fonts.push(crate::inline::WebFont {- data: decoded,- family,- weight,- italic,- });+ for (key, src) in rule.sources {+ if !seen.insert(key) {+ continue;+ }+ if let Some(decoded) = fetch_and_decode_font(&src, base_url, cache) {+ fonts.push(crate::inline::WebFont {+ data: decoded,+ family: rule.family,+ weight: rule.weight,+ italic: rule.italic,+ });+ break;+ }}}fonts}+/// Exclude source formats that fontdb cannot consume before issuing a request.+/// Unknown and extensionless URLs are retained because their response bytes can+/// still identify a supported sfnt, WOFF, or WOFF2 resource.+fn font_source_may_be_supported(src: &str) -> bool {+ let path = src+ .split(['?', '#'])+ .next()+ .unwrap_or(src)+ .to_ascii_lowercase();+ !path.ends_with(".eot") && !path.ends_with(".svg")+}+fn font_resource_key(src: &str, base_url: Option<&str>) -> String {url::Url::parse(src).ok()@@ -7055,13 +7102,14 @@ fn font_face_blocks(css: &str) -> Vec<&str> {fn font_face_declaration<'a>(face: &'a str, name: &str) -> Option<&'a str> {split_css_top_level(face, ';').into_iter()- .find_map(|declaration| {+ .filter_map(|declaration| {let (property, value) = declaration.split_once(':')?;property.trim().eq_ignore_ascii_case(name).then_some(value.trim())})+ .last()}fn font_face_family(face: &str) -> Option<String> {@@ -15112,6 +15160,76 @@ mod tests {assert_eq!(font_face_urls(face), vec!["example.otf"]);}+ #[test]+ fn font_face_uses_the_first_decodable_source() {+ let tree = parse_html(+ r#"<html><head><style>+ @font-face {+ font-family: Fixture;+ src: url("fixture.eot") format("embedded-opentype"),+ url("fixture.woff2") format("woff2"),+ url("fixture.ttf") format("truetype");+ }+ </style></head><body></body></html>"#,+ );+ let loads = Arc::new(std::sync::Mutex::new(Vec::new()));+ let loader_loads = Arc::clone(&loads);+ let mut resources = RenderResourceCache::with_loader(move |url: &str| {+ loader_loads+ .lock()+ .expect("font loads")+ .push(url.to_string());+ match url {+ // A server can return malformed bytes for a preferred source;+ // CSS Fonts requires trying the next candidate in the list.+ "https://example.test/fixture.woff2" => Some(b"not a font".to_vec()),+ "https://example.test/fixture.ttf" => Some(SERIF_FONT_BYTES.to_vec()),+ _ => None,+ }+ });++ let fonts = collect_web_fonts(+ &tree,+ Some("https://example.test/page.html"),+ &mut resources,+ &[],+ );++ assert_eq!(fonts.len(), 1);+ assert_eq!(fonts[0].family.as_deref(), Some("Fixture"));+ assert_eq!(fonts[0].data, SERIF_FONT_BYTES);+ assert_eq!(+ *loads.lock().expect("font loads"),+ vec![+ "https://example.test/fixture.woff2".to_string(),+ "https://example.test/fixture.ttf".to_string(),+ ],+ "unsupported EOT must be skipped without a request"+ );+ }++ #[test]+ fn font_face_uses_the_last_duplicate_src_descriptor() {+ let css = r#"@font-face {+ font-family: FontAwesome;+ src: url("legacy.eot");+ src: url("legacy.eot?#iefix") format("embedded-opentype"),+ url("icons.woff2") format("woff2"),+ url("icons.ttf") format("truetype");+ }"#;+ let face = font_face_blocks(css)[0];++ assert_eq!(+ font_face_urls(face),+ vec![+ "legacy.eot?#iefix".to_string(),+ "icons.woff2".to_string(),+ "icons.ttf".to_string(),+ ],+ "CSS keeps the final duplicate @font-face descriptor"+ );+ }+#[test]fn dynamic_font_face_uses_shared_fetch_decode_and_layout_path() {let tree = parse_html(