mirror of
https://github.com/lexmount/moli.git
synced 2026-11-25 00:02:32 +00:00
fix(print): reuse loaded CSS font sources across media views
Keep loaded source registrations until current capture declarations have been projected by source key, descriptors and declaration order. Remove the earlier slot filter that discarded another media rule's cached bytes. Allow the shared declaration selector to reuse CSS-connected registrations loaded through FontFace.load(), preserving scoped selection and byte Arcs. Cover no-store font URLs returning 404 after their first load, same-family and renamed print declarations, 65 cached source declarations, unchanged screen state, and both PDF and raster output in OnDemand and Realtime. Validation: cargo fmt --all; complete workspace/all-target/all-feature Clippy; 9 focused regressions passed; full nextest: 22,954 passed, 20 skipped.
This commit is contained in:
@@ -1407,7 +1407,10 @@ impl DocumentLayoutServices {
|
||||
continue;
|
||||
}
|
||||
let Some(cached) = self.web_fonts.values().find(|font| {
|
||||
font.membership.stylesheet
|
||||
// FontFace.load() may register a CSS-connected face before
|
||||
// its native stylesheet loader registers the same source.
|
||||
(font.membership.stylesheet
|
||||
|| font.membership.font_face_set == Some(FontFaceSetMembership::Connected))
|
||||
&& font.source_key.as_deref() == Some(declaration.source_key)
|
||||
}) else {
|
||||
continue;
|
||||
|
||||
@@ -555,6 +555,49 @@ fn batch_membership_retirement_rebuilds_once_and_preserves_other_owners() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_css_declarations_reuse_loaded_connected_sources() {
|
||||
for scope in [
|
||||
WebFontRegistrationScope::Stylesheet,
|
||||
WebFontRegistrationScope::FontFaceSetConnected,
|
||||
] {
|
||||
let mut services =
|
||||
DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
|
||||
services
|
||||
.register_web_font(
|
||||
registration("screen-rule", "ScreenAlias", TEST_TTF)
|
||||
.with_scope(scope)
|
||||
.with_source_key(Some("shared-css-source".into())),
|
||||
)
|
||||
.unwrap();
|
||||
let source = services.web_fonts["screen-rule"].sfnt_bytes.id();
|
||||
let print_face = WebFontFace::new("PrintAlias");
|
||||
services.with_stylesheet_font_declarations(
|
||||
[WebFontDeclaration {
|
||||
slot: "print-rule",
|
||||
source_key: "shared-css-source",
|
||||
face: &print_face,
|
||||
}],
|
||||
|selected| {
|
||||
assert_eq!(selected.web_font_count(), 1, "{scope:?}");
|
||||
assert!(selected.web_font_decoded_bytes("screen-rule").is_none());
|
||||
assert_eq!(selected.web_fonts["print-rule"].sfnt_bytes.id(), source);
|
||||
assert_eq!(
|
||||
shape_one_character(
|
||||
selected.parley_mut(),
|
||||
web_font_style("PrintAlias", 400.0),
|
||||
'A',
|
||||
),
|
||||
TEST_TTF,
|
||||
);
|
||||
},
|
||||
);
|
||||
assert_eq!(services.web_font_count(), 1);
|
||||
assert_eq!(services.web_fonts["screen-rule"].sfnt_bytes.id(), source);
|
||||
assert!(services.web_font_decoded_bytes("print-rule").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_css_order_keeps_sources_and_restores_selection_after_an_error() {
|
||||
let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);
|
||||
|
||||
@@ -130,17 +130,19 @@ impl CaptureLayoutOverlay {
|
||||
self.reused_fonts.insert(identity, available);
|
||||
}
|
||||
|
||||
/// Keep loaded source candidates until the pass's declarations have been
|
||||
/// projected. Another media rule can reuse a source under a different slot;
|
||||
/// with_stylesheet_font_declarations then filters the selected view.
|
||||
pub(crate) fn font_services_for_document(
|
||||
&self,
|
||||
identity: CaptureLayoutIdentity,
|
||||
live: &DocumentLayoutServices,
|
||||
is_active: impl Fn(&str) -> bool,
|
||||
) -> DocumentLayoutServices {
|
||||
if let Some(reused) = self.reused_fonts.get(&identity) {
|
||||
let selected = live.clone_for_temporary_layout(&is_active, Some(&reused.0));
|
||||
selected.clone_for_temporary_layout(is_active, self.fonts.get(&identity))
|
||||
let selected = live.clone_for_temporary_layout(|_| true, Some(&reused.0));
|
||||
selected.clone_for_temporary_layout(|_| true, self.fonts.get(&identity))
|
||||
} else {
|
||||
live.clone_for_temporary_layout(is_active, self.fonts.get(&identity))
|
||||
live.clone_for_temporary_layout(|_| true, self.fonts.get(&identity))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -177,13 +177,7 @@ fn build_native_layout_pass_recursive(
|
||||
"missing current stylesheet resource manifest",
|
||||
)
|
||||
})?;
|
||||
let active = fonts
|
||||
.web_fonts()
|
||||
.iter()
|
||||
.filter_map(|resource| resource.web_font().map(|font| font.registration_slot()))
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
let temporary = overlay
|
||||
.font_services_for_document(identity, services, |slot| active.contains(slot));
|
||||
let temporary = overlay.font_services_for_document(identity, services);
|
||||
Some((identity, fonts, temporary))
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -258,6 +258,77 @@ async fn print_cached_fonts_do_not_consume_resource_admission() {
|
||||
.expect("ready print fonts are not new preparation work");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn print_reuses_loaded_font_sources_without_new_preparation_entries() {
|
||||
run_page_vm_async_test(async move {
|
||||
use base64::Engine;
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../moli-layout/tests/fixtures/moli-ahem.woff2"
|
||||
)));
|
||||
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
|
||||
for policy in [LayoutPolicy::OnDemand, LayoutPolicy::Realtime] {
|
||||
let (mut page, _, _) = page_vm_with_bound_task_sources_and_owner_wake(
|
||||
&loader,
|
||||
Url::parse("https://cached-print-sources.test/")?,
|
||||
);
|
||||
page.layout_configuration.policy = policy;
|
||||
page.vm_mut().set_layout_policy(policy);
|
||||
assert_eq!(page.vm_mut().eval(&format!(r#"(() => {{
|
||||
const rules=prefix=>Array.from({{length:65}},(_,i)=>
|
||||
`@font-face{{font-family:${{prefix}}${{i}};src:url(data:font/woff2;base64,{data})}}`).join('');
|
||||
document.head.innerHTML='<style>@media screen{{'+rules('Screen')+
|
||||
'}}@media print{{'+rules('Print')+'p{{font-family:Print0}}}}</style>';
|
||||
document.body.innerHTML='<p style="font-size:16px">Cached text</p>';
|
||||
window.screenFonts=document.fonts;
|
||||
window.screenFaces=[...screenFonts];
|
||||
for(const face of screenFaces)face.load();
|
||||
return JSON.stringify([screenFaces.length,screenFaces.every(face=>face.status==='loaded')]);
|
||||
}})()"#))?, "[65,true]");
|
||||
let fonts = page.vm_mut().document_web_font_counts_for_test();
|
||||
let publishes = page.vm().layout_snapshot_cache_observability_for_test().2;
|
||||
for raster in [false, true] {
|
||||
let mut job = if raster {
|
||||
PrintCaptureJob::new(RendererCaptureScreenshotRequest {
|
||||
purpose: RendererScreenshotPurpose::Print {
|
||||
print_background: true,
|
||||
},
|
||||
..RendererCaptureScreenshotRequest::viewport_png()
|
||||
})?
|
||||
} else {
|
||||
PrintCaptureJob::new(RendererPrintToPdfRequest::default())?
|
||||
};
|
||||
let before = page.vm().layout_pass_observability_for_test().1;
|
||||
match page.advance_print_capture(&mut job)? {
|
||||
PrintCaptureAdvance::Complete(PrintCaptureReply::Pdf(
|
||||
RendererPrintToPdfReply::Printed(bytes),
|
||||
)) => {
|
||||
let pdf = lopdf::Document::load_mem(&bytes)?;
|
||||
assert!(pdf.extract_text(&[1])?.contains("Cached text"));
|
||||
}
|
||||
PrintCaptureAdvance::Complete(PrintCaptureReply::Raster(
|
||||
RendererCaptureScreenshotReply::Captured(image),
|
||||
)) => assert!(!image.bytes.is_empty()),
|
||||
_ => anyhow::bail!("cached sources must satisfy new print declaration identities"),
|
||||
}
|
||||
assert_eq!(page.vm().layout_pass_observability_for_test().1 - before, 1);
|
||||
assert!(job.entries.is_empty(), "cached sources are not new preparation work");
|
||||
assert!(job.fetches.is_empty());
|
||||
assert_eq!(job.overlay.retained_font_bytes(), 0, "shared decoded data must not be charged as new bytes");
|
||||
assert_eq!(page.vm().layout_snapshot_cache_observability_for_test().2, publishes);
|
||||
assert_eq!(page.vm_mut().document_web_font_counts_for_test(), fonts);
|
||||
assert_eq!(page.vm_mut().eval(
|
||||
"JSON.stringify([document.fonts===screenFonts,document.fonts.size,screenFaces.every(face=>screenFonts.has(face)&&face.status==='loaded'),matchMedia('print').matches])"
|
||||
)?, "[true,65,true,false]");
|
||||
page.cancel_print_capture(&mut job);
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.expect("cached sources survive temporary media declaration selection");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn print_new_fonts_still_respect_preparation_entry_limit() {
|
||||
run_page_vm_async_test(async move {
|
||||
|
||||
@@ -138,3 +138,123 @@ async fn print_fonts_follow_current_declaration_order_and_manual_priority() {
|
||||
result.unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_print_reuses_loaded_font_source(renamed: bool) {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use tokio::{io::AsyncWriteExt, net::TcpListener};
|
||||
|
||||
for policy in [LayoutPolicy::OnDemand, LayoutPolicy::Realtime] {
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let seen = requests.clone();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server: tokio::task::JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut stream, _) = listener.accept().await?;
|
||||
let request = read_owner_wake_http_request_head(&mut stream).await;
|
||||
anyhow::ensure!(request.starts_with("GET /font.ttf "), "{request}");
|
||||
let first = seen.fetch_add(1, Ordering::SeqCst) == 0;
|
||||
let (status, body): (_, &[u8]) = if first {
|
||||
(
|
||||
"200 OK",
|
||||
include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../moli-layout/tests/fixtures/moli-ahem-wide.ttf"
|
||||
)),
|
||||
)
|
||||
} else {
|
||||
("404 Not Found", &[])
|
||||
};
|
||||
stream.write_all(format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Type: font/ttf\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",body.len()
|
||||
).as_bytes()).await?;
|
||||
stream.write_all(body).await?;
|
||||
stream.shutdown().await?;
|
||||
}
|
||||
});
|
||||
let runtime = JsRuntime::initialize();
|
||||
runtime
|
||||
.renderer_owner_handle()
|
||||
.configure_layout_policy(policy)
|
||||
.unwrap();
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
loader.set_optional_resource_fetch_mask(
|
||||
crate::protocol_types::OptionalResourceFetchMask::FONT,
|
||||
);
|
||||
let mut page = create_test_html_page(
|
||||
&runtime,
|
||||
&loader,
|
||||
url::Url::parse(&format!("{base}/page")).unwrap(),
|
||||
"<!doctype html><body>",
|
||||
)
|
||||
.await;
|
||||
let result = tokio::time::timeout(Duration::from_secs(20), async {
|
||||
page.run_async_command(RendererPageCommand::SetViewportSurface(Some(
|
||||
crate::protocol_types::ViewportSurface {
|
||||
inner_width:220,inner_height:96,device_pixel_ratio:1.0,..Default::default()
|
||||
}
|
||||
))).await?;
|
||||
let print_family = if renamed { "CaptureAlias" } else { "CaptureSource" };
|
||||
let setup = format!(r#"(async()=>{{
|
||||
document.head.innerHTML=`<style>
|
||||
@media screen{{@font-face{{font-family:CaptureSource;src:url({base}/font.ttf)}}}}
|
||||
html,body{{margin:0;background:white;scrollbar-width:none}}
|
||||
#probe{{position:absolute;left:8px;top:8px;display:inline-block;font:40px/40px CaptureSource;color:black}}
|
||||
@media print{{@font-face{{font-family:{print_family};src:url({base}/font.ttf)}}
|
||||
#probe{{font-family:{print_family}}}}}
|
||||
</style>`;
|
||||
document.body.innerHTML='<span id=probe>AAAA</span>';
|
||||
await document.fonts.load('40px CaptureSource','AAAA');
|
||||
await document.fonts.ready;
|
||||
window.liveFonts=document.fonts;window.liveReady=liveFonts.ready;
|
||||
window.screenFace=[...liveFonts][0];
|
||||
return JSON.stringify([probe.getBoundingClientRect().width,liveFonts.size,screenFace.status]);
|
||||
}})()"#);
|
||||
anyhow::ensure!(evaluate_print_fixture(&page,setup,true).await?==serde_json::json!("[160,1,\"loaded\"]"));
|
||||
anyhow::ensure!(requests.load(Ordering::SeqCst)==1,"screen must load the shared source once");
|
||||
let (reply, _) = page.run_async_command(RendererPageCommand::PrintToPdf(
|
||||
RendererPrintToPdfRequest::default(),
|
||||
)).await?;
|
||||
let RendererPageReply::PrintToPdf(RendererPrintToPdfReply::Printed(bytes)) = reply else {
|
||||
anyhow::bail!("cached source print must produce a PDF");
|
||||
};
|
||||
anyhow::ensure!(requests.load(Ordering::SeqCst)==1,
|
||||
"printing must reuse the loaded source instead of requesting its now-unavailable URL: {policy:?}, renamed={renamed}, requests={}",requests.load(Ordering::SeqCst));
|
||||
let pdf=lopdf::Document::load_mem(&bytes)?;
|
||||
anyhow::ensure!(pdf.extract_text(&[1])?.contains("AAAA"));
|
||||
let font_names=pdf.objects.values().filter_map(|object|
|
||||
object.as_dict().ok()?.get(b"FontName").ok()?.as_name().ok()
|
||||
).collect::<Vec<_>>();
|
||||
anyhow::ensure!(font_names.len()==1 && font_names[0].ends_with(b"MoliAhem-Regular"),
|
||||
"the PDF must embed the loaded fixture font: {font_names:?}");
|
||||
assert_capture_font_pixel(&page,true).await?;
|
||||
anyhow::ensure!(requests.load(Ordering::SeqCst)==1,"raster print must share the same cached source");
|
||||
anyhow::ensure!(evaluate_print_fixture(&page,
|
||||
"JSON.stringify([probe.getBoundingClientRect().width,document.fonts===liveFonts,document.fonts.ready===liveReady,liveFonts.size,liveFonts.has(screenFace),screenFace.status,matchMedia('print').matches])".to_owned(),false
|
||||
).await?==serde_json::json!("[160,true,true,1,true,\"loaded\",false]"),
|
||||
"temporary print declarations must not change live screen fonts");
|
||||
Ok::<_,anyhow::Error>(())
|
||||
}).await;
|
||||
page.close_async().await.unwrap();
|
||||
server.abort();
|
||||
let server_result = server.await;
|
||||
assert!(
|
||||
matches!(server_result,Err(error) if error.is_cancelled()),
|
||||
"font fixture must stay live until shutdown"
|
||||
);
|
||||
result.unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn print_reuses_loaded_font_source_for_same_family() {
|
||||
assert_print_reuses_loaded_font_source(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn print_reuses_loaded_font_source_for_renamed_family() {
|
||||
assert_print_reuses_loaded_font_source(true).await;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user